repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jmacdonald/purge
filesystem/directory/navigator/presenter.go
18
package navigator
gpl-3.0
nickkolok/chas-ege
zdn/mat2014/B11/26861.js
536
(function(){ NAinfo.requireApiVersion(0, 0); var a; var y; var e; var b; var c; do { a = sluchch(2, 10); y = sluchch(2, 10); e = sluchch(2, 10); b = Math.pow(a, y); c = Math.pow(e, y); } while (b > 100 || c > 100 || b == c); NAtask.setTask({ text: 'Найдите значение выражения $${'+a+'}^{\\log_{'+b+'}{'+c+'}}$$', answers: e, },{ tags: { log:1, }, }); })(); //https://math-ege.sdamgia.ru/problem?id=26861 //Автор: Арахов Никита //Reviewed and commited by Aisse-258
gpl-3.0
txthinking/brook
client.go
4333
// Copyright (c) 2016-present Cloud <cloud@txthinking.com> // // This program is free software; you can redistribute it and/or // modify it under the terms of version 3 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. package brook import ( "log" "net" "time" "github.com/txthinking/brook/limits" "github.com/txthinking/socks5" ) // Client. type Client struct { Server *socks5.Server ServerAddress string Password []byte TCPTimeout int UDPTimeout int } // NewClient returns a new Client. func NewClient(addr, ip, server, password string, tcpTimeout, udpTimeout int) (*Client, error) { s5, err := socks5.NewClassicServer(addr, ip, "", "", tcpTimeout, udpTimeout) if err != nil { return nil, err } if err := limits.Raise(); err != nil { log.Println("Try to raise system limits, got", err) } x := &Client{ ServerAddress: server, Server: s5, Password: []byte(password), TCPTimeout: tcpTimeout, UDPTimeout: udpTimeout, } return x, nil } // ListenAndServe will let client start a socks5 proxy. func (x *Client) ListenAndServe() error { return x.Server.ListenAndServe(x) } // TCPHandle handles tcp request. func (x *Client) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error { if r.Cmd == socks5.CmdConnect { debug("dial tcp", r.Address()) rc, err := Dial.Dial("tcp", x.ServerAddress) if err != nil { return ErrorReply(r, c, err) } defer rc.Close() if x.TCPTimeout != 0 { if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPTimeout) * time.Second)); err != nil { return ErrorReply(r, c, err) } } dst := make([]byte, 0, 1+len(r.DstAddr)+2) dst = append(dst, r.Atyp) dst = append(dst, r.DstAddr...) dst = append(dst, r.DstPort...) sc, err := NewStreamClient("tcp", x.Password, dst, rc, x.TCPTimeout) if err != nil { return ErrorReply(r, c, err) } defer sc.Clean() a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String()) if err != nil { return ErrorReply(r, c, err) } rp := socks5.NewReply(socks5.RepSuccess, a, address, port) if _, err := rp.WriteTo(c); err != nil { return err } if err := sc.Exchange(c); err != nil { return nil } return nil } if r.Cmd == socks5.CmdUDP { _, err := r.UDP(c, x.Server.ServerAddr) if err != nil { return err } return nil } return socks5.ErrUnsupportCmd } type UDPExchange struct { Conn net.Conn Any interface{} Dst []byte } // UDPHandle handles udp request. func (x *Client) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error { src := addr.String() dst := d.Address() any, ok := s.UDPExchanges.Get(src + dst) if ok { ue := any.(*UDPExchange) return ue.Any.(*PacketClient).LocalToServer(ue.Dst, d.Data, ue.Conn, x.UDPTimeout) } debug("dial udp", dst) var laddr *net.UDPAddr any, ok = s.UDPSrc.Get(src + dst) if ok { laddr = any.(*net.UDPAddr) } raddr, err := net.ResolveUDPAddr("udp", x.ServerAddress) if err != nil { return err } rc, err := Dial.DialUDP("udp", laddr, raddr) if err != nil { return err } defer rc.Close() if laddr == nil { s.UDPSrc.Set(src+dst, rc.LocalAddr().(*net.UDPAddr), -1) } dstb := make([]byte, 0, 1+len(d.DstAddr)+2) dstb = append(dstb, d.Atyp) dstb = append(dstb, d.DstAddr...) dstb = append(dstb, d.DstPort...) pc := NewPacketClient(x.Password) defer pc.Clean() if err := pc.LocalToServer(dstb, d.Data, rc, x.UDPTimeout); err != nil { return err } ue := &UDPExchange{ Conn: rc, Any: pc, Dst: dstb, } s.UDPExchanges.Set(src+dst, ue, -1) defer s.UDPExchanges.Delete(src + dst) err = pc.RunServerToLocal(rc, s.UDPTimeout, func(dst, b []byte) (int, error) { d.Data = b return s.UDPConn.WriteToUDP(d.Bytes(), addr) }) if err != nil { return nil } return nil } // Shutdown used to stop the client. func (x *Client) Shutdown() error { return x.Server.Shutdown() }
gpl-3.0
educacaoitajai/erudio
erudio-front-beta/apps/professor/eventos/controllers/eventoHomeController.js
6325
(function (){ /* * @ErudioDoc Instituição Form Controller * @Module instituicoesForm * @Controller InstituicaoFormController */ class EventoHomeController { constructor(service, util, erudioConfig, routeParams, $timeout, $mdDialog, $mdMenu, turmaService){ this.service = service; this.util = util; this.routeParams = routeParams; this.erudioConfig = erudioConfig; this.timeout = $timeout; this.turmaService = turmaService; this.mdDialog = $mdDialog; this.mdMenu = $mdMenu; this.calendario = null; this.mesCalendario = []; this.semanaCalendario = []; this.permissaoLabel = "HOME_PROFESSOR"; this.linkModulo = "/#!/calendarios/"; this.nomeForm = "calendarioForm"; this.mes = null; this.ano = null; this.disciplinaEscolhida = false; this.possuiEnturmacoes = parseInt(sessionStorage.getItem('possuiEnturmacoes')); this.iniciar(); } verificarPermissao(){ return this.util.verificaPermissao(this.permissaoLabel); } verificaEscrita() { return this.util.verificaEscrita(this.permissaoLabel); } validarEscrita(opcao) { if (opcao.validarEscrita) { return this.util.validarEscrita(opcao.opcao, this.opcoes, this.escrita); } else { return true; } } resetCalendario() { this.mesCalendario = []; this.semanaCalendario = []; } preparaCalendario(mes,ano) { var self = this; if (this.util.isVazio(mes) && this.util.isVazio(ano)) { var dateBase = new Date(); this.mes = dateBase.getMonth(); this.ano = dateBase.getFullYear(); this.preparaCalendario(this.mes, this.ano); } else { this.diaS = 1; this.mes = mes; this.ano = ano; this.diaSemana = new Date(this.ano,this.mes,this.diaS).getDay(); this.counterCalendario = this.diaSemana; this.gapInicio = this.diaSemana; this.diasMes = this.util.diasNoMes(this.mes,this.ano); this.semanaCalendario = new Array(this.gapInicio); this.nomeMes = this.util.nomeMes(this.mes); this.timeout(function(){ self.linkPaginacao(); },500); self.buscarEventos(); } }; buscarCalendario() { if (!this.util.isVazio(sessionStorage.getItem('turmaSelecionada'))) { this.disciplinaEscolhida = true; var self = this; var obj = JSON.parse(sessionStorage.getItem('turmaSelecionada')); this.turmaService.get(obj.turma.id,true).then((turma) => { this.calendario = turma.calendario; this.preparaCalendario(); }); } } abrirDia(dia) { this.dia = dia; var self = this; this.mdDialog.show({locals: {dia: {dia: dia, config: this.erudioConfig} }, controller: this.modalControl, templateUrl: this.erudioConfig.dominio+'/apps/professor/eventos/partials/dia.html', parent: angular.element(document.body), targetEvent: event, clickOutsideToClose: true}); } modalControl($scope, dia) { $scope.dia = dia.dia; $scope.config = dia.config; $scope.dia.eventos.forEach((evento) => { let ini = evento.inicio.split(":"); evento.inicio = ini[0]+":"+ini[1]; let termino = evento.termino.split(":"); evento.termino = termino[0]+":"+termino[1]; }); $scope.abreMenu = function ($mdMenu, ev) { var origemEv = ev; $mdMenu.open(ev); }; } buscarEventos() { this.service.getDiasPorMes(this.calendario,this.mes+1,true).then((dias) => { this.dias = dias; for (var i=0; i<this.diasMes; i++) { this.counterCalendario++; this.semanaCalendario.push(this.dias[i]); if (this.counterCalendario === 7) { this.mesCalendario.push(this.semanaCalendario); this.counterCalendario = 0; this.semanaCalendario = []; } if (i === this.diasMes-1) { var dataFinal = new Date(this.ano,this.mes,i+1); this.gapFinal = 6 - dataFinal.getDay(); for (var j=0; j<this.gapFinal; j++) { this.semanaCalendario.push(null); if (j === this.gapFinal-1) { this.mesCalendario.push(this.semanaCalendario); } } } } }); } linkPaginacao() { this.proximoMes = new Date(this.ano,this.mes,1); this.proximoMes.setMonth(this.proximoMes.getMonth()+1); this.mesAnterior = new Date(this.ano,this.mes,1); this.mesAnterior.setMonth(this.mesAnterior.getMonth()-1); } classeTipoDia(dia){ if (!this.util.isVazio(dia)) { if (dia.efetivo) { return 'calendario-dia-efetivo'; } else if (dia.letivo) { return 'calendario-dia-letivo'; } else { return 'calendario-dia-nao-letivo'; } } } paginaProxima(){ this.resetCalendario(); this.preparaCalendario(this.proximoMes.getMonth(),this.proximoMes.getFullYear()); } paginaAnterior(){ this.resetCalendario(); this.preparaCalendario(this.mesAnterior.getMonth(),this.mesAnterior.getFullYear()); } iniciar(){ let permissao = this.verificarPermissao(); if (permissao) { this.fab = {tooltip: 'Voltar à lista', icone: 'arrow_back', href: this.erudioConfig.dominio + this.linkModulo}; this.util.comPermissao(); this.attr = JSON.parse(sessionStorage.getItem('atribuicoes')); this.util.setTitulo(this.titulo); this.escrita = this.verificaEscrita(); this.isAdmin = this.util.isAdmin(); this.buscarCalendario(); this.util.inicializar(); } else { this.util.semPermissao(); } } } EventoHomeController.$inject = ["CalendarioService","Util","ErudioConfig","$routeParams","$timeout","$mdDialog","$mdMenu","TurmaService"]; angular.module('EventoHomeController',['ngMaterial', 'util', 'erudioConfig']).controller('EventoHomeController',EventoHomeController); })();
gpl-3.0
ckaestne/KBuildMiner
src/test/scala/gsd/buildanalysis/linux/test/FuzzyParserTest.scala
1017
/* * Copyright (c) 2010 Thorsten Berger <berger@informatik.uni-leipzig.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gsd.buildanalysis.linux.test import org.scalatest.FunSuite import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class FuzzyParserTest extends FunSuite{ test("placeholder"){ // to be implemented... assert( true ) } }
gpl-3.0
siteserver/cms
src/SSCMS.Web/Controllers/Admin/Settings/Administrators/AdministratorsAccessTokensController.Dto.cs
581
using System.Collections.Generic; using SSCMS.Models; namespace SSCMS.Web.Controllers.Admin.Settings.Administrators { public partial class AdministratorsAccessTokensController { public class ListResult { public List<AccessToken> Tokens { get; set; } public List<string> AdminNames { get; set; } public List<string> Scopes { get; set; } public string AdminName { get; set; } } public class TokensResult { public List<AccessToken> Tokens { get; set; } } } }
gpl-3.0
h3x4d3c1m4l/h3xmonitor
src/h3xmonitor/Logging/LoglineLevel.cs
956
/* This file is part of h3xmonitor. h3xmonitor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. h3xmonitor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace h3xmonitor.Logging { public enum LoglineLevel { Fatal = 0, Error = 1, Warning = 2, Info = 3, Debug = 4 } }
gpl-3.0
magic3org/magic3
include/wp/plugins/woocommerce/includes/abstracts/abstract-wc-shipping-method.php
14964
<?php if ( ! defined( 'ABSPATH' ) ) { exit; } /** * WooCommerce Shipping Method Class. * * Extended by shipping methods to handle shipping calculations etc. * * @class WC_Shipping_Method * @version 3.0.0 * @package WooCommerce/Abstracts * @category Abstract Class * @author WooThemes */ abstract class WC_Shipping_Method extends WC_Settings_API { //abstract class WC_Shipping_Method { /** * Features this method supports. Possible features used by core: * - shipping-zones Shipping zone functionality + instances * - instance-settings Instance settings screens. * - settings Non-instance settings screens. Enabled by default for BW compatibility with methods before instances existed. * - instance-settings-modal Allows the instance settings to be loaded within a modal in the zones UI. * @var array */ public $supports = array( 'settings' ); /** * Unique ID for the shipping method - must be set. * @var string */ public $id = ''; /** * Method title. * @var string */ public $method_title = ''; /** * Method description. * @var string */ public $method_description = ''; /** * yes or no based on whether the method is enabled. * @var string */ public $enabled = 'yes'; /** * Shipping method title for the frontend. * @var string */ public $title; /** * This is an array of rates - methods must populate this array to register shipping costs. * @var array */ public $rates = array(); /** * If 'taxable' tax will be charged for this method (if applicable). * @var string */ public $tax_status = 'taxable'; /** * Fee for the method (if applicable). * @var string */ public $fee = null; /** * Minimum fee for the method (if applicable). * @var string */ public $minimum_fee = null; /** * Instance ID if used. * @var int */ public $instance_id = 0; /** * Instance form fields. * @var array */ public $instance_form_fields = array(); /** * Instance settings. * @var array */ public $instance_settings = array(); /** * Availability - legacy. Used for method Availability. * No longer useful for instance based shipping methods. * @deprecated 2.6.0 * @var string */ public $availability; /** * Availability countries - legacy. Used for method Availability. * No longer useful for instance based shipping methods. * @deprecated 2.6.0 * @var array */ public $countries = array(); /** * Constructor. * @param int $instance_id */ public function __construct( $instance_id = 0 ) { $this->instance_id = absint( $instance_id ); } /** * Check if a shipping method supports a given feature. * * Methods should override this to declare support (or lack of support) for a feature. * * @param $feature string The name of a feature to test support for. * @return bool True if the shipping method supports the feature, false otherwise. */ public function supports( $feature ) { return apply_filters( 'woocommerce_shipping_method_supports', in_array( $feature, $this->supports ), $feature, $this ); } /** * Called to calculate shipping rates for this method. Rates can be added using the add_rate() method. * * @param array $package */ public function calculate_shipping( $package = array() ) {} /** * Whether or not we need to calculate tax on top of the shipping rate. * @return boolean */ public function is_taxable() { return wc_tax_enabled() && 'taxable' === $this->tax_status && ! WC()->customer->get_is_vat_exempt(); } /** * Whether or not this method is enabled in settings. * @since 2.6.0 * @return boolean */ public function is_enabled() { return 'yes' === $this->enabled; } /** * Return the shipping method instance ID. * @since 2.6.0 * @return int */ public function get_instance_id() { return $this->instance_id; } /** * Return the shipping method title. * @since 2.6.0 * @return string */ public function get_method_title() { return apply_filters( 'woocommerce_shipping_method_title', $this->method_title, $this ); } /** * Return the shipping method description. * @since 2.6.0 * @return string */ public function get_method_description() { return apply_filters( 'woocommerce_shipping_method_description', $this->method_description, $this ); } /** * Return the shipping title which is user set. * * @return string */ public function get_title() { return apply_filters( 'woocommerce_shipping_method_title', $this->title, $this->id ); } /** * Return calculated rates for a package. * @since 2.6.0 * @param object $package * @return array */ public function get_rates_for_package( $package ) { $this->rates = array(); if ( $this->is_available( $package ) && ( empty( $package['ship_via'] ) || in_array( $this->id, $package['ship_via'] ) ) ) { $this->calculate_shipping( $package ); } return $this->rates; } /** * Returns a rate ID based on this methods ID and instance, with an optional * suffix if distinguishing between multiple rates. * @since 2.6.0 * @param string $suffix * @return string */ public function get_rate_id( $suffix = '' ) { $rate_id = array( $this->id ); if ( $this->instance_id ) { $rate_id[] = $this->instance_id; } if ( $suffix ) { $rate_id[] = $suffix; } return implode( ':', $rate_id ); } /** * Add a shipping rate. If taxes are not set they will be calculated based on cost. * @param array $args (default: array()) */ public function add_rate( $args = array() ) { $args = wp_parse_args( $args, array( 'id' => $this->get_rate_id(), // ID for the rate. If not passed, this id:instance default will be used. 'label' => '', // Label for the rate 'cost' => '0', // Amount or array of costs (per item shipping) 'taxes' => '', // Pass taxes, or leave empty to have it calculated for you, or 'false' to disable calculations 'calc_tax' => 'per_order', // Calc tax per_order or per_item. Per item needs an array of costs 'meta_data' => array(), // Array of misc meta data to store along with this rate - key value pairs. 'package' => false, // Package array this rate was generated for @since 2.6.0 ) ); // ID and label are required if ( ! $args['id'] || ! $args['label'] ) { return; } // Total up the cost $total_cost = is_array( $args['cost'] ) ? array_sum( $args['cost'] ) : $args['cost']; $taxes = $args['taxes']; // Taxes - if not an array and not set to false, calc tax based on cost and passed calc_tax variable. This saves shipping methods having to do complex tax calculations. if ( ! is_array( $taxes ) && false !== $taxes && $total_cost > 0 && $this->is_taxable() ) { $taxes = 'per_item' === $args['calc_tax'] ? $this->get_taxes_per_item( $args['cost'] ) : WC_Tax::calc_shipping_tax( $total_cost, WC_Tax::get_shipping_tax_rates() ); } // Round the total cost after taxes have been calculated. $total_cost = wc_format_decimal( $total_cost, wc_get_price_decimals() ); // Create rate object $rate = new WC_Shipping_Rate( $args['id'], $args['label'], $total_cost, $taxes, $this->id ); if ( ! empty( $args['meta_data'] ) ) { foreach ( $args['meta_data'] as $key => $value ) { $rate->add_meta_data( $key, $value ); } } // Store package data if ( $args['package'] ) { $items_in_package = array(); foreach ( $args['package']['contents'] as $item ) { $product = $item['data']; $items_in_package[] = $product->get_name() . ' &times; ' . $item['quantity']; } $rate->add_meta_data( __( 'Items', 'woocommerce' ), implode( ', ', $items_in_package ) ); } $this->rates[ $args['id'] ] = $rate; } /** * Calc taxes per item being shipping in costs array. * @since 2.6.0 * @access protected * @param array $costs * @return array of taxes */ protected function get_taxes_per_item( $costs ) { $taxes = array(); // If we have an array of costs we can look up each items tax class and add tax accordingly if ( is_array( $costs ) ) { $cart = WC()->cart->get_cart(); foreach ( $costs as $cost_key => $amount ) { if ( ! isset( $cart[ $cost_key ] ) ) { continue; } $item_taxes = WC_Tax::calc_shipping_tax( $amount, WC_Tax::get_shipping_tax_rates( $cart[ $cost_key ]['data']->get_tax_class() ) ); // Sum the item taxes foreach ( array_keys( $taxes + $item_taxes ) as $key ) { $taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 ); } } // Add any cost for the order - order costs are in the key 'order' if ( isset( $costs['order'] ) ) { $item_taxes = WC_Tax::calc_shipping_tax( $costs['order'], WC_Tax::get_shipping_tax_rates() ); // Sum the item taxes foreach ( array_keys( $taxes + $item_taxes ) as $key ) { $taxes[ $key ] = ( isset( $item_taxes[ $key ] ) ? $item_taxes[ $key ] : 0 ) + ( isset( $taxes[ $key ] ) ? $taxes[ $key ] : 0 ); } } } return $taxes; } /** * Is this method available? * @param array $package * @return bool */ public function is_available( $package ) { $available = $this->is_enabled(); // Country availability (legacy, for non-zone based methods) if ( ! $this->instance_id && $available ) { $countries = is_array( $this->countries ) ? $this->countries : array(); switch ( $this->availability ) { case 'specific' : case 'including' : $available = in_array( $package['destination']['country'], array_intersect( $countries, array_keys( WC()->countries->get_shipping_countries() ) ) ); break; case 'excluding' : $available = in_array( $package['destination']['country'], array_diff( array_keys( WC()->countries->get_shipping_countries() ), $countries ) ); break; default : $available = in_array( $package['destination']['country'], array_keys( WC()->countries->get_shipping_countries() ) ); break; } } return apply_filters( 'woocommerce_shipping_' . $this->id . '_is_available', $available, $package ); } /** * Get fee to add to shipping cost. * @param string|float $fee * @param float $total * @return float */ public function get_fee( $fee, $total ) { if ( strstr( $fee, '%' ) ) { $fee = ( $total / 100 ) * str_replace( '%', '', $fee ); } if ( ! empty( $this->minimum_fee ) && $this->minimum_fee > $fee ) { $fee = $this->minimum_fee; } return $fee; } /** * Does this method have a settings page? * @return bool */ public function has_settings() { return $this->instance_id ? $this->supports( 'instance-settings' ) : $this->supports( 'settings' ); } /** * Return admin options as a html string. * @return string */ public function get_admin_options_html() { if ( $this->instance_id ) { $settings_html = $this->generate_settings_html( $this->get_instance_form_fields(), false ); } else { $settings_html = $this->generate_settings_html( $this->get_form_fields(), false ); } return '<table class="form-table">' . $settings_html . '</table>'; } /** * Output the shipping settings screen. */ public function admin_options() { if ( ! $this->instance_id ) { echo '<h2>' . esc_html( $this->get_method_title() ) . '</h2>'; } echo wp_kses_post( wpautop( $this->get_method_description() ) ); echo $this->get_admin_options_html(); } /** * get_option function. * * Gets and option from the settings API, using defaults if necessary to prevent undefined notices. * * @param string $key * @param mixed $empty_value * @return mixed The value specified for the option or a default value for the option. */ public function get_option( $key, $empty_value = null ) { // Instance options take priority over global options if ( $this->instance_id && array_key_exists( $key, $this->get_instance_form_fields() ) ) { return $this->get_instance_option( $key, $empty_value ); } // Return global option return parent::get_option( $key, $empty_value ); } /** * Gets an option from the settings API, using defaults if necessary to prevent undefined notices. * * @param string $key * @param mixed $empty_value * @return mixed The value specified for the option or a default value for the option. */ public function get_instance_option( $key, $empty_value = null ) { if ( empty( $this->instance_settings ) ) { $this->init_instance_settings(); } // Get option default if unset. if ( ! isset( $this->instance_settings[ $key ] ) ) { $form_fields = $this->get_instance_form_fields(); $this->instance_settings[ $key ] = $this->get_field_default( $form_fields[ $key ] ); } if ( ! is_null( $empty_value ) && '' === $this->instance_settings[ $key ] ) { $this->instance_settings[ $key ] = $empty_value; } return $this->instance_settings[ $key ]; } /** * Get settings fields for instances of this shipping method (within zones). * Should be overridden by shipping methods to add options. * @since 2.6.0 * @return array */ public function get_instance_form_fields() { return apply_filters( 'woocommerce_shipping_instance_form_fields_' . $this->id, array_map( array( $this, 'set_defaults' ), $this->instance_form_fields ) ); } /** * Return the name of the option in the WP DB. * @since 2.6.0 * @return string */ public function get_instance_option_key() { return $this->instance_id ? $this->plugin_id . $this->id . '_' . $this->instance_id . '_settings' : ''; } /** * Initialise Settings for instances. * @since 2.6.0 */ public function init_instance_settings() { $this->instance_settings = get_option( $this->get_instance_option_key(), null ); // If there are no settings defined, use defaults. if ( ! is_array( $this->instance_settings ) ) { $form_fields = $this->get_instance_form_fields(); $this->instance_settings = array_merge( array_fill_keys( array_keys( $form_fields ), '' ), wp_list_pluck( $form_fields, 'default' ) ); } } /** * Processes and saves options. * If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out. * @since 2.6.0 * @return bool was anything saved? */ public function process_admin_options() { if ( $this->instance_id ) { $this->init_instance_settings(); $post_data = $this->get_post_data(); foreach ( $this->get_instance_form_fields() as $key => $field ) { if ( 'title' !== $this->get_field_type( $field ) ) { try { $this->instance_settings[ $key ] = $this->get_field_value( $key, $field, $post_data ); } catch ( Exception $e ) { $this->add_error( $e->getMessage() ); } } } return update_option( $this->get_instance_option_key(), apply_filters( 'woocommerce_shipping_' . $this->id . '_instance_settings_values', $this->instance_settings, $this ) ); } else { return parent::process_admin_options(); } } }
gpl-3.0
Robotips/rtprog
tool/udk-sim/simmodules/simmodulefactory.cpp
1525
/** ** This file is part of the UDK-SDK project. ** Copyright 2019 UniSwarm sebastien.caux@uniswarm.eu ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "simmodulefactory.h" #include "simmodule_uart.h" #include "simmodule_adc.h" #include "simmodule_gui.h" #include "simmodule_mrobot.h" SimModule *SimModuleFactory::getSimModule(SimClient *client, uint16_t idModule, uint16_t idPeriph) { SimModule *module; switch (idModule) { case UART_SIM_MODULE: module = new SimModuleUart(client, idPeriph); break; case ADC_SIM_MODULE: module = new SimModuleAdc(client, idPeriph); break; case GUI_SIM_MODULE: module = new SimModuleGui(client, idPeriph); break; case MROBOT_SIM_MODULE: module = new SimModuleMRobot(client, idPeriph); break; default: module = NULL; break; } return module; }
gpl-3.0
bfrgoncalves/Online-PhyloViZ
routes/api/index.js
1946
var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next){ res.render('api/apiIndex', { title: 'PHYLOViZ Online', isAuthenticated: req.isAuthenticated(), //function given by passport user: req.user //also given by passport. an user object }); }); router.get('/help/login', function(req, res, next){ res.render('api/apiHelpUpload', { title: 'PHYLOViZ Online', isAuthenticated: req.isAuthenticated(), //function given by passport user: req.user //also given by passport. an user object }); }); router.get('/help/upload', function(req, res, next){ res.render('api/apiHelpUpload', { title: 'PHYLOViZ Online', isAuthenticated: req.isAuthenticated(), //function given by passport user: req.user //also given by passport. an user object }); }); router.get('/help/finddata', function(req, res, next){ res.render('api/apiHelpfinddata', { title: 'PHYLOViZ Online', isAuthenticated: req.isAuthenticated(), //function given by passport user: req.user //also given by passport. an user object }); }); router.get('/help/phylovizinput', function(req, res, next){ res.render('api/apiHelpInput', { title: 'PHYLOViZ Online', isAuthenticated: req.isAuthenticated(), //function given by passport user: req.user //also given by passport. an user object }); }); router.get('/help/goeBURST', function(req, res, next){ res.render('api/apiHelpgoeBURST', { title: 'PHYLOViZ Online', isAuthenticated: req.isAuthenticated(), //function given by passport user: req.user //also given by passport. an user object }); }); router.get('/help/tabledata', function(req, res, next){ res.render('api/apiHelptable', { title: 'PHYLOViZ Online', isAuthenticated: req.isAuthenticated(), //function given by passport user: req.user //also given by passport. an user object }); }); module.exports = router;
gpl-3.0
thm-projects/arsnova-flashcards
imports/util/lockScreen.js
8961
import {NavigatorCheck} from "./navigatorCheck"; import {defaultBackground, backgrounds} from "../config/lockScreen"; function getMaximumFromGameConfig(subConfig, current, style, title) { const mobile = NavigatorCheck.isSmartphone() || NavigatorCheck.isTablet(); const landscape = NavigatorCheck.isLandscape(); if (!mobile) { if (subConfig.desktop) { return [ current > subConfig.desktop ? subConfig.desktop : current, style + title + ":" + subConfig.desktop + "px;" ]; } } else if (subConfig.mobile) { if (landscape) { if (subConfig.mobile.landscape) { return [ current > subConfig.mobile.landscape ? subConfig.mobile.landscape : current, style + title + ":" + subConfig.mobile.landscape + "px;" ]; } } else { if (subConfig.mobile.portrait) { return [ current > subConfig.mobile.portrait ? subConfig.mobile.portrait : current, style + title + ":" + subConfig.mobile.portrait + "px;" ]; } } } return [current, style]; } export let LockScreen = class LockScreen { static setPomodoroCorner (options = "top_right") { const overlay = $("#pomodoroTimerOverlay")[0]; const corner = options.split("_"); if (corner[0] === "bottom") { overlay.style.setProperty("bottom", "0", "important"); } else { overlay.style.bottom = ""; } if (corner.length > 1 && corner[1] === "right") { overlay.style.setProperty("right", "0", "important"); } else { overlay.style.right = ""; } } static openGame (gameId, options) { LockScreen.hideBackground(); let width = window.innerWidth, height = window.innerHeight, style = "border: none;"; if (options) { if (options.maxWidth) { [width, style] = getMaximumFromGameConfig(options.maxWidth, width, style, 'max-width'); } if (options.maxHeight) { [height, style] = getMaximumFromGameConfig(options.maxWidth, height, style, 'max-height'); } } const elem = $('#gameModal .modal-dialog'); elem.html('<iframe id="gameViewer" style="' + style + '" width="' + width + 'px" height="' + height + 'px" src="/games/game' + gameId + '/index.html"></iframe>'); if (options.background) { elem[0].style.setProperty("background", options.background, "important"); } else { elem[0].style.setProperty("background", "var(--games-and-backgrounds-default-background)", "important"); } LockScreen.setPomodoroCorner(options.clockPosition); $('#gameModal').modal('show').css("display", "flex"); LockScreen.showNavbarForGamesAndBackgrounds(false); } static hideGame () { setTimeout(function () { $('#gameModal').modal('hide').css("display", "none"); }, 1000); } static openBackground (backgroundId, options) { LockScreen.hideGame(); const elem = $('#gameBackgroundModal .modal-dialog'); elem.html('<iframe id="backgroundViewer" style="border: none;" width="' + window.innerWidth + 'px" height="' + window.innerHeight + 'px" src="/gameBackgrounds/background' + backgroundId + '/index.html"></iframe>'); if (options.background) { elem[0].style.setProperty("background", options.background, "important"); } else { elem[0].style.setProperty("background", "var(--games-and-backgrounds-default-background)", "important"); } LockScreen.setPomodoroCorner(options.clockPosition); $('#gameBackgroundModal').modal('show').css("display", "flex"); LockScreen.showNavbarForGamesAndBackgrounds(false); } static hideBackground () { setTimeout(function () { $('#gameBackgroundModal').modal('hide').css("display", "none"); }, 1000); } static resize () { const modal = $('#gameBackgroundModal > .modal-dialog > iframe'); if (modal.length) { modal.height(window.innerHeight + 'px'); modal.width(window.innerWidth + 'px'); } const gameModal = $('#gameModal > .modal-dialog > iframe'); if (modal.length) { let height = gameModal.css('max-height') || window.innerHeight; let width = gameModal.css('max-width') || window.innerWidth; if (height > window.innerHeight) { height = window.innerHeight; } if (width > window.innerWidth) { width = window.innerWidth; } gameModal.height(height + 'px'); gameModal.width(width + 'px'); } LockScreen.showNavbarForGamesAndBackgrounds(); } static filterByFeatures (configObject) { const mobile = NavigatorCheck.isTablet() || NavigatorCheck.isSmartphone(); const safari = NavigatorCheck.isSafari(); return configObject.filter((elem) => { if (elem.features) { if ((elem.features.mobile === false && mobile) || (elem.features.safari === false && safari)) { return false; } } return true; }); } static showNavbarForGamesAndBackgrounds (active) { const navbar = $('.lockScreenCarouselWrapper')[0]; if (!navbar) { return; } if (active === true) { navbar.classList.add("active"); } else if (active === false) { navbar.classList.remove("active"); } const backgroundsQuery = $('#backgrounds'); const heightBackgrounds = backgroundsQuery[0].offsetHeight; const heightGames = $('#games')[0].offsetHeight; let height; if (heightBackgrounds > 1000 && heightGames < 1000) { height = heightGames; } else if (heightGames > 1000 && heightBackgrounds < 1000) { height = heightBackgrounds; } else { height = heightBackgrounds > heightGames ? heightBackgrounds : heightGames; } if (height < 1) { height = backgroundsQuery.height(); } navbar.style.bottom = -height + "px"; $('.tab-content').css("height", height + "px"); } static setBackgroundOverlayActive (active) { const backgroundElem = $('#background')[0].parentElement; const backgroundOverlay = $('#backgrounds')[0]; const gameElem = $('#game')[0].parentElement; const gameOverlay = $('#games')[0]; if (active) { backgroundOverlay.classList.add("active", "in"); gameOverlay.classList.remove("active", "in"); backgroundElem.classList.add("active"); gameElem.classList.remove("active"); } else { gameOverlay.classList.add("active", "in"); backgroundOverlay.classList.remove("active", "in"); gameElem.classList.add("active"); backgroundElem.classList.remove("active"); } } static initOwlCarousel (id) { $(id).owlCarousel({ loop: true, margin: 10, nav: true, navText: [ "<span class='fa fa-caret-left'></span>", "<span class='fa fa-caret-right'></span>" ], autoplay: false, autoplayHoverPause: false, responsive: { 0: { items: 1 }, 450: { items: 2 }, 600: { items: 3 }, 1000: { items: 5 } } }); } static hideGameUI () { $("#pomodoroTimerOverlay")[0].style.display = ""; } static changeToGameUI (activate) { const overlay = $("#pomodoroTimerOverlay"); const timer = $(".pomodoroTimer"); const clock = $(".pomodoroClock"); if (activate) { if (!$('#gameBackgroundModal > .modal-dialog > iframe').length) { const background = backgrounds.find(elem => elem.id === defaultBackground); if (background) { LockScreen.openBackground(defaultBackground, background); } } else { $('#gameBackgroundModal').modal('show'); } overlay[0].style.transition = ""; overlay[0].style.setProperty("background-color", "unset", "important"); timer[0].style.setProperty("width", "100%", "important"); setTimeout(function () { overlay[0].style.transition = "all 1s"; overlay[0].style.setProperty("height", "20%", "important"); overlay[0].style.setProperty("display", "inline-block", "important"); overlay[0].style.zIndex = "3300"; }); clock[0].style.setProperty("width", "auto", "important"); setTimeout(function () { timer[0].style.setProperty("width", "20vh", "important"); overlay[0].style.width = "unset"; setTimeout(function () { LockScreen.showNavbarForGamesAndBackgrounds(true); }); }, 1000); } else { overlay[0].style.height = ""; overlay[0].style.right = ""; overlay[0].style.bottom = ""; overlay[0].style.backgroundColor = ""; overlay[0].style.width = ""; overlay[0].style.zIndex = ""; clock[0].style.width = ""; timer[0].style.width = ""; setTimeout(function () { overlay[0].style.transition = ""; timer[0].style.transition = ""; }, 1000); LockScreen.hideBackground(); LockScreen.hideGame(); } } static checkAnimationActive () { const elem = $(".lockScreenCarouselWrapper"); if (elem && elem[0] && elem[0].classList.contains("hidden")) { LockScreen.startBreakAnimation(); } } static startBreakAnimation () { LockScreen.setBackgroundOverlayActive(true); LockScreen.changeToGameUI(true); const dom = $(".lockScreenCarouselWrapper")[0]; dom.style.opacity = "0"; dom.classList.remove("hidden"); setTimeout(() => { dom.style.opacity = "1"; }, 1000); } static endBreakAnimation () { const dom = $(".lockScreenCarouselWrapper")[0]; if (dom) { dom.style.opacity = "0"; dom.classList.add("hidden"); } LockScreen.changeToGameUI(false); } };
gpl-3.0
ParisCoin/Paris
src/core_write.cpp
4341
// Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the GPL3 software license, see the accompanying // file COPYING or http://www.gnu.org/licenses/gpl.html. #include "core_io.h" #include "base58.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" #include "streams.h" #include "univalue.h" #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; string FormatScript(const CScript& script) { string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_CHECKMULTISIGVERIFY) { string str(GetOpName(op)); if (str.substr(0, 3) == string("OP_")) { ret += str.substr(3, string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } string EncodeHexTx(const CTransaction& tx) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", scriptPubKey.ToString()); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.pushKV("addresses", a); } void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry) { entry.pushKV("txid", tx.GetHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); BOOST_FOREACH(const CTxIn& txin, tx.vin) { UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { in.pushKV("txid", txin.prevout.hash.GetHex()); in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", txin.scriptSig.ToString()); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); } in.pushKV("sequence", (int64_t)txin.nSequence); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue)); out.pushKV("value", outValue); out.pushKV("n", (int64_t)i); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } entry.pushKV("vout", vout); if (hashBlock != 0) entry.pushKV("blockhash", hashBlock.GetHex()); entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". }
gpl-3.0
systemeFriche/RN
src/Principale.java
6123
import com.sun.star.lang.XComponent; import com.sun.star.sheet.XSpreadsheet; public class Principale { public static void main(String[] args) { SpreadsheetDocuments spreadsheetDocumentsNotes = new SpreadsheetDocuments(); SpreadsheetDocuments spreadsheetDocumentsRn = new SpreadsheetDocuments(); SpreadsheetDocuments spreadsheetDocumentsRecap = new SpreadsheetDocuments(); XComponent xDocNotes, xDocRN; XSpreadsheet feuilleEPR, feuilleELP, feuilleRN; //A TESTER MAIS A PRIORI CHEMIN RELATIF ? String workDir="/Users/fguntz/Documents/NOTES/NOTES_2016-2017"; try { //********************************************************************************** // OPERATION DE RECUPERATION DES INFOS DE LA PROMO //********************************************************************************** //A TERME LE NOM DU FICHIER JSON DE LA PROMO SERAIT PASSE EN ARGUMENT DE L'APPLI //POUR L'INSTANT ON CHANGE A LA MANO //MMI1-S1 //String cheminFichierJSON = workDir+"/mmi1S1.json"; //MMI2-S3 //String cheminFichierJSON = workDir+"/mmi2S3.json"; //MMI2A-S3 String cheminFichierJSON = workDir+"/mmi2S3A.json"; //INITIALISATION PROMO Promo promo = new Promo(); promo.getInfosPromo(cheminFichierJSON); //********************************************************************************** // DEFINITION DE TOUS LES CHEMINS DE FICHIER ER REPERTOIRE //********************************************************************************** String semestre=promo.getSemestre(); //chemin destination RN String workDestRNODS="RN_"+semestre+"_ODS/"; String workDestRNPDF="RN_"+semestre+"_PDF/"; //chemin fichier Recap String fichierRecapPromo = "recap_"+semestre+".ods"; String modelRN = "1617_RN_"+semestre+"_model.ods"; String dest = workDestRNODS+"1617_RN_"+semestre+"_"; String fichierLocalNotes=Divers.getNomFichierUrl(promo.getUrlNotes()); String cheminFichierLocalNotes="file:///"+workDir+"/"+fichierLocalNotes; String cheminFichierRecapPromo = "file:///"+workDir+"/"+fichierRecapPromo; String cheminFichierRn="file:///"+workDir+"/"+modelRN; String cheminFichierRnEtuOdsBase="file:///"+workDir+"/"+dest; String cheminFichierRnEtuPdfBase="file:///"+workDir+"/"+workDestRNPDF; //********************************************************************************** // OPERATION DE RECUPERATION SUR LE RESEAU DU FICHIER EXPORT DE NOTES //********************************************************************************** String filename = workDir+"/"+fichierLocalNotes; //à placer en argument de l'appli boolean onLine=true; if(onLine){Divers.getFichierNotes(filename,promo.getUrlNotes());} //********************************************************************************** // OUVERTURE DU FICHIER EXPORT DE NOTES // RECUPERATION FEUILLE NOTES SEM, UE ET MODULES // RECUPERATION FEUILLE NOTES EPREUVES // OUVERTURE DU FICHIER RECAP PROMO // RECUPERATION FEUILLE RECAP PROMO // OUVERTURE MODELE RELEVE DE NOTES // RECUPERATION FEUILLE RELEVE DE NOTES //********************************************************************************** //ON OUVRE FICHIER NOTES xDocNotes = spreadsheetDocumentsNotes.openSpreadsheetDocument(cheminFichierLocalNotes); Divers.addMessage("fichier notes local ouvert - "+cheminFichierLocalNotes); //ON RECUPERE FEUILLE CONTENANT LES MODULES ET LES EPREUVES feuilleELP=spreadsheetDocumentsNotes.getFeuille(xDocNotes,0); feuilleEPR=spreadsheetDocumentsNotes.getFeuille(xDocNotes,1); //ON OUVRE FICHIER MODELE RELEVE DE NOTES xDocRN = spreadsheetDocumentsRn.openSpreadsheetDocument(cheminFichierRn); //ON RECUPERE FEUILLE MODULE RN feuilleRN=spreadsheetDocumentsRn.getFeuille(xDocRN,0); //********************************************************************************** // OPERATION DE RECUPERATION DE LA STRUCTURE D'UNE PROMO : UE, MODULES, EPREUVES // AU PASSAGE ON RECUPERE TOUTES LES NOTES CONNUES ET CALCULEES PAR APOGEE // AU PASSAGE ON DETERMINE MIN, MAX, MOY ET CLASSEMENT EPREUVE //*********************************************************************************** promo.getStructureEtNotesPromo(cheminFichierJSON,spreadsheetDocumentsNotes,feuilleELP,feuilleEPR,spreadsheetDocumentsRn,feuilleRN); //ON FERME RELEVE DE NOTES spreadsheetDocumentsRn.closeSpreadsheetDocument(xDocRN); //********************************************************************************** // OPERATION DE CALCUL MOYENNE DE MODULE DE CHAQUE UE ET MOYENNE GENERALE // ET INFOS MIN, MAX, MOY CLASSEMENT POUR CHAQUE MODULE, UE ET MOY GENERALE // AU PASSAGE ON VERIFIE COHERENCE ENTRE CALCUL INTERNE ET CALCUL APOGEE //********************************************************************************** promo.verificationMoyennesPromo(); //********************************************************************************** // OPERATION DE GENERATION DES RELEVES DE NOTES // RECUPERATION DES NOTES DE CHAQUE ETUDIANT //********************************************************************************** promo.initialisationListeEtudiants(spreadsheetDocumentsNotes,feuilleELP); promo.generationFicheEtudiant(); promo.generationRnEtudiant(spreadsheetDocumentsRn,cheminFichierRn,cheminFichierRnEtuOdsBase,cheminFichierRnEtuPdfBase); //********************************************************************************** // OPERATION DE GENERATION DU RECAP PROMO //********************************************************************************** promo.generationRecapPromo(spreadsheetDocumentsRecap,cheminFichierRecapPromo); //FERMETURE FICHIER NOTES //ON FERME LE FICHIER DE NOTES spreadsheetDocumentsNotes.closeSpreadsheetDocument(xDocNotes); Divers.addMessage("fichier notes local fermé - "+cheminFichierLocalNotes); //ON SORT DU PROGRAMME Divers.addMessage("programme terminé"); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } }
gpl-3.0
FergusInLondon/phpservermon
src/lang/da_DK.lang.php
14505
<?php /** * PHP Server Monitor * Monitor your servers and websites. * * This file is part of PHP Server Monitor. * PHP Server Monitor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PHP Server Monitor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PHP Server Monitor. If not, see <http://www.gnu.org/licenses/>. * * @package phpservermon * @author nerdalertdk * @copyright Copyright (c) 2008-2015 Pepijn Over <pep@peplab.net> * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 * @version Release: @package_version@ * @link http://www.phpservermonitor.org/ **/ $sm_lang = array( 'name' => 'Dansk - Danish', 'locale' => array('da_DK.UTF-8', 'da_DK', 'danish', 'danish-dk'), 'locale_tag' => 'da', 'locale_dir' => 'ltr', 'system' => array( 'title' => 'Server Monitor', 'install' => 'Installere', 'action' => 'Action', 'save' => 'Gem', 'edit' => 'Redigere', 'delete' => 'Slet', 'date' => 'Dato', 'message' => 'Besked', 'yes' => 'Ja', 'no' => 'Nej', 'insert' => 'Indsæt', 'add_new' => 'Tilføj ny', 'update_available' => 'En ny version ({version}) er tilgængelig på <a href="http://www.phpservermonitor.org" target="_blank">http://www.phpservermonitor.org</a>.', 'back_to_top' => 'Til toppen', 'go_back' => 'Tilbage', 'ok' => 'OK', 'cancel' => 'Annuller', // date/time format according the strftime php function format parameter http://php.net/manual/function.strftime.php 'short_day_format' => '%B %e', 'long_day_format' => '%B %e, %Y', 'yesterday_format' => 'Igår %k:%M', 'other_day_format' => '%A %k:%M', 'never' => 'Aldrig', 'hours_ago' => '%d timer siden', 'an_hour_ago' => 'omkring en time siden', 'minutes_ago' => '%d minutter siden', 'a_minute_ago' => 'omkring et minut siden', 'seconds_ago' => '%d sekunder siden', 'a_second_ago' => 'et sekund siden', ), 'menu' => array( 'config' => 'Indstillinger', 'server' => 'Servere', 'server_log' => 'Log', 'server_status' => 'Status', 'server_update' => 'Opdatere', 'user' => 'Brugere', 'help' => 'Hjælp', ), 'users' => array( 'user' => 'Bruger', 'name' => 'Navn', 'user_name' => 'Brugernavn', 'password' => 'Adgangskode', 'password_repeat' => 'Adgangskode igen', 'password_leave_blank' => 'Udfyldes hvis du vil skifte kode', 'level' => 'Level', 'level_10' => 'Administrator', 'level_20' => 'Bruger', 'level_description' => '<b>Administratore</b> har fuld adgang: De kan styre servere, brugere og indstillingere.<br/><b>Brugere</b> kan kun se og køre opdatere for servere som er tildelt til dem.', 'mobile' => 'Mobil', 'email' => 'Email', 'pushover' => 'Pushover', 'pushover_description' => 'Pushover is a service that makes it easy to get real-time notifications. See <a href="https://pushover.net/">their website</a> for more info.', 'pushover_key' => 'Pushover Key', 'pushover_device' => 'Pushover Device', 'pushover_device_description' => 'Device name to send the message to. Leave empty to send it to all devices.', 'delete_title' => 'Slet bruger', 'delete_message' => 'Er du sikker på du vil slette bruger \'%1\'?', 'deleted' => 'Bruger slettet.', 'updated' => 'Bruger opdateret.', 'inserted' => 'Bruger tilføjet.', 'profile' => 'Profil', 'profile_updated' => 'Din profil er opdateret.', 'error_user_name_bad_length' => 'Brugernavn skal være mellem 2 til 64 tegn.', 'error_user_name_invalid' => 'Brugernavn må kun indholde alfabetiske tegn (a-z, A-Z), tal (0-9) og (_).', 'error_user_name_exists' => 'Det valgte brugernavn findes allerede.', 'error_user_email_bad_length' => 'Email addresser skal være mellem 5 til 255 tegn.', 'error_user_email_invalid' => 'Den valgte email er ugyldig.', 'error_user_level_invalid' => 'Det angivet bruger niveau er ugyldig.', 'error_user_no_match' => 'Brugeren findes ikke.', 'error_user_password_invalid' => 'Den indtastede adgangskode er ugyldig.', 'error_user_password_no_match' => 'De to adgangskode er ikke ens.', ), 'log' => array( 'title' => 'Logposter', 'type' => 'Type', 'status' => 'Status', 'email' => 'Email', 'sms' => 'SMS', 'pushover' => 'Pushover', 'no_logs' => 'Intet i loggen', ), 'servers' => array( 'server' => 'Server', 'status' => 'Status', 'label' => 'Label', 'domain' => 'Domæne/IP', 'timeout' => 'Timeout', 'timeout_description' => 'Number of seconds to wait for the server to respond.', 'port' => 'Port', 'type' => 'Type', 'type_website' => 'Hjemmeside', 'type_service' => 'Tjeneste', 'pattern' => 'Søge streng/mønster', 'pattern_description' => 'Hvis dette mønster ikke findes på hjemmesiden, vil serveren blive markeret offline. Regulære udtryk er tilladt.', 'last_check' => 'Sidst kontrolleret', 'last_online' => 'Sidst online', 'monitoring' => 'Overvågning', 'no_monitoring' => 'Ingen overvågning', 'email' => 'Email', 'send_email' => 'Send Email', 'sms' => 'SMS', 'send_sms' => 'Send SMS', 'pushover' => 'Pushover', 'users' => 'Users', 'delete_title' => 'Slet server', 'delete_message' => 'Er du sikker på du vil slette server \'%1\'?', 'deleted' => 'Server slettet.', 'updated' => 'Server opdateret.', 'inserted' => 'Server tilføjet.', 'latency' => 'Latency', 'latency_max' => 'Latency (maksimum)', 'latency_min' => 'Latency (minimum)', 'latency_avg' => 'Latency (gennemsnitlig)', 'uptime' => 'Oppetid', 'year' => 'År', 'month' => 'Måned', 'week' => 'Uge', 'day' => 'Dag', 'hour' => 'Time', 'warning_threshold' => 'Advarsel grænse', 'warning_threshold_description' => 'Antal af fejl før status skifter til offline.', 'chart_last_week' => 'Sidste uge', 'chart_history' => 'Historie', // Charts date format according jqPlot date format http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html 'chart_day_format' => '%d-%m-%Y', 'chart_long_date_format' => '%d-%m-%Y %H:%M:%S', 'chart_short_date_format' => '%d/%m %H:%M', 'chart_short_time_format' => '%H:%M', 'warning_notifications_disabled_sms' => 'SMS notifications are disabled.', 'warning_notifications_disabled_email' => 'Email notifications are disabled.', 'warning_notifications_disabled_pushover' => 'Pushover notifications are disabled.', 'error_server_no_match' => 'Server not found.', 'error_server_label_bad_length' => 'The label must be between 1 and 255 characters.', 'error_server_ip_bad_length' => 'The domain / IP must be between 1 and 255 characters.', 'error_server_ip_bad_service' => 'The IP address is not valid.', 'error_server_ip_bad_website' => 'The website URL is not valid.', 'error_server_type_invalid' => 'The selected server type is invalid.', 'error_server_warning_threshold_invalid' => 'The warning threshold must be a valid integer greater than 0.', ), 'config' => array( 'general' => 'Generelt', 'language' => 'Sprog', 'show_update' => 'Opdateringer', 'email_status' => 'Tillad at sende mail', 'email_from_email' => 'Email fra adresse', 'email_from_name' => 'Email fra navn', 'email_smtp' => 'Aktiver SMTP', 'email_smtp_host' => 'SMTP vært', 'email_smtp_port' => 'SMTP port', 'email_smtp_security' => 'SMTP security', 'email_smtp_security_none' => 'None', 'email_smtp_username' => 'SMTP brugernavn', 'email_smtp_password' => 'SMTP adgangskode', 'email_smtp_noauth' => 'Efterladt blank hvis det ikke er opkrævet', 'sms_status' => 'Tillad at sende SMS beskeder', 'sms_gateway' => 'SMS Gateway', 'sms_gateway_mosms' => 'Mosms', 'sms_gateway_mollie' => 'Mollie', 'sms_gateway_spryng' => 'Spryng', 'sms_gateway_inetworx' => 'Inetworx', 'sms_gateway_clickatell' => 'Clickatell', 'sms_gateway_textmarketer' => 'Textmarketer', 'sms_gateway_smsglobal' => 'SMSGlobal', 'sms_gateway_smsit' => 'Smsit', 'sms_gateway_freevoipdeal' => 'FreeVoipDeal', 'sms_gateway_username' => 'Gateway brugernavn/apikey', 'sms_gateway_password' => 'Gateway adgangskode', 'sms_from' => 'Afsenders navn.', 'pushover_status' => 'Allow sending Pushover messages', 'pushover_description' => 'Pushover is a service that makes it easy to get real-time notifications. See <a href="https://pushover.net/">their website</a> for more info.', 'pushover_clone_app' => 'Click here to create your Pushover app', 'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token_description' => 'Before you can use Pushover, you need to <a href="%1$s" target="_blank">register an App</a> at their website and enter the App API Token here.', 'alert_type' => 'Vælg hvornår du vil modtage besked', 'alert_type_description' => '<b>Status ændring:</b> '. 'Du vil modtage en notifcation når en server har en ændring i status. Fra online -> offline eller offline -> online.<br/>'. '<br /><b>Offline:</b> '. 'Du vil modtage en meddelelse, når en server går offline for * kun første gang *. for eksempel, '. 'Hvis dit cronjob køre hvert kvatere og din server går ned kl 01 og kommer først op kl 06 '. ' så vil du kun modtage en mail kl 01.<br/>'. '<br><b>Altid:</b> '. 'Du vil modtage en besked, hver gang scriptet kører og et websted er nede, selvom site har været offline i flere timer.', 'alert_type_status' => 'Status ændret', 'alert_type_offline' => 'Offline', 'alert_type_always' => 'Altid', 'log_status' => 'Log status', 'log_status_description' => 'Hvis log status er sat til TRUE, vil monitoren logge hændelsen hver gang status ændre sig.', 'log_email' => 'Log mails sendt af systemet', 'log_sms' => 'Log SMS sendt af systemet', 'log_pushover' => 'Log pushover messages sent by the script', 'updated' => 'Indstillingerne er blevet opdateret.', 'tab_email' => 'Email', 'tab_sms' => 'SMS', 'tab_pushover' => 'Pushover', 'settings_email' => 'Email indstillinger', 'settings_sms' => 'SMS indstillinger', 'settings_pushover' => 'Pushover settings', 'settings_notification' => 'Meddelelse indstillinger', 'settings_log' => 'Log indstillinger', 'auto_refresh' => 'Genopfriske automatisk', 'auto_refresh_servers' => 'Genopfriske automatisk server sider.<br/>'. '<span class="small">'. 'Tid i sekunder, Hvis 0 vil siden ikke genopfriske automatisk'. '</span>', 'seconds' => 'sekunder', 'test' => 'Test', 'test_email' => 'En email vil blive sendt til den adresse, der er angivet i din brugerprofil.', 'test_sms' => 'En SMS vil blive sendt til det nummer, der er angivet i din brugerprofil.', 'test_pushover' => 'A Pushover notification will be sent to the user key/device specified in your user profile.', 'send' => 'Send', 'test_subject' => 'Test', 'test_message' => 'Test besked', 'email_sent' => 'Email sendt', 'email_error' => 'Fejl ved afsendelse af email', 'sms_sent' => 'Sms sendt', 'sms_error' => 'Fejl ved afsendelse af SMS', 'sms_error_nomobile' => 'Unable to send test SMS: no valid phone number found in your profile.', 'pushover_sent' => 'Pushover notification sent', 'pushover_error' => 'An error has occurred while sending the Pushover notification: %s', 'pushover_error_noapp' => 'Unable to send test notification: no Pushover App API token found in the global configuration.', 'pushover_error_nokey' => 'Unable to send test notification: no Pushover key found in your profile.', 'log_retention_period' => 'Log retention period', 'log_retention_period_description' => 'Number of days to keep logs of notifications and archives of server uptime. Enter 0 to disable log cleanup.', 'log_retention_days' => 'days', ), // for newlines in the email messages use <br/> 'notifications' => array( 'off_sms' => 'Server \'%LABEL%\' is DOWN: ip=%IP%, port=%PORT%. Fejl=%ERROR%', 'off_email_subject' => 'VIGTIG: Server \'%LABEL%\' is DOWN', 'off_email_body' => "Det lykkedes ikke at oprette forbindelse til følgende server:<br/><br/>Server: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Fejl: %ERROR%<br/>Date: %DATE%", 'off_pushover_title' => 'Server \'%LABEL%\' is DOWN', 'off_pushover_message' => "Det lykkedes ikke at oprette forbindelse til følgende server:<br/><br/>Server: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Fejl: %ERROR%<br/>Date: %DATE%", 'on_sms' => 'Server \'%LABEL%\' is RUNNING: ip=%IP%, port=%PORT%', 'on_email_subject' => 'VIGTIG: Server \'%LABEL%\' is RUNNING', 'on_email_body' => "Server '%LABEL%' køre igen:<br/><br/>Server: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Dato: %DATE%", 'on_pushover_title' => 'Server \'%LABEL%\' is RUNNING', 'on_pushover_message' => "Server '%LABEL%' køre igen:<br/><br/>Server: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Dato: %DATE%", ), 'login' => array( 'welcome_usermenu' => 'Velkommen, %user_name%', 'title_sign_in' => 'Log ind', 'title_forgot' => 'Glemt adgangskode?', 'title_reset' => 'Nulstil din adgangskode', 'submit' => 'Indsend', 'remember_me' => 'Husk kode', 'login' => 'Log ind', 'logout' => 'Log ud', 'username' => 'Brugernavn', 'password' => 'Adgangskode', 'password_repeat' => 'Skriv adgangskode igen', 'password_forgot' => 'Glemt adgangskode?', 'password_reset' => 'Nulstil adgangskode', 'password_reset_email_subject' => 'Nulstil din adgangskode for PHP Server Monitor', 'password_reset_email_body' => 'Brug venligst følgende link for at nulstille din adgangskode. Bemærk det udløber på 1 time.<br/><br/>%link%', 'error_user_incorrect' => 'Det angivet brugernavn kunne ikke findes.', 'error_login_incorrect' => 'Oplysningerne stemmer ikke overens.', 'error_login_passwords_nomatch' => 'De angivet adgangskoder matcher ikke.', 'error_reset_invalid_link' => 'Følgende link er ugyldigt.', 'success_password_forgot' => 'En e-mail er blevet sendt til dig med oplysninger om, hvordan du nulstiller din adgangskode.', 'success_password_reset' => 'Dit password er blevet nulstillet. venligst log ind.', ), 'error' => array( '401_unauthorized' => 'Unauthorized', '401_unauthorized_description' => 'You do not have the privileges to view this page.', ), );
gpl-3.0
dragthor/cryptojs
renderer.js
1075
// This file is required by the index.html file and will // be executed in the renderer process for that window. // All of the Node.js APIs are available in this process. const electron = require("electron"); const ipc = electron.ipcRenderer; // var last = ""; // document.getElementById("body").addEventListener("keydown", function (e) { // if (last.length === 0) { // last = e.key; // } else { // if (last === "Control" && e.key === "c") { // last = ""; // var selection = getSelectionText(); // if (selection != null && selection.length > 0) { // ipc.send("control+C", selection); // } // } else { // last = e.key; // } // } // }); // function getSelectionText() { // var text = ""; // if (document.getSelection) { // text = document.getSelection().toString(); // } else if (document.selection && document.selection.type != "Control") { // text = document.selection.createRange().text; // } // return text; // }
gpl-3.0
substance/notes
server/NotesDocumentServer.js
530
var DocumentServer = require('substance/collab/DocumentServer'); /* DocumentServer module. Can be bound to an express instance */ function NotesDocumentServer() { NotesDocumentServer.super.apply(this, arguments); } NotesDocumentServer.Prototype = function() { // var _super = NotesDocumentServer.super.prototype; // this.bind = function(app) { // _super.bind.apply(this, arguments); // // Add notes specific routes // }; }; DocumentServer.extend(NotesDocumentServer); module.exports = NotesDocumentServer;
gpl-3.0
ekansa/open-context-py
opencontext_py/apps/ldata/federalregistry/api.py
11622
import json import os import codecs import requests import feedparser import hashlib from time import sleep from django.conf import settings from django.utils.http import urlquote, quote_plus, urlquote_plus from opencontext_py.libs.general import LastUpdatedOrderedDict from opencontext_py.libs.generalapi import GeneralAPI class FederalRegistryAPI(): """ Interacts with the Federal Registry API Fo relate DINAA trinomials with Federal Registry documents from opencontext_py.apps.ldata.federalregistry.api import FederalRegistryAPI fed_api = FederalRegistryAPI() fed_api.get_cache_keyword_searches() """ API_BASE_URL = 'https://www.federalregister.gov/api/v1/documents.json' SLEEP_TIME = .5 def __init__(self): self.request_error = False self.request_url = False self.results = False self.best_match = False self.html_url = False self.cache_batch_prefix = '2019-07-20' self.delay_before_request = self.SLEEP_TIME self.root_act_dir = settings.STATIC_IMPORTS_ROOT self.working_search_dir = 'federal-reg-search' self.working_doc_dir = 'federal-reg-docs' self.recs_per_page = 500 self.json_url_list = [] self.raw_text_url_list = [] self.keyword_a_list = [ 'archeology', 'archeological', 'archaeology', 'archaeological', 'NAGPRA', 'cultural', 'heritage', ] self.keyword_bb_list = [ 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', ] self.keyword_b_list = [ 'site', 'sites', 'place', 'places', ] def get_list_cached_keyword_searches(self): """ makes a list of search results from keyword searches """ file_list = [] for keyword_a in self.keyword_a_list: for keyword_b in self.keyword_b_list: act_keywords = [ keyword_a, keyword_b ] url = self.make_search_json_url(act_keywords) key = self.make_cache_key(self.cache_batch_prefix, url) file_list.append(key) return file_list def get_cache_keyword_searches(self): """ gets search results and caches them based on literating though two list of key words """ for keyword_a in self.keyword_a_list: for keyword_b in self.keyword_b_list: act_keywords = [ keyword_a, keyword_b ] print('------------------------') print('Working on: ' + str(act_keywords)) print('------------------------') url = self.make_search_json_url(act_keywords) json_r = self.get_cache_keyword_search_json(url) docs = LastUpdatedOrderedDict() docs['raw'] = self.raw_text_url_list docs['json'] = self.json_url_list key = 'all-document-list' self.save_serialized_json(key, docs) # now iterate through the raw_text_urls to save these docs for raw_text_url in self.raw_text_url_list: self.get_cache_raw_doc_text(raw_text_url) def get_cache_raw_doc_text(self, url): """ gets and caches raw text for found documents """ ok = False url_ex = url.split('/') file_name = url_ex[-1] exists = self.check_exists(file_name, self.working_doc_dir) if exists is False: text = self.get_remote_text_from_url(url) if isinstance(text, str): path = self.prep_directory(self.working_doc_dir) dir_file = path + file_name print('save to path: ' + dir_file) file = codecs.open(dir_file, 'w', 'utf-8') file.write(text) file.close() ok = True else: # found it already ok = True return ok def add_to_doc_lists(self, json_r): """ adds to lists of json and raw document urls """ if isinstance(json_r, dict): if 'results' in json_r: for result in json_r['results']: if 'json_url' in result: json_url = result['json_url'] if json_url not in self.json_url_list: self.json_url_list.append(json_url) if 'raw_text_url' in result: raw_text_url = result['raw_text_url'] if raw_text_url not in self.raw_text_url_list: self.raw_text_url_list.append(raw_text_url) def make_search_json_url(self, keyword_list): """ makes a search url from a keyword list """ url_key_words = ' '.join(keyword_list) url = self.API_BASE_URL url += '?fields%5B%5D=agencies&fields%5B%5D=json_url&fields%5B%5D=raw_text_url' url += '&fields%5B%5D=document_number&fields%5B%5D=html_url&fields%5B%5D=title' url += '&order=relevance' url += '&per_page=' + str(self.recs_per_page) url += '&conditions%5Bterm%5D=' + urlquote_plus(url_key_words) return url def get_cache_keyword_search_json(self, url, recursive=True): """ gets json data from API in response to a keyword search """ key = self.make_cache_key(self.cache_batch_prefix, url) json_r = self.get_dict_from_file(key) if not isinstance(json_r, dict): json_r = self.get_remote_json_from_url(url) self.save_serialized_json(key, json_r) # add to the list of documents in the search results self.add_to_doc_lists(json_r) if recursive and isinstance(json_r, dict): if 'next_page_url' in json_r: next_url = json_r['next_page_url'] print('Getting next page of results: ' + str(next_url)) json_r = self.get_cache_keyword_search_json(next_url, recursive) return json_r def get_remote_json_from_url(self, url): """ gets remote data from a URL """ if self.delay_before_request > 0: # default to sleep BEFORE a request is sent, to # give the remote service a break. sleep(self.delay_before_request) try: gapi = GeneralAPI() r = requests.get(url, timeout=240, headers=gapi.client_headers) self.request_url = r.url r.raise_for_status() json_r = r.json() except: self.request_error = True json_r = False return json_r def get_remote_text_from_url(self, url): """ gets remote text content from a URL """ if self.delay_before_request > 0: # default to sleep BEFORE a request is sent, to # give the remote service a break. sleep(self.delay_before_request) try: gapi = GeneralAPI() r = requests.get(url, timeout=240, headers=gapi.client_headers) self.request_url = r.url r.raise_for_status() text = r.text except: self.request_error = True text = False return text def get_dict_from_file(self, key): """ gets the file string if the file exists, """ if '.json' not in key: file_name = key + '.json' json_obj = None ok = self.check_exists(file_name, self.working_search_dir) if ok: path = self.prep_directory(self.working_search_dir) dir_file = path + file_name try: json_obj = json.load(codecs.open(dir_file, 'r', 'utf-8-sig')) except: print('Cannot parse as JSON: ' + dir_file) json_obj = False return json_obj def get_string_from_file(self, file_name, act_dir): """ gets the file string if the file exists, """ text = None ok = self.check_exists(file_name, act_dir) if ok: path = self.prep_directory(act_dir) dir_file = path + file_name text = open(dir_file, 'r').read() return text def check_exists(self, file_name, act_dir): """ checks to see if a file exists """ path = self.prep_directory(act_dir) dir_file = path + file_name if os.path.exists(dir_file): output = True else: # print('Cannot find: ' + dir_file) output = False return output def save_serialized_json(self, key, dict_obj): """ saves a data in the appropriate path + file """ file_name = key + '.json' path = self.prep_directory(self.working_search_dir) dir_file = path + file_name print('save to path: ' + dir_file) json_output = json.dumps(dict_obj, indent=4, ensure_ascii=False) file = codecs.open(dir_file, 'w', 'utf-8') file.write(json_output) file.close() def prep_directory(self, act_dir): """ Prepares a directory to receive export files """ output = False full_dir = self.root_act_dir + act_dir + '/' full_dir.replace('//', '/') if not os.path.exists(full_dir): print('Prepared directory: ' + str(full_dir)) os.makedirs(full_dir) if os.path.exists(full_dir): output = full_dir if output[-1] != '/': output += '/' return output def make_cache_key(self, prefix, identifier): """ makes a valid OK cache key """ hash_obj = hashlib.sha1() concat_string = str(prefix) + " " + str(identifier) hash_obj.update(concat_string.encode('utf-8')) return hash_obj.hexdigest() def pause_request(self): """ pauses between requests """ sleep(self.delay_before_request)
gpl-3.0
kirigayakazushin/deepin-topbar
src/widgets/dactionlabel.cpp
1087
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: kirigaya <kirigaya@mkacg.com> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "widgets/dactionlabel.h" using namespace dtb; using namespace dtb::widgets; DActionLabel::DActionLabel(QWidget *parent) : QWidgetAction(parent) { m_widget = new DActionButton; m_widget->setContent(parent); } QWidget *DActionLabel::createWidget(QWidget *parent) { m_widget->setParent(parent); return m_widget; }
gpl-3.0
msoner1/bilet_otomasyon
admin/kernel/verify.php
1546
<?php require("db.class.php"); $db = new db(); $site_adress= "http://127.0.0.1/otobus/"; if($_POST["process"] == "kontrol") { session_destroy(); session_start(); $email = $_POST["email"]; $sifre = md5(md5($_POST["sifre"])); $db->bindMore(array("email" => $email, "sifre" => $sifre)); $uye_bilgileri = $db->query("SELECT * FROM admins WHERE email = :email AND sifre = :sifre"); if (empty($uye_bilgileri[0]['email'])) { header("Location: " . $site_adress . "admin/login.html?hata"); } else { $_SESSION['admin'] = 1; $_SESSION['id'] = $uye_bilgileri[0]['id']; $_SESSION['ad_soyad'] = $uye_bilgileri[0]['ad_soyad']; $_SESSION['email'] = $uye_bilgileri[0]['email']; $_SESSION['statu'] = $uye_bilgileri[0]['statu']; header("Location: " . $site_adress . "admin/"); } } else if($_POST["process"] == "get_bus"){ $otobus_id = $_POST["id"]; $db->bind("id" , $otobus_id); $otobus = $db->query("SELECT * FROM otobus_tip WHERE id = :id"); echo '{"id" : "'.$otobus[0]['id'].'" , "adi" : "'.$otobus[0]['tip_adi'].'" , "tv" : "'.$otobus[0]['tv'].'" , "internet" : "'.$otobus[0]['internet'].'" , "rahat_koltuk" : "'.$otobus[0]['rahat_koltuk'].'" , "kulaklik" : "'.$otobus[0]['kulaklik'].'"}'; } else if($_POST["process"] == "get_firma"){ $firma_id = $_POST["id"]; $db->bind("id" , $firma_id); $firma = $db->query("SELECT firma_ad FROM firmalar WHERE firma_id = :id"); echo '{"adi" : "'.$firma[0]['firma_ad'].'"}'; }
gpl-3.0
unassailable/uinfo
inc/css.compbox.php
1015
/* COMP-BOX */ .comp-box { background:<?=_SEC2_?>; /* border-radius:4px; */ box-shadow: inset -3px 3px 10px -3px <?=_BLACK2_?>; /* border:3px solid <?=_GRAY_?>; */ color:<?=_GRAY_?>; padding:.5vh 1%; } .comp-box ::-moz-selection { background:<?=_SEC2_LT_?>; color:<?=_GRAY_?>; text-shadow:none; } .comp-box ::selection { background:<?=_SEC2_LT_?>; color:<?=_GRAY_?>; text-shadow:none; } .comp-box a:link,.comp-box a:visited,.comp-box a:active { color:<?=_PRIM_DKR_?>; } .comp-box a:hover { color:<?=_PRIM_?>; } .comp-box h1,.comp-box h2,.comp-box h3,.comp-box h4,.comp-box h5 { color:<?=_COMP_DKR_?>; text-shadow:0px 2px 1px <?=_SEC2_LT6_?>; } .comp-box hr { background:<?=_PRIM_?>; border-radius:5px; border-bottom:.3em double <?=_PRIM_DKR8_?>; border-left:.1em solid <?=_PRIM_DKR8_?>; border-right:.1em solid <?=_PRIM_DKR8_?>; color:<?=_PRIM_DKR_?>; } .comp-box hr:after { background:<?=_SEC2_?>; }
gpl-3.0
Playos/IsBridgeUp
Properties/Resources.Designer.cs
2773
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace rlel.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("rlel.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
gpl-3.0
shuqin/ALLIN
src/main/java/zzz/study/patterns/dutychain/simple/Parseable.java
108
package zzz.study.patterns.dutychain.simple; public interface Parseable { boolean parse(String s); }
gpl-3.0
rjromo/PythonESPOL
5.8.5/13.py
706
"""3 trabajadores""" h1=int(input("Ingrese horas trabajador 1: ")) s1=float(input("Salario por hora:$ ")) d1=float(input("Descuentos:$ ")) h2=int(input("Ingrese horas trabajador 2: ")) s2=float(input("Salario por hora:$ ")) d2=float(input("Descuentos:$ ")) h3=int(input("Ingrese horas trabajador 3: ")) s3=float(input("Salario por hora:$ ")) d3=float(input("Descuentos:$ ")) t1=h1*s1-d1 t2=h2*s2-d2 t3=h3*s3-d3 if t1>t2>t3 or t1>t3>t2: print("El trabajador 1 recibirá el mayor pago semanal $%3.2f"%t1) elif t2>t1>t3 or t2>t3>t1: print("El trabajador 2 recibirá el mayor pago semanal $%3.2f"%t2) else : print("El trabajador 3 recibirá el mayor pago semanal $%3.2f"%t3)
gpl-3.0
dykstrom/jcc
src/main/java/se/dykstrom/jcc/common/compiler/Compiler.java
1450
/* * Copyright (C) 2016 Johan Dykstrom * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package se.dykstrom.jcc.common.compiler; import org.antlr.v4.runtime.CharStream; import se.dykstrom.jcc.common.assembly.AsmProgram; import se.dykstrom.jcc.common.error.CompilationErrorListener; /** * Defines operations that should be implemented by all compilers. * * @author Johan Dykstrom */ public interface Compiler { void setSourceFilename(String sourceFilename); String getSourceFilename(); void setInputStream(CharStream inputStream); CharStream getInputStream(); void setErrorListener(CompilationErrorListener errorListener); CompilationErrorListener getErrorListener(); /** * Compiles the source code read from the ANTLR input stream into an assembly code program. */ AsmProgram compile(); }
gpl-3.0
derhofbauer/fesearch
setup/data/typo3/AdditionalConfiguration.php
753
<?php // $GLOBALS['TYPO3_CONF_VARS']['DB']['database'] = getenv('MYSQL_DATABASE'); // $GLOBALS['TYPO3_CONF_VARS']['DB']['host'] = getenv('MYSQL_DB_HOST'); // $GLOBALS['TYPO3_CONF_VARS']['DB']['username'] = getenv('MYSQL_ROOT_USER'); // $GLOBALS['TYPO3_CONF_VARS']['DB']['password'] = getenv('MYSQL_ROOT_PASSWORD'); if(\TYPO3\CMS\Core\Utility\GeneralUtility::getApplicationContext()->isDevelopment()) { foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'] as $cacheName => $cacheConfiguration) { $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'][$cacheName]['backend'] = \TYPO3\CMS\Core\Cache\Backend\NullBackend::class; } $GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'] = 1; } ?>
gpl-3.0
flukehan/MixERP
src/Libraries/Server Controls/Project/MixERP.Net.WebControls.StockTransactionFactory/Control/Form/GridView/HeaderRow.cs
2438
/******************************************************************************** Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org). This file is part of MixERP. MixERP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MixERP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MixERP. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************************/ using MixERP.Net.i18n.Resources; using MixERP.Net.WebControls.StockTransactionFactory.Helpers; using System.Web.UI.WebControls; namespace MixERP.Net.WebControls.StockTransactionFactory { public partial class StockTransactionForm { private static void CreateHeaderRow(Table grid) { using (TableRow header = new TableRow()) { header.TableSection = TableRowSection.TableHeader; TableHelper.CreateHeaderCell(header, Titles.ItemCode, "ItemCodeInputText"); TableHelper.CreateHeaderCell(header, Titles.ItemName, "ItemSelect"); TableHelper.CreateHeaderCell(header, Titles.QuantityAbbreviated, "QuantityInputText"); TableHelper.CreateHeaderCell(header, Titles.Unit, "UnitSelect"); TableHelper.CreateHeaderCell(header, Titles.Price, "PriceInputText"); TableHelper.CreateHeaderCell(header, Titles.Amount, "AmountInputText"); TableHelper.CreateHeaderCell(header, Titles.Discount, "DiscountInputText"); TableHelper.CreateHeaderCell(header, Titles.ShippingCharge, "ShippingChargeInputText"); TableHelper.CreateHeaderCell(header, Titles.SubTotal, "SubTotalInputText"); TableHelper.CreateHeaderCell(header, Titles.TaxForm, "TaxSelect"); TableHelper.CreateHeaderCell(header, Titles.Tax, "TaxInputText"); TableHelper.CreateHeaderCell(header, Titles.Action, null); grid.Rows.Add(header); } } } }
gpl-3.0
hpl1nk/nonamegame
xray/animation/sources/mixing_n_ary_tree_destroyer.cpp
2069
//////////////////////////////////////////////////////////////////////////// // Created : 04.03.2010 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "mixing_n_ary_tree_destroyer.h" #include "mixing_n_ary_tree_animation_node.h" #include "mixing_n_ary_tree_weight_node.h" #include "mixing_n_ary_tree_addition_node.h" #include "mixing_n_ary_tree_subtraction_node.h" #include "mixing_n_ary_tree_multiplication_node.h" #include "mixing_n_ary_tree_transition_node.h" using xray::animation::mixing::n_ary_tree_destroyer; using xray::animation::mixing::n_ary_tree_animation_node; using xray::animation::mixing::n_ary_tree_weight_node; using xray::animation::mixing::n_ary_tree_addition_node; using xray::animation::mixing::n_ary_tree_subtraction_node; using xray::animation::mixing::n_ary_tree_multiplication_node; using xray::animation::mixing::n_ary_tree_transition_node; using xray::animation::mixing::n_ary_tree_n_ary_operation_node; template < typename T > static inline void destroy ( T& node ) { node.~T ( ); } void n_ary_tree_destroyer::visit ( n_ary_tree_animation_node& node ) { propagate ( node ); } void n_ary_tree_destroyer::visit ( n_ary_tree_weight_node& node ) { destroy ( node ); } void n_ary_tree_destroyer::visit ( n_ary_tree_transition_node& node ) { node.from().accept ( *this ); node.to().accept ( *this ); destroy ( node ); } void n_ary_tree_destroyer::visit ( n_ary_tree_addition_node& node ) { propagate ( node ); } void n_ary_tree_destroyer::visit ( n_ary_tree_subtraction_node& node ) { propagate ( node ); } void n_ary_tree_destroyer::visit ( n_ary_tree_multiplication_node& node ) { propagate ( node ); } template < typename T > inline void n_ary_tree_destroyer::propagate ( T& node ) { n_ary_tree_base_node** i = node.operands( sizeof(T) ); n_ary_tree_base_node** const e = i + node.operands_count( ); for ( ; i != e; ++i ) (*i)->accept( *this ); destroy ( node ); }
gpl-3.0
Shinil35/Shat
src/shinil35/shat/peer/PeerManager.java
6841
/* Copyright (C) 2013 Emilio Cafe' Nunes * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package shinil35.shat.peer; import java.security.PublicKey; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.concurrent.ConcurrentHashMap; import shinil35.shat.Database; import shinil35.shat.Main; import shinil35.shat.log.Log; import shinil35.shat.log.LogTraceType; import shinil35.shat.network.NetworkConnectionData; import shinil35.shat.util.Encoding; import shinil35.shat.util.Hash; import shinil35.shat.util.Hashing; import shinil35.shat.util.Utility; public class PeerManager { private static ConcurrentHashMap<Hash, Peer> peers; private static boolean initialized = false; private static int maxPeerLoaded = 200; private static long lastPeerListUpdating = 0; public static void addPeer(Peer p) { addPeer(p, true); } public static void addPeer(Peer p, boolean database) { if (!initialized || peers.containsKey(p.getHash()) || Hashing.getHash(Main.getPublicKey()).equals(p.getHash())) return; Log.trace("New peer discovered: " + p.getIP() + ":" + p.getPort(), LogTraceType.PEER_DISCOVERED); if (!database) { peers.put(p.getHash(), p); lastPeerListUpdating = Utility.getTimeNow(); return; } try { PreparedStatement st = Database.getConnection().prepareStatement("INSERT INTO peers VALUES(?, ?, ?, ?, ?)"); st.setString(1, p.getHash().getReadableHash()); st.setBytes(2, Encoding.encodePublicKey(p.getPublicKey())); st.setString(3, p.getIP()); st.setInt(4, p.getPort()); st.setLong(5, p.getLastCommunication()); st.executeUpdate(); st.close(); peers.put(p.getHash(), p); lastPeerListUpdating = Utility.getTimeNow(); } catch (SQLException e) { Log.localizedWarn("[SQL_QUERY_ERROR]", e.getMessage()); } } public static void addPeerDataList(Collection<PeerData> peerList) { if (!initialized || peerList == null) return; for (PeerData p : peerList) addPeer(p.getPeer()); removeExceedingPeers(); } public static void close() { if (!initialized) return; initialized = false; if (peers != null) peers.clear(); } public static void generatePeer(NetworkConnectionData data) { if (!initialized || data == null) return; PublicKey pk = data.getPublicKey(); String ip = data.getIP(); int port = data.getPort(); long date = new Date().getTime(); Peer p = new Peer(pk, ip, port, date); addPeer(p); } public static long getLastPeerListUpdate() { return lastPeerListUpdating; } public static ArrayList<PeerData> getPeerDataList(int maxPeers, Hash exclude, ArrayList<Hash> alreadySendedPeers) { if (!initialized) return null; ArrayList<PeerData> toReturn = new ArrayList<PeerData>(); if (maxPeers < 0 || maxPeers >= peers.size()) { for (Peer p : peers.values()) { if (alreadySendedPeers.contains(p.getHash())) continue; if (p.getHash().equals(exclude)) // TODO: Block self-connection loop in other way continue; toReturn.add(p.getPeerData()); } } else { ArrayList<Peer> orderedPeers = sortPeerList(new ArrayList<Peer>(peers.values())); for (Peer p : orderedPeers) { if (alreadySendedPeers.contains(p.getHash())) continue; if (p.getHash().equals(exclude)) // TODO: Block self-connection loop in other way continue; toReturn.add(p.getPeerData()); } toReturn = new ArrayList<PeerData>(toReturn.subList(0, maxPeers)); } return toReturn; } public static Peer getPeerIfExists(Hash hash) { if (!initialized || !peers.containsKey(hash)) return null; return peers.get(hash); } public static ArrayList<Peer> getPeerList() { return new ArrayList<Peer>(peers.values()); } public static int getPeerQuantity() { if (!initialized) return 0; return peers.size(); } public static void init() { peers = new ConcurrentHashMap<Hash, Peer>(); initialized = true; loadPeerList(); startPeerConnector(); } public static void loadPeerList() { if (!Database.isInitialized()) return; try { Statement sta = Database.getConnection().createStatement(); ResultSet rs = sta.executeQuery("SELECT * FROM peers"); while (rs.next()) { PublicKey pk = Encoding.decodePublicKey(rs.getBytes("public_key")); String ip = rs.getString("ip"); int port = rs.getInt("port"); long last = rs.getLong("last_access"); Peer p = new Peer(pk, ip, port, last); addPeer(p, false); } sta.close(); } catch (SQLException e) { Log.localizedWarn("[SQL_QUERY_ERROR]", e.getMessage()); } } public static void removeExceedingPeers() { if (!initialized) return; synchronized (peers) { if (peers.size() <= maxPeerLoaded) return; ArrayList<Peer> exceedingPeers = new ArrayList<Peer>(peers.values()); exceedingPeers = sortPeerList(exceedingPeers); exceedingPeers.subList(exceedingPeers.size() - maxPeerLoaded, exceedingPeers.size()); for (Peer p : exceedingPeers) { removePeer(p.getHash()); lastPeerListUpdating = Utility.getTimeNow(); } } } public static void removePeer(Hash peerHash) { if (!initialized || !peers.containsKey(peerHash)) return; try { PreparedStatement st = Database.getConnection().prepareStatement("DELETE FROM peers WHERE hash=?"); st.setString(1, peerHash.getReadableHash()); st.executeUpdate(); st.close(); peers.remove(peerHash); lastPeerListUpdating = Utility.getTimeNow(); } catch (SQLException e) { Log.localizedWarn("[SQL_QUERY_ERROR]", e.getMessage()); } } public static ArrayList<Peer> sortPeerList(ArrayList<Peer> p) { Collections.sort(p, new Comparator<Peer>() { @Override public int compare(Peer a, Peer b) { long aLast = 0; long bLast = 0; if (a != null) aLast = a.getLastCommunication(); if (b != null) bLast = b.getLastCommunication(); return (int) (bLast - aLast); } }); return p; } public static void startPeerConnector() { } }
gpl-3.0
DFEAGILEDEVOPS/MTC
pupil-api/src/services/redis-pupil-auth.service.spec.ts
10807
import * as moment from 'moment' import { RedisPupilAuthenticationService, IPupilLoginMessage } from './redis-pupil-auth.service' import { IRedisService } from './redis.service' import { IQueueMessageService } from './queue-message.service' let sut: RedisPupilAuthenticationService let redisServiceMock: IRedisService let messageDispatchMock: IQueueMessageService const RedisServiceMock = jest.fn<IRedisService, any>(() => ({ get: jest.fn(), setex: jest.fn(), drop: jest.fn(), quit: jest.fn(), ttl: jest.fn(), expire: jest.fn() })) const MessageDispatchMock = jest.fn<IQueueMessageService, any>(() => ({ dispatch: jest.fn() })) describe('redis-pupil-auth.service', () => { beforeEach(() => { redisServiceMock = new RedisServiceMock() messageDispatchMock = new MessageDispatchMock() sut = new RedisPupilAuthenticationService(redisServiceMock, messageDispatchMock) }) test('should be defined', () => { expect(sut).toBeDefined() }) test('it should call redis:get with correct key format', async () => { let actualKey: string = '' jest.spyOn(redisServiceMock, 'get').mockImplementation(async (key: string) => { actualKey = key }) const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' const expectedKey = `preparedCheck:${schoolPin}:${pupilPin}` await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(actualKey).toStrictEqual(expectedKey) }) test('an error should be thrown if schoolPin is not provided', async () => { let schoolPin const pupilPin = '1234' const buildNumber = '1-2-3' try { await sut.authenticate(schoolPin, pupilPin, buildNumber) fail('expected error to be thrown') } catch (error) { expect(error.message).toBe('schoolPin is required') } expect(redisServiceMock.get).not.toHaveBeenCalled() }) test('an error should be thrown if schoolPin is an empty string', async () => { const schoolPin = '' const pupilPin = '1234' const buildNumber = '1-2-3' try { await sut.authenticate(schoolPin, pupilPin, buildNumber) fail('expected error to be thrown') } catch (error) { expect(error.message).toBe('schoolPin is required') } expect(redisServiceMock.get).not.toHaveBeenCalled() }) test('an error should be thrown if pupilPin is not provided', async () => { const schoolPin = 'abc' const pupilPin = undefined const buildNumber = '1-2-3' try { await sut.authenticate(schoolPin, pupilPin, buildNumber) fail('expected error to be thrown') } catch (error) { expect(error.message).toBe('pupilPin is required') } expect(redisServiceMock.get).not.toHaveBeenCalled() }) test('an error should be thrown if pupilPin is an empty string', async () => { const schoolPin = 'abc' const pupilPin = '' const buildNumber = '1-2-3' try { await sut.authenticate(schoolPin, pupilPin, buildNumber) fail('expected error to be thrown') } catch (error) { expect(error.message).toBe('pupilPin is required') } expect(redisServiceMock.get).not.toHaveBeenCalled() }) test('an error should be thrown if buildVersion is an empty string', async () => { const schoolPin = 'abc' const pupilPin = '1234' const buildNumber = '' try { await sut.authenticate(schoolPin, pupilPin, buildNumber) fail('expected error to be thrown') } catch (error) { expect(error.message).toBe('buildVersion is required') } expect(redisServiceMock.get).not.toHaveBeenCalled() }) test('an error should be thrown if buildVersion is not provided', async () => { const schoolPin = 'abc' const pupilPin = '1234' const buildNumber = undefined try { await sut.authenticate(schoolPin, pupilPin, buildNumber) fail('expected error to be thrown') } catch (error) { expect(error.message).toBe('buildVersion is required') } expect(redisServiceMock.get).not.toHaveBeenCalled() }) test('the check payload should be returned if item found in cache and the pin is valid', async () => { const pinValidFromUtc = moment().startOf('day') const pinExpiresAtUtc = moment().endOf('day') const expectedPayload = { checkCode: '1111-2222-AAAA-4444', config: { practice: true }, pinValidFromUtc: pinValidFromUtc, pinExpiresAtUtc: pinExpiresAtUtc } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' const payload = await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(payload).toStrictEqual(expectedPayload) }) test('authorisation is denied if the pin is not yet valid', async () => { const pinValidFromUtc = moment().add(1, 'hour') const pinExpiresAtUtc = moment().add(2, 'hour') const expectedPayload = { checkCode: '1111-2222-AAAA-4444', config: { practice: false }, pinValidFromUtc: pinValidFromUtc, pinExpiresAtUtc: pinExpiresAtUtc } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' const payload = await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(payload).toBeUndefined() }) test('authorisation is denied if the pin was valid in the past', async () => { const pinValidFromUtc = moment().subtract(2, 'hour') const pinExpiresAtUtc = moment().subtract(1, 'hour') const expectedPayload = { checkCode: '1111-2222-AAAA-4444', config: { practice: false }, pinValidFromUtc: pinValidFromUtc, pinExpiresAtUtc: pinExpiresAtUtc } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' const payload = await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(payload).toBeUndefined() }) test('null should be returned if item not found in cache', async () => { jest.spyOn(redisServiceMock, 'get').mockResolvedValue(undefined) const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' const payload = await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(payload).toBeUndefined() }) test('redis item TTL should be set to 30 minutes from now if config.practice is defined and false', async () => { const thirtyMinutesInSeconds = 1800 const expectedPayload = { checkCode: '1111-2222-AAAA-4444', pinExpiresAtUtc: moment.utc().add(1, 'hour'), // valid pinValidFromUtc: moment.utc().subtract(1, 'hour'), // valid config: { practice: false } } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) let actualPreparedCheckExpiryValue: number = -1 jest.spyOn(redisServiceMock, 'expire').mockImplementation(async (key: string, ttl: number) => { actualPreparedCheckExpiryValue = ttl }) const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(actualPreparedCheckExpiryValue).toStrictEqual(thirtyMinutesInSeconds) }) test('no redis expiry is set if config.practice is true', async () => { const expectedPayload = { checkCode: '1111-2222-AAAA-4444', pinExpiresAtUtc: moment.utc().add(1, 'hour'), // valid pinValidFromUtc: moment.utc().subtract(1, 'hour'), // valid config: { practice: true } } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) jest.spyOn(redisServiceMock, 'setex') jest.spyOn(redisServiceMock, 'expire') const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(redisServiceMock.expire).not.toHaveBeenCalled() }) test('no redis expiry is set if config.practice does not exist', async () => { const expectedPayload = { checkCode: '1111-2222-AAAA-4444', pinExpiresAtUtc: moment.utc().add(1, 'hour'), // valid pinValidFromUtc: moment.utc().subtract(1, 'hour'), // valid config: {} } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) jest.spyOn(redisServiceMock, 'setex') jest.spyOn(redisServiceMock, 'expire') const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(redisServiceMock.expire).not.toHaveBeenCalled() }) test('no redis expiry is set if config.practice is undefined', async () => { const expectedPayload = { checkCode: '1111-2222-AAAA-4444', pinExpiresAtUtc: moment.utc().add(1, 'hour'), // valid pinValidFromUtc: moment.utc().subtract(1, 'hour'), // valid config: { practice: undefined } } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) jest.spyOn(redisServiceMock, 'setex') jest.spyOn(redisServiceMock, 'expire') const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(redisServiceMock.expire).not.toHaveBeenCalled() }) test('pupil-login message should be dispatched upon successful authentication', async () => { const expectedPayload = { checkCode: 'check-code', pinExpiresAtUtc: moment.utc().add(1, 'hour'), // valid pinValidFromUtc: moment.utc().subtract(1, 'hour'), // valid config: { practice: true } } jest.spyOn(redisServiceMock, 'get').mockResolvedValue(expectedPayload) // Define `actualMessage` here as TS absolutely does not believe this message get assigned before test. let actualMessage: IPupilLoginMessage = { checkCode: '', loginAt: new Date(1970), practice: true, version: -1, clientBuildVersion: '1.2', apiBuildVersion: '1.2' } jest.spyOn(messageDispatchMock, 'dispatch').mockImplementation(async (message) => { actualMessage = message.body }) const schoolPin = 'abc12def' const pupilPin = '5678' const buildNumber = '1-2-3' await sut.authenticate(schoolPin, pupilPin, buildNumber) expect(messageDispatchMock.dispatch).toHaveBeenCalledTimes(1) expect(actualMessage.checkCode).toBe(expectedPayload.checkCode) expect(actualMessage.practice).toBe(expectedPayload.config.practice) expect(actualMessage.version).toBe(1) expect(actualMessage.loginAt).toBeDefined() }) })
gpl-3.0
Wraithaven/Talantra
Talantra/src/net/tal/shared/packets/EntityMovePacket.java
2352
package net.tal.shared.packets; import java.util.UUID; import org.joml.Vector3f; import net.tal.client.entity.PhysicsEntity; import net.tal.server.Handler; import net.tal.server.OpenClientHandle; import net.tal.server.OpenServerHandle; import net.tal.server.data.User; import net.tal.shared.Entity; import net.tal.shared.Location; import net.tal.shared.log.Log; public class EntityMovePacket implements Packet { private static final long serialVersionUID = 8127450539532661248L; private Vector3f position = new Vector3f(); private float yaw, pitch; private UUID uuid; private transient boolean server; private transient Handler handle; private transient User user; public EntityMovePacket(UUID uuid, Location location) { this.uuid = uuid; position.set(location.getX(), location.getY(), location.getZ()); yaw = location.getYaw(); pitch = location.getPitch(); } @Override public void handle() { if (server) { OpenServerHandle ser = (OpenServerHandle) handle; Entity entity = ser.getEntity(uuid); if (entity != null) { entity.getLocation().setPosition(position); entity.getLocation().setRotation(yaw, pitch); for (User user : ser.getOnlinePlayers()) if (user != this.user) user.send(this); } else Log.logWarning("Entity move packet failed to handle. Entity not found. @" + uuid); } else { OpenClientHandle client = (OpenClientHandle) handle; Entity entity = client.getTalantraInstance().getRenderLoop().getWorld().getEntity(uuid); if (entity != null) { if (entity instanceof PhysicsEntity) { Location location = entity.getLocation().copy(); location.setPosition(position); location.setRotation(yaw, pitch); ((PhysicsEntity) entity).smoothMoveTo(location); } else { entity.getLocation().setPosition(position); entity.getLocation().setRotation(yaw, pitch); } } else Log.logWarning("Entity move packet failed to handle. Entity not found. @" + uuid); } } @Override public void setHandler(Handler handle) { this.handle = handle; } @Override public void setSendingClient(User user) { this.user = user; } @Override public void setServer(boolean server) { this.server = server; } }
gpl-3.0
Letractively/fxlgui
co.fxl.gui/src/main/java/co/fxl/gui/api/LayoutProviderNotFoundException.java
963
/** * Copyright (c) 2010-2015 Dangelmayr IT GmbH. All rights reserved. * * This file is part of FXL GUI API. * * FXL GUI API is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FXL GUI API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FXL GUI API. If not, see <http://www.gnu.org/licenses/>. */ package co.fxl.gui.api; public class LayoutProviderNotFoundException extends RuntimeException { private static final long serialVersionUID = -3898016064937477818L; }
gpl-3.0
LemoProject/lemo2
src/main/java/de/lemo/dms/processing/questions/QPerformanceUserTest.java
9170
/** * File ./src/main/java/de/lemo/dms/processing/questions/QPerformanceUserTest.java * Lemo-Data-Management-Server for learning analytics. * Copyright (C) 2013 * Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ /** * File ./main/java/de/lemo/dms/processing/questions/QPerformanceUserTest.java * Date 2013-02-26 * Project Lemo Learning Analytics */ package de.lemo.dms.processing.questions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import de.lemo.dms.core.config.ServerConfiguration; import de.lemo.dms.db.IDBHandler; import de.lemo.dms.db.mapping.abstractions.ICourseRatedObjectAssociation; import de.lemo.dms.db.mapping.abstractions.IRatedLogObject; import de.lemo.dms.processing.MetaParam; import de.lemo.dms.processing.StudentHelper; import de.lemo.dms.processing.resulttype.ResultListLongObject; import de.lemo.dms.processing.resulttype.ResultListStringObject; import de.lemo.dms.service.ServiceRatedObjects; /** * Gathers and returns all all test results for every student and every test in a course * * @author Sebastian Schwarzrock */ @Path("performanceUserTest") public class QPerformanceUserTest { private Logger logger = Logger.getLogger(this.getClass()); /** * @param courses * (optional) List of course-ids that shall be included * @param users * (optional) List of user-ids * @param quizzes * (mandatory) List of learning object ids (the ids have to start with the type specific prefix (11 for * "assignment", 14 for "quiz", 17 for "scorm")) * @param resolution * (mandatory) Used to scale the results. If set to 0, the method * returns the actual results of the test. Otherwise it returns the * results scaled using the value of resolution. * @param startTime * (mandatory) * @param endTime * (mandatory) * @return */ @SuppressWarnings("unchecked") @POST public ResultListLongObject compute( @FormParam(MetaParam.COURSE_IDS) final List<Long> courses, @FormParam(MetaParam.USER_IDS) List<Long> users, @FormParam(MetaParam.QUIZ_IDS) final List<Long> quizzes, @FormParam(MetaParam.RESOLUTION) final Long resolution, @FormParam(MetaParam.START_TIME) final Long startTime, @FormParam(MetaParam.END_TIME) final Long endTime, @FormParam(MetaParam.GENDER) final List<Long> gender) { if (logger.isDebugEnabled()) { if ((courses != null) && (courses.size() > 0)) { StringBuffer buffer = new StringBuffer(); buffer.append("Parameter list: Courses: " + courses.get(0)); for (int i = 1; i < courses.size(); i++) { buffer.append(", " + courses.get(i)); } logger.debug(buffer.toString()); } if ((users != null) && (users.size() > 0)) { StringBuffer buffer = new StringBuffer(); buffer.append("Parameter list: Users: " + users.get(0)); for (int i = 1; i < users.size(); i++) { buffer.append(", " + users.get(i)); } logger.debug(buffer.toString()); } logger.debug("Parameter list: Resolution: : " + resolution); logger.debug("Parameter list: Start time: : " + startTime); logger.debug("Parameter list: End time: : " + endTime); } final IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler(); final Session session = dbHandler.getMiningSession(); Criteria criteria; if(users == null || users.size() == 0) { users = new ArrayList<Long>(StudentHelper.getCourseStudentsAliasKeys(courses, gender).values()); } else { Map<Long, Long> userMap = StudentHelper.getCourseStudentsAliasKeys(courses, gender); List<Long> tmp = new ArrayList<Long>(); for(int i = 0; i < users.size(); i++) { tmp.add(userMap.get(users.get(i))); } users = tmp; } criteria = session.createCriteria(IRatedLogObject.class, "log"); criteria.add(Restrictions.between("log.timestamp", startTime, endTime)); if ((courses != null) && (courses.size() > 0)) { criteria.add(Restrictions.in("log.course.id", courses)); } if(users != null && users.size() > 0) criteria.add(Restrictions.in("log.user.id", users)); final ArrayList<IRatedLogObject> list = (ArrayList<IRatedLogObject>) criteria.list(); final Map<Long, Integer> obj = new HashMap<Long, Integer>(); if(quizzes.size() > 0) { for (int i = 0; i < quizzes.size(); i++) { obj.put(quizzes.get(i), i); } } else { ServiceRatedObjects sro = new ServiceRatedObjects(); ResultListStringObject rso = sro.getRatedObjects(courses); String s = new String(); int count = 0; for(int i = 0; i < rso.getElements().size(); i++) { if((i + 1) % 3 != 0) { s += rso.getElements().get(i); } else { obj.put(Long.valueOf(s), count); quizzes.add(Long.valueOf(s)); s= ""; count++; } } } final Map<String, IRatedLogObject> singleResults = new HashMap<String, IRatedLogObject>(); Collections.sort(list); Set<Long> u = new HashSet<Long>(); // This is for making sure there is just one entry per student and test for (int i = list.size() - 1; i >= 0; i--) { final IRatedLogObject log = list.get(i); final String key = log.getPrefix() + " " + log.getLearnObjId() + " " + log.getUser().getId(); u.add(log.getUser().getId()); if (log.getFinalGrade() != null && (singleResults.get(key) == null || (log.getFinalGrade() > singleResults.get(key).getFinalGrade()))) { singleResults.put(key, log); } } // Determine length of result array final int objects = quizzes.size() + u.size() * quizzes.size() + u.size(); final Long[] results = new Long[objects]; Map<Long, ArrayList<Long>> fin = new HashMap<Long, ArrayList<Long>>(); for (final IRatedLogObject log : singleResults.values()) { if ((obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null) && (log.getFinalGrade() != null) && (log.getMaxGrade() != null) && (log.getMaxGrade() > 0)) { Double step = 1d; // Determine size of each interval if(resolution != 0) step = log.getMaxGrade() / resolution; if (step > 0d) { // Determine interval for specific grade Integer pos = (int) (log.getFinalGrade() / step); if (resolution > 0 && pos > (resolution - 1)) { pos = resolution.intValue() - 1; } if(fin.get(log.getUser().getId()) == null) { ArrayList<Long> l = new ArrayList<Long>(); for(int i = 0; i < quizzes.size(); i++) { l.add(-1L); } fin.put(log.getUser().getId(), l); fin.get(log.getUser().getId()).set(quizzes.indexOf(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())), pos.longValue()); } else { fin.get(log.getUser().getId()).set(quizzes.indexOf(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())), pos.longValue()); } } } } criteria = session.createCriteria(ICourseRatedObjectAssociation.class, "aso"); criteria.add(Restrictions.in("aso.course.id", courses)); ArrayList<ICourseRatedObjectAssociation> q = (ArrayList<ICourseRatedObjectAssociation>) criteria.list(); HashMap<Long, Double> maxGrades = new HashMap<Long, Double>(); for(ICourseRatedObjectAssociation aso : q) { maxGrades.put(Long.valueOf(aso.getPrefix() + "" + aso.getRatedObject().getId()), aso.getRatedObject().getMaxGrade()); } //Determine maximum number of points for every quiz for(int i = 0; i < quizzes.size(); i++) { if(maxGrades.get(quizzes.get(i)) != null) results[i] = maxGrades.get(quizzes.get(i)).longValue(); else results[i] = -1L; } int i = quizzes.size(); Map<Long, Long> idToAlias = StudentHelper.getCourseStudentsRealKeys(courses, gender); for(Entry<Long, ArrayList<Long>> entry : fin.entrySet()) { //Insert user-id into result list results[i] = idToAlias.get(entry.getKey()); //Insert all test results for user to result list for(Long l : entry.getValue()) { i++; results[i] = l; } i++; } session.close(); return new ResultListLongObject(Arrays.asList(results)); } }
gpl-3.0
waikato-datamining/adams-base
adams-ml/src/test/java/adams/ml/model/classification/AbstractClassifierTestCase.java
10009
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * AbstractClassifierTestCase.java * Copyright (C) 2016 University of Waikato, Hamilton, NZ */ package adams.ml.model.classification; import adams.core.Utils; import adams.core.io.FileUtils; import adams.core.logging.LoggingHelper; import adams.core.option.OptionUtils; import adams.data.io.input.ChunkedSpreadSheetReader; import adams.data.io.input.SpreadSheetReader; import adams.data.spreadsheet.Row; import adams.data.spreadsheet.SpreadSheet; import adams.data.spreadsheet.SpreadSheetHelper; import adams.ml.data.Dataset; import adams.ml.data.DefaultDataset; import adams.test.AbstractTestHelper; import adams.test.AdamsTestCase; import adams.test.TestHelper; import adams.test.TmpFile; /** * Ancestor for classifier tests. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class AbstractClassifierTestCase extends AdamsTestCase { /** * Constructs the test case. Called by subclasses. * * @param name the name of the test */ public AbstractClassifierTestCase(String name) { super(name); } /** * Returns the test helper class to use. * * @return the helper class instance */ @Override protected AbstractTestHelper newTestHelper() { return new TestHelper(this, "adams/ml/model/classification/data"); } /** * Returns a typical setup. * * @return the setup */ protected abstract Classifier getTypicalSetup(); /** * Returns a typical dataset. * * @return the dataset */ protected abstract Dataset getTypicalDataset(); /** * Tests whether the algorithm changes the input data. */ public void testDoesntChangeInput() { Dataset data; Dataset dataCopy; Classifier algorithm; data = getTypicalDataset(); dataCopy = data.getClone(); algorithm = getTypicalSetup(); try { algorithm.buildModel(data); } catch (Exception e) { fail("Failed to build model: " + LoggingHelper.throwableToString(e)); return; } assertNull("Changed input data", SpreadSheetHelper.compare(dataCopy, data)); } /** * Tests whether the algorithm produces the same data in subsequent builds. */ public void testSubsequentBuilds() { Dataset data; Classifier algorithm; double[][] pred1; double[][] pred2; int x; int y; data = getTypicalDataset(); algorithm = getTypicalSetup(); try { algorithm.buildModel(data); pred1 = predict(algorithm, data); } catch (Exception e) { fail("Failed to build model (1): " + LoggingHelper.throwableToString(e)); return; } try { algorithm.buildModel(data); pred2 = predict(algorithm, data); } catch (Exception e) { fail("Failed to build model (1): " + LoggingHelper.throwableToString(e)); return; } for (y = 0; y < pred1.length; y++) { if ((pred1[y] == null) && (pred2[y] == null)) continue; assertNotNull("predictions1 at #" + (y+1) + " are null", pred1[y]); assertNotNull("predictions2 at #" + (y+1) + " are null", pred2[y]); assertEquals("Number of predictions at #" + (y+1) + " differ in length", pred1[y].length, pred2[y].length); assertEqualsArrays("Predictions at #" + (y+1) + " differ", pred1[y], pred2[y]); } } /** * Returns the filenames (without path) of the input data files to use * in the regression test. * * @return the filenames */ protected abstract String[] getRegressionInputFiles(); /** * Returns the readers for the input data files to use * in the regression test. * * @return the readers */ protected abstract SpreadSheetReader[] getRegressionInputReaders(); /** * Returns the class attributes names for the input data files to use * in the regression test. * * @return the attribute names */ protected abstract String[] getRegressionInputClasses(); /** * Returns the setups to use in the regression test. * * @return the setups */ protected abstract Classifier[] getRegressionSetups(); /** * Returns the ignored line indices to use in the regression test. * * @return the line indices */ protected int[] getRegressionIgnoredLineIndices() { return new int[0]; } /** * Reads the data using the reader. * * @param filename the file to read (no path) * @param reader the reader for loading the data * @param cls the class attribute name * @return the generated content */ protected Dataset load(String filename, SpreadSheetReader reader, String cls) { DefaultDataset result; SpreadSheet full; SpreadSheet chunk; m_TestHelper.copyResourceToTmp(filename); full = reader.read(new TmpFile(filename)); if (reader instanceof ChunkedSpreadSheetReader) { while (((ChunkedSpreadSheetReader) reader).hasMoreChunks()) { chunk = ((ChunkedSpreadSheetReader) reader).nextChunk(); for (Row row : chunk.rows()) full.addRow().assign(row); } } m_TestHelper.deleteFileFromTmp(filename); result = new DefaultDataset(full); result.setClassAttributeByName(cls, true); return result; } /** * Trains the classifier and returns the predictions. * * @param cls the classifier to use * @param data the training data * @return the predictions on the training data */ protected double[][] predict(Classifier cls, Dataset data) { double[][] result; ClassificationModel model; int i; result = new double[data.getRowCount()][]; try { model = cls.buildModel(data); } catch (Exception e) { fail( "Failed to build model on data!\n" + "Algorithm: " + OptionUtils.getCommandLine(cls) + "\n" + "Data:\n" + data); return null; } for (i = 0; i < data.getRowCount(); i++) { try { result[i] = model.distribution(data.getRow(i)); } catch (Exception e) { result[i] = null; } } return result; } /** * Saves the generated predictions as file. * * @param preds the generated predictions * @param filename the file to save the data to (in the temp directory) * @return true if successfully saved */ protected boolean save(double[][] preds, String filename) { StringBuilder data; int i; data = new StringBuilder(); for (double[] pred: preds) { if (data.length() > 0) data.append("\n"); if (pred == null) { data.append("null"); } else { for (i = 0; i < pred.length; i++) { if (i > 0) data.append(","); data.append(Utils.doubleToString(pred[i], 6)); } } } return FileUtils.writeToFile(new TmpFile(filename).getAbsolutePath(), data, false); } /** * Creates an output filename based on the input filename. * * @param input the input filename (no path) * @param no the number of the test * @return the generated output filename (no path) */ protected String createOutputFilename(String input, int no) { String result; int index; String ext; ext = "-out" + no; index = input.lastIndexOf('.'); if (index == -1) { result = input + ext; } else { result = input.substring(0, index); result += ext; result += input.substring(index); } return result; } /** * Compares the processed data against previously saved output data. */ public void testRegression() { Dataset data; boolean ok; String regression; int i; String[] input; SpreadSheetReader[] readers; String[] classes; Classifier[] setups; String[] output; double[][] classDist; TmpFile[] outputFiles; if (m_NoRegressionTest) return; input = getRegressionInputFiles(); readers = getRegressionInputReaders(); classes = getRegressionInputClasses(); output = new String[input.length]; setups = getRegressionSetups(); assertEquals("Number of files and readers differ!", input.length, readers.length); assertEquals("Number of files and classes differ!", input.length, classes.length); assertEquals("Number of files and setups differ!", input.length, setups.length); // process data for (i = 0; i < input.length; i++) { data = load(input[i], readers[i], classes[i]); assertNotNull("Failed to load data?", data); classDist = predict(setups[i], data); assertNotNull("Failed to make predictions?", classDist); output[i] = createOutputFilename(input[i], i); ok = save(classDist, output[i]); assertTrue("Failed to save regression data?", ok); } // test regression outputFiles = new TmpFile[output.length]; for (i = 0; i < output.length; i++) outputFiles[i] = new TmpFile(output[i]); regression = m_Regression.compare(outputFiles, getRegressionIgnoredLineIndices()); assertNull("Output differs:\n" + regression, regression); // remove output, clean up scheme for (i = 0; i < output.length; i++) { setups[i].destroy(); m_TestHelper.deleteFileFromTmp(output[i]); } cleanUpAfterRegression(); } /** * For further cleaning up after the regression tests. * <br><br> * Default implementation does nothing. */ protected void cleanUpAfterRegression() { } }
gpl-3.0
clementine-player/Clementine
src/internet/jamendo/jamendoservice.cpp
18351
/* This file is part of Clementine. Copyright 2010-2013, David Sansome <me@davidsansome.com> Copyright 2010, 2014, John Maguire <john.maguire@gmail.com> Copyright 2011, Tyler Rhodes <tyler.s.rhodes@gmail.com> Copyright 2011, Paweł Bara <keirangtp@gmail.com> Copyright 2011, Andrea Decorte <adecorte@gmail.com> Copyright 2014, Chocobozzz <florian.bigard@gmail.com> Copyright 2014, Krzysztof Sobiecki <sobkas@gmail.com> Clementine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clementine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Clementine. If not, see <http://www.gnu.org/licenses/>. */ #include "jamendoservice.h" #include <QDesktopServices> #include <QMenu> #include <QMessageBox> #include <QNetworkReply> #include <QSortFilterProxyModel> #include <QXmlStreamReader> #include <QtConcurrentRun> #include "core/application.h" #include "core/database.h" #include "core/logging.h" #include "core/mergedproxymodel.h" #include "core/network.h" #include "core/scopedtransaction.h" #include "core/taskmanager.h" #include "core/timeconstants.h" #include "globalsearch/globalsearch.h" #include "globalsearch/librarysearchprovider.h" #include "internet/core/internetmodel.h" #include "jamendodynamicplaylist.h" #include "jamendoplaylistitem.h" #include "library/librarybackend.h" #include "library/libraryfilterwidget.h" #include "library/librarymodel.h" #include "qtiocompressor.h" #include "smartplaylists/generator.h" #include "smartplaylists/querygenerator.h" #include "ui/iconloader.h" const char* JamendoService::kServiceName = "Jamendo"; const char* JamendoService::kDirectoryUrl = "https://imgjam.com/data/dbdump_artistalbumtrack.xml.gz"; const char* JamendoService::kMp3StreamUrl = "http://api.jamendo.com/get2/stream/track/redirect/" "?id=%1&streamencoding=mp31"; const char* JamendoService::kOggStreamUrl = "http://api.jamendo.com/get2/stream/track/redirect/" "?id=%1&streamencoding=ogg2"; const char* JamendoService::kAlbumCoverUrl = "http://api.jamendo.com/get2/image/album/redirect/?id=%1&imagesize=300"; const char* JamendoService::kHomepage = "http://www.jamendo.com/"; const char* JamendoService::kAlbumInfoUrl = "http://www.jamendo.com/album/%1"; const char* JamendoService::kDownloadAlbumUrl = "http://www.jamendo.com/download/album/%1"; const char* JamendoService::kSongsTable = "jamendo.songs"; const char* JamendoService::kFtsTable = "jamendo.songs_fts"; const char* JamendoService::kTrackIdsTable = "jamendo.track_ids"; const char* JamendoService::kTrackIdsColumn = "track_id"; const char* JamendoService::kSettingsGroup = "Jamendo"; const int JamendoService::kBatchSize = 10000; const int JamendoService::kApproxDatabaseSize = 450000; JamendoService::JamendoService(Application* app, InternetModel* parent) : InternetService(kServiceName, app, parent, parent), network_(new NetworkAccessManager(this)), library_backend_(nullptr), library_filter_(nullptr), library_model_(nullptr), library_sort_model_(new QSortFilterProxyModel(this)), search_provider_(nullptr), load_database_task_id_(0), total_song_count_(0), accepted_download_(false) { library_backend_.reset(new LibraryBackend, [](QObject* obj) { obj->deleteLater(); }); library_backend_->moveToThread(app_->database()->thread()); library_backend_->Init(app_->database(), kSongsTable, kFtsTable); connect(library_backend_.get(), SIGNAL(TotalSongCountUpdated(int)), SLOT(UpdateTotalSongCount(int))); using smart_playlists::Generator; using smart_playlists::GeneratorPtr; using smart_playlists::QueryGenerator; using smart_playlists::Search; using smart_playlists::SearchTerm; library_model_ = new LibraryModel(library_backend_, app_, this); library_model_->set_show_various_artists(false); library_model_->set_show_smart_playlists(false); library_model_->set_default_smart_playlists( LibraryModel::DefaultGenerators() << (LibraryModel::GeneratorList() << GeneratorPtr(new JamendoDynamicPlaylist( tr("Jamendo Top Tracks of the Month"), JamendoDynamicPlaylist::OrderBy_RatingMonth)) << GeneratorPtr(new JamendoDynamicPlaylist( tr("Jamendo Top Tracks of the Week"), JamendoDynamicPlaylist::OrderBy_RatingWeek)) << GeneratorPtr(new JamendoDynamicPlaylist( tr("Jamendo Top Tracks"), JamendoDynamicPlaylist::OrderBy_Rating)) << GeneratorPtr(new JamendoDynamicPlaylist( tr("Jamendo Most Listened Tracks"), JamendoDynamicPlaylist::OrderBy_Listened))) << (LibraryModel::GeneratorList() << GeneratorPtr(new QueryGenerator( tr("Dynamic random mix"), Search(Search::Type_All, Search::TermList(), Search::Sort_Random, SearchTerm::Field_Title), true)))); library_sort_model_->setSourceModel(library_model_); library_sort_model_->setSortRole(LibraryModel::Role_SortText); library_sort_model_->setDynamicSortFilter(true); library_sort_model_->setSortLocaleAware(true); library_sort_model_->sort(0); search_provider_ = new LibrarySearchProvider( library_backend_.get(), tr("Jamendo"), "jamendo", IconLoader::Load("jamendo", IconLoader::Provider), false, app_, this); app_->global_search()->AddProvider(search_provider_); connect(app_->global_search(), SIGNAL(ProviderToggled(const SearchProvider*, bool)), SLOT(SearchProviderToggled(const SearchProvider*, bool))); } JamendoService::~JamendoService() {} QStandardItem* JamendoService::CreateRootItem() { QStandardItem* item = new QStandardItem( IconLoader::Load("jamendo", IconLoader::Provider), kServiceName); item->setData(true, InternetModel::Role_CanLazyLoad); return item; } void JamendoService::LazyPopulate(QStandardItem* item) { switch (item->data(InternetModel::Role_Type).toInt()) { case InternetModel::Type_Service: { if (total_song_count_ == 0 && !load_database_task_id_) { DownloadDirectory(); } model()->merged_model()->AddSubModel(item->index(), library_sort_model_); break; } default: break; } } void JamendoService::UpdateTotalSongCount(int count) { total_song_count_ = count; if (total_song_count_ > 0) { library_model_->set_show_smart_playlists(true); accepted_download_ = true; // the user has previously accepted } } void JamendoService::DownloadDirectory() { // don't ask if we're refreshing the database if (total_song_count_ == 0) { if (QMessageBox::question(nullptr, tr("Jamendo database"), tr("This action will create a database which " "could be as big as 150 MB.\n" "Do you want to continue anyway?"), QMessageBox::Ok | QMessageBox::Cancel) != QMessageBox::Ok) return; } accepted_download_ = true; QNetworkRequest req = QNetworkRequest(QUrl(kDirectoryUrl)); req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork); QNetworkReply* reply = network_->get(req); connect(reply, SIGNAL(finished()), SLOT(DownloadDirectoryFinished())); connect(reply, SIGNAL(downloadProgress(qint64, qint64)), SLOT(DownloadDirectoryProgress(qint64, qint64))); if (!load_database_task_id_) { load_database_task_id_ = app_->task_manager()->StartTask(tr("Downloading Jamendo catalogue")); } } void JamendoService::DownloadDirectoryProgress(qint64 received, qint64 total) { float progress = static_cast<float>(received) / total; app_->task_manager()->SetTaskProgress(load_database_task_id_, static_cast<int>(progress * 100), 100); } void JamendoService::DownloadDirectoryFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); Q_ASSERT(reply); app_->task_manager()->SetTaskFinished(load_database_task_id_); load_database_task_id_ = 0; // TODO(John Maguire): Not leak reply. QtIOCompressor* gzip = new QtIOCompressor(reply); gzip->setStreamFormat(QtIOCompressor::GzipFormat); if (!gzip->open(QIODevice::ReadOnly)) { qLog(Warning) << "Jamendo library not in gzip format"; delete gzip; return; } load_database_task_id_ = app_->task_manager()->StartTask(tr("Parsing Jamendo catalogue")); QFuture<void> future = QtConcurrent::run(this, &JamendoService::ParseDirectory, gzip); NewClosure(future, this, SLOT(ParseDirectoryFinished())); } void JamendoService::ParseDirectory(QIODevice* device) const { int total_count = 0; // Bit of a hack: don't update the model while we're parsing the xml disconnect(library_backend_.get(), SIGNAL(SongsDiscovered(SongList)), library_model_, SLOT(SongsDiscovered(SongList))); disconnect(library_backend_.get(), SIGNAL(TotalSongCountUpdated(int)), this, SLOT(UpdateTotalSongCount(int))); // Delete the database and recreate it. This is faster than dropping tables // or removing rows. library_backend_->db()->RecreateAttachedDb("jamendo"); TrackIdList track_ids; SongList songs; QXmlStreamReader reader(device); while (!reader.atEnd()) { reader.readNext(); if (reader.tokenType() == QXmlStreamReader::StartElement && reader.name() == "artist") { songs << ReadArtist(&reader, &track_ids); } if (songs.count() >= kBatchSize) { // Add the songs to the database in batches library_backend_->AddOrUpdateSongs(songs); InsertTrackIds(track_ids); total_count += songs.count(); songs.clear(); track_ids.clear(); // Update progress info app_->task_manager()->SetTaskProgress(load_database_task_id_, total_count, kApproxDatabaseSize); } } library_backend_->AddOrUpdateSongs(songs); InsertTrackIds(track_ids); connect(library_backend_.get(), SIGNAL(SongsDiscovered(SongList)), library_model_, SLOT(SongsDiscovered(SongList))); connect(library_backend_.get(), SIGNAL(TotalSongCountUpdated(int)), SLOT(UpdateTotalSongCount(int))); library_backend_->UpdateTotalSongCount(); } void JamendoService::InsertTrackIds(const TrackIdList& ids) const { QMutexLocker l(library_backend_->db()->Mutex()); QSqlDatabase db(library_backend_->db()->Connect()); ScopedTransaction t(&db); QSqlQuery insert(db); insert.prepare(QString("INSERT INTO %1 (%2) VALUES (:id)") .arg(kTrackIdsTable, kTrackIdsColumn)); for (int id : ids) { insert.bindValue(":id", id); if (!insert.exec()) { qLog(Warning) << "Query failed" << insert.lastQuery(); } } t.Commit(); } SongList JamendoService::ReadArtist(QXmlStreamReader* reader, TrackIdList* track_ids) const { SongList ret; QString current_artist; while (!reader->atEnd()) { reader->readNext(); if (reader->tokenType() == QXmlStreamReader::StartElement) { QStringRef name = reader->name(); if (name == "name") { current_artist = reader->readElementText().trimmed(); } else if (name == "album") { ret << ReadAlbum(current_artist, reader, track_ids); } } else if (reader->isEndElement() && reader->name() == "artist") { break; } } return ret; } SongList JamendoService::ReadAlbum(const QString& artist, QXmlStreamReader* reader, TrackIdList* track_ids) const { SongList ret; QString current_album; QString cover; int current_album_id = 0; while (!reader->atEnd()) { reader->readNext(); if (reader->tokenType() == QXmlStreamReader::StartElement) { if (reader->name() == "name") { current_album = reader->readElementText().trimmed(); } else if (reader->name() == "id") { QString id = reader->readElementText(); cover = QString(kAlbumCoverUrl).arg(id); current_album_id = id.toInt(); } else if (reader->name() == "track") { ret << ReadTrack(artist, current_album, cover, current_album_id, reader, track_ids); } } else if (reader->isEndElement() && reader->name() == "album") { break; } } return ret; } Song JamendoService::ReadTrack(const QString& artist, const QString& album, const QString& album_cover, int album_id, QXmlStreamReader* reader, TrackIdList* track_ids) const { Song song; song.set_artist(artist); song.set_album(album); song.set_filetype(Song::Type_Stream); song.set_directory_id(0); song.set_mtime(0); song.set_ctime(0); song.set_filesize(0); // Shoehorn the album ID into the comment field song.set_comment(QString::number(album_id)); while (!reader->atEnd()) { reader->readNext(); if (reader->isStartElement()) { QStringRef name = reader->name(); if (name == "name") { song.set_title(reader->readElementText().trimmed()); } else if (name == "duration") { const int length = reader->readElementText().toFloat(); song.set_length_nanosec(length * kNsecPerSec); } else if (name == "id3genre") { int genre_id = reader->readElementText().toInt(); // In theory, genre 0 is "blues"; in practice it's invalid. if (genre_id != 0) { song.set_genre_id3(genre_id); } } else if (name == "id") { QString id_text = reader->readElementText(); int id = id_text.toInt(); if (id == 0) continue; QString mp3_url = QString(kMp3StreamUrl).arg(id_text); song.set_url(QUrl(mp3_url)); song.set_art_automatic(album_cover); song.set_valid(true); // Rely on songs getting added in this exact order track_ids->append(id); } } else if (reader->isEndElement() && reader->name() == "track") { break; } } return song; } void JamendoService::ParseDirectoryFinished() { // show smart playlists library_model_->set_show_smart_playlists(true); library_model_->Reset(); app_->task_manager()->SetTaskFinished(load_database_task_id_); load_database_task_id_ = 0; } void JamendoService::EnsureMenuCreated() { if (library_filter_) return; context_menu_.reset(new QMenu); context_menu_->addActions(GetPlaylistActions()); album_info_ = context_menu_->addAction( IconLoader::Load("view-media-lyrics", IconLoader::Base), tr("Album info on jamendo.com..."), this, SLOT(AlbumInfo())); download_album_ = context_menu_->addAction( IconLoader::Load("download", IconLoader::Base), tr("Download this album..."), this, SLOT(DownloadAlbum())); context_menu_->addSeparator(); context_menu_->addAction(IconLoader::Load("download", IconLoader::Base), tr("Open %1 in browser").arg("jamendo.com"), this, SLOT(Homepage())); context_menu_->addAction(IconLoader::Load("view-refresh", IconLoader::Base), tr("Refresh catalogue"), this, SLOT(DownloadDirectory())); if (accepted_download_) { library_filter_ = new LibraryFilterWidget(0); library_filter_->SetSettingsGroup(kSettingsGroup); library_filter_->SetLibraryModel(library_model_); library_filter_->SetFilterHint(tr("Search Jamendo")); library_filter_->SetAgeFilterEnabled(false); context_menu_->addSeparator(); context_menu_->addMenu(library_filter_->menu()); } } void JamendoService::ShowContextMenu(const QPoint& global_pos) { EnsureMenuCreated(); const bool enabled = accepted_download_ && model()->current_index().model() == library_sort_model_; // make menu items visible and enabled only when needed GetAppendToPlaylistAction()->setVisible(accepted_download_); GetAppendToPlaylistAction()->setEnabled(enabled); GetReplacePlaylistAction()->setVisible(accepted_download_); GetReplacePlaylistAction()->setEnabled(enabled); GetOpenInNewPlaylistAction()->setEnabled(enabled); GetOpenInNewPlaylistAction()->setVisible(accepted_download_); album_info_->setEnabled(enabled); album_info_->setVisible(accepted_download_); download_album_->setEnabled(enabled); download_album_->setVisible(accepted_download_); context_menu_->popup(global_pos); } QWidget* JamendoService::HeaderWidget() const { const_cast<JamendoService*>(this)->EnsureMenuCreated(); return library_filter_; } void JamendoService::AlbumInfo() { SongList songs(library_model_->GetChildSongs( library_sort_model_->mapToSource(model()->current_index()))); if (songs.isEmpty()) return; // We put the album ID into the comment field int id = songs.first().comment().toInt(); if (!id) return; QDesktopServices::openUrl(QUrl(QString(kAlbumInfoUrl).arg(id))); } void JamendoService::DownloadAlbum() { SongList songs(library_model_->GetChildSongs( library_sort_model_->mapToSource(model()->current_index()))); if (songs.isEmpty()) return; // We put the album ID into the comment field int id = songs.first().comment().toInt(); if (!id) return; QDesktopServices::openUrl(QUrl(QString(kDownloadAlbumUrl).arg(id))); } void JamendoService::Homepage() { QDesktopServices::openUrl(QUrl(kHomepage)); } void JamendoService::SearchProviderToggled(const SearchProvider* provider, bool enabled) { // If the use enabled our provider and he hasn't downloaded the directory yet, // prompt him to do so now. if (provider == search_provider_ && enabled && total_song_count_ == 0) { DownloadDirectory(); } }
gpl-3.0
vondruska/flickrimportr
controllers/import_controller.php
8328
<?php /* * This file is part of FlickrImportr. FlickrImportr is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FlickrImportr. If not, see <http://www.gnu.org/licenses/>. * * @author Steven Vondruska <vondruska@gmail.com> * */ class ImportController extends AppController { var $uses = array(); function beforeFilter() { parent::beforeFilter(); $this->enableFlickrCache(); } function build() { if ($this->isAjax()) { $startTime = time(); $time = false; $arrayKey = array_keys($_SESSION['photos']); $photo = $_SESSION['photos']; if (!isset($_SESSION['start_cache'])) $_SESSION['start_cache'] = 0; for ($_SESSION['start_cache']; $_SESSION['start_cache'] < count($_SESSION['photos']); $_SESSION['start_cache']++) { $this->flickr->photos_getInfo($_SESSION['photos'][$_SESSION['start_cache']]); $return['photos'][] = $photo[$_SESSION['start_cache']]; if (time() - $startTime > 5) { $time = true; break; } } if ($time) $return['status'] = 'in progress'; else { $return['status'] = 'completed'; $return['percent'] = '100'; if (isset($_SESSION['start_cache'])) unset($_SESSION['start_cache']); } if (!isset($return['percent'])) $return['percent'] = round(($_SESSION['start_cache'] / count($_SESSION['photos'])) * 100); $this->set('output', json_encode($return)); $this->render('ajax'); } } function cache($photoid) { $this->enableFlickrCache(); $this->flickr->photos_getInfo($photoid); $this->set('output', json_encode(array('status' => 'completed'))); $this->render('ajax'); } function go() { //$settings = $this->User->find('all', array('conditions' => array('User.id' => $this->user))); if (!empty($this->params['form']['user_id'])) { $accounts = $this->facebook->api('/me/accounts'); foreach ($accounts['data'] as $account) { echo $this->params['form']['user_id']; if ($account['id'] == $this->params['form']['user_id']) { $access_token = $account['access_token']; $import_object_id = $account['id']; } } } else { $access_token = $this->facebook->getAccessToken(); $import_object_id = "me"; } $this->Job->save( array('Job' => array( 'user_id' => $this->user['id'], 'access_token' => $access_token, 'import_object_id' => $import_object_id, 'status' => 1, 'title' => isset($this->params['form']['album_name']) ? $this->params['form']['album_name'] : "", 'description' => isset($this->params['form']['album_desc']) ? $this->params['form']['album_desc'] : "", 'album_id' => ($this->params['form']['album_from'] == "facebook" && isset($this->params['form']['album_id']) && is_numeric($this->params['form']['album_id'])) ? $this->params['form']['album_id'] : 0, 'album_link' => (isset($album[0]['aid'])) ? $album[0]['link'] : '', 'album_privacy' => (isset($this->params['form']['album_privacy'])) ? $this->params['form']['album_privacy'] : 'EVERYONE' ) ) ); $jobId = $this->Job->id; foreach ($_SESSION['photos'] as $photo) { $data[] = array( 'job_id' => $jobId, 'flickr_id' => $photo, 'description' => (isset($this->params['form']['desc_' . $photo])) ? $this->params['form']['desc_' . $photo] : "", 'status' => 1 ); } $this->Photo->saveAll($data); $this->Process->start($jobId); $_SESSION['photos'] = array(); // clear photos $this->redirect('/' . $GLOBALS['appPath'] . '/jobs/'); } function review() { if ($_POST['action'] == "remove_photo") { $this->layout = 'ajax'; $this->viewPath = 'ajax'; $return = array(); $key = array_search($_POST['photo_id'], $_SESSION['photos']); unset($_SESSION['photos'][$key]); $return['status'] = ($key === false) ? 'not found' : 'completed'; $return['key'] = $key; $return['id'] = $_POST['photo_id']; $this->set('output', json_encode($return)); $this->render('ajax'); } else { if (count($_SESSION['photos']) == 0) { $this->set('errorMessage', 'No photos are queued for import. Please add some photos and return to this page.'); } else { if (isset($_SESSION['quick'])) { $this->set('quick', $_SESSION['quick']); $_SESSION['quick'] = null; } foreach ($_SESSION['photos'] as $photo) { $flickr = $this->flickr->photos_getInfo($photo); $tags = array(); foreach ($flickr['tags']['tag'] as $tag) { $tags[] = $tag['raw']; } $array[$flickr['id']] = array('title' => $flickr['title'], 'id' => $flickr['id'], 'url' => $this->flickr->buildPhotoURL($flickr, "small"), 'description' => strip_tags($flickr['description']), 'flickr_url' => $flickr['urls']['url'][0]['_content'], 'date_taken' => "Taken on " . date("M. jS, Y \a\\t H:i", strtotime($flickr['dates']['taken'])), 'tags' => implode(",", $tags)); } $this->set('photos', $array); $array = array(); $photosets = $this->flickr->photosets_getList(); foreach ($photosets['photoset'] as $photoset) { $array[$photoset['id']] = array('title' => $photoset['title'], 'id' => $photoset['id'], 'description' => $photoset['description']); } $this->set('photosets', $array); $array = array(); $facebook_albums = $this->facebook->api("/me/albums", 'get', array('limit' => '1000')); foreach ($facebook_albums['data'] as $album) { $array[$album['id']] = array('name' => $album['name'], 'aid' => $album['id']); } $this->set('facebook_albums', $array); $array = array(); $accounts = $this->facebook->api("/me/accounts"); foreach ($accounts['data'] as $key => $value) { if (isset($value['access_token']) && !empty($value['name'])) { $page_albums = $this->facebook->api("/" . $value['id'] . "/albums", array('limit' => 1000)); foreach ($page_albums['data'] as $album_key => $album_value) { if ($album_value['type'] == 'normal') $page_album_array[$album_value['id']] = array('name' => $album_value['name'], 'aid' => $album_value['id']); } $array[$value['id']] = array('id' => $value['id'], 'albums' => $page_album_array, 'name' => $value['name'] . " [" . $value['category'] . "]"); $page_album_array = array(); } } $this->set('page_albums', $array); $array = array(); } } } } ?>
gpl-3.0
gurugithub/thinkup
plugins/foursquare/model/class.FoursquareAPIAccessor.php
3427
<?php /** * * ThinkUp/webapp/plugins/foursquare/model/class.FoursquareAPIAccessor.php * * Copyright (c) 2012-2013 Aaron Kalair * * LICENSE: * * This file is part of ThinkUp (http://thinkupapp.com). * * ThinkUp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any * later version. * * ThinkUp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with ThinkUp. If not, see * <http://www.gnu.org/licenses/>. * * Foursquare API Accessor * * Makes calls to the foursquare API * * @author Aaron Kalair <aaronkalair[at]gmail[dot][com]> * @license http://www.gnu.org/licenses/gpl.html * @copyright 2012-2013 Aaron Kalair */ class FoursquareAPIAccessor{ /** * The base URL for making foursquare API requests. * @var str */ var $api_domain = 'https://api.foursquare.com/v2/'; /** Make a foursquare API request. * @param str $endpoint API endpoint to access * @param str $access_token OAuth token for the user * @param arr $fields Array of URL parameters * @return array Decoded JSON response */ public function apiRequest($endpoint, $access_token, $fields=null) { // Add endpoint and OAuth token to the URL $url = $this->api_domain.$endpoint.'?oauth_token='.$access_token; // If there are additional parameters passed in add them to the URL also if($fields != null){ foreach( $fields as $key=>$value) { $url = $url.'&'.$key.'='.$value; } } // Foursquare requires us to add the date at the end of the request so get a date array $date = getdate(); // Add the year month and day at the end of the URL $url = $url."&v=".$date['year'].$date['mon'].$date['mday']; // Get any results returned from this request $result = Utils::getURLContents($url); // Return the results $parsed_result = json_decode($result); if (isset($parsed_result->meta->errorType)) { $exception_description = $parsed_result->meta->errorType; if (isset($parsed_result->meta->errorDetail)) { $exception_description .= ": ".$parsed_result->meta->errorDetail; } throw new Exception($exception_description); } else { return $parsed_result; } } /** * Make an API request with an absolute URL, the URL you pass in is litterally the request you want to make * with OAuth tokens etc * * @param str $path - The URL of the API request you want to make * @param bool $decode_json Defaults to true, if true returns decoded JSON * @return array Decoded JSON response */ public function rawPostApiRequest($path, $fields, $decode_json=true) { // Get the result of the API query $result = Utils::getURLContentsViaPost($path, $fields); // Decode the results if ($decode_json) { $result = json_decode($result); } return $result; } }
gpl-3.0
wandora-team/wandora
src/org/wandora/application/tools/DeleteTopicsWithoutVariants.java
2013
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2016 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.wandora.application.tools; import java.util.*; import org.wandora.topicmap.*; import org.wandora.application.*; /** * * @author akivela */ public class DeleteTopicsWithoutVariants extends DeleteTopics implements WandoraTool { /** Creates a new instance of DeleteTopicsWithoutVariants */ public DeleteTopicsWithoutVariants() { } @Override public String getName() { return "Delete topics without variant names"; } @Override public String getDescription() { return "Delete context topics without variant names."; } @Override public boolean shouldDelete(Topic topic) throws TopicMapException { try { if(topic != null && !topic.isRemoved()) { Set variantScopes = topic.getVariantScopes(); if(variantScopes == null || variantScopes.isEmpty()) { if(confirm) { return confirmDelete(topic); } else { return true; } } } } catch(Exception e) { log(e); } return false; } }
gpl-3.0
axzcfgg/fps_keeper
FpsKeeper.cpp
1480
#include "FpsKeeper.hpp" #include <limits.h> // Windows #if defined(WIN_BUILD) #include <windows.h> #endif // Linux #if defined(LINUX_BUILD) #include <unistd.h> #include <sys/time.h> typedef unsigned long DWORD; #endif class sec { public: enum { U_SEC = 1000000 , M_SEC = 1000 }; }; // constructor fps::keeper::keeper() : frame_time(1000) , prev_time(0) , bresenham_err(0) , fps(60) { } // constructor fps::keeper::keeper(const unsigned int fps_) : frame_time(1000) , prev_time(0) , bresenham_err(0) , fps(fps_) { } //timeGetTime() on linux #if defined (LINUX_BUILD) DWORD timeGetTime() { struct timeval t={0}; gettimeofday( &t , 0 ); return ( (t.tv_sec * sec::U_SEC) + t.tv_usec ) / sec::M_SEC; } #endif void fps::keeper::set_fps(const unsigned int fps_) { if(fps_ == 0) return; fps = fps_; } bool fps::keeper::wait() { DWORD nowTime = timeGetTime() * fps; if(prev_time > nowTime){ nowTime += ULONG_MAX - prev_time; prev_time = 0; } DWORD processTime = nowTime - prev_time; prev_time = nowTime; if(frame_time + bresenham_err > processTime){ DWORD waitTime = frame_time + bresenham_err - processTime; bresenham_err = waitTime % fps; waitTime -= bresenham_err; fps::keeper::sleep(waitTime / fps); prev_time += waitTime; return true; } return false; } void fps::keeper::sleep(const unsigned int m_sec) { #if defined(WIN_BUILD) Sleep(m_sec); #elif defined(LINUX_BUILD) usleep( m_sec * sec::M_SEC ); #endif }
gpl-3.0
JavierAntonioGonzalezTrejo/SCAZAC
calidadAire/models.py
7488
# Reports of change # Modification 20170723: Adding the Class MonitoringMap # Modification 20170807: Added idStation to the ImecaData.. models # Modification 20170808: Added # Added Class ImecaDataHour 20170812 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from investigacion.models import MonitoringStation import datetime import dateutil.parser YEAR_CHOICES = [] for r in range(1980, (datetime.datetime.now().year+1)): YEAR_CHOICES.append((r,r)) # Create your models here. class MonitoringReports(models.Model): """Class which will hols information about the air Quality Reports made by goverment""" idReport = models.IntegerField(primary_key=True) year = models.IntegerField(('year'),choices=YEAR_CHOICES, default=datetime.datetime.now().year) # Modified 201707 fileLocation = models.FileField(upload_to='reports/%Y/%m/%d/') # Added Date of upload title = models.CharField(max_length=200) # Aproximate length of each title image cover = models.ImageField(upload_to='reImages/%Y/%m/%d/') # Added date of upload and folder def __str__(self): """The class whill be represented by the title""" return str(self.title) class MonitoringMap(models.Model): """Holds Zoom and posistion information about the Map showed on the first view and developer String to use google maps""" idMap = models.IntegerField(primary_key=True) centerLatitude = models.DecimalField(max_digits=10, decimal_places=7) centerLength = models.DecimalField(max_digits=10, decimal_places=7) zoom = models.IntegerField(); googleAPIKey = models.CharField(max_length=100) def __str__(self): """The representation of the class""" return self.googleAPIKey class ImecaDataDay(models.Model): """Hold the IMECA value of each day on the system""" fecha = models.DateField() # Of each Day, Modificated 20170807: fecha no longer serves a the primary key, now the id django autogenerated field serves that porpuse idStation = models.ForeignKey( 'investigacion.MonitoringStation', on_delete=models.CASCADE, ) # Added 20170807 Added to have the same date for diferents stations register # IMECA Values imecaO3 = models.DecimalField(null=True, max_digits=6, decimal_places=2) # 0.00 For the imecas imecaNO = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaNO2 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaNOX = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaSO2 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaCO = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaPM10 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaPM25 = models.DecimalField(null=True, max_digits=6, decimal_places=2) def __str__(self): """Function to represent the model""" return str(self.fecha) class Meta:# Added 20170807 """Class to hold constraints of the database, espesificaly to enforce the rule of the unique convination of fecha and idStation: Have a unique date register per monitoring station""" unique_together = ("idStation", "fecha") class ImecaDataMonth(models.Model): """Hold the IMECA data for each month """ fecha = models.DateField() # Of each Month (will be handel by function, this is to not get bottered whit the day on the DateFIeld, Modificated 20170807: fecha no longer serves a the primary key, now the id django autogenerated field serves that porpuse idStation = models.ForeignKey( 'investigacion.MonitoringStation', on_delete=models.CASCADE, ) # Added 20170807 Added to have the same date for diferents stations register # IMECA Values imecaO3 = models.DecimalField(null=True, max_digits=6, decimal_places=2) # 0.00 For the imecas imecaNO = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaNO2 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaNOX = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaSO2 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaCO = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaPM10 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaPM25 = models.DecimalField(null=True, max_digits=6, decimal_places=2) def setFecha(self, year, month): """Set the Date of the IMECA without the Day""" self.fecha = dateutil.parser.parse(year + "-" + month + "-" + "01") # Corrected Bug here 20170806 def getFecha(self): return self.__str__() def __str__(self): """Function to represent the model""" return str(self.fecha.year) + "-" + str(self.fecha.month) class Meta: # Added 20170807 """Class to hold constraints of the database, espesificaly to enforce the rule of the unique convination of fecha and idStation: Have a unique date register per monitoring station""" unique_together = ("idStation", "fecha") class ImecaDataHour(models.Model): # Added 20170812 """Hold the IMECA data for each Hour """ fecha = models.DateTimeField() # Of each Hour idStation = models.ForeignKey( 'investigacion.MonitoringStation', on_delete=models.CASCADE, ) # IMECA Values imecaO3 = models.DecimalField(null=True, max_digits=6, decimal_places=2) # 0.00 For the imecas imecaNO = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaNO2 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaNOX = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaSO2 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaCO = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaPM10 = models.DecimalField(null=True, max_digits=6, decimal_places=2) imecaPM25 = models.DecimalField(null=True, max_digits=6, decimal_places=2) def setFecha(self, year, month, day, hour): """Set the Date of the IMECA without the Day""" self.fecha = dateutil.parser.parse(year + "-" + month + "-" + day + " " + hour + ":00") # Parse the DateTimeField giving to each hour 0 minutes def getFecha(self): return self.__str__() def __str__(self): """Function to represent the model""" return str(self.fecha.year) + "-" + str(self.fecha.month) + "-" + str(self.fecha.day) + " " + str(self.fecha.hour) + ":00" # The last string is to give the number of each hour an hour format class Meta: """Class to hold constraints of the database, espesificaly to enforce the rule of the unique combination of fecha and idStation: Have a unique date register per monitoring station""" unique_together = ("idStation", "fecha")
gpl-3.0
mlkdru/nyloc
src/main/java/com/lawek/Entree.java
127
package com.lawek; public class Entree extends Neuron { public void setEtat(double newEtat) { this.etat = newEtat; } }
gpl-3.0
getgauge/Intellij-Plugin
src/com/thoughtworks/gauge/extract/stepBuilder/SpecStepsBuilder.java
1053
package com.thoughtworks.gauge.extract.stepBuilder; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.thoughtworks.gauge.language.psi.impl.SpecStepImpl; import java.util.List; public class SpecStepsBuilder extends StepsBuilder { public SpecStepsBuilder(Editor editor, PsiFile psiFile) { super(editor, psiFile); } public List<PsiElement> build() { List<PsiElement> specSteps = getPsiElements(SpecStepImpl.class); Integer count = 0; for (PsiElement element : specSteps) { SpecStepImpl specStep = (SpecStepImpl) element; if (specStep.getInlineTable() != null && TextToTableMap.get(specStep.getInlineTable().getText().trim()) == null) { tableMap.put("table" + (++count).toString(), specStep.getInlineTable().getText().trim()); TextToTableMap.put(specStep.getInlineTable().getText().trim(), "table" + (count).toString()); } } return specSteps; } }
gpl-3.0
thavoo/laravel_vue
database/migrations/2017_04_21_144754_create_items_table.php
679
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateItemsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('items', function (Blueprint $table) { // $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists("items"); } }
gpl-3.0
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/handler/usercommands/UserCommandHandler.java
1981
package l2s.gameserver.handler.usercommands; import gnu.trove.map.hash.TIntObjectHashMap; import l2s.commons.data.xml.AbstractHolder; import l2s.gameserver.handler.usercommands.impl.ClanPenalty; import l2s.gameserver.handler.usercommands.impl.ClanWarsList; import l2s.gameserver.handler.usercommands.impl.CommandChannel; import l2s.gameserver.handler.usercommands.impl.Escape; import l2s.gameserver.handler.usercommands.impl.InstanceZone; import l2s.gameserver.handler.usercommands.impl.Loc; import l2s.gameserver.handler.usercommands.impl.MyBirthday; import l2s.gameserver.handler.usercommands.impl.OlympiadStat; import l2s.gameserver.handler.usercommands.impl.PartyInfo; import l2s.gameserver.handler.usercommands.impl.Time; public class UserCommandHandler extends AbstractHolder { private static final UserCommandHandler _instance = new UserCommandHandler(); public static UserCommandHandler getInstance() { return _instance; } private TIntObjectHashMap<IUserCommandHandler> _datatable = new TIntObjectHashMap<IUserCommandHandler>(); private UserCommandHandler() { registerUserCommandHandler(new ClanWarsList()); registerUserCommandHandler(new ClanPenalty()); registerUserCommandHandler(new CommandChannel()); registerUserCommandHandler(new Escape()); registerUserCommandHandler(new Loc()); registerUserCommandHandler(new MyBirthday()); registerUserCommandHandler(new OlympiadStat()); registerUserCommandHandler(new PartyInfo()); registerUserCommandHandler(new InstanceZone()); registerUserCommandHandler(new Time()); } public void registerUserCommandHandler(IUserCommandHandler handler) { int[] ids = handler.getUserCommandList(); for(int element : ids) _datatable.put(element, handler); } public IUserCommandHandler getUserCommandHandler(int userCommand) { return _datatable.get(userCommand); } @Override public int size() { return _datatable.size(); } @Override public void clear() { _datatable.clear(); } }
gpl-3.0
fairplaysk/datacamp
spec/features/dataset_categories_spec.rb
2606
require 'spec_helper' describe 'DatasetCategories' do before(:each) do login_as(admin_user) end it 'user can see categories in dataset description screen' do FactoryGirl.create(:category, title: 'documents') FactoryGirl.create(:category, title: 'persons') visit dataset_descriptions_path(locale: :en) page.should have_content 'documents' page.should have_content 'persons' end # not sure if this test is needed, but it is in the system, so I wrote a test for it it 'user can see categories in category listing' do FactoryGirl.create(:category, title: 'documents') FactoryGirl.create(:category, title: 'persons') visit categories_path(locale: :en) page.should have_content 'documents' page.should have_content 'persons' end it 'user is able to create new category' do visit new_category_path(locale: :en) click_button 'Save' page.should have_content 'can\'t be blank' fill_in 'dataset_category_en_title', with: 'documents' fill_in 'dataset_category_sk_title', with: 'documents' click_button 'Save' page.should have_content 'documents' end it 'user is able to create new category from dataset description page', js: true do visit dataset_descriptions_path(locale: :en) click_link 'New category' fill_in 'dataset_category_en_title', with: 'documents' click_button 'Submit' page.should have_content 'documents' end it 'user is able to edit category' do category = FactoryGirl.create(:category, title: 'documents') visit edit_dataset_category_path(id: category, locale: :en) fill_in 'dataset_category_en_title', with: 'important documents' click_button 'Save' page.should have_content 'important documents' end it 'user should see if he tries to update category to invalid' it 'user is able to inline edit category', js: true do category = FactoryGirl.create(:category, title: 'documents') visit dataset_descriptions_path(locale: :en) within("li#dataset_category_#{category.id}") do click_link 'Edit' end fill_in 'dataset_category[title]', with: 'important documents' within("li#dataset_category_#{category.id}") do click_link 'Edit' end page.should have_content 'important documents' end it 'user is able to delete category' do category = FactoryGirl.create(:category, title: 'documents') visit dataset_descriptions_path(locale: :en) within("li#dataset_category_#{category.id}") do click_link 'Delete' end page.should_not have_content 'important documents' end end
gpl-3.0
IgorGulyaev/iteamzen
client/src/views/fields/link-multiple-with-primary.js
7313
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EspoCRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ Espo.define('views/fields/link-multiple-with-primary', 'views/fields/link-multiple', function (Dep) { return Dep.extend({ primaryLink: null, events: { 'click [data-action="switchPrimary"]': function (e) { $target = $(e.currentTarget); var id = $target.data('id'); if (!$target.hasClass('active')) { this.$el.find('button[data-action="switchPrimary"]').removeClass('active').children().addClass('text-muted'); $target.addClass('active').children().removeClass('text-muted'); this.setPrimaryId(id); } } }, getAttributeList: function () { var list = Dep.prototype.getAttributeList.call(this); list.push(this.primaryIdFieldName); list.push(this.primaryNameFieldName); return list; }, setup: function () { this.primaryLink = this.options.primaryLink || this.primaryLink; this.primaryIdFieldName = this.primaryLink + 'Id'; this.primaryNameFieldName = this.primaryLink + 'Name'; Dep.prototype.setup.call(this); this.primaryId = this.model.get(this.primaryIdFieldName); this.primaryName = this.model.get(this.primaryNameFieldName); this.listenTo(this.model, 'change:' + this.primaryIdFieldName, function () { this.primaryId = this.model.get(this.primaryIdFieldName); this.primaryName = this.model.get(this.primaryNameFieldName); }.bind(this)); }, setPrimaryId: function (id) { this.primaryId = id; if (id) { this.primaryName = this.nameHash[id]; } else { this.primaryName = null; } this.trigger('change'); }, renderLinks: function () { if (this.primaryId) { this.addLinkHtml(this.primaryId, this.primaryName); } this.ids.forEach(function (id) { if (id != this.primaryId) { this.addLinkHtml(id, this.nameHash[id]); } }, this); }, getValueForDisplay: function () { if (this.mode == 'detail' || this.mode == 'list') { var names = []; if (this.primaryId) { names.push(this.getDetailLinkHtml(this.primaryId, this.primaryName)); } if (!this.ids.length) { return; } this.ids.forEach(function (id) { if (id != this.primaryId) { names.push(this.getDetailLinkHtml(id)); } }, this); return '<div>' + names.join('</div><div>') + '</div>'; } }, deleteLink: function (id) { if (id == this.primaryId) { this.setPrimaryId(null); } Dep.prototype.deleteLink.call(this, id); }, deleteLinkHtml: function (id) { Dep.prototype.deleteLinkHtml.call(this, id); this.managePrimaryButton(); }, addLinkHtml: function (id, name) { if (this.mode == 'search') { return Dep.prototype.addLinkHtml.call(this, id, name); } var $container = this.$el.find('.link-container'); var $el = $('<div class="form-inline list-group-item link-with-role">').addClass('link-' + id).attr('data-id', id); var nameHtml = '<div>' + name + '&nbsp;' + '</div>'; var removeHtml = '<a href="javascript:" class="pull-right" data-id="' + id + '" data-action="clearLink"><span class="glyphicon glyphicon-remove"></a>'; $left = $('<div class="pull-left">').css({ 'width': '92%', 'display': 'inline-block' }); $left.append(nameHtml); $el.append($left); $right = $('<div>').css({ 'width': '8%', 'display': 'inline-block', 'vertical-align': 'top' }); $right.append(removeHtml); $el.append($right); $el.append('<br style="clear: both;" />'); var isPrimary = (id == this.primaryId); var iconHtml = '<span class="glyphicon glyphicon-star ' + (!isPrimary ? 'text-muted' : '') + '"></span>'; var title = this.translate('Primary'); var $primary = $('<button type="button" class="btn btn-link btn-sm pull-right hidden" title="'+title+'" data-action="switchPrimary" data-id="'+id+'">'+iconHtml+'</button>'); $primary.insertBefore($el.children().first().children().first()); $container.append($el); this.managePrimaryButton(); return $el; }, afterRender: function () { Dep.prototype.afterRender.call(this); }, managePrimaryButton: function () { var $primary = this.$el.find('button[data-action="switchPrimary"]'); if ($primary.size() > 1) { $primary.removeClass('hidden'); } else { $primary.addClass('hidden'); } if ($primary.filter('.active').size() == 0) { var $first = $primary.first(); if ($first.size()) { $first.addClass('active').children().removeClass('text-muted'); this.setPrimaryId($first.data('id')); } } }, fetch: function () { var data = Dep.prototype.fetch.call(this); data[this.primaryIdFieldName] = this.primaryId; data[this.primaryNameFieldName] = this.primaryName; return data; }, }); });
gpl-3.0
DySense/DySense
dysense/core/issue.py
2109
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time class Issue(object): min_expire_increment = 1 # second def __init__(self, **kargs): self._id = kargs['id'] self._sub_id = kargs['sub_id'] self._issue_type = kargs['type'] self._reason = kargs.get('reason', '') self._level = kargs.get('level', 'error') self.start_time = kargs.get('start_time', time.time()) self.expiration_time = kargs.get('expiration_time', 0) # Right now these are only used by presenter. Should consider storing these outside of class. self.acked = False self.resolved = False @property def public_info(self): return {'id': self.id, 'sub_id': self.sub_id, 'type': self.issue_type, 'reason': self._reason, 'level': self._level, 'start_time': self.start_time, 'end_time': self.expiration_time, } @property def id(self): return self._id @property def sub_id(self): return self._sub_id @property def issue_type(self): return self._issue_type @property def reason(self): return self._reason @property def level(self): return self._level @reason.setter def reason(self, new_value): self._reason = new_value @level.setter def level(self, new_value): self._level = new_value @property def expired(self): return (self.expiration_time > 0) and (time.time() >= self.expiration_time) def matches(self, info): return self._id == info['id'] and self._sub_id == info['sub_id'] and self._issue_type == info['type'] def renew(self): self.expiration_time = 0 def expire(self, force_expire=False): if self.expiration_time > 0: return # already set to expire if force_expire: self.expiration_time = time.time() else: self.expiration_time = time.time() + Issue.min_expire_increment
gpl-3.0
kontalk/androidclient
app/src/main/java/org/kontalk/ui/prefs/CopyDatabasePreference.java
5878
/* * Kontalk Android client * Copyright (C) 2020 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.ui.prefs; import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.net.Uri; import android.os.Build; import android.os.Environment; import androidx.fragment.app.Fragment; import androidx.preference.Preference; import android.util.AttributeSet; import android.widget.Toast; import org.kontalk.Kontalk; import org.kontalk.Log; import org.kontalk.R; import org.kontalk.provider.MessagesProvider; import org.kontalk.reporting.ReportingManager; import org.kontalk.util.DataUtils; import org.kontalk.util.MediaStorage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.afollestad.materialdialogs.folderselector.FolderChooserDialog; /** * Preference for copying the messages database to the external storage. * @author Daniele Ricci */ public class CopyDatabasePreference extends Preference { private static final String TAG = Kontalk.TAG; public static final int REQUEST_COPY_DATABASE = Activity.RESULT_FIRST_USER + 4; private static final String DBFILE_MIME = "application/x-sqlite3"; public static final String DBFILE_NAME = "kontalk-messages.db"; private Fragment mFragment; public CopyDatabasePreference(Context context) { super(context); init(); } public CopyDatabasePreference(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CopyDatabasePreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public CopyDatabasePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { requestFile(getContext()); return true; } }); } public void setParentFragment(Fragment fragment) { mFragment = fragment; } void requestFile(Context context) { try { if (MediaStorage.isStorageAccessFrameworkAvailable()) { MediaStorage.createFile(mFragment, DBFILE_MIME, DBFILE_NAME, REQUEST_COPY_DATABASE); return; } } catch (ActivityNotFoundException e) { Log.w(TAG, "Storage Access Framework not working properly"); ReportingManager.logException(e); } // also used as a fallback if SAF is not working properly Context ctx = getContext(); if (ctx != null) { new FolderChooserDialog.Builder(ctx) .tag(getClass().getName()) .initialPath(Environment.getExternalStorageDirectory().toString()) .show(mFragment.getParentFragmentManager()); } } public static void copyDatabase(Context context, File dbOutFile) { OutputStream dbOut = null; try { dbOut = new FileOutputStream(dbOutFile); copyDatabase(context, dbOut, dbOut.toString()); } catch (IOException e) { Toast.makeText(context, context .getString(R.string.msg_copy_database_failed, e.toString()), Toast.LENGTH_LONG) .show(); } finally { DataUtils.close(dbOut); } } public static void copyDatabase(Context context, Uri dbOutFile) { OutputStream dbOut = null; try { dbOut = context.getContentResolver().openOutputStream(dbOutFile); copyDatabase(context, dbOut, dbOutFile.toString()); } catch (IOException e) { Toast.makeText(context, context .getString(R.string.msg_copy_database_failed, e.toString()), Toast.LENGTH_LONG) .show(); } finally { DataUtils.close(dbOut); } } private static void copyDatabase(Context context, OutputStream dbOut, String filename) { MessagesProvider.lockForImport(context); InputStream dbIn = null; try { dbIn = new FileInputStream(MessagesProvider.getDatabaseUri(context)); DataUtils.copy(dbIn, dbOut); Toast.makeText(context, context .getString(R.string.msg_copy_database_success, filename), Toast.LENGTH_LONG) .show(); } catch (IOException e) { Toast.makeText(context, context .getString(R.string.msg_copy_database_failed, e.toString()), Toast.LENGTH_LONG) .show(); } finally { DataUtils.close(dbIn); DataUtils.close(dbOut); } MessagesProvider.unlockForImport(context); } }
gpl-3.0
kaibioinfo/sirius
isotope_pattern/isotope_pattern_analysis/src/test/java/de/unijena/bioinf/IsotopePatternAnalysis/PatternExtractionTest.java
4222
package de.unijena.bioinf.IsotopePatternAnalysis; /** * Created by kaidu on 15.03.2015. */ public class PatternExtractionTest { /* @Test public void testPatternExtraction() { final MutableMeasurementProfile profile = new MutableMeasurementProfile(); profile.setAllowedMassDeviation(new Deviation(10,0.0002)); profile.setFormulaConstraints(FormulaConstraints.create("C", "H", "N", "O", "P", "S", "Mg")); final SimpleMutableSpectrum glucose = new SimpleMutableSpectrum(); glucose.addPeak(181.0707, 92.34); glucose.addPeak(182.0741, 6.34); glucose.addPeak(183.0753, 1.32); final SimpleMutableSpectrum chlorophyl = new SimpleMutableSpectrum(); chlorophyl.addPeak(619.2402, 53.52); chlorophyl.addPeak(620.2427, 27.58); chlorophyl.addPeak(621.2415, 14.69); chlorophyl.addPeak(622.2431, 4.22); final SimpleMutableSpectrum fictional = new SimpleMutableSpectrum(); // C12S5H10 fictional.addPeak(314.9459, 67.90); fictional.addPeak(315.9483, 11.61); fictional.addPeak(316.9422, 16.28); fictional.addPeak(317.9444, 2.55); fictional.addPeak(318.9387, 1.651); final SimpleMutableSpectrum fictional2 = new SimpleMutableSpectrum(); // C100H120 fictional2.addPeak(1321.9463, 33.80); fictional2.addPeak(1322.9497, 37.02); fictional2.addPeak(1323.9531, 20.081); fictional2.addPeak(1324.9565, 7.19); fictional2.addPeak(1325.9598, 1.91); final SimpleMutableSpectrum merged = new SimpleMutableSpectrum(); for (Peak p : glucose) merged.addPeak(p); for (Peak p : chlorophyl) merged.addPeak(p); for (Peak p : fictional) merged.addPeak(p); for (Peak p : fictional2) merged.addPeak(p); // add noise merged.addPeak(313.01, 0.01); merged.addPeak(320.001, 0.2); merged.addPeak(1320.082, 11); merged.addPeak(618.001, 120); final List<IsotopePattern> candidates = new ArrayList<IsotopePattern>(new ExtractAll().extractPatternMs1(profile, merged)); Collections.sort(candidates, new Comparator<IsotopePattern>() { @Override public int compare(IsotopePattern o1, IsotopePattern o2) { return Double.compare(o1.getMonoisotopicMass(), o2.getMonoisotopicMass()); } }); assertEquals(5, candidates.size()); assertTrue("isotope pattern of glucose with monoisotopic mass 181.0707", findCandidateWithMono(candidates, 181.0707)); assertTrue("isotope pattern of C12S5H10 with monoisotopic mass 314.9459", findCandidateWithMono(candidates, 314.9459)); assertTrue("isotope pattern of chlorophyl with monoisotopic mass 619.2402", findCandidateWithMono(candidates, 619.2402)); assertTrue("isotope pattern of C100H120 with monoisotopic mass 1321.9463", findCandidateWithMono(candidates, 1321.9463)); assertTrue("Maybe the isotope pattern at 1321.9463 is an overlap of two pattern. Therefore, allow both possibilities:", numberOfCandidatesWithMono(candidates,1321.9463)==2); assertEquals(314.9459, candidates.get(1).getMonoisotopicMass(), 1e-3); assertEquals(619.2402, candidates.get(2).getMonoisotopicMass(), 1e-3); assertEquals(1321.9463, candidates.get(3).getMonoisotopicMass(), 1e-3); assertEquals(glucose.size(), candidates.get(0).getPattern().size()); assertEquals(fictional.size(), candidates.get(1).getPattern().size()); assertEquals(chlorophyl.size(), candidates.get(2).getPattern().size()); assertEquals(fictional2.size(), candidates.get(3).getPattern().size()); } private static boolean findCandidateWithMono(List<IsotopePattern> patterns, double mono) { for (IsotopePattern p : patterns) { if (Math.abs(p.getMonoisotopicMass()-mono) < 1e-3) return true; } return false; } private static int numberOfCandidatesWithMono(List<IsotopePattern> patterns, double mono) { int c=0; for (IsotopePattern p : patterns) { if (Math.abs(p.getMonoisotopicMass()-mono) < 1e-3) ++c; } return c; } */ }
gpl-3.0
LEPTON-project/LEPTON_2
upload/modules/tinymce/tinymce/plugins/about/register_class_secure.php
577
<?php /** * @module about-plugin for TinyMCE * @version see info.php of this module * @authors Ryan Djurovich, Chio Maisriml, Thomas Hornik, Dietrich Roland Pehlke * @copyright 2004-2017 Ryan Djurovich, Chio Maisriml, Thomas Hornik, Dietrich Roland Pehlke * @license GNU General Public License * @license terms see info.php of this module * @platform see info.php of this module * */ $files_to_register = array( 'about.php' ); LEPTON_secure::getInstance()->accessFiles( $files_to_register ); ?>
gpl-3.0
old-town/workflow-zf2-dispatch
test/phpunit/Bootstrap.php
2381
<?php /** * @link https://github.com/old-town/workflow-zf2-dispatch * @author Malofeykin Andrey <and-rey2@yandex.ru> */ namespace OldTown\Workflow\ZF2\Dispatch\PhpUnit\Test; use Zend\Loader\AutoloaderFactory; use Zend\Loader\StandardAutoloader; use RuntimeException; error_reporting(E_ALL | E_STRICT); chdir(__DIR__); /** * Class Bootstrap * * @package OldTown\Workflow\ZF2\Dispatch\PhpUnit\Test */ class Bootstrap { /** * Настройка тестов * * @throws \RuntimeException */ public static function init() { static::initAutoloader(); } /** * Инициализация автозагрузчика * * @return void * * @throws RuntimeException */ protected static function initAutoloader() { $vendorPath = static::findParentPath('vendor'); if (is_readable($vendorPath . '/autoload.php')) { /** @noinspection PhpIncludeInspection */ include $vendorPath . '/autoload.php'; } if (!class_exists(AutoloaderFactory::class)) { $errMsg = 'Ошибка инициации автолоадеров'; throw new RuntimeException($errMsg); } try { AutoloaderFactory::factory([ StandardAutoloader::class => [ 'autoregister_zf' => true, 'namespaces' => [ 'OldTown\\Workflow\\ZF2\\Dispatch' => __DIR__ . '/../../src/', __NAMESPACE__ => __DIR__ . '/tests/', 'OldTown\\Workflow\\ZF2\\Dispatch\\PhpUnit\\TestData' => __DIR__ . '/_files', ] ] ]); } catch (\Exception $e) { $errMsg = 'Ошибка инициации автолоадеров'; throw new RuntimeException($errMsg, $e->getCode(), $e); } } /** * @param $path * * @return bool|string */ protected static function findParentPath($path) { $dir = __DIR__; $previousDir = '.'; while (!is_dir($dir . '/' . $path)) { $dir = dirname($dir); if ($previousDir === $dir) { return false; } $previousDir = $dir; } return $dir . '/' . $path; } } Bootstrap::init();
gpl-3.0
s20121035/rk3288_android5.1_repo
external/clang/test/CodeGenCXX/blocks-cxx11.cpp
3900
// RUN: %clang_cc1 %s -fblocks -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - | FileCheck %s template <class T> void takeItByValue(T); void takeABlock(void (^)()); // rdar://problem/11022704 namespace test_int { void test() { const int x = 100; takeABlock(^{ takeItByValue(x); }); // CHECK: call void @_Z13takeItByValueIiEvT_(i32 100) } } namespace test_int_ref { void test() { const int y = 200; const int &x = y; takeABlock(^{ takeItByValue(x); }); // TODO: there's no good reason that this isn't foldable. // CHECK: call void @_Z13takeItByValueIiEvT_(i32 {{%.*}}) } } namespace test_float { void test() { const float x = 1; takeABlock(^{ takeItByValue(x); }); // CHECK: call void @_Z13takeItByValueIfEvT_(float 1.0 } } namespace test_float_ref { void test() { const float y = 100; const float &x = y; takeABlock(^{ takeItByValue(x); }); // TODO: there's no good reason that this isn't foldable. // CHECK: call void @_Z13takeItByValueIfEvT_(float {{%.*}}) } } namespace test_complex_int { void test() { constexpr _Complex int x = 500; takeABlock(^{ takeItByValue(x); }); // CHECK: store { i32, i32 } { i32 500, i32 0 }, // CHECK: store i32 500, // CHECK-NEXT: store i32 0, // CHECK-NEXT: [[COERCE:%.*]] = bitcast // CHECK-NEXT: [[CVAL:%.*]] = load i64* [[COERCE]] // CHECK-NEXT: call void @_Z13takeItByValueICiEvT_(i64 [[CVAL]]) } } namespace test_complex_int_ref { void test() { const _Complex int y = 100; const _Complex int &x = y; takeABlock(^{ takeItByValue(x); }); // CHECK: call void @_Z13takeItByValueICiEvT_(i64 } } namespace test_complex_int_ref_mutable { _Complex int y = 100; void test() { const _Complex int &x = y; takeABlock(^{ takeItByValue(x); }); // CHECK: [[R:%.*]] = load i32* getelementptr inbounds ({ i32, i32 }* @_ZN28test_complex_int_ref_mutable1yE, i32 0, i32 0) // CHECK-NEXT: [[I:%.*]] = load i32* getelementptr inbounds ({ i32, i32 }* @_ZN28test_complex_int_ref_mutable1yE, i32 0, i32 1) // CHECK-NEXT: [[RSLOT:%.*]] = getelementptr inbounds { i32, i32 }* [[CSLOT:%.*]], i32 0, i32 0 // CHECK-NEXT: [[ISLOT:%.*]] = getelementptr inbounds { i32, i32 }* [[CSLOT]], i32 0, i32 1 // CHECK-NEXT: store i32 [[R]], i32* [[RSLOT]] // CHECK-NEXT: store i32 [[I]], i32* [[ISLOT]] // CHECK-NEXT: [[COERCE:%.*]] = bitcast { i32, i32 }* [[CSLOT]] to i64* // CHECK-NEXT: [[CVAL:%.*]] = load i64* [[COERCE]], // CHECK-NEXT: call void @_Z13takeItByValueICiEvT_(i64 [[CVAL]]) } } // rdar://13295759 namespace test_block_in_lambda { void takeBlock(void (^block)()); // The captured variable has to be non-POD so that we have a copy expression. struct A { void *p; A(const A &); ~A(); void use() const; }; void test(A a) { auto lambda = [a]() { takeBlock(^{ a.use(); }); }; lambda(); // make sure we emit the invocation function } // CHECK-LABEL: define internal void @"_ZZN20test_block_in_lambda4testENS_1AEENK3$_0clEv"( // CHECK: [[BLOCK:%.*]] = alloca [[BLOCK_T:<{.*}>]], align 8 // CHECK: [[THIS:%.*]] = load [[LAMBDA_T:%.*]]** // CHECK: [[TO_DESTROY:%.*]] = getelementptr inbounds [[BLOCK_T]]* [[BLOCK]], i32 0, i32 5 // CHECK: [[T0:%.*]] = getelementptr inbounds [[BLOCK_T]]* [[BLOCK]], i32 0, i32 5 // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds [[LAMBDA_T]]* [[THIS]], i32 0, i32 0 // CHECK-NEXT: call void @_ZN20test_block_in_lambda1AC1ERKS0_({{.*}}* [[T0]], {{.*}}* nonnull [[T1]]) // CHECK-NEXT: [[T0:%.*]] = bitcast [[BLOCK_T]]* [[BLOCK]] to void ()* // CHECK-NEXT: call void @_ZN20test_block_in_lambda9takeBlockEU13block_pointerFvvE(void ()* [[T0]]) // CHECK-NEXT: call void @_ZN20test_block_in_lambda1AD1Ev({{.*}}* [[TO_DESTROY]]) // CHECK-NEXT: ret void }
gpl-3.0
thequbit/mc911feedwatcher
web/tools/EventType.class.php
74
<? class EventType { public $eventtypeid; public $eventtype; } ?>
gpl-3.0
obulpathi/java
deitel/ch06/fig06_10/MethodOverload.java
2029
// Fig. 6.10: MethodOverload.java // Overloaded method declarations. public class MethodOverload { // test overloaded square methods public static void main( String[] args ) { System.out.printf( "Square of integer 7 is %d\n", square( 7 ) ); System.out.printf( "Square of double 7.5 is %f\n", square( 7.5 ) ); } // end main // square method with int argument public static int square( int intValue ) { System.out.printf( "\nCalled square with int argument: %d\n", intValue ); return intValue * intValue; } // end method square with int argument // square method with double argument public static double square( double doubleValue ) { System.out.printf( "\nCalled square with double argument: %f\n", doubleValue ); return doubleValue * doubleValue; } // end method square with double argument } // end class MethodOverload /************************************************************************** * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
gpl-3.0
ckaestne/LEADT
workspace/argouml_diagrams/argouml-app/src/org/argouml/uml/ui/behavior/common_behavior/PropPanelDestroyAction.java
2088
// $Id: PropPanelDestroyAction.java 13794 2007-11-20 01:08:14Z tfmorris $ // Copyright (c) 1996-2007 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui.behavior.common_behavior; /** * The properties panel for a DestroyAction. * <p> * TODO: this property panel needs refactoring to remove dependency on * old gui components. */ public class PropPanelDestroyAction extends PropPanelAction { /** * The constructor. * */ public PropPanelDestroyAction() { super("label.destroy-action", lookupIcon("DestroyAction")); } }
gpl-3.0
gohdan/DFC
known_files/hashes/modules/skin/bootstrap/js/charts/flot/jquery.flot.tooltip.js
47
HostCMS 6.7 = 031ba3e5111586efa89b1d42a3b9a807
gpl-3.0
Stratehm/multipool-stats-backend
src/main/java/strat/mining/multipool/stats/client/mvp/presenter/waffle/PaidoutViewPresenter.java
7684
/** * multipool-stats-backend is a web application which collects statistics * on several Switching-profit crypto-currencies mining pools and display * then in a Browser. * Copyright (C) 2014 Stratehm (stratehm@hotmail.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with multipool-stats-backend. If not, see <http://www.gnu.org/licenses/>. */ package strat.mining.multipool.stats.client.mvp.presenter.waffle; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import strat.mining.multipool.stats.client.factory.ClientFactory; import strat.mining.multipool.stats.client.mvp.event.EveryAddressPaidoutLoadedEvent; import strat.mining.multipool.stats.client.mvp.handler.EveryAddressPaidoutLoadHandler; import strat.mining.multipool.stats.client.mvp.view.waffle.PaidoutView; import strat.mining.multipool.stats.client.mvp.view.waffle.impl.PaidoutViewImpl; import strat.mining.multipool.stats.dto.AddressPaidoutDTO; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.i18n.shared.DateTimeFormat; import com.google.gwt.i18n.shared.DateTimeFormat.PredefinedFormat; import com.sencha.gxt.widget.core.client.event.HideEvent.HideHandler; public class PaidoutViewPresenter implements PaidoutView.PaidoutViewPresenter { private ClientFactory clientFactory; private PaidoutView view; private static final DateTimeFormat dateNormalizer = DateTimeFormat.getFormat(PredefinedFormat.DATE_SHORT); private List<String> requestedAddresses; public PaidoutViewPresenter(ClientFactory clientFactory, List<String> addresses, boolean isAllAddress) { this.clientFactory = clientFactory; this.requestedAddresses = addresses; String title = "Paidout for "; if (isAllAddress) { title += "all selected addresses"; } else { if (addresses != null) { for (String address : addresses) { title += address + ", "; } // remove the two last characters. title = title.substring(0, title.length() - 2); } } view = new PaidoutViewImpl(title); loadData(isAllAddress); } private void loadData(boolean isAllAddress) { // If all addresses selected, check if all addresses data are // available. Map<String, List<AddressPaidoutDTO>> addressesPaidout = clientFactory.getMainDataManager().getWaffleDataManager().getDataContainer() .getAddressesPaidout(); if (addressesPaidout.keySet().containsAll(requestedAddresses)) { // If data already available, then fill the graph fillGraph(addressesPaidout); } else { // If not already available, add a handler to be notified when // data are loaded clientFactory.getMainDataManager().getWaffleDataManager() .addEveryAddressPaidoutLoadHandler(new EveryAddressPaidoutLoadHandler<AddressPaidoutDTO>() { public void everyAddressPaidoutLoaded(EveryAddressPaidoutLoadedEvent<AddressPaidoutDTO> event) { fillGraph(event.getPaidout()); } }); // And request the load. clientFactory.getMainDataManager().getWaffleDataManager().loadAllPaidout(); } } /** * Fill the graph with the given data. * * @param addressesPaidout */ private void fillGraph(Map<String, List<AddressPaidoutDTO>> addressesPaidout) { Map<String, List<AddressPaidoutDTO>> clonedData = new HashMap<String, List<AddressPaidoutDTO>>(); // Keep only requested addresses for (String address : requestedAddresses) { List<AddressPaidoutDTO> addressPaidout = addressesPaidout.get(address); if (addressPaidout != null) { clonedData.put(address, new ArrayList<AddressPaidoutDTO>(addressPaidout)); } else { clonedData.put(address, new ArrayList<AddressPaidoutDTO>()); } } // If several addresses to display, normalize the data. // if (clonedData.size() > 1) { normalizeData(clonedData); // } // Then display all addresses for (Entry<String, List<AddressPaidoutDTO>> entry : clonedData.entrySet()) { view.addAddressPaidout(entry.getKey(), entry.getValue()); } } /** * Add missing data in all series. At the end of the method, all series have * the same number of data. * * @param addressesPaidout */ private void normalizeData(Map<String, List<AddressPaidoutDTO>> addressesPaidout) { if (addressesPaidout != null) { Map<String, Map<Date, List<AddressPaidoutDTO>>> addressPaidoutByDate = new HashMap<String, Map<Date, List<AddressPaidoutDTO>>>(); Set<Date> dateSet = new HashSet<Date>(); // Build a map from the initial one. for (Entry<String, List<AddressPaidoutDTO>> entry : addressesPaidout.entrySet()) { Map<Date, List<AddressPaidoutDTO>> paidoutByDate = new HashMap<Date, List<AddressPaidoutDTO>>(); for (AddressPaidoutDTO paidout : entry.getValue()) { Date date = dateNormalizer.parse(dateNormalizer.format(paidout.getTime())); dateSet.add(date); // If the date is already present, add the transaction to // the already present one List<AddressPaidoutDTO> alreadyPresentPaidout = paidoutByDate.get(date); if (alreadyPresentPaidout == null) { alreadyPresentPaidout = new ArrayList<AddressPaidoutDTO>(); paidoutByDate.put(date, alreadyPresentPaidout); } alreadyPresentPaidout.add(paidout); } addressPaidoutByDate.put(entry.getKey(), paidoutByDate); } // Fill missing date in all series for (Map<Date, List<AddressPaidoutDTO>> paidoutByDate : addressPaidoutByDate.values()) { for (Date date : dateSet) { // If the dto does not exist for the given date, then create // a fake dto. if (!paidoutByDate.containsKey(date)) { List<AddressPaidoutDTO> dtos = new ArrayList<AddressPaidoutDTO>(); AddressPaidoutDTO dto = new AddressPaidoutDTO(); dto.setAmount(0F); dto.setTime(date); dto.setTransactionId(null); dtos.add(dto); paidoutByDate.put(date, dtos); } } } // For all address, sort the new list of DTOs for (Entry<String, Map<Date, List<AddressPaidoutDTO>>> entry : addressPaidoutByDate.entrySet()) { List<AddressPaidoutDTO> dtos = new ArrayList<AddressPaidoutDTO>(); for (List<AddressPaidoutDTO> dateDtos : entry.getValue().values()) { dtos.addAll(dateDtos); } Collections.sort(dtos, new Comparator<AddressPaidoutDTO>() { public int compare(AddressPaidoutDTO o1, AddressPaidoutDTO o2) { return o1.getTime().compareTo(o2.getTime()); } }); // Replace the list of DTOs with the new one for the given // address. addressesPaidout.put(entry.getKey(), dtos); } } } @Override public PaidoutView getView() { return view; } @Override public HandlerRegistration addHideHandler(HideHandler handler) { return view.addHideHandler(handler); } @Override public void bringToFront() { if (view != null) { view.show(); } } @Override public ClientFactory getClientFactory() { return clientFactory; } @Override public void hide() { view.hide(); } @Override public void activate() { view.activate(); } }
gpl-3.0
siviotti/ubre
ubre-core/src/main/java/br/net/ubre/data/var/Datex.java
4543
package br.net.ubre.data.var; import java.text.DateFormat; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.logging.Logger; import br.net.ubre.exception.CTDException; import br.net.ubre.exception.FreezeException; /** * [DATE EXTENSION] Data imutável estendida. * * @author Douglas Siviotti (073.116.317-69) * @version 21/10/2015 * */ public class Datex extends Date { private static final String DATEX_CANNOT_CHANGE = "O código fonte está tentando fazer uma alteração indevida em um objeto imutável da classe Datex"; private static final String DATEX_INVALID_TOKEN = "Data ou hora inválida:"; public static final long MILIS_IN_ONE_DAY = 86400000; // 1000 * 60 * 60 * 24 private static final Logger LOGGER = Logger.getLogger("Datex"); private static final long serialVersionUID = 1L; public static final Datex ZERO = new Datex("01/01/0001 00:00:00"); private boolean useDate; private boolean useTime; public Datex(String source) { super(); if (source.contains("/")) { useDate = true; if (source.contains(":")) { useTime = true; } else { useTime = false; } } else { useTime = true; } DateFormat dateFormat = getDateFormat(); Date date; try { date = dateFormat.parse(source); } catch (ParseException e) { throw new CTDException(DATEX_INVALID_TOKEN, e); } super.setTime(date.getTime()); } /** * Cria uma instância com milisegundos igual a uma instância de Date. * Equivale a fazer <code>new Date()</code>. Este construtor não faz nenhuma * formatação e é muito mais rápido (100 vezes) que o que recebe dois * booleanos. */ public Datex() { useDate = true; useTime = true; super.setTime(new Date().getTime()); } public Datex(boolean useDate, boolean useTime) { this.useDate = useDate; this.useTime = useTime; super.setTime(new Date().getTime()); DateFormat dateFormat = getDateFormat(); String source = dateFormat.format(this); try { super.setTime(dateFormat.parse(source).getTime()); } catch (ParseException e) { throw new CTDException(DATEX_INVALID_TOKEN, e); } } /** * Construtor para datas sem time a partir dos campos ano, mês e dia * separados. * * @param year * O inteiro que corresponde ao ano. * @param month * O número do mês de 1:Janeiro até 12:Dezembro. * @param day * O inteiro do dia dentro do mês (1 a 31). */ public Datex(int year, int month, int day) { Calendar calendar = new GregorianCalendar(year, month - 1, day); super.setTime(calendar.getTimeInMillis()); useDate = true; useTime = false; } public Datex(long timeInMillis) { super(timeInMillis); useDate = true; useTime = true; } public DateFormat getDateFormat() { if (useDate) { if (useTime) { return DateFormat.getDateTimeInstance(); } else { return DateFormat.getDateInstance(); } } else { if (useTime) { return DateFormat.getTimeInstance(); } else { return DateFormat.getDateInstance(); } } } // ********** Aritimética de Datas ********** /** * Retorna quantos dias faltam da data atual pára a data passada como * parâmetro. Se a data passada for anterior á data atual será retornado um * número negativo. * * @param date * A data de comparação sobre a qual será feita a diferença. * @return A diferença em dias */ public long daysTo(Date date) { long dif = date.getTime() - getTime(); return dif / MILIS_IN_ONE_DAY; } // ********** Override de Date ********** @Override public void setTime(long time) { LOGGER.warning(DATEX_CANNOT_CHANGE); } @Override public void setDate(int date) { LOGGER.warning(DATEX_CANNOT_CHANGE); } @Override public void setHours(int hours) { LOGGER.warning(DATEX_CANNOT_CHANGE); } @Override public void setMinutes(int minutes) { LOGGER.warning(DATEX_CANNOT_CHANGE); } @Override public void setMonth(int month) { LOGGER.warning(DATEX_CANNOT_CHANGE); } @Override public void setSeconds(int seconds) { LOGGER.warning(DATEX_CANNOT_CHANGE); } @Override public void setYear(int year) { LOGGER.warning(DATEX_CANNOT_CHANGE); } @Override public String toString() { return asFormatted(); } // ********** GET / SET ********** public boolean isUseDate() { return useDate; } public boolean isUseTime() { return useTime; } public String asFormatted() { return getDateFormat().format(this); } }
gpl-3.0
alicechoi8/Aura
src/ChannelServer/Skills/SkillHelper.cs
5997
// Copyright (c) Aura development team - Licensed under GNU GPL // For more information, see license file in the main folder using Aura.Channel.Network.Sending; using Aura.Channel.Skills.Base; using Aura.Channel.Skills.Combat; using Aura.Channel.World.Entities; using Aura.Shared.Mabi.Const; using Aura.Shared.Util; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aura.Channel.Skills { public static class SkillHelper { private const int DefenseAttackerStun = 2500; private const int DefenseTargetStun = 1000; /// <summary> /// Checks if target's Mana Shield is active, calculates mana /// damage, and sets target action's Mana Damage property if applicable. /// </summary> /// <param name="target"></param> /// <param name="damage"></param> /// <param name="tAction"></param> public static void HandleManaShield(Creature target, ref float damage, TargetAction tAction) { // Mana Shield active? if (!target.Conditions.Has(ConditionsA.ManaShield)) return; // Get Mana Shield skill to get the rank's vars var manaShield = target.Skills.Get(SkillId.ManaShield); if (manaShield == null) // Checks for things that should never ever happen, yay. return; // Var 1 = Efficiency var manaDamage = damage / manaShield.RankData.Var1; if (target.Mana >= manaDamage) { // Damage is 0 if target's mana is enough to cover it damage = 0; } else { // Set mana damage to target's mana and reduce the remaining // damage from life if the mana is not enough. damage -= (manaDamage - target.Mana) * manaShield.RankData.Var1; manaDamage = target.Mana; } // Reduce mana target.Mana -= manaDamage; if (target.Mana <= 0) ChannelServer.Instance.SkillManager.GetHandler<StartStopSkillHandler>(SkillId.ManaShield).Stop(target, manaShield); tAction.ManaDamage = manaDamage; } /// <summary> /// Checks if attacker has Critical Hit and applies crit bonus /// by chance. Also sets the target action's critical option if a /// crit happens. /// </summary> /// <param name="attacker"></param> /// <param name="critChance"></param> /// <param name="damage"></param> /// <param name="tAction"></param> public static void HandleCritical(Creature attacker, float critChance, ref float damage, TargetAction tAction) { // Check if attacker actually has critical hit var critSkill = attacker.Skills.Get(SkillId.CriticalHit); if (critSkill == null) return; // Does the crit happen? if (RandomProvider.Get().NextDouble() > critChance) return; // Add crit bonus var bonus = critSkill.RankData.Var1 / 100f; damage = damage + (damage * bonus); // Set target option tAction.Set(TargetOptions.Critical); } /// <summary> /// Checks if target has Defense skill activated and makes the necessary /// changes to the actions, stun times, and damage. /// </summary> /// <param name="aAction"></param> /// <param name="tAction"></param> /// <param name="damage"></param> /// <returns></returns> public static bool HandleDefense(AttackerAction aAction, TargetAction tAction, ref float damage) { // Defense if (!tAction.Creature.Skills.IsActive(SkillId.Defense)) return false; // Update actions tAction.Type = CombatActionType.Defended; tAction.SkillId = SkillId.Defense; tAction.Creature.Stun = tAction.Stun = DefenseTargetStun; aAction.Creature.Stun = aAction.Stun = DefenseAttackerStun; // Reduce damage var defenseSkill = tAction.Creature.Skills.Get(SkillId.Defense); if (defenseSkill != null) damage -= defenseSkill.RankData.Var3; Send.SkillUseStun(tAction.Creature, SkillId.Defense, 1000, 0); return true; } /// <summary> /// Reduces damage by target's defense and protection. /// </summary> /// <param name="target"></param> /// <param name="damage"></param> /// <param name="defense"></param> /// <param name="protection"></param> public static void HandleDefenseProtection(Creature target, ref float damage, bool defense = true, bool protection = true) { if (defense) damage = Math.Max(1, damage - target.Defense); if (protection && damage > 1) damage = Math.Max(1, damage - (damage * target.Protection)); } /// <summary> /// Returns true if target has counter active and used it. /// </summary> /// <param name="target"></param> /// <param name="attacker"></param> /// <returns></returns> public static bool HandleCounter(Creature target, Creature attacker) { if (!target.Skills.IsActive(SkillId.Counterattack)) return false; var handler = ChannelServer.Instance.SkillManager.GetHandler<Counterattack>(SkillId.Counterattack); handler.Use(target, attacker); return true; } /// <summary> /// Reduces weapon's durability and increases its proficiency. /// Only updates weapon type items that are not null. /// </summary> /// <param name="creature"></param> /// <param name="weapon"></param> public static void UpdateWeapon(Creature attacker, Creature target, params Item[] weapons) { if (attacker == null) return; var rnd = RandomProvider.Get(); foreach (var weapon in weapons.Where(a => a != null && a.IsTrainableWeapon)) { // Durability if (!ChannelServer.Instance.Conf.World.NoDurabilityLoss) { weapon.Durability -= rnd.Next(1, 30); Send.ItemDurabilityUpdate(attacker, weapon); } // Proficiency // Only if the weapon isn't broken and the target is not "Weakest". if (weapon.Durability != 0 && attacker != null && attacker.GetPowerRating(target) >= PowerRating.Weak) { short prof = 0; if (attacker.Age >= 10 && attacker.Age <= 12) prof = 48; else if (attacker.Age >= 13 && attacker.Age <= 19) prof = 60; else prof = 72; weapon.Proficiency += prof; Send.ItemExpUpdate(attacker, weapon); } } } } }
gpl-3.0
BackupTheBerlios/openmm
src/plugin/Sink/Alsa/AlsaAudioSink.cpp
8479
/***************************************************************************| | OMM - Open Multimedia | | | | Copyright (C) 2009, 2010 | | Jörg Bakker (jb'at'open-multimedia.org) | | | | This file is part of OMM. | | | | OMM is free software: you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation version 3 of the License. | | | | OMM is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License | | along with this program. If not, see <http://www.gnu.org/licenses/>. | ***************************************************************************/ #include <Poco/ClassLibrary.h> #include <Poco/Format.h> #include <Poco/NumberFormatter.h> #include <Poco/RunnableAdapter.h> #include <Omm/Log.h> #include "AlsaAudioSink.h" AlsaAudioSink::AlsaAudioSink() : AudioSink("alsa audio sink"), _writeThread(getName() + " write thread"), _writeThreadRunnable(*this, &AlsaAudioSink::writeThread), _quitWriteThread(false), _pcmPlayback(0), _device("default"), _format(SND_PCM_FORMAT_S16), _rate(48000), _channels(2), _periods(2), _startPeriodSize(8192), _periodSize(_startPeriodSize), _bufferSize(0), _buffer(0) { if (!open()) { LOGNS(Omm::AvStream, avstream, error, "can not open ALSA PCM device."); } } AlsaAudioSink::~AlsaAudioSink() { close(); delete _buffer; } bool AlsaAudioSink::open() { return open("default"); } bool AlsaAudioSink::open(const std::string& _device) { LOGNS(Omm::AvStream, avstream, debug, Poco::format("%s opening with device: %s", getName(), _device)); int err = snd_pcm_open(&_pcmPlayback, _device.c_str(), SND_PCM_STREAM_PLAYBACK, 0); if (err < 0) { LOGNS(Omm::AvStream, avstream, error, Poco::format("%s could not open device: %s", getName(), _device)); return false; } LOGNS(Omm::AvStream, avstream, debug, Poco::format("%s opened.", getName())); return true; } void AlsaAudioSink::close() { if (_pcmPlayback) { snd_pcm_close(_pcmPlayback); } LOGNS(Omm::AvStream, avstream, debug, Poco::format("%s closed.", getName())); } bool AlsaAudioSink::initDevice() { snd_pcm_hw_params_alloca(&_hwParams); if (snd_pcm_hw_params_any(_pcmPlayback, _hwParams) < 0) { LOGNS(Omm::AvStream, avstream, error, "can not configure PCM device."); return false; } if (snd_pcm_hw_params_set_access(_pcmPlayback, _hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) < 0) { LOGNS(Omm::AvStream, avstream, error, "setting PCM device access."); return false; } if (snd_pcm_hw_params_set_format(_pcmPlayback, _hwParams, _format) < 0) { LOGNS(Omm::AvStream, avstream, error, "setting PCM device format."); return false; } _rate = sampleRate(); if (snd_pcm_hw_params_set_rate_near(_pcmPlayback, _hwParams, &_rate, 0) < 0) { LOGNS(Omm::AvStream, avstream, error, "setting PCM device rate to: " + Poco::NumberFormatter::format(_rate)); return false; } _channels = channels(); if (snd_pcm_hw_params_set_channels(_pcmPlayback, _hwParams, _channels) < 0) { LOGNS(Omm::AvStream, avstream, error, "setting PCM device channels to: " + Poco::NumberFormatter::format(_channels)); return false; } // if (snd_pcm_hw_params_set_periods(_pcmPlayback, _hwParams, _periods, 0) < 0) { // LOGNS(Omm::AvStream, avstream, error, "setting PCM device periods."); // return false; // } // Set buffer size (in frames). The resulting latency is given by // latency = periodSize * periods / (rate * bytes_per_frame) // snd_pcm_uframes_t bufferSizeInFrames = (_startPeriodSize * _periods) >> 2; snd_pcm_uframes_t bufferSizeInFrames = frameCount(_startPeriodSize * _channels); if (int ret = snd_pcm_hw_params_set_buffer_size_near(_pcmPlayback, _hwParams, &bufferSizeInFrames)) { LOGNS(Omm::AvStream, avstream, error, getName() + " setting up PCM device buffer to size: " + Poco::NumberFormatter::format(_bufferSize) + " returns: " + Poco::NumberFormatter::format(ret)); return false; } if (_buffer) { delete _buffer; } _bufferSize = byteCount(bufferSizeInFrames); _buffer = new char[_bufferSize]; LOGNS(Omm::AvStream, avstream, debug, getName() + " setting up PCM device buffer to number of frames: " + Poco::NumberFormatter::format(bufferSizeInFrames) + ", audio read buffer size in bytes is: " + Poco::NumberFormatter::format(_bufferSize)); _periodSize = _startPeriodSize; if (int ret = snd_pcm_hw_params_set_period_size_near(_pcmPlayback, _hwParams, &_periodSize, 0)) { LOGNS(Omm::AvStream, avstream, error, getName() + " setting up PCM device period to size: " + Poco::NumberFormatter::format(_periodSize) + " returns: " + Poco::NumberFormatter::format(ret)); return false; } if (snd_pcm_hw_params(_pcmPlayback, _hwParams) < 0) { LOGNS(Omm::AvStream, avstream, error, getName() + " initializing device."); return false; } return true; } bool AlsaAudioSink::closeDevice() { return true; } void AlsaAudioSink::startPresentation() { LOGNS(Omm::AvStream, avstream, debug, getName() + " starting write thread ..."); _writeThread.start(_writeThreadRunnable); _writeThread.setPriority(Poco::Thread::PRIO_HIGHEST); } void AlsaAudioSink::stopPresentation() { LOGNS(Omm::AvStream, avstream, debug, getName() + " stopping write thread ..."); setStopWriting(true); } void AlsaAudioSink::waitPresentationStop() { LOGNS(Omm::AvStream, avstream, debug, getName() + " trying to join write thread ..."); try { if (_writeThread.isRunning()) { _writeThread.join(500); } } catch(...) { LOGNS(Omm::AvStream, avstream, warning, getName() + " failed to cleanly shutdown alsa audio write thread"); } setStopWriting(false); LOGNS(Omm::AvStream, avstream, debug, getName() + " write thread joined."); if (_pcmPlayback) { snd_pcm_drop(_pcmPlayback); } } void AlsaAudioSink::writeThread() { LOGNS(Omm::AvStream, avstream, debug, "alsa audio sink write thread started."); const int bufferSizeInFrames = frameCount(_bufferSize); while(!getStopWriting()) { audioReadBlocking(_buffer, _bufferSize); int samplesWritten = 0; LOGNS(Omm::AvStream, avstream, trace, "alsa audio sink write thread, trying to write " + Poco::NumberFormatter::format(_bufferSize) + " bytes"); // last parameter of snd_pcm_writei are the number of frames (not bytes) to write to the pcm ringbuffer while ((samplesWritten = snd_pcm_writei(_pcmPlayback, _buffer, bufferSizeInFrames)) < 0) { snd_pcm_prepare(_pcmPlayback); LOGNS(Omm::AvStream, avstream, warning, "<<<<<<<<<<<<<<< " + getName() + " buffer underrun >>>>>>>>>>>>>>>"); } LOGNS(Omm::AvStream, avstream, trace, "alsa audio sink write thread, bytes written: " + Poco::NumberFormatter::format(samplesWritten << 2)); } LOGNS(Omm::AvStream, avstream, debug, "alsa audio sink write thread finished."); } void AlsaAudioSink::setStopWriting(bool stop) { _writeLock.lock(); _quitWriteThread = stop; _writeLock.unlock(); } bool AlsaAudioSink::getStopWriting() { bool stop = false; _writeLock.lock(); stop = _quitWriteThread; _writeLock.unlock(); return stop; } #ifdef OMMPLUGIN POCO_BEGIN_MANIFEST(Omm::AvStream::AudioSink) POCO_EXPORT_CLASS(AlsaAudioSink) POCO_END_MANIFEST #endif
gpl-3.0
dyarob/SpaceRamble
Gam_Ramble.class.hpp
130
#ifndef GAM_RAMBLE_CLASS_HPP #define GAM_RAMBLE_CLASS_HPP #include "Game.class.hpp" class Gam_Ramble : public Game { }; #endif
gpl-3.0
memphis518/UrbanHitchhiker
spec/decorators/trip_decorator_spec.rb
53
require 'spec_helper' describe TripDecorator do end
gpl-3.0
eXistence/fhDOOM
neo/renderer/tr_lightrun.cpp
23313
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../idlib/precompiled.h" #pragma hdrstop #include "tr_local.h" /* Prelight models "_prelight_<lightname>", ie "_prelight_light1" Static surfaces available to dmap will be processed to optimized shadow and lit surface geometry Entity models are never prelighted. Light entity can have a "noPrelight 1" key set to avoid the preprocessing and carving of the world. A light that will move should usually have this set. Prelight models will usually have multiple surfaces Shadow volume surfaces will have the material "_shadowVolume" The exact same vertexes as the ambient surfaces will be used for the non-shadow surfaces, so there is opportunity to share Reference their parent surfaces? Reference their parent area? If we don't track parts that are in different areas, there will be huge losses when an areaportal closed door has a light poking slightly through it. There is potential benefit to splitting even the shadow volumes at area boundaries, but it would involve the possibility of an extra plane of shadow drawing at the area boundary. interaction lightName numIndexes Shadow volume surface Surfaces in the world cannot have "no self shadow" properties, because all the surfaces are considered together for the optimized shadow volume. If you want no self shadow on a static surface, you must still make it into an entity so it isn't considered in the prelight. r_hidePrelights r_hideNonPrelights each surface could include prelight indexes generation procedure in dmap: carve original surfaces into areas for each light build shadow volume and beam tree cut all potentially lit surfaces into the beam tree move lit fragments into a new optimize group optimize groups build light models */ /* ================================================================================= LIGHT TESTING ================================================================================= */ /* ==================== R_ModulateLights_f Modifies the shaderParms on all the lights so the level designers can easily test different color schemes ==================== */ void R_ModulateLights_f( const idCmdArgs &args ) { if ( !tr.primaryWorld ) { return; } if ( args.Argc() != 4 ) { common->Printf( "usage: modulateLights <redFloat> <greenFloat> <blueFloat>\n" ); return; } float modulate[3]; int i; for ( i = 0 ; i < 3 ; i++ ) { modulate[i] = atof( args.Argv( i+1 ) ); } int count = 0; for ( i = 0 ; i < tr.primaryWorld->lightDefs.Num() ; i++ ) { idRenderLightLocal *light; light = tr.primaryWorld->lightDefs[i]; if ( light ) { count++; for ( int j = 0 ; j < 3 ; j++ ) { light->parms.shaderParms[j] *= modulate[j]; } } } common->Printf( "modulated %i lights\n", count ); } //====================================================================================== /* =============== R_CreateEntityRefs Creates all needed model references in portal areas, chaining them to both the area and the entityDef. Bumps tr.viewCount. =============== */ void R_CreateEntityRefs( idRenderEntityLocal *def ) { int i; idVec3 transformed[8]; idVec3 v; if ( !def->parms.hModel ) { def->parms.hModel = renderModelManager->DefaultModel(); } // if the entity hasn't been fully specified due to expensive animation calcs // for md5 and particles, use the provided conservative bounds. if ( def->parms.callback ) { def->referenceBounds = def->parms.bounds; } else { def->referenceBounds = def->parms.hModel->Bounds( &def->parms ); } // some models, like empty particles, may not need to be added at all if ( def->referenceBounds.IsCleared() ) { return; } if ( r_showUpdates.GetBool() && ( def->referenceBounds[1][0] - def->referenceBounds[0][0] > 1024 || def->referenceBounds[1][1] - def->referenceBounds[0][1] > 1024 ) ) { common->Printf( "big entityRef: %f,%f\n", def->referenceBounds[1][0] - def->referenceBounds[0][0], def->referenceBounds[1][1] - def->referenceBounds[0][1] ); } for (i = 0 ; i < 8 ; i++) { v[0] = def->referenceBounds[i&1][0]; v[1] = def->referenceBounds[(i>>1)&1][1]; v[2] = def->referenceBounds[(i>>2)&1][2]; R_LocalPointToGlobal( def->modelMatrix, v, transformed[i] ); } // bump the view count so we can tell if an // area already has a reference tr.viewCount++; // push these points down the BSP tree into areas def->world->PushVolumeIntoTree( def, NULL, 8, transformed ); } /* ================================================================================= CREATE LIGHT REFS ================================================================================= */ /* ===================== R_SetLightProject All values are reletive to the origin Assumes that right and up are not normalized This is also called by dmap during map processing. ===================== */ void R_SetLightProject( idPlane lightProject[4], const idVec3 origin, const idVec3 target, const idVec3 rightVector, const idVec3 upVector, const idVec3 start, const idVec3 stop ) { float dist; float scale; float rLen, uLen; idVec3 normal; float ofs; idVec3 right, up; idVec3 startGlobal; idVec4 targetGlobal; right = rightVector; rLen = right.Normalize(); up = upVector; uLen = up.Normalize(); normal = up.Cross( right ); //normal = right.Cross( up ); normal.Normalize(); dist = target * normal; // - ( origin * normal ); if ( dist < 0 ) { dist = -dist; normal = -normal; } scale = ( 0.5f * dist ) / rLen; right *= scale; scale = -( 0.5f * dist ) / uLen; up *= scale; lightProject[2] = normal; lightProject[2][3] = -( origin * lightProject[2].Normal() ); lightProject[0] = right; lightProject[0][3] = -( origin * lightProject[0].Normal() ); lightProject[1] = up; lightProject[1][3] = -( origin * lightProject[1].Normal() ); // now offset to center targetGlobal.ToVec3() = target + origin; targetGlobal[3] = 1; ofs = 0.5f - ( targetGlobal * lightProject[0].ToVec4() ) / ( targetGlobal * lightProject[2].ToVec4() ); lightProject[0].ToVec4() += ofs * lightProject[2].ToVec4(); ofs = 0.5f - ( targetGlobal * lightProject[1].ToVec4() ) / ( targetGlobal * lightProject[2].ToVec4() ); lightProject[1].ToVec4() += ofs * lightProject[2].ToVec4(); // set the falloff vector normal = stop - start; dist = normal.Normalize(); if ( dist <= 0 ) { dist = 1; } lightProject[3] = normal * ( 1.0f / dist ); startGlobal = start + origin; lightProject[3][3] = -( startGlobal * lightProject[3].Normal() ); } /* =================== R_SetLightFrustum Creates plane equations from the light projection, positive sides face out of the light =================== */ void R_SetLightFrustum( const idPlane lightProject[4], idPlane frustum[6] ) { int i; // we want the planes of s=0, s=q, t=0, and t=q frustum[0] = lightProject[0]; frustum[1] = lightProject[1]; frustum[2] = lightProject[2] - lightProject[0]; frustum[3] = lightProject[2] - lightProject[1]; // we want the planes of s=0 and s=1 for front and rear clipping planes frustum[4] = lightProject[3]; frustum[5] = lightProject[3]; frustum[5][3] -= 1.0f; frustum[5] = -frustum[5]; for ( i = 0 ; i < 6 ; i++ ) { float l; frustum[i] = -frustum[i]; l = frustum[i].Normalize(); frustum[i][3] /= l; } } /* ==================== R_FreeLightDefFrustum ==================== */ void R_FreeLightDefFrustum( idRenderLightLocal *ldef ) { int i; // free the frustum tris if ( ldef->frustumTris ) { R_FreeStaticTriSurf( ldef->frustumTris ); ldef->frustumTris = NULL; } // free frustum windings for ( i = 0; i < 6; i++ ) { if ( ldef->frustumWindings[i] ) { delete ldef->frustumWindings[i]; ldef->frustumWindings[i] = NULL; } } } /* ================= R_DeriveLightData Fills everything in based on light->parms ================= */ void R_DeriveLightData( idRenderLightLocal *light ) { int i; // decide which light shader we are going to use if ( light->parms.shader ) { light->lightShader = light->parms.shader; } if ( !light->lightShader ) { if ( light->parms.pointLight ) { light->lightShader = declManager->FindMaterial( "lights/defaultPointLight" ); } else { light->lightShader = declManager->FindMaterial( "lights/defaultProjectedLight" ); } } // get the falloff image light->falloffImage = light->lightShader->LightFalloffImage(); if ( !light->falloffImage ) { // use the falloff from the default shader of the correct type const idMaterial *defaultShader; if ( light->parms.pointLight ) { defaultShader = declManager->FindMaterial( "lights/defaultPointLight" ); light->falloffImage = defaultShader->LightFalloffImage(); } else { // projected lights by default don't diminish with distance defaultShader = declManager->FindMaterial( "lights/defaultProjectedLight" ); light->falloffImage = defaultShader->LightFalloffImage(); } } // set the projection if ( !light->parms.pointLight ) { // projected light R_SetLightProject( light->lightProject, vec3_origin /* light->parms.origin */, light->parms.target, light->parms.right, light->parms.up, light->parms.start, light->parms.end); } else { // point light memset( light->lightProject, 0, sizeof( light->lightProject ) ); light->lightProject[0][0] = 0.5f / light->parms.lightRadius[0]; light->lightProject[1][1] = 0.5f / light->parms.lightRadius[1]; light->lightProject[3][2] = 0.5f / light->parms.lightRadius[2]; light->lightProject[0][3] = 0.5f; light->lightProject[1][3] = 0.5f; light->lightProject[2][3] = 1.0f; light->lightProject[3][3] = 0.5f; } // set the frustum planes R_SetLightFrustum( light->lightProject, light->frustum ); // rotate the light planes and projections by the axis R_AxisToModelMatrix( light->parms.axis, light->parms.origin, light->modelMatrix ); for ( i = 0 ; i < 6 ; i++ ) { idPlane temp; temp = light->frustum[i]; R_LocalPlaneToGlobal( light->modelMatrix, temp, light->frustum[i] ); } for ( i = 0 ; i < 4 ; i++ ) { idPlane temp; temp = light->lightProject[i]; R_LocalPlaneToGlobal( light->modelMatrix, temp, light->lightProject[i] ); } // adjust global light origin for off center projections and parallel projections // we are just faking parallel by making it a very far off center for now if ( light->parms.parallel ) { idVec3 dir; dir = light->parms.lightCenter; if ( !dir.Normalize() ) { // make point straight up if not specified dir[2] = 1; } light->globalLightOrigin = light->parms.origin + dir * 100000; } else { light->globalLightOrigin = light->parms.origin + light->parms.axis * light->parms.lightCenter; } R_FreeLightDefFrustum( light ); light->frustumTris = R_PolytopeSurface( 6, light->frustum, light->frustumWindings ); // a projected light will have one shadowFrustum, a point light will have // six unless the light center is outside the box R_MakeShadowFrustums( light ); // Rendering shadow maps requires a slightly different frustum (needs to be // symmetric, even if the light itself is not symmetric (globalLightOrigin // not centered) R_MakeShadowMapFrustums( light ); } /* ================= R_CreateLightRefs ================= */ #define MAX_LIGHT_VERTS 40 void R_CreateLightRefs( idRenderLightLocal *light ) { idVec3 points[MAX_LIGHT_VERTS]; int i; srfTriangles_t *tri; tri = light->frustumTris; // because a light frustum is made of only six intersecting planes, // we should never be able to get a stupid number of points... if ( tri->numVerts > MAX_LIGHT_VERTS ) { common->Error( "R_CreateLightRefs: %i points in frustumTris!", tri->numVerts ); } for ( i = 0 ; i < tri->numVerts ; i++ ) { points[i] = tri->verts[i].xyz; } if ( r_showUpdates.GetBool() && ( tri->bounds[1][0] - tri->bounds[0][0] > 1024 || tri->bounds[1][1] - tri->bounds[0][1] > 1024 ) ) { common->Printf( "big lightRef: %f,%f\n", tri->bounds[1][0] - tri->bounds[0][0] ,tri->bounds[1][1] - tri->bounds[0][1] ); } // determine the areaNum for the light origin, which may let us // cull the light if it is behind a closed door // it is debatable if we want to use the entity origin or the center offset origin, // but we definitely don't want to use a parallel offset origin light->areaNum = light->world->PointInArea( light->globalLightOrigin ); if ( light->areaNum == -1 ) { light->areaNum = light->world->PointInArea( light->parms.origin ); } // bump the view count so we can tell if an // area already has a reference tr.viewCount++; // if we have a prelight model that includes all the shadows for the major world occluders, // we can limit the area references to those visible through the portals from the light center. // We can't do this in the normal case, because shadows are cast from back facing triangles, which // may be in areas not directly visible to the light projection center. if ( light->parms.prelightModel && r_useLightPortalFlow.GetBool() && light->lightShader->LightCastsShadows() ) { light->world->FlowLightThroughPortals( light ); } else { // push these points down the BSP tree into areas light->world->PushVolumeIntoTree( NULL, light, tri->numVerts, points ); } } /* =============== R_RenderLightFrustum Called by the editor and dmap to operate on light volumes =============== */ void R_RenderLightFrustum( const renderLight_t &renderLight, idPlane lightFrustum[6] ) { idRenderLightLocal fakeLight; fakeLight.parms = renderLight; R_DeriveLightData( &fakeLight ); R_FreeStaticTriSurf( fakeLight.frustumTris ); for ( int i = 0 ; i < 6 ; i++ ) { lightFrustum[i] = fakeLight.frustum[i]; } } //================================================================================= /* =============== WindingCompletelyInsideLight =============== */ bool WindingCompletelyInsideLight( const idWinding *w, const idRenderLightLocal *ldef ) { int i, j; for ( i = 0 ; i < w->GetNumPoints() ; i++ ) { for ( j = 0 ; j < 6 ; j++ ) { float d; d = (*w)[i].ToVec3() * ldef->frustum[j].Normal() + ldef->frustum[j][3]; if ( d > 0 ) { return false; } } } return true; } /* ====================== R_CreateLightDefFogPortals When a fog light is created or moved, see if it completely encloses any portals, which may allow them to be fogged closed. ====================== */ void R_CreateLightDefFogPortals( idRenderLightLocal *ldef ) { areaReference_t *lref; portalArea_t *area; ldef->foggedPortals = NULL; if ( !ldef->lightShader->IsFogLight() ) { return; } // some fog lights will explicitly disallow portal fogging if ( ldef->lightShader->TestMaterialFlag( MF_NOPORTALFOG ) ) { return; } for ( lref = ldef->references ; lref ; lref = lref->ownerNext ) { // check all the models in this area area = lref->area; portal_t *prt; doublePortal_t *dp; for ( prt = area->portals ; prt ; prt = prt->next ) { dp = prt->doublePortal; // we only handle a single fog volume covering a portal // this will never cause incorrect drawing, but it may // fail to cull a portal if ( dp->fogLight ) { continue; } if ( WindingCompletelyInsideLight( prt->w, ldef ) ) { dp->fogLight = ldef; dp->nextFoggedPortal = ldef->foggedPortals; ldef->foggedPortals = dp; } } } } /* ==================== R_FreeLightDefDerivedData Frees all references and lit surfaces from the light ==================== */ void R_FreeLightDefDerivedData( idRenderLightLocal *ldef ) { areaReference_t *lref, *nextRef; // rmove any portal fog references for ( doublePortal_t *dp = ldef->foggedPortals ; dp ; dp = dp->nextFoggedPortal ) { dp->fogLight = NULL; } // free all the interactions while ( ldef->firstInteraction != NULL ) { ldef->firstInteraction->UnlinkAndFree(); } // free all the references to the light for ( lref = ldef->references ; lref ; lref = nextRef ) { nextRef = lref->ownerNext; // unlink from the area lref->areaNext->areaPrev = lref->areaPrev; lref->areaPrev->areaNext = lref->areaNext; // put it back on the free list for reuse ldef->world->areaReferenceAllocator.Free( lref ); } ldef->references = NULL; R_FreeLightDefFrustum( ldef ); } /* =================== R_FreeEntityDefDerivedData Used by both RE_FreeEntityDef and RE_UpdateEntityDef Does not actually free the entityDef. =================== */ void R_FreeEntityDefDerivedData( idRenderEntityLocal *def, bool keepDecals, bool keepCachedDynamicModel ) { int i; areaReference_t *ref, *next; // demo playback needs to free the joints, while normal play // leaves them in the control of the game if ( session->readDemo ) { if ( def->parms.joints ) { Mem_Free16( def->parms.joints ); def->parms.joints = NULL; } if ( def->parms.callbackData ) { Mem_Free( def->parms.callbackData ); def->parms.callbackData = NULL; } for ( i = 0; i < MAX_RENDERENTITY_GUI; i++ ) { if ( def->parms.gui[ i ] ) { delete def->parms.gui[ i ]; def->parms.gui[ i ] = NULL; } } } // free all the interactions while ( def->firstInteraction != NULL ) { def->firstInteraction->UnlinkAndFree(); } // clear the dynamic model if present if ( def->dynamicModel ) { def->dynamicModel = NULL; } if ( !keepDecals ) { R_FreeEntityDefDecals( def ); R_FreeEntityDefOverlay( def ); } if ( !keepCachedDynamicModel ) { delete def->cachedDynamicModel; def->cachedDynamicModel = NULL; } // free the entityRefs from the areas for ( ref = def->entityRefs ; ref ; ref = next ) { next = ref->ownerNext; // unlink from the area ref->areaNext->areaPrev = ref->areaPrev; ref->areaPrev->areaNext = ref->areaNext; // put it back on the free list for reuse def->world->areaReferenceAllocator.Free( ref ); } def->entityRefs = NULL; } /* ================== R_ClearEntityDefDynamicModel If we know the reference bounds stays the same, we only need to do this on entity update, not the full R_FreeEntityDefDerivedData ================== */ void R_ClearEntityDefDynamicModel( idRenderEntityLocal *def ) { // free all the interaction surfaces for( idInteraction *inter = def->firstInteraction; inter != NULL && !inter->IsEmpty(); inter = inter->entityNext ) { inter->FreeSurfaces(); } // clear the dynamic model if present if ( def->dynamicModel ) { def->dynamicModel = NULL; } } /* =================== R_FreeEntityDefDecals =================== */ void R_FreeEntityDefDecals( idRenderEntityLocal *def ) { while( def->decals ) { idRenderModelDecal *next = def->decals->Next(); idRenderModelDecal::Free( def->decals ); def->decals = next; } } /* =================== R_FreeEntityDefFadedDecals =================== */ void R_FreeEntityDefFadedDecals( idRenderEntityLocal *def, int time ) { def->decals = idRenderModelDecal::RemoveFadedDecals( def->decals, time ); } /* =================== R_FreeEntityDefOverlay =================== */ void R_FreeEntityDefOverlay( idRenderEntityLocal *def ) { if ( def->overlay ) { idRenderModelOverlay::Free( def->overlay ); def->overlay = NULL; } } /* =================== R_FreeDerivedData ReloadModels and RegenerateWorld call this // FIXME: need to do this for all worlds =================== */ void R_FreeDerivedData( void ) { int i, j; idRenderWorldLocal *rw; idRenderEntityLocal *def; idRenderLightLocal *light; for ( j = 0; j < tr.worlds.Num(); j++ ) { rw = tr.worlds[j]; for ( i = 0; i < rw->entityDefs.Num(); i++ ) { def = rw->entityDefs[i]; if ( !def ) { continue; } R_FreeEntityDefDerivedData( def, false, false ); } for ( i = 0; i < rw->lightDefs.Num(); i++ ) { light = rw->lightDefs[i]; if ( !light ) { continue; } R_FreeLightDefDerivedData( light ); } } } /* =================== R_CheckForEntityDefsUsingModel =================== */ void R_CheckForEntityDefsUsingModel( idRenderModel *model ) { int i, j; idRenderWorldLocal *rw; idRenderEntityLocal *def; for ( j = 0; j < tr.worlds.Num(); j++ ) { rw = tr.worlds[j]; for ( i = 0 ; i < rw->entityDefs.Num(); i++ ) { def = rw->entityDefs[i]; if ( !def ) { continue; } if ( def->parms.hModel == model ) { //assert( 0 ); // this should never happen but Radiant messes it up all the time so just free the derived data R_FreeEntityDefDerivedData( def, false, false ); } } } } /* =================== R_ReCreateWorldReferences ReloadModels and RegenerateWorld call this // FIXME: need to do this for all worlds =================== */ void R_ReCreateWorldReferences( void ) { int i, j; idRenderWorldLocal *rw; idRenderEntityLocal *def; idRenderLightLocal *light; // let the interaction generation code know this shouldn't be optimized for // a particular view tr.viewDef = NULL; for ( j = 0; j < tr.worlds.Num(); j++ ) { rw = tr.worlds[j]; for ( i = 0 ; i < rw->entityDefs.Num() ; i++ ) { def = rw->entityDefs[i]; if ( !def ) { continue; } // the world model entities are put specifically in a single // area, instead of just pushing their bounds into the tree if ( i < rw->numPortalAreas ) { rw->AddEntityRefToArea( def, &rw->portalAreas[i] ); } else { R_CreateEntityRefs( def ); } } for ( i = 0 ; i < rw->lightDefs.Num() ; i++ ) { light = rw->lightDefs[i]; if ( !light ) { continue; } renderLight_t parms = light->parms; light->world->FreeLightDef( i ); rw->UpdateLightDef( i, &parms ); } } } /* =================== R_RegenerateWorld_f Frees and regenerates all references and interactions, which must be done when switching between display list mode and immediate mode =================== */ void R_RegenerateWorld_f( const idCmdArgs &args ) { R_FreeDerivedData(); // watch how much memory we allocate tr.staticAllocCount = 0; R_ReCreateWorldReferences(); common->Printf( "Regenerated world, staticAllocCount = %i.\n", tr.staticAllocCount ); }
gpl-3.0
UTN-FRBA-Mobile/Clases-2017c1
app/src/main/java/ar/edu/utn/frba/myapplication/service/RTMService.java
12107
package ar.edu.utn.frba.myapplication.service; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.util.SparseArray; import android.widget.Toast; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.internal.ws.WebSocket; import com.squareup.okhttp.internal.ws.WebSocketListener; import org.json.JSONObject; import java.io.IOException; import java.nio.charset.Charset; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import ar.edu.utn.frba.myapplication.api.Callback; import ar.edu.utn.frba.myapplication.api.PushServerApi; import ar.edu.utn.frba.myapplication.api.ResponseParser; import ar.edu.utn.frba.myapplication.api.SlackApi; import ar.edu.utn.frba.myapplication.api.requests.UserPushUnregistration; import ar.edu.utn.frba.myapplication.api.responses.AuthRevokeResponse; import ar.edu.utn.frba.myapplication.api.responses.Chat; import ar.edu.utn.frba.myapplication.api.responses.ChatHistoryResponse; import ar.edu.utn.frba.myapplication.api.responses.RtmStartResponse; import ar.edu.utn.frba.myapplication.api.responses.event.Event; import ar.edu.utn.frba.myapplication.api.responses.event.MessageEvent; import ar.edu.utn.frba.myapplication.api.responses.event.ResponseEvent; import ar.edu.utn.frba.myapplication.session.Session; import ar.edu.utn.frba.myapplication.session.SessionImpl; import ar.edu.utn.frba.myapplication.storage.Preferences; import ar.edu.utn.frba.myapplication.util.Util; import okio.Buffer; import okio.BufferedSource; import retrofit2.Call; import retrofit2.Response; /** * Created by emanuel on 25/9/16. */ public class RTMService extends Service { public static final String SessionChangedIntentAction = "ar.edu.utn.frba.mobile.clases.SessionChangedIntentAction"; public static final String NewEventIntentAction = "ar.edu.utn.frba.mobile.clases.NewEventIntentAction"; public static final String EventExtraKey = "EventExtra"; private static final String TAG = RTMService.class.getName(); private final IBinder binder = new Binder(); private ExecutorService executor = Executors.newSingleThreadExecutor(); private Preferences preferences = Preferences.get(this); private Handler handler = new Handler(); private boolean shouldConnect = false; private boolean obtainingUrl = false; private String websocketUrl = null; private WebSocket webSocket = null; private boolean connected = false; private int lastId = 1; private SessionImpl session; private SparseArray<Event> pendingEvents = new SparseArray<>(); private PushServerApi mApiService = Util.createPushServerNetworkClient(); @Nullable @Override public IBinder onBind(Intent intent) { connect(); return binder; } @Override public boolean onUnbind(Intent intent) { disconnect(new Runnable() { @Override public void run() { executor.shutdown(); } }); return super.onUnbind(intent); } public void connect() { shouldConnect = true; connectIfRequired(); } private void connectIfRequired() { if (!shouldConnect || obtainingUrl || webSocket != null || preferences.getAccessToken() == null) { return; } if (websocketUrl == null) { obtainWebSocketURI(); } else { connectWebSocket(); } } private void connectWebSocket() { final OkHttpClient client = new OkHttpClient(); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder() .url(websocketUrl) .build(); webSocket = WebSocket.newWebSocket(client, request); executor.execute(new Runnable() { @Override public void run() { try { Log.d(TAG, "Conectando al WebSocket."); webSocket.connect(new WebSocketListener() { @Override public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException { Log.d(TAG, "Mensaje recibido."); final String message = payload.readUtf8(); Event event = ResponseParser.instance.parseEvent(message); if (event instanceof ResponseEvent) { event = updatePendingEvent((ResponseEvent) event); } if (event != null) { broadcastEvent(event); } payload.close(); } @Override public void onClose(int code, String reason) { webSocket = null; connected = false; Log.d(TAG, "Conexión cerrada."); retryConnectionDelayed(); } @Override public void onFailure(IOException e) { e.printStackTrace(); Log.d(TAG, "Error de conexión."); retryConnectionDelayed(); } }); connected = true; websocketUrl = null; Log.d(TAG, "Conectado."); // Trigger shutdown of the dispatcher's executor so this process can exit cleanly. client.getDispatcher().getExecutorService().shutdown(); } catch (IOException e) { e.printStackTrace(); Log.d(TAG, "Falló la conexión al WebSocket."); retryConnectionDelayed(); } } }); } private Event updatePendingEvent(ResponseEvent event) { try { int id = Integer.parseInt(event.getReplyTo()); Event realEvent = pendingEvents.get(id); if (realEvent != null && event.isOk()) { realEvent.setTs(event.getTs()); } return realEvent; } catch (Exception e) { return null; } } private void broadcastEvent(Event event) { Intent intent = new Intent(NewEventIntentAction); intent.putExtra(EventExtraKey, event); sendBroadcast(intent); } private void obtainWebSocketURI() { obtainingUrl = true; Runnable request = SlackApi.rtmStart(preferences.getAccessToken(), new Callback<RtmStartResponse>() { @Override public void onSuccess(RtmStartResponse response) { obtainingUrl = false; websocketUrl = response.getUrl(); session = new SessionImpl(); session.setSelf(response.getSelf()); session.setTeam(response.getTeam()); session.setChannels(response.getChannels()); session.setUsers(response.getUsers()); session.setIMs(response.getIMs()); broadcastSessionChanged(); Log.d(TAG, "ws url: " + websocketUrl); connectIfRequired(); } @Override public void onError(Exception e) { obtainingUrl = false; if (e != null) { e.printStackTrace(); } session = null; broadcastSessionChanged(); retryConnectionDelayed(); } }); executor.execute(request); } private void disconnect(final Runnable next) { shouldConnect = false; session = null; if (webSocket != null && connected) { executor.execute(new Runnable() { @Override public void run() { try { webSocket.close(1000, "end"); } catch (IOException e) { e.printStackTrace(); } next.run(); } }); } else { executor.execute(next); } broadcastSessionChanged(); } public void logout() { String currentAccessToken = preferences.getAccessToken(); String currentUserId = preferences.getUserId(); preferences.setAccessToken(null); preferences.setUserId(null); session = null; broadcastSessionChanged(); disconnect(SlackApi.authRevoke(currentAccessToken, new Callback<AuthRevokeResponse>() { @Override public void onSuccess(AuthRevokeResponse response) { } @Override public void onError(Exception e) { } })); Call<Void> response = mApiService.unregisterUser(new UserPushUnregistration(currentUserId)); response.enqueue(new retrofit2.Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if(response.isSuccessful()){ Toast.makeText(RTMService.this, "User unregistered from Push server", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(RTMService.this, "Error while unregistering User from Push server", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Void> call, Throwable t) { Toast.makeText(RTMService.this, "Connection error", Toast.LENGTH_SHORT).show(); } }); } private void broadcastSessionChanged() { Intent intent = new Intent(SessionChangedIntentAction); sendBroadcast(intent); } private void retryConnectionDelayed() { handler.postDelayed(new Runnable() { @Override public void run() { connectIfRequired(); } }, 1000); } public boolean isConnecting() { return obtainingUrl; } public boolean isConnected() { return connected; } public Session getSession() { return session; } public void sendMessage(final String channelId, final String text) { executor.execute(new Runnable() { @Override public void run() { try { int id = nextId(); String userId = session.getMe().getId(); String type = "message"; JSONObject json = new JSONObject(); json.put("type", type); json.put("id", id); json.put("channel", channelId); json.put("text", text); MessageEvent message = new MessageEvent(id, channelId, userId, type, text); pendingEvents.put(id, message); broadcastEvent(message); Buffer payload = new Buffer(); payload.writeString(json.toString(), Charset.defaultCharset()); webSocket.sendMessage(WebSocket.PayloadType.TEXT, payload); } catch (Exception e) { e.printStackTrace(); } } }); } public Runnable retrieveChatHistory(Chat chat, Callback<ChatHistoryResponse> callback) { Runnable runnable = SlackApi.chatHistory(preferences.getAccessToken(), chat, null, null, true, 100, false, callback); executor.execute(runnable); return runnable; } int nextId() { return lastId++; } public class Binder extends android.os.Binder { public RTMService getService() { return RTMService.this; } } }
gpl-3.0
Cecer1/-IHI-StandardOut
Properties/AssemblyInfo.cs
2178
#region GPLv3 // // Copyright (C) 2012 Chris Chenery // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #endregion #region Usings using System.Reflection; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("StandardOut")] [assembly: AssemblyDescription("Provides a WebAdmin page for testing Standard Out.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StandardOut")] [assembly: AssemblyCopyright("Copyright © Chris Chenery 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7fec2737-a627-43ea-ae29-b5b45e5845d7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
opf-labs/ots-schema
src/edu/harvard/hul/ois/ots/schemas/XmlContent/AnyXml.java
4583
/* * Copyright 2010 Harvard University Library * * This file is part of OTS-Schemas. * * OTS-Schemas is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OTS-Schemas is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with OTS-Schemas. If not, see <http://www.gnu.org/licenses/>. */ package edu.harvard.hul.ois.ots.schemas.XmlContent; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.jdom.Document; import org.jdom.JDOMException; import edu.harvard.hul.ois.ots.schemas.XmlComponent; import edu.harvard.hul.ois.ots.schemas.StaxUtils.OTSJDOMFactory; import edu.harvard.hul.ois.ots.schemas.StaxUtils.StAXBuilder; import edu.harvard.hul.ois.ots.schemas.StaxUtils.StAXOutputter; public class AnyXml implements XmlComponent { private Document dom; public AnyXml() { } public AnyXml(XMLStreamReader reader) throws XMLStreamException { this(); parse(reader); } public Document getXml() { return dom; } @Override public void output(XMLStreamWriter writer) throws XMLStreamException { StAXOutputter staxOut = new StAXOutputter(writer); //if dom has the default 'anyxml' element as the root node then do not output if(!dom.getRootElement().getName().equals("anyxml")) { try { staxOut.output(dom.getRootElement(),false); } catch (JDOMException e) { throw new XMLStreamException("Error outputting JDOM",e); } } } @Override public AnyXml parse(XMLStreamReader reader) throws XMLStreamException { StAXBuilder staxBuilder = new StAXBuilder(); staxBuilder.setFactory(new OTSJDOMFactory()); dom = staxBuilder.build(reader); return this; } @Override public boolean validate() { // TODO Auto-generated method stub return true; } /** Returns a List of all namespace schema contexts used within this JDOM object. * If a default namespace is inherited from the enclosing element, we don't list * it. */ @Override public List<NamespaceSchemaContext> getAllNamespaceSchemaContexts() { List<NamespaceSchemaContext> ctxts = new ArrayList<NamespaceSchemaContext> (); //Element topElem = dom.getRootElement(); //addNamespaceSchemaContexts (ctxts, topElem); return ctxts; } /* private void addNamespaceSchemaContexts (List<NamespaceSchemaContext> ctxts, Element elem) { Namespace ns = elem.getNamespace (); String nsPrefix = ns.getPrefix (); String nsURI = ns.getURI (); // We can get the schemaLocation only if it's an attribute in this element. If it isn't, // we assume that the schemaLocation is inherited and thus already listed, and we // don't bother with it. String loc = elem.getAttributeValue("schemaLocation", ns); if (loc != null) { NamespaceSchemaContext ctx = new NamespaceSchemaContext(nsURI, nsPrefix, loc); boolean dup = false; for (NamespaceSchemaContext ctx1 : ctxts) { if (ctx1.equals (ctx)) { dup = true; break; } } if (!dup) { ctxts.add (ctx); } } // Now recurse down List children = elem.getChildren(); Iterator childIter = children.iterator (); while (childIter.hasNext ()) { Element child = (Element) childIter.next (); addNamespaceSchemaContexts (ctxts, child); } } */ /** * return the namespace and schema context for this xml * @return */ @Override public NamespaceSchemaContext getNamespaceSchemaContext() { return null; /* Element topElem = dom.getRootElement(); org.jdom.Namespace ns = topElem.getNamespace (); String nsPrefix = ns.getPrefix (); String nsURI = ns.getURI (); // In this case we return the best information we have. String loc = topElem.getAttributeValue("schemaLocation", ns); return new NamespaceSchemaContext (nsURI, nsPrefix, loc);*/ } @Override public void setRoot(boolean root) { //do nothing } }
gpl-3.0
Kristaba/tiles-creator
plugins/BasiCasioExport/basicasioexport.cpp
948
#include "basicasioexport.h" void BasiCasioExport::exportProject(TcProject project){ this->totalExport(project); } void BasiCasioExport::totalExport(const TcProject& project){ if( !project.tiles.isEmpty() ){ for( int i = 0 ; i < project.tiles.size() ; i++ ){ } } } void BasiCasioExport::tilesExport(const QList<TcTile> &tiles){ } QString BasiCasioExport::getHexa2(unsigned char num){ QString ret; ret = "0x"+QString::number(num, 16).toUpper(); if (ret.size() < 4) ret.insert(2, '0'); return ret; } QString BasiCasioExport::nameToValidString(const QString &s) { QString ret; for (int i=0; i<s.size(); i++) { QChar c = s.at(i); if (c.isLower() || c.isDigit()) ret.append(c); else if (c.isUpper()) ret.append(c.toLower()); else ret.append('_'); } return ret; } Q_EXPORT_PLUGIN2(BasiCasioExporter, BasiCasioExport)
gpl-3.0
ryanfreckleton/thinkgraph
thinkgraph/parser.py
5808
#!/usr/bin/env python # -*- coding: utf-8 -*- # CAVEAT UTILITOR # # This file was automatically generated by Grako. # # https://pypi.python.org/pypi/grako/ # # Any changes you make to it will be overwritten the next time # the file is generated. from __future__ import print_function, division, absolute_import, unicode_literals from grako.buffering import Buffer from grako.parsing import graken, Parser from grako.util import re, RE_FLAGS, generic_main # noqa KEYWORDS = {} class thinkingprocessesBuffer(Buffer): def __init__( self, text, whitespace=None, nameguard=None, comments_re=None, eol_comments_re=None, ignorecase=None, namechars='', **kwargs ): super(thinkingprocessesBuffer, self).__init__( text, whitespace=whitespace, nameguard=nameguard, comments_re=comments_re, eol_comments_re=eol_comments_re, ignorecase=ignorecase, namechars=namechars, **kwargs ) class thinkingprocessesParser(Parser): def __init__( self, whitespace=None, nameguard=None, comments_re=None, eol_comments_re=None, ignorecase=None, left_recursion=False, parseinfo=True, keywords=None, namechars='', buffer_class=thinkingprocessesBuffer, **kwargs ): if keywords is None: keywords = KEYWORDS super(thinkingprocessesParser, self).__init__( whitespace=whitespace, nameguard=nameguard, comments_re=comments_re, eol_comments_re=eol_comments_re, ignorecase=ignorecase, left_recursion=left_recursion, parseinfo=parseinfo, keywords=keywords, namechars=namechars, buffer_class=buffer_class, **kwargs ) @graken() def _statements_(self): def block0(): with self._choice(): with self._option(): self._label_() with self._option(): self._relation_() with self._option(): self._loop_() with self._option(): self._conflict_() self._error('no available options') self._positive_closure(block0) self._check_eof() @graken() def _label_(self): self._identifier_() self.name_last_node('id') with self._group(): with self._choice(): with self._option(): self._token('.') self._CLASS_() self.name_last_node('cls') with self._option(): self._token('.') self._error('expecting one of: .') self._string_() self.name_last_node('label') self.ast._define( ['cls', 'id', 'label'], [] ) @graken() def _relation_(self): self._and_stmt_() self.name_last_node('source') self._token('->') self._identifier_() self.name_last_node('destination') self._NEWLINE_() self.ast._define( ['destination', 'source'], [] ) @graken() def _loop_(self): self._and_stmt_() self.name_last_node('source') self._token('=>') self._identifier_() self.name_last_node('destination') self._NEWLINE_() self.ast._define( ['destination', 'source'], [] ) @graken() def _and_stmt_(self): self._identifier_() self.add_last_node_to_name('@') def block1(): self._token('and') self._identifier_() self.add_last_node_to_name('@') self._closure(block1) @graken() def _conflict_(self): self._identifier_() self.add_last_node_to_name('@') self._token('<>') self._identifier_() self.add_last_node_to_name('@') self._NEWLINE_() @graken() def _identifier_(self): self._pattern(r'\w+') @graken() def _string_(self): self._pattern(r'.*') @graken() def _NEWLINE_(self): self._pattern(r'\r?\n') @graken() def _CLASS_(self): with self._choice(): with self._option(): self._token('inj') with self._option(): self._token('obs') with self._option(): self._token('red') with self._option(): self._token('green') self._error('expecting one of: green inj obs red') class thinkingprocessesSemantics(object): def statements(self, ast): return ast def label(self, ast): return ast def relation(self, ast): return ast def loop(self, ast): return ast def and_stmt(self, ast): return ast def conflict(self, ast): return ast def identifier(self, ast): return ast def string(self, ast): return ast def NEWLINE(self, ast): return ast def CLASS(self, ast): return ast def main(filename, startrule, **kwargs): with open(filename) as f: text = f.read() parser = thinkingprocessesParser() return parser.parse(text, startrule, filename=filename, **kwargs) if __name__ == '__main__': import json from grako.util import asjson ast = generic_main(main, thinkingprocessesParser, name='thinkingprocesses') print('AST:') print(ast) print() print('JSON:') print(json.dumps(asjson(ast), indent=2)) print()
gpl-3.0
gnumdk/lollypop
lollypop/progressbar.py
1612
# Copyright (c) 2014-2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gtk class ProgressBar(Gtk.ProgressBar): """ A smart progress bar """ def __init__(self): """ Init progress bar """ Gtk.ProgressBar.__init__(self) self.__callers = [] def add(self, caller): """ Add caller @param caller as Instance """ if caller not in self.__callers: self.__callers.insert(0, caller) def set_fraction(self, fraction, caller): """ Set fraction if caller is on top. """ if not self.__callers: return if caller == self.__callers[0]: self.show() Gtk.ProgressBar.set_fraction(self, fraction) if fraction == 1: self.__callers.remove(caller) self.hide() Gtk.ProgressBar.set_fraction(self, 0.0)
gpl-3.0
wojtask/CormenPy
src/chapter10/exercise10_4_4.py
128
def tree_walk(x): if x is not None: print(x.key) tree_walk(x.left_child) tree_walk(x.right_sibling)
gpl-3.0
jdupl/lancoder
src/main/java/org/lancoder/ffmpeg/FFmpegReader.java
2644
package org.lancoder.ffmpeg; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Scanner; import java.util.logging.Logger; import org.lancoder.common.ServiceAdapter; import org.lancoder.common.exceptions.MissingThirdPartyException; /** * Class to create a process, read its output and provide information about it's closing state. * * */ public class FFmpegReader extends ServiceAdapter { Process p; FFmpegReaderListener listener; /** * Create a process and read the desired output. Interface's onMessage method is called on each line. * * @param args * The arguments of the command line * @param listener * The listener that will read the lines * @param useStdErr * True to read from stderr, false to read from stdout * @return true if FFmpeg exited cleanly * @throws MissingThirdPartyException */ public boolean read(ArrayList<String> args, FFmpegReaderListener listener, boolean useStdErr) throws MissingThirdPartyException { return read(args, listener, useStdErr, null); } /** * Create a process in the specified directory and read the desired output. Interface's onMessage method is called * on each line. * * @param args * The arguments of the command line * @param listener * The listener that will read the lines * @param useStdErr * True to read from stderr, false to read from stdout * @param processDirectory * The directory to execute the process in * @return true if FFmpeg exited cleanly * @throws MissingThirdPartyException */ public boolean read(ArrayList<String> args, FFmpegReaderListener listener, boolean useStdErr, File processDirectory) throws MissingThirdPartyException { this.listener = listener; boolean success = false; Logger logger = Logger.getLogger("lancoder"); ProcessBuilder pb = new ProcessBuilder(args); pb.directory(processDirectory); logger.finer(pb.command().toString() + "\n"); Scanner s = null; try { p = pb.start(); InputStream stream = useStdErr ? p.getErrorStream() : p.getInputStream(); s = new Scanner(stream); while (s.hasNext() && !close) { listener.onMessage(s.nextLine()); } success = p.waitFor() == 0 ? true : false; } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { } finally { if (close && p != null) { p.destroy(); } if (s != null) { s.close(); } } return success; } @Override public void stop() { super.stop(); if (p != null) { p.destroy(); } } }
gpl-3.0
bitwarden/mobile
src/iOS.Core/Renderers/CustomEditorRenderer.cs
1577
using Bit.iOS.Core.Renderers; using System.ComponentModel; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(Editor), typeof(CustomEditorRenderer))] namespace Bit.iOS.Core.Renderers { public class CustomEditorRenderer : EditorRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Editor> e) { base.OnElementChanged(e); if (e.NewElement is Editor) { var descriptor = UIFontDescriptor.PreferredBody; Control.Font = UIFont.FromDescriptor(descriptor, descriptor.PointSize); // Remove padding Control.TextContainerInset = new UIEdgeInsets(0, 0, 0, 0); Control.TextContainer.LineFragmentPadding = 0; UpdateTintColor(); UpdateKeyboardAppearance(); } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == Editor.TextColorProperty.PropertyName) { UpdateTintColor(); } } private void UpdateTintColor() { Control.TintColor = Element.TextColor.ToUIColor(); } private void UpdateKeyboardAppearance() { if (!Utilities.ThemeHelpers.LightTheme) { Control.KeyboardAppearance = UIKeyboardAppearance.Dark; } } } }
gpl-3.0
CCChapel/ccchapel.com
CMS/CMSModules/Workflows/Workflow_New.aspx.cs
1740
using System; using CMS.Core; using CMS.Helpers; using CMS.PortalEngine; using CMS.UIControls; using CMS.WorkflowEngine; using CMS.Base; [Help("workflow_new", "helpTopic")] [EditedObject("cms.workflow", "workflowid")] public partial class CMSModules_Workflows_Workflow_New : CMSWorkflowPage { protected void Page_Load(object sender, EventArgs e) { Title = "Workflows - New Workflow"; // Redirect after successful action editElem.Form.RedirectUrlAfterCreate = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "EditWorkflow", false), "&objectID={%EditedObject.ID%}&saved=1"); editElem.CurrentWorkflow.WorkflowType = (WorkflowTypeEnum)QueryHelper.GetInteger("type", (int)WorkflowTypeEnum.Basic); // Initializes labels string workflowList = GetString("Development-Workflow_Edit.Workflows"); string newResString = (WorkflowType == WorkflowTypeEnum.Basic) ? "Development-Workflow_List.NewWorkflow" : "Development-Workflow_List.NewAdvancedWorkflow"; string currentWorkflow = GetString(newResString); // Initialize master page elements CreateBreadcrumbs(workflowList, currentWorkflow); } /// <summary> /// Creates breadcrumbs on master page title. /// </summary> private void CreateBreadcrumbs(string workflowList, string currentWorkflow) { // Initializes page title PageBreadcrumbs.AddBreadcrumb(new BreadcrumbItem() { Text = workflowList, RedirectUrl = UIContextHelper.GetElementUrl(ModuleName.CMS, "Workflows", false) }); PageBreadcrumbs.AddBreadcrumb(new BreadcrumbItem() { Text = currentWorkflow }); } }
gpl-3.0
alunkeit/ancat
ancat/importer/graphml/GraphOrderType.java
1634
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.12.26 at 03:18:19 PM MEZ // package ancat.importer.graphml; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for graph.order.type. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="graph.order.type"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="free"/> * &lt;enumeration value="nodesfirst"/> * &lt;enumeration value="adjacencylist"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "graph.order.type") @XmlEnum public enum GraphOrderType { @XmlEnumValue("free") FREE("free"), @XmlEnumValue("nodesfirst") NODESFIRST("nodesfirst"), @XmlEnumValue("adjacencylist") ADJACENCYLIST("adjacencylist"); private final String value; GraphOrderType(String v) { value = v; } public String value() { return value; } public static GraphOrderType fromValue(String v) { for (GraphOrderType c: GraphOrderType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
gpl-3.0
picon-software/eoit
eoit-industry-api/src/main/java/fr/piconsoft/eoit/api/services/MarketService.java
1105
/* * Copyright (C) 2014 Picon software * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package fr.piconsoft.eoit.api.services; import fr.piconsoft.eoit.api.model.MarketPrice; import retrofit.http.GET; import retrofit.http.Path; /** * @author picon.software */ public interface MarketService { @GET("/api/market/prices/{regionId}/{itemId}") MarketPrice price(@Path("regionId") int regionId, @Path("itemId") int itemId); }
gpl-3.0
tetrabox/minitl
plugins/org.tetrabox.example.minitl/src-gen/org/tetrabox/example/minitl/aspects/BinaryExpressionAspectBinaryExpressionAspectContext.java
1188
package org.tetrabox.example.minitl.aspects; import java.util.Map; import org.tetrabox.example.minitl.minitl.BinaryExpression; import org.tetrabox.example.minitl.aspects.BinaryExpressionAspectBinaryExpressionAspectProperties; @SuppressWarnings("all") public class BinaryExpressionAspectBinaryExpressionAspectContext { public final static BinaryExpressionAspectBinaryExpressionAspectContext INSTANCE = new BinaryExpressionAspectBinaryExpressionAspectContext(); public static BinaryExpressionAspectBinaryExpressionAspectProperties getSelf(final BinaryExpression _self) { if (!INSTANCE.map.containsKey(_self)) INSTANCE.map.put(_self, new org.tetrabox.example.minitl.aspects.BinaryExpressionAspectBinaryExpressionAspectProperties()); return INSTANCE.map.get(_self); } private Map<BinaryExpression, BinaryExpressionAspectBinaryExpressionAspectProperties> map = new java.util.WeakHashMap<org.tetrabox.example.minitl.minitl.BinaryExpression, org.tetrabox.example.minitl.aspects.BinaryExpressionAspectBinaryExpressionAspectProperties>(); public Map<BinaryExpression, BinaryExpressionAspectBinaryExpressionAspectProperties> getMap() { return map; } }
gpl-3.0
Quexten/UlricianumPlanner
app/src/main/java/com/quexten/ulricianumplanner/courseplan/TeacherManager.java
3259
package com.quexten.ulricianumplanner.courseplan; import android.content.Context; import com.google.gson.Gson; import com.quexten.ulricianumplanner.R; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; /** * Created by Quexten on 03-Mar-17. */ public class TeacherManager { private TeacherList teacherList; public TeacherManager(Context context) { teacherList = getTeacherList(context, R.raw.teachers); } /** * Gets the full teacher name for a given shorthand * @param shorthand - the shorthand * @return - the full name or the shorthand if none was found */ public String getFullTeacherName(String shorthand) { for(TeacherEntry entry : teacherList.list) { if(entry.shortName.equalsIgnoreCase(shorthand)) return entry.fullName; } return shorthand; } /** * Gets the shorthand for a full teacher name * @param name - the full name * @return - the shorthand or the full name if none was found */ public String getTeacherShorthand(String name) { for(TeacherEntry entry : teacherList.list) { if(entry.fullName.equalsIgnoreCase(name)) return entry.shortName; } return name; } /** * Gets the subjects for a given teacher * @param teacherShorthand - the teachers shorthand * @return a String array of the subjects, an empty String * array if no matching teacher is found */ public String[] getTeacherSubjects(String teacherShorthand) { for(TeacherEntry entry : teacherList.list) { if(entry.shortName.equalsIgnoreCase(teacherShorthand)) return entry.subjects; } return new String[0]; } public String[] getShorthandTeacherList() { int size = teacherList.list.length; String[] list = new String[size]; for(int i = 0; i < size; i++) list[i] = teacherList.list[i].shortName; return list; } public String[] getFullTeacherList() { int size = teacherList.list.length; String[] list = new String[size]; for(int i = 0; i < size; i++) list[i] = teacherList.list[i].fullName; return list; } /** * Loads the teacher list from a specified resource * @param context - the context of the application * @param resourceId - the resource to load * @return - the populated TeacherList object */ private TeacherList getTeacherList(Context context, int resourceId) { InputStream is = context.getResources().openRawResource(resourceId); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } is.close(); } catch(Exception ex) { ex.printStackTrace(); } return new Gson().fromJson(writer.toString(), TeacherList.class); } }
gpl-3.0
PapenfussLab/PathOS
Tools/Hl7Tools/src/main/java/org/petermac/hl7/model/v251/segment/DSP.java
5976
/* * This class is an auto-generated source file for a HAPI * HL7 v2.x standard structure class. * * For more information, visit: http://hl7api.sourceforge.net/ * * The contents of this file are subject to the Mozilla Public License Version 1.1 * (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.mozilla.org/MPL/ * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the * specific language governing rights and limitations under the License. * * The Original Code is "[file_name]". Description: * "[one_line_description]" * * The Initial Developer of the Original Code is University Health Network. Copyright (C) * 2012. All Rights Reserved. * * Contributor(s): ______________________________________. * * Alternatively, the contents of this file may be used under the terms of the * GNU General Public License (the "GPL"), in which case the provisions of the GPL are * applicable instead of those above. If you wish to allow use of your version of this * file only under the terms of the GPL and not to allow others to use your version * of this file under the MPL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by the GPL License. * If you do not delete the provisions above, a recipient may use your version of * this file under either the MPL or the GPL. * */ package org.petermac.hl7.model.v251.segment; // import org.petermac.hl7.model.v251.group.*; import org.petermac.hl7.model.v251.datatype.*; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.parser.ModelClassFactory; import ca.uhn.hl7v2.parser.DefaultModelClassFactory; import ca.uhn.hl7v2.model.AbstractMessage; import ca.uhn.hl7v2.model.Group; import ca.uhn.hl7v2.model.Type; import ca.uhn.hl7v2.model.AbstractSegment; import ca.uhn.hl7v2.model.Varies; /** *<p>Represents an HL7 DSP message segment (Display Data). * This segment has the following fields:</p> * <ul> * <li>DSP-1: Set ID - DSP (SI) <b>optional </b> * <li>DSP-2: Display Level (SI) <b>optional </b> * <li>DSP-3: Data Line (TX) <b> </b> * <li>DSP-4: Logical Break Point (ST) <b>optional </b> * <li>DSP-5: Result ID (TX) <b>optional </b> * </ul> */ @SuppressWarnings("unused") public class DSP extends AbstractSegment { /** * Creates a new DSP segment */ public DSP(Group parent, ModelClassFactory factory) { super(parent, factory); init(factory); } private void init(ModelClassFactory factory) { try { this.add(SI.class, false, 1, 4, new Object[]{ getMessage() }, "Set ID - DSP"); this.add(SI.class, false, 1, 4, new Object[]{ getMessage() }, "Display Level"); this.add(TX.class, true, 1, 300, new Object[]{ getMessage() }, "Data Line"); this.add(ST.class, false, 1, 2, new Object[]{ getMessage() }, "Logical Break Point"); this.add(TX.class, false, 1, 20, new Object[]{ getMessage() }, "Result ID"); } catch(HL7Exception e) { log.error("Unexpected error creating DSP - this is probably a bug in the source code generator.", e); } } /** * Returns * DSP-1: "Set ID - DSP" - creates it if necessary */ public SI getSetIDDSP() { SI retVal = this.getTypedField(1, 0); return retVal; } /** * Returns * DSP-1: "Set ID - DSP" - creates it if necessary */ public SI getDsp1_SetIDDSP() { SI retVal = this.getTypedField(1, 0); return retVal; } /** * Returns * DSP-2: "Display Level" - creates it if necessary */ public SI getDisplayLevel() { SI retVal = this.getTypedField(2, 0); return retVal; } /** * Returns * DSP-2: "Display Level" - creates it if necessary */ public SI getDsp2_DisplayLevel() { SI retVal = this.getTypedField(2, 0); return retVal; } /** * Returns * DSP-3: "Data Line" - creates it if necessary */ public TX getDataLine() { TX retVal = this.getTypedField(3, 0); return retVal; } /** * Returns * DSP-3: "Data Line" - creates it if necessary */ public TX getDsp3_DataLine() { TX retVal = this.getTypedField(3, 0); return retVal; } /** * Returns * DSP-4: "Logical Break Point" - creates it if necessary */ public ST getLogicalBreakPoint() { ST retVal = this.getTypedField(4, 0); return retVal; } /** * Returns * DSP-4: "Logical Break Point" - creates it if necessary */ public ST getDsp4_LogicalBreakPoint() { ST retVal = this.getTypedField(4, 0); return retVal; } /** * Returns * DSP-5: "Result ID" - creates it if necessary */ public TX getResultID() { TX retVal = this.getTypedField(5, 0); return retVal; } /** * Returns * DSP-5: "Result ID" - creates it if necessary */ public TX getDsp5_ResultID() { TX retVal = this.getTypedField(5, 0); return retVal; } /** {@inheritDoc} */ protected Type createNewTypeWithoutReflection(int field) { switch (field) { case 0: return new SI(getMessage()); case 1: return new SI(getMessage()); case 2: return new TX(getMessage()); case 3: return new ST(getMessage()); case 4: return new TX(getMessage()); default: return null; } } }
gpl-3.0
s20121035/rk3288_android5.1_repo
external/proguard/src/proguard/classfile/editor/InterfaceAdder.java
2111
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile.editor; import proguard.classfile.*; import proguard.classfile.attribute.*; import proguard.classfile.attribute.annotation.*; import proguard.classfile.attribute.preverification.*; import proguard.classfile.constant.ClassConstant; import proguard.classfile.constant.visitor.ConstantVisitor; import proguard.classfile.util.SimplifiedVisitor; /** * This ConstantVisitor adds all interfaces that it visits to the given * target class. * * @author Eric Lafortune */ public class InterfaceAdder extends SimplifiedVisitor implements ConstantVisitor { private final ConstantAdder constantAdder; private final InterfacesEditor interfacesEditor; /** * Creates a new InterfaceAdder that will add interfaces to the given * target class. */ public InterfaceAdder(ProgramClass targetClass) { constantAdder = new ConstantAdder(targetClass); interfacesEditor = new InterfacesEditor(targetClass); } // Implementations for ConstantVisitor. public void visitClassConstant(Clazz clazz, ClassConstant classConstant) { interfacesEditor.addInterface(constantAdder.addConstant(clazz, classConstant)); } }
gpl-3.0
dj7777/vidWebHq
objects/userGroupsAddNew.json.php
484
<?php header('Content-Type: application/json'); if(empty($global['systemRootPath'])){ $global['systemRootPath'] = "../"; } require_once $global['systemRootPath'].'videos/configuration.php'; require_once $global['systemRootPath'] . 'objects/user.php'; if (!User::isAdmin()) { die('{"error":"'.__("Permission denied").'"}'); } require_once 'userGroups.php'; $obj = new UserGroups(@$_POST['id']); $obj->setGroup_name($_POST['group_name']); echo '{"status":"'.$obj->save().'"}';
gpl-3.0
cjd/xLights
xSchedule/PlayList/PlayListItemSetColour.cpp
5288
/*************************************************************** * This source files comes from the xLights project * https://www.xlights.org * https://github.com/smeighan/xLights * See the github commit history for a record of contributing * developers. * Copyright claimed based on commit dates recorded in Github * License: https://github.com/smeighan/xLights/blob/master/License.txt **************************************************************/ #include "PlayListItemSetColour.h" #include <wx/xml/xml.h> #include <wx/notebook.h> #include "PlayListItemSetColourPanel.h" #include "../../xLights/outputs/OutputManager.h" PlayListItemSetColour::PlayListItemSetColour(OutputManager* outputManager, wxXmlNode* node) : PlayListItem(node) { _outputManager = outputManager; _sc = 0; _nodes = 0; _startChannel = "1"; _duration = 50; _value = *wxBLACK; _applyMethod = APPLYMETHOD::METHOD_OVERWRITE; _fadeToBlack = false; _perFrame = 999; PlayListItemSetColour::Load(node); } void PlayListItemSetColour::Load(wxXmlNode* node) { PlayListItem::Load(node); _duration = wxAtoi(node->GetAttribute("Duration", "50")); _value = wxColor(node->GetAttribute("Value", "Black")); _applyMethod = (APPLYMETHOD)wxAtoi(node->GetAttribute("ApplyMethod", "")); _startChannel = node->GetAttribute("StartChannel", "1").ToStdString(); _nodes = wxAtol(node->GetAttribute("Nodes", "0")); _fadeToBlack = (node->GetAttribute("FadeToBlack", "FALSE") == "TRUE"); } PlayListItemSetColour::PlayListItemSetColour(OutputManager* outputManager) : PlayListItem() { _type = "PLISetColour"; _outputManager = outputManager; _sc = 0; _nodes = 0; _startChannel = "1"; _duration = 50; _value = *wxBLACK; _fadeToBlack = false; _perFrame = 999; _applyMethod = APPLYMETHOD::METHOD_OVERWRITE; SetName("Set Colour"); } PlayListItem* PlayListItemSetColour::Copy() const { PlayListItemSetColour* res = new PlayListItemSetColour(_outputManager); res->_duration = _duration; res->_outputManager = _outputManager; res->_applyMethod = _applyMethod; res->_value = _value; res->_nodes = _nodes; res->_startChannel = _startChannel; res->_fadeToBlack = _fadeToBlack; PlayListItem::Copy(res); return res; } size_t PlayListItemSetColour::GetStartChannelAsNumber() { if (_sc == 0) { _sc = _outputManager->DecodeStartChannel(_startChannel); } return _sc; } wxXmlNode* PlayListItemSetColour::Save() { wxXmlNode * node = new wxXmlNode(nullptr, wxXML_ELEMENT_NODE, GetType()); node->AddAttribute("Duration", wxString::Format(wxT("%i"), (long)_duration)); node->AddAttribute("Value", _value.GetAsString()); node->AddAttribute("ApplyMethod", wxString::Format(wxT("%i"), (int)_applyMethod)); node->AddAttribute("StartChannel", _startChannel); node->AddAttribute("Nodes", wxString::Format(wxT("%ld"), (long)_nodes)); if (_fadeToBlack) node->AddAttribute("FadeToBlack", "TRUE"); PlayListItem::Save(node); return node; } std::string PlayListItemSetColour::GetTitle() const { return "Set Colour"; } void PlayListItemSetColour::Configure(wxNotebook* notebook) { notebook->AddPage(new PlayListItemSetColourPanel(notebook, _outputManager, this), GetTitle(), true); } void PlayListItemSetColour::Frame(uint8_t* buffer, size_t size, size_t ms, size_t framems, bool outputframe) { if (outputframe) { if (_perFrame == 999) { if (_fadeToBlack) { _perFrame = 1 / ((float)_duration / (float)framems); } else { _perFrame = 0; } } if (ms >= _delay && ms <= _delay + _duration) { long sc = GetStartChannelAsNumber(); if (sc > size) return; size_t toset = _nodes * 3 + sc - 1 < size ? _nodes : (size - sc + 1) / 3; if (_nodes == 0) { toset = size / 3; } if (toset > 0) { uint8_t data[3]; data[0] = _value.Red(); data[1] = _value.Green(); data[2] = _value.Blue(); if (_perFrame > 0) { int frame = (ms - _delay) / framems; float fade = _perFrame * frame; float f0 = (float)data[0] - ((float)data[0] * fade); float f1 = (float)data[1] - ((float)data[1] * fade); float f2 = (float)data[2] - ((float)data[2] * fade); if (f0 < 0) f0 = 0; if (f1 < 0) f1 = 0; if (f2 < 0) f2 = 0; data[0] = f0; data[1] = f1; data[2] = f2; } uint8_t* values = (uint8_t*)malloc(toset * 3); if (values != nullptr) { for (int i = 0; i < toset; i++) { memcpy(values + i * 3, data, sizeof(data)); } Blend(buffer, size, values, toset * 3, _applyMethod, sc - 1); free(values); } } } } }
gpl-3.0
langqiu/never_give_up
machine_learning/lr/lr_momentum.cc
2856
#include "lr_momentum.h" using namespace util; namespace lr { LRMomentum::LRMomentum(DataSet* p_train_dataset, DataSet* p_test_dataset, const hash2index_type& f_hash2index, const index2hash_type& f_index2hash, const f_index_type& f_size) : LR(p_train_dataset, p_test_dataset, f_hash2index, f_index2hash, f_size) {} void LRMomentum::_backward(const size_t& l, const size_t& r) { /* * attention! element-wise operation * g(t) = -1 * [g(logloss) + g(L2)] * v(t) = beta_1 * v(t-1) + alpha * g(t) * theta(t) = theta(t-1) + v(t) */ #ifdef _DEBUG if (_curr_batch == 1) std::cout << "lr momentum backward" << std::endl; #endif auto& data = _p_train_dataset->get_data(); // get train dataset std::unordered_set<f_index_type> theta_updated; // record theta in BGD _theta_updated_vector.clear(); // clear before backward // calculate -1 * gradient param_type factor = -1 * _lambda / (r - l); // L2 gradient factor for (size_t i=l; i<r; i++) { auto& curr_sample = data[i]; // current sample for (size_t k=0; k<curr_sample._sparse_f_list.size(); k++) { // loop features auto& curr_f = curr_sample._sparse_f_list[k]; // current feature _gradient[curr_f.first] += (curr_sample._label - curr_sample._score) * curr_f.second / (r - l); // gradient from logloss // gradient from L2 if (r - l == 1) { // SGD _gradient[curr_f.first] += factor * _theta[curr_f.first]; _theta_updated_vector.push_back(curr_f.first); } else if (theta_updated.find(curr_f.first) == theta_updated.end()) { // BGD _gradient[curr_f.first] += factor * _theta[curr_f.first]; theta_updated.insert(curr_f.first); // record the index of feature that has showed up _theta_updated_vector.push_back(curr_f.first); } } _gradient[_f_size-1] += (curr_sample._label - curr_sample._score) / (r - l); // gradient from logloss for bias } _theta_updated_vector.push_back(_f_size-1); _gradient[_f_size-1] += factor * _theta[_f_size-1]; // gradient from L2 for bias // accumulate gradient of history separately in each direction for (auto& index : _theta_updated_vector) { _first_moment_vector[index] = _beta_1 * _first_moment_vector[index] + _alpha * _gradient[index]; } // calculate theta_new for (auto& index : _theta_updated_vector) { _theta_new[index] += _first_moment_vector[index]; } } void LRMomentum::_update() { #ifdef _DEBUG if (_curr_batch == 1) std::cout << "lr momentum update" << std::endl; #endif _theta = _theta_new; for (size_t i=0; i<_f_size; i++) { // do not set zero to moment vector, because features don't show up continuously between batchs _gradient[i] = 0.0; } } } // namespace lr
gpl-3.0
austencm/portfolio-react
webpack/dev.config.js
1724
const path = require('path'), merge = require('webpack-merge'), common = require('./common.config.js'), ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = merge(common, { devtool: 'inline-source-map', devServer: { compress: true, port: 8080, historyApiFallback: { rewrites: [ // { from: /^\/$/, to: '/views/landing.html' }, // { from: /^\/subpage/, to: '/views/subpage.html' }, // { from: /./, to: '/views/404.html' } ] } }, module: { rules: [ // SASS { test: /(\.css|\.scss)$/, include: path.resolve('client/style'), use: ['css-hot-loader'].concat(ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', query: { // modules: true, sourceMap: true, importLoaders: 1, // localIdentName: '[name]__[local]__[hash:base64:5]' } }, { loader : 'sass-loader', options: { sourceMap: true, // includePaths: ['client/style'], // data: '@import "imports/base";' } }, { loader: 'sass-resources-loader', options: { resources: path.resolve('client/style/imports/_resources.scss') }, } ] })) }, // Images { test: /\.(gif|png|jpe?g|svg)$/i, include: path.resolve('client/projects/assets'), loaders: [ { loader: 'file-loader', options: { name: '[name].[hash].[ext]', } } ] }, ] } })
gpl-3.0
eae/opendental
OpenDentBusiness/Misc/ConvertDatabases2.cs
649422
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Design; using System.Drawing.Text; using System.Drawing.Drawing2D; using System.Drawing.Printing; using System.Globalization; using System.IO; using System.Net; using System.Resources; using System.Text; //using System.Windows.Forms; //using OpenDentBusiness; using CodeBase; namespace OpenDentBusiness { //The other file was simply getting too big. It was bogging down VS speed. ///<summary></summary> public partial class ConvertDatabases { private static void To6_2_9() { if(FromVersion<new Version("6.2.9.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.2.9"));//No translation in convert script. string command="ALTER TABLE fee CHANGE FeeSched FeeSched int NOT NULL"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.2.9.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_3_1(); } private static void To6_3_1() { if(FromVersion<new Version("6.3.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.3.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference (PrefName, ValueString,Comments) VALUES ('MobileSyncPath','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName, ValueString,Comments) VALUES ('MobileSyncLastFileNumber','0','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName, ValueString,Comments) VALUES ('MobileSyncDateTimeLastRun','0001-01-01','')"; Db.NonQ32(command); //I had originally deleted these. But decided instead to just comment them as obsolete because I think it caused a bug in our upgrade. command="UPDATE preference SET Comments = 'Obsolete' WHERE PrefName = 'LettersIncludeReturnAddress'"; Db.NonQ32(command); command="UPDATE preference SET Comments = 'Obsolete' WHERE PrefName ='StationaryImage'"; Db.NonQ32(command); command="UPDATE preference SET Comments = 'Obsolete' WHERE PrefName ='StationaryDocument'"; Db.NonQ32(command); } else {//oracle } command="UPDATE preference SET ValueString = '6.3.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_3_3(); } private static void To6_3_3() { if(FromVersion<new Version("6.3.3.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.3.3"));//No translation in convert script. string command="INSERT INTO preference (PrefName, ValueString,Comments) VALUES ('CoPay_FeeSchedule_BlankLikeZero','1','1 to treat blank entries like zero copay. 0 to make patient responsible on blank entries.')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.3.3.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_3_4(); } private static void To6_3_4() { if(FromVersion<new Version("6.3.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.3.4"));//No translation in convert script. string command="ALTER TABLE sheetfielddef CHANGE FieldValue FieldValue text NOT NULL"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.3.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_4_1(); } private static void To6_4_1() { if(FromVersion<new Version("6.4.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.4.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="UPDATE preference SET Comments = '-1 indicates min for all dates' WHERE PrefName = 'RecallDaysPast'"; Db.NonQ32(command); command="UPDATE preference SET Comments = '-1 indicates max for all dates' WHERE PrefName = 'RecallDaysFuture'"; Db.NonQ32(command); command="INSERT INTO preference (PrefName, ValueString,Comments) VALUES ('RecallShowIfDaysFirstReminder','-1','-1 indicates do not show')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName, ValueString,Comments) VALUES ('RecallShowIfDaysSecondReminder','-1','-1 indicates do not show')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailMessage','You are due for your regular dental check-up on ?DueDate Please call our office today to schedule an appointment.','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailFamMsg','You are due for your regular dental check-up. [FamilyList] Please call our office today to schedule an appointment.','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailSubject2','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailMessage2','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallPostcardMessage2','','')"; Db.NonQ32(command); string prefVal; DataTable table; command="SELECT ValueString FROM preference WHERE PrefName='RecallPostcardMessage'"; table=Db.GetTable(command); prefVal=table.Rows[0][0].ToString().Replace("?DueDate","[DueDate]"); command="UPDATE preference SET ValueString='"+POut.String(prefVal)+"' WHERE PrefName='RecallPostcardMessage'"; Db.NonQ32(command); command="SELECT ValueString FROM preference WHERE PrefName='RecallPostcardFamMsg'"; table=Db.GetTable(command); prefVal=table.Rows[0][0].ToString().Replace("?FamilyList","[FamilyList]"); command="UPDATE preference SET ValueString='"+POut.String(prefVal)+"' WHERE PrefName='RecallPostcardFamMsg'"; Db.NonQ32(command); command="SELECT ValueString FROM preference WHERE PrefName='ConfirmPostcardMessage'"; table=Db.GetTable(command); prefVal=table.Rows[0][0].ToString().Replace("?date","[date]"); prefVal=prefVal.Replace("?time","[time]"); command="UPDATE preference SET ValueString='"+POut.String(prefVal)+"' WHERE PrefName='ConfirmPostcardMessage'"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailSubject3','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailMessage3','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallPostcardMessage3','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailFamMsg2','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallEmailFamMsg3','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallPostcardFamMsg2','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallPostcardFamMsg3','','')"; Db.NonQ32(command); command="ALTER TABLE autonote CHANGE ControlsToInc MainText text"; Db.NonQ32(command); command="UPDATE autonote SET MainText = ''"; Db.NonQ32(command); command="UPDATE autonotecontrol SET ControlType='Text' WHERE ControlType='MultiLineTextBox'"; Db.NonQ32(command); command="UPDATE autonotecontrol SET ControlType='OneResponse' WHERE ControlType='ComboBox'"; Db.NonQ32(command); command="UPDATE autonotecontrol SET ControlType='Text' WHERE ControlType='TextBox'"; Db.NonQ32(command); command="UPDATE autonotecontrol SET ControlOptions=MultiLineText WHERE MultiLineText != ''"; Db.NonQ32(command); command="ALTER TABLE autonotecontrol DROP PrefaceText"; Db.NonQ32(command); command="ALTER TABLE autonotecontrol DROP MultiLineText"; Db.NonQ32(command); } else {//oracle } command="UPDATE preference SET ValueString = '6.4.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_4_4(); } private static void To6_4_4() { if(FromVersion<new Version("6.4.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.4.4"));//No translation in convert script. string command; //Convert comma-delimited autonote controls to carriage-return delimited. command="SELECT AutoNoteControlNum,ControlOptions FROM autonotecontrol"; DataTable table=Db.GetTable(command); string newVal; for(int i=0;i<table.Rows.Count;i++) { newVal=table.Rows[i]["ControlOptions"].ToString(); newVal=newVal.TrimEnd(','); newVal=newVal.Replace(",","\r\n"); command="UPDATE autonotecontrol SET ControlOptions='"+POut.String(newVal) +"' WHERE AutoNoteControlNum="+table.Rows[i]["AutoNoteControlNum"].ToString(); Db.NonQ32(command); } command="UPDATE preference SET ValueString = '6.4.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_5_1(); } private static void To6_5_1() { if(FromVersion<new Version("6.5.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.5.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('ShowFeatureMedicalInsurance','0','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingUseElectronic','0','Set to 1 to used e-billing.')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingElectVendorId','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingElectVendorPMSCode','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingElectCreditCardChoices','V,MC','Choices of V,MC,D,A comma delimited.')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingElectClientAcctNumber','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingElectUserName','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingElectPassword','','')"; Db.NonQ32(command); command="INSERT INTO definition (Category,ItemOrder,ItemName,ItemValue,ItemColor,IsHidden) VALUES(12,22,'Status Condition','',-8978432,0)"; Db.NonQ32(command); command="INSERT INTO definition (Category,ItemOrder,ItemName,ItemValue,ItemColor,IsHidden) VALUES(22,16,'Condition','',-5169880,0)"; Db.NonQ32(command); command="INSERT INTO definition (Category,ItemOrder,ItemName,ItemValue,ItemColor,IsHidden) VALUES(22,17,'Condition (light)','',-1678747,0)"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingIgnoreInPerson','0','Set to 1 to ignore walkout statements.')"; Db.NonQ32(command); //eClinicalWorks Bridge--------------------------------------------------------------------------- command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'eClinicalWorks', " +"'eClinicalWorks from www.eclinicalworks.com', " +"'0', " +"'', " +"'', " +"'')"; int programNum=Db.NonQ32(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'HL7FolderIn', " +"'')"; Db.NonQ32(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'HL7FolderOut', " +"'')"; Db.NonQ32(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'DefaultUserGroup', " +"'')"; Db.NonQ32(command); command = "ALTER TABLE anesthmedsgiven ADD AnesthMedNum int NOT NULL"; Db.NonQ32(command); command = "ALTER TABLE provider ADD AnesthProvType int NOT NULL"; Db.NonQ32(command); command="DROP TABLE IF EXISTS hl7msg"; Db.NonQ32(command); command=@"CREATE TABLE hl7msg ( HL7MsgNum int NOT NULL auto_increment, HL7Status int NOT NULL, MsgText text, AptNum int NOT NULL, PRIMARY KEY (HL7MsgNum), INDEX (AptNum) ) DEFAULT CHARSET=utf8"; Db.NonQ32(command); } else {//oracle } command="UPDATE preference SET ValueString = '6.5.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_6_1(); } private static void To6_6_1() { if(FromVersion<new Version("6.6.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.6.1"));//No translation in convert script. string command; DataTable table; if(DataConnection.DBtype==DatabaseType.MySql) { //Change defaults for XDR bridge------------------------------------------------------------------- command="SELECT Enabled,ProgramNum FROM program WHERE ProgName='XDR'"; table=Db.GetTable(command); int programNum; if(table.Rows.Count>0 && table.Rows[0]["Enabled"].ToString()=="0") {//if XDR not enabled //change the defaults programNum=PIn.Int(table.Rows[0]["ProgramNum"].ToString()); command="UPDATE program SET Path='"+POut.String(@"C:\XDRClient\Bin\XDR.exe")+"' WHERE ProgramNum="+POut.Long(programNum); Db.NonQ32(command); command="UPDATE programproperty SET PropertyValue='"+POut.String(@"C:\XDRClient\Bin\infofile.txt")+"' " +"WHERE ProgramNum="+POut.Long(programNum)+" " +"AND PropertyDesc='InfoFile path'"; Db.NonQ32(command); command="UPDATE toolbutitem SET ToolBar=7 "//The toolbar at the top that is common to all modules. +"WHERE ProgramNum="+POut.Long(programNum); Db.NonQ32(command); } //iCat Bridge--------------------------------------------------------------------------- command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'iCat', " +"'iCat from www.imagingsciences.com', " +"'0', " +"'"+POut.String(@"C:\Program Files\ISIP\iCATVision\Vision.exe")+"', " +"'', " +"'')"; programNum=Db.NonQ32(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+programNum.ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+programNum.ToString()+"', " +"'Acquisition computer name', " +"'')"; Db.NonQ32(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+programNum.ToString()+"', " +"'XML output file path', " +"'"+POut.String(@"C:\iCat\Out\pm.xml")+"')"; Db.NonQ32(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+programNum.ToString()+"', " +"'Return folder path', " +"'"+POut.String(@"C:\iCat\Return")+"')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Long((int)ToolBarsAvail.ChartModule)+"', " +"'iCat')"; Db.NonQ32(command); //end of iCat Bridge string[] commands = new string[]{ "ALTER TABLE anesthvsdata ADD MessageID varchar(50)", "ALTER TABLE anesthvsdata ADD HL7Message longtext" }; Db.NonQ32(commands); command="ALTER TABLE computer DROP PrinterName"; Db.NonQ32(command); command="ALTER TABLE computer ADD LastHeartBeat datetime NOT NULL default '0001-01-01'"; Db.NonQ32(command); command="ALTER TABLE registrationkey ADD UsesServerVersion tinyint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE registrationkey ADD IsFreeVersion tinyint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE registrationkey ADD IsOnlyForTesting tinyint NOT NULL"; Db.NonQ32(command); } else {//oracle } command="UPDATE preference SET ValueString = '6.6.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_6_2(); } private static void To6_6_2() { if(FromVersion<new Version("6.6.2.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.6.2"));//No translation in convert script. string command; command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('WebServiceServerName','','Blank if not using web service.')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.6.2.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_6_3(); } private static void To6_6_3() { if(FromVersion<new Version("6.6.3.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.6.3"));//No translation in convert script. string command; command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('UpdateInProgressOnComputerName','','Will be blank if update is complete. If in the middle of an update, the named workstation is the only one allowed to startup OD.')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.6.3.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_6_8(); } private static void To6_6_8() { if(FromVersion<new Version("6.6.8.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.6.8"));//No translation in convert script. string command; command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('UpdateMultipleDatabases','','Comma delimited')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.6.8.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_6_16(); } private static void To6_6_16() { if(FromVersion<new Version("6.6.16.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.6.16"));//No translation in convert script. string command; command="SELECT ProgramNum FROM program WHERE ProgName='MediaDent'"; int programNum=PIn.Int(Db.GetScalar(command)); command="DELETE FROM programproperty WHERE ProgramNum="+POut.Long(programNum) +" AND PropertyDesc='Image Folder'"; Db.NonQ32(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'"+POut.String("Text file path")+"', " +"'"+POut.String(@"C:\MediadentInfo.txt")+"')"; Db.NonQ32(command); command="UPDATE program SET Note='Text file path needs to be the same on all computers.' WHERE ProgramNum="+POut.Long(programNum); Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.6.16.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_6_19(); } private static void To6_6_19() { if(FromVersion<new Version("6.6.19.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.6.19"));//No translation in convert script. string command; command="UPDATE employee SET LName='O' WHERE LName='' AND FName=''"; Db.NonQ32(command); command="UPDATE schedule SET SchedType=1 WHERE ProvNum != 0 AND SchedType != 1"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.6.19.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_7_1(); } private static void To6_7_1() { if(FromVersion<new Version("6.7.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.7.1"));//No translation in convert script. string command; command="ALTER TABLE document ADD DateTStamp TimeStamp"; Db.NonQ32(command); command="UPDATE document SET DateTStamp=NOW()"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('StatementShowNotes','0','Payments and adjustments.')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('StatementShowProcBreakdown','0','')"; Db.NonQ32(command); command="ALTER TABLE etrans ADD EtransMessageTextNum INT NOT NULL"; Db.NonQ32(command); command="DROP TABLE IF EXISTS etransmessagetext"; Db.NonQ32(command); command=@"CREATE TABLE etransmessagetext ( EtransMessageTextNum int NOT NULL auto_increment, MessageText text NOT NULL, PRIMARY KEY (EtransMessageTextNum), INDEX(MessageText(255)) ) DEFAULT CHARSET=utf8"; Db.NonQ32(command); command="ALTER TABLE etrans ADD INDEX(MessageText(255))"; Db.NonQ32(command); command="INSERT INTO etransmessagetext (MessageText) " +"SELECT DISTINCT MessageText FROM etrans " +"WHERE etrans.MessageText != ''"; Db.NonQ32(command); command="UPDATE etrans,etransmessagetext " +"SET etrans.EtransMessageTextNum=etransmessagetext.EtransMessageTextNum " +"WHERE etrans.MessageText=etransmessagetext.MessageText"; Db.NonQ32(command); command="ALTER TABLE etrans DROP MessageText"; Db.NonQ32(command); command="ALTER TABLE etransmessagetext DROP INDEX MessageText"; Db.NonQ32(command); command="ALTER TABLE etrans ADD AckEtransNum INT NOT NULL"; Db.NonQ32(command); //Fill the AckEtransNum values for existing claims. command=@"DROP TABLE IF EXISTS etack; CREATE TABLE etack ( EtransNum int(11) NOT NULL auto_increment, DateTimeTrans datetime NOT NULL, ClearinghouseNum int(11) NOT NULL, BatchNumber int(11) NOT NULL, PRIMARY KEY (`EtransNum`) ) SELECT * FROM etrans WHERE Etype=21; UPDATE etrans etorig, etack SET etorig.AckEtransNum=etack.EtransNum WHERE etorig.EtransNum != etack.EtransNum AND etorig.BatchNumber=etack.BatchNumber AND etorig.ClearinghouseNum=etack.ClearinghouseNum AND etorig.DateTimeTrans > DATE_SUB(etack.DateTimeTrans,INTERVAL 14 DAY) AND etorig.DateTimeTrans < DATE_ADD(etack.DateTimeTrans,INTERVAL 1 DAY); DROP TABLE IF EXISTS etAck"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('UpdateWebProxyAddress','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('UpdateWebProxyUserName','','')"; Db.NonQ32(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('UpdateWebProxyPassword','','')"; Db.NonQ32(command); command="ALTER TABLE etrans ADD PlanNum INT NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans ADD INDEX (PlanNum)"; Db.NonQ32(command); //Added new enum value of 0=None to CoverageLevel. command="UPDATE benefit SET CoverageLevel=CoverageLevel+1 WHERE BenefitType=2 OR BenefitType=5";//Deductible, Limitations Db.NonQ32(command); command="ALTER TABLE benefit CHANGE Percent Percent tinyint NOT NULL";//So that we can store -1. Db.NonQ32(command); command="UPDATE benefit SET Percent=-1 WHERE BenefitType != 1";//set Percent empty where not CoInsurance Db.NonQ32(command); command="ALTER TABLE benefit DROP OldCode"; Db.NonQ32(command); //set MonetaryAmt empty when ActiveCoverage,CoInsurance,Exclusion command="UPDATE benefit SET MonetaryAmt=-1 WHERE BenefitType=0 OR BenefitType=1 OR BenefitType=4"; Db.NonQ32(command); //set MonetaryAmt empty when Limitation and a quantity is entered command="UPDATE benefit SET MonetaryAmt=-1 WHERE BenefitType=5 AND Quantity != 0"; Db.NonQ32(command); if(CultureInfo.CurrentCulture.Name=="en-US") { command="UPDATE covcat SET CovOrder=CovOrder+1 WHERE CovOrder > 1"; Db.NonQ32(command); command="INSERT INTO covcat (Description,DefaultPercent,CovOrder,IsHidden,EbenefitCat) VALUES('X-Ray',100,2,0,13)"; int covCatNum=Db.NonQ32(command,true); command="INSERT INTO covspan (CovCatNum,FromCode,ToCode) VALUES("+POut.Long(covCatNum)+",'D0200','D0399')"; Db.NonQ32(command); command="SELECT MAX(CovOrder) FROM covcat"; int covOrder=PIn.Int(Db.GetScalar(command)); command="INSERT INTO covcat (Description,DefaultPercent,CovOrder,IsHidden,EbenefitCat) VALUES('Adjunctive',-1," +POut.Long(covOrder+1)+",0,14)";//adjunctive covCatNum=Db.NonQ32(command,true); command="INSERT INTO covspan (CovCatNum,FromCode,ToCode) VALUES("+POut.Long(covCatNum)+",'D9000','D9999')"; Db.NonQ32(command); command="SELECT CovCatNum FROM covcat WHERE EbenefitCat=1";//general covCatNum=Db.NonQ32(command,true); command="DELETE FROM covspan WHERE CovCatNum="+POut.Long(covCatNum); Db.NonQ32(command); command="INSERT INTO covspan (CovCatNum,FromCode,ToCode) VALUES("+POut.Long(covCatNum)+",'D0000','D7999')"; Db.NonQ32(command); command="INSERT INTO covspan (CovCatNum,FromCode,ToCode) VALUES("+POut.Long(covCatNum)+",'D9000','D9999')"; Db.NonQ32(command); } command="ALTER TABLE claimproc ADD DedEst double NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc ADD DedEstOverride double NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc ADD InsEstTotal double NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc ADD InsEstTotalOverride double NOT NULL"; Db.NonQ32(command); command="UPDATE claimproc SET DedApplied=-1 WHERE ClaimNum=0";//if not attached to a claim, clear this value Db.NonQ32(command); command="UPDATE claimproc SET DedEstOverride=-1"; Db.NonQ32(command); command="UPDATE claimproc SET InsEstTotal=BaseEst"; Db.NonQ32(command); command="UPDATE claimproc SET InsEstTotalOverride=OverrideInsEst"; Db.NonQ32(command); command="ALTER TABLE claimproc DROP OverrideInsEst"; Db.NonQ32(command); command="ALTER TABLE claimproc DROP DedBeforePerc"; Db.NonQ32(command); command="ALTER TABLE claimproc DROP OverAnnualMax"; Db.NonQ32(command); command="ALTER TABLE claimproc ADD PaidOtherInsOverride double NOT NULL"; Db.NonQ32(command); command="UPDATE claimproc SET PaidOtherInsOverride=PaidOtherIns"; Db.NonQ32(command); command="ALTER TABLE claimproc ADD EstimateNote varchar(255) NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan ADD MonthRenew tinyint NOT NULL"; Db.NonQ32(command); command="SELECT insplan.PlanNum,MONTH(DateEffective) " +"FROM insplan,benefit " +"WHERE insplan.PlanNum=benefit.PlanNum " +"AND benefit.TimePeriod=1 " +"GROUP BY insplan.PlanNum";//service year DataTable table=Db.GetTable(command); for(int i=0;i<table.Rows.Count;i++) { command="UPDATE insplan SET MonthRenew="+table.Rows[i][1].ToString() +" WHERE PlanNum="+table.Rows[i][0].ToString(); Db.NonQ32(command); } command="ALTER TABLE appointment ADD InsPlan1 INT NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment ADD INDEX (InsPlan1)"; Db.NonQ32(command); command="ALTER TABLE appointment ADD InsPlan2 INT NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment ADD INDEX (InsPlan2)"; Db.NonQ32(command); command="DROP TABLE IF EXISTS insfilingcode"; Db.NonQ32(command); command=@"CREATE TABLE insfilingcode ( InsFilingCodeNum INT AUTO_INCREMENT, Descript VARCHAR(255), EclaimCode VARCHAR(100), ItemOrder INT, PRIMARY KEY(InsFilingCodeNum), INDEX(ItemOrder) )"; Db.NonQ32(command); command="DROP TABLE IF EXISTS insfilingcodesubtype"; Db.NonQ32(command); command=@"CREATE TABLE insfilingcodesubtype ( InsFilingCodeSubtypeNum INT AUTO_INCREMENT, InsFilingCodeNum INT, Descript VARCHAR(255), INDEX(InsFilingCodeNum), PRIMARY KEY(InsFilingCodeSubtypeNum) )"; Db.NonQ32(command); command="ALTER TABLE insplan ADD FilingCodeSubtype INT NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan ADD INDEX (FilingCodeSubtype)"; Db.NonQ32(command); //eCW bridge enhancements command="SELECT ProgramNum FROM program WHERE ProgName='eClinicalWorks'"; int programNum=PIn.Int(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'ShowImagesModule', " +"'0')"; Db.NonQ32(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'IsStandalone', " +"'0')";//starts out as false Db.NonQ32(command); command="UPDATE insplan SET FilingCode = FilingCode+1"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(1,'Commercial_Insurance','CI',0)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(2,'SelfPay','09',1)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(3,'OtherNonFed','11',2)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(4,'PPO','12',3)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(5,'POS','13',4)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(6,'EPO','14',5)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(7,'Indemnity','15',6)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(8,'HMO_MedicareRisk','16',7)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(9,'DMO','17',8)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(10,'BCBS','BL',9)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(11,'Champus','CH',10)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(12,'Disability','DS',11)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(13,'FEP','FI',12)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(14,'HMO','HM',13)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(15,'LiabilityMedical','LM',14)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(16,'MedicarePartB','MB',15)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(17,'Medicaid','MC',16)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(18,'ManagedCare_NonHMO','MH',17)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(19,'OtherFederalProgram','OF',18)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(20,'SelfAdministered','SA',19)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(21,'Veterans','VA',20)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(22,'WorkersComp','WC',21)"; Db.NonQ32(command); command="INSERT INTO insfilingcode VALUES(23,'MutuallyDefined','ZZ',22)"; Db.NonQ32(command); //Fixes bug here instead of db maint //Duplicated in version 6.6 command="UPDATE employee SET LName='O' WHERE LName='' AND FName=''"; Db.NonQ32(command); command="UPDATE schedule SET SchedType=1 WHERE ProvNum != 0 AND SchedType != 1"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.7.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_7_3(); } private static void To6_7_3() { if(FromVersion<new Version("6.7.3.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.7.3"));//No translation in convert script. string command=@"UPDATE claimform,claimformitem SET claimformitem.FieldName='IsGroupHealthPlan' WHERE claimformitem.FieldName='IsStandardClaim' AND claimform.ClaimFormNum=claimformitem.ClaimFormNum AND claimform.UniqueID='OD9'";//1500 Db.NonQ32(command); command=@"UPDATE claimform,claimformitem SET claimformitem.XPos='97' WHERE claimformitem.XPos='30' AND claimform.ClaimFormNum=claimformitem.ClaimFormNum AND claimform.UniqueID='OD9'"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.7.3.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_7_4(); } private static void To6_7_4() { if(FromVersion<new Version("6.7.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.7.4"));//No translation in convert script. string command="DELETE FROM medicationpat WHERE EXISTS(SELECT * FROM patient WHERE medicationpat.PatNum=patient.PatNum AND patient.PatStatus=4)"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.7.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_7_5(); } private static void To6_7_5() { if(FromVersion<new Version("6.7.5.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.7.5"));//No translation in convert script. string command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('ClaimsValidateACN','0','If set to 1, then any claim with a groupName containing ADDP will require an ACN number in the claim remarks.')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.7.5.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_7_12(); } private static void To6_7_12() { if(FromVersion<new Version("6.7.12.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.7.12"));//No translation in convert script. string command; //Camsight Bridge--------------------------------------------------------------------------- command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Camsight', " +"'Camsight from www.camsight.com', " +"'0', " +"'"+POut.String(@"C:\cdm\cdm\cdmx\cdmx.exe")+"', " +"'', " +"'')"; int programNum=Db.NonQ32(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+programNum.ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Long((int)ToolBarsAvail.ChartModule)+"', " +"'Camsight')"; Db.NonQ32(command); //CliniView Bridge--------------------------------------------------------------------------- command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'CliniView', " +"'CliniView', " +"'0', " +"'"+POut.String(@"C:\Program Files\CliniView\CliniView.exe")+"', " +"'', " +"'')"; programNum=Db.NonQ32(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+programNum.ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Long((int)ToolBarsAvail.ChartModule)+"', " +"'CliniView')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.7.12.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_7_15(); } private static void To6_7_15() { //duplicated in 6.6.26 if(FromVersion<new Version("6.7.15.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.7.15"));//No translation in convert script. string command; command="ALTER TABLE insplan CHANGE FeeSched FeeSched int NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE CopayFeeSched CopayFeeSched int NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE AllowedFeeSched AllowedFeeSched int NOT NULL"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '6.7.15.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_7_22(); } private static void To6_7_22() { if(FromVersion<new Version("6.7.22.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.7.22"));//No translation in convert script. string command; command="UPDATE preference SET ValueString ='http://opendentalsoft.com:1942/WebServiceCustomerUpdates/Service1.asmx' WHERE PrefName='UpdateServerAddress' AND ValueString LIKE '%70.90.133.65%'"; Db.NonQ(command); try { command="ALTER TABLE document ADD INDEX (PatNum)"; Db.NonQ(command); command="ALTER TABLE procedurelog ADD INDEX (BillingTypeOne)"; Db.NonQ(command); command="ALTER TABLE procedurelog ADD INDEX (BillingTypeTwo)"; Db.NonQ(command); command="ALTER TABLE securitylog ADD INDEX (PatNum)"; Db.NonQ(command); command="ALTER TABLE toothinitial ADD INDEX (PatNum)"; Db.NonQ(command); command="ALTER TABLE patplan ADD INDEX (PlanNum)"; Db.NonQ(command); } catch { //in case any of the indices arlready exists. } command="UPDATE preference SET ValueString = '6.7.22.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To6_8_1(); } //To6_7_25()//duplicated further down private static void To6_8_1() { if(FromVersion<new Version("6.8.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.8.1"));//No translation in convert script. string command; //add TreatPlanEdit,ReportProdInc,TimecardDeleteEntry permissions to all groups------------------------------------------------------ command="SELECT UserGroupNum FROM usergroup"; DataTable table=Db.GetTable(command); int groupNum; for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Int(table.Rows[i][0].ToString()); command="INSERT INTO grouppermission (NewerDate,UserGroupNum,PermType) " +"VALUES('0001-01-01',"+POut.Long(groupNum)+","+POut.Long((int)Permissions.TreatPlanEdit)+")"; Db.NonQ32(command); command="INSERT INTO grouppermission (NewerDate,UserGroupNum,PermType) " +"VALUES('0001-01-01',"+POut.Long(groupNum)+","+POut.Long((int)Permissions.ReportProdInc)+")"; Db.NonQ32(command); command="INSERT INTO grouppermission (NewerDate,UserGroupNum,PermType) " +"VALUES('0001-01-01',"+POut.Long(groupNum)+","+POut.Long((int)Permissions.TimecardDeleteEntry)+")"; Db.NonQ32(command); } command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('BillingExcludeIfUnsentProcs','0','')"; Db.NonQ32(command); command="SELECT MAX(DefNum) FROM definition"; int defNum=PIn.Int(Db.GetScalar(command))+1; command="SELECT MAX(ItemOrder) FROM definition WHERE Category=18"; int order=PIn.Int(Db.GetScalar(command))+1; command="INSERT INTO definition (DefNum,Category,ItemOrder,ItemName,ItemValue,ItemColor,IsHidden) VALUES(" +POut.Long(defNum)+",18,"+POut.Long(order)+",'Tooth Charts','T',0,0)"; Db.NonQ32(command); command="ALTER TABLE apptview ADD OnlyScheduledProvs tinyint unsigned NOT NULL"; Db.NonQ32(command); //Get rid of some old columns command="ALTER TABLE appointment DROP Lab"; Db.NonQ32(command); command="ALTER TABLE appointment DROP InstructorNum"; Db.NonQ32(command); command="ALTER TABLE appointment DROP SchoolClassNum"; Db.NonQ32(command); command="ALTER TABLE appointment DROP SchoolCourseNum"; Db.NonQ32(command); command="ALTER TABLE appointment DROP GradePoint"; Db.NonQ32(command); command="DROP TABLE IF EXISTS graphicassembly"; Db.NonQ32(command); command="DROP TABLE IF EXISTS graphicelement"; Db.NonQ32(command); command="DROP TABLE IF EXISTS graphicpoint"; Db.NonQ32(command); command="DROP TABLE IF EXISTS graphicshape"; Db.NonQ32(command); command="DROP TABLE IF EXISTS graphictype"; Db.NonQ32(command); command="DROP TABLE IF EXISTS proclicense"; Db.NonQ32(command); command="DROP TABLE IF EXISTS scheddefault"; Db.NonQ32(command); //Change all primary and foreign keys to 64 bit--------------------------------------------------------------- command="ALTER TABLE account CHANGE AccountNum AccountNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE accountingautopay CHANGE AccountingAutoPayNum AccountingAutoPayNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE accountingautopay CHANGE PayType PayType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE adjustment CHANGE AdjNum AdjNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE adjustment CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE adjustment CHANGE AdjType AdjType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE adjustment CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE adjustment CHANGE ProcNum ProcNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE AptNum AptNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE Confirmed Confirmed bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE Op Op bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE ProvHyg ProvHyg bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE NextAptNum NextAptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE UnschedStatus UnschedStatus bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE Assistant Assistant bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE InsPlan1 InsPlan1 bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointment CHANGE InsPlan2 InsPlan2 bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE appointmentrule CHANGE AppointmentRuleNum AppointmentRuleNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE apptview CHANGE ApptViewNum ApptViewNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE apptviewitem CHANGE ApptViewItemNum ApptViewItemNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE apptviewitem CHANGE ApptViewNum ApptViewNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE apptviewitem CHANGE OpNum OpNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE apptviewitem CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE autocode CHANGE AutoCodeNum AutoCodeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE autocodecond CHANGE AutoCodeCondNum AutoCodeCondNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE autocodecond CHANGE AutoCodeItemNum AutoCodeItemNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE autocodeitem CHANGE AutoCodeItemNum AutoCodeItemNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE autocodeitem CHANGE AutoCodeNum AutoCodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE autocodeitem CHANGE CodeNum CodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE autonote CHANGE AutoNoteNum AutoNoteNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE autonotecontrol CHANGE AutoNoteControlNum AutoNoteControlNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE benefit CHANGE BenefitNum BenefitNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE benefit CHANGE PlanNum PlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE benefit CHANGE PatPlanNum PatPlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE benefit CHANGE CovCatNum CovCatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE benefit CHANGE CodeNum CodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE canadianclaim CHANGE ClaimNum ClaimNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE canadianextract CHANGE CanadianExtractNum CanadianExtractNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE canadianextract CHANGE ClaimNum ClaimNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE canadiannetwork CHANGE CanadianNetworkNum CanadianNetworkNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE carrier CHANGE CarrierNum CarrierNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE carrier CHANGE CanadianNetworkNum CanadianNetworkNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE ClaimNum ClaimNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE PlanNum PlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE ProvTreat ProvTreat bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE ProvBill ProvBill bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE ReferringProv ReferringProv bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE PlanNum2 PlanNum2 bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claim CHANGE ClaimForm ClaimForm bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimattach CHANGE ClaimAttachNum ClaimAttachNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claimattach CHANGE ClaimNum ClaimNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimcondcodelog CHANGE ClaimCondCodeLogNum ClaimCondCodeLogNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claimcondcodelog CHANGE ClaimNum ClaimNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimform CHANGE ClaimFormNum ClaimFormNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claimformitem CHANGE ClaimFormItemNum ClaimFormItemNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claimformitem CHANGE ClaimFormNum ClaimFormNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimpayment CHANGE ClaimPaymentNum ClaimPaymentNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claimpayment CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimpayment CHANGE DepositNum DepositNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc CHANGE ClaimProcNum ClaimProcNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claimproc CHANGE ProcNum ProcNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc CHANGE ClaimNum ClaimNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc CHANGE ClaimPaymentNum ClaimPaymentNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimproc CHANGE PlanNum PlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE claimvalcodelog CHANGE ClaimValCodeLogNum ClaimValCodeLogNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE claimvalcodelog CHANGE ClaimNum ClaimNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE clearinghouse CHANGE ClearinghouseNum ClearinghouseNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE clinic CHANGE ClinicNum ClinicNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE clinic CHANGE InsBillingProv InsBillingProv bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE clockevent CHANGE ClockEventNum ClockEventNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE clockevent CHANGE EmployeeNum EmployeeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE commlog CHANGE CommlogNum CommlogNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE commlog CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE commlog CHANGE CommType CommType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE commlog CHANGE UserNum UserNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE computer CHANGE ComputerNum ComputerNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE computerpref CHANGE ComputerPrefNum ComputerPrefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE contact CHANGE ContactNum ContactNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE contact CHANGE Category Category bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE covcat CHANGE CovCatNum CovCatNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE covspan CHANGE CovSpanNum CovSpanNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE covspan CHANGE CovCatNum CovCatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE definition CHANGE DefNum DefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE deletedobject CHANGE DeletedObjectNum DeletedObjectNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE deletedobject CHANGE ObjectNum ObjectNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE deposit CHANGE DepositNum DepositNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE disease CHANGE DiseaseNum DiseaseNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE disease CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE disease CHANGE DiseaseDefNum DiseaseDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE diseasedef CHANGE DiseaseDefNum DiseaseDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE displayfield CHANGE DisplayFieldNum DisplayFieldNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE document CHANGE DocNum DocNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE document CHANGE DocCategory DocCategory bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE document CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE document CHANGE MountItemNum MountItemNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE dunning CHANGE DunningNum DunningNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE dunning CHANGE BillingType BillingType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE electid CHANGE ElectIDNum ElectIDNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE emailattach CHANGE EmailAttachNum EmailAttachNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE emailattach CHANGE EmailMessageNum EmailMessageNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE emailmessage CHANGE EmailMessageNum EmailMessageNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE emailmessage CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE emailtemplate CHANGE EmailTemplateNum EmailTemplateNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE employee CHANGE EmployeeNum EmployeeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE employer CHANGE EmployerNum EmployerNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE EtransNum EtransNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE ClearingHouseNum ClearingHouseNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE ClaimNum ClaimNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE CarrierNum CarrierNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE CarrierNum2 CarrierNum2 bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE EtransMessageTextNum EtransMessageTextNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE AckEtransNum AckEtransNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etrans CHANGE PlanNum PlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE etransmessagetext CHANGE EtransMessageTextNum EtransMessageTextNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE fee CHANGE FeeNum FeeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE fee CHANGE FeeSched FeeSched bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE fee CHANGE CodeNum CodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE feesched CHANGE FeeSchedNum FeeSchedNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE files CHANGE DocNum DocNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE formpat CHANGE FormPatNum FormPatNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE formpat CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE grouppermission CHANGE GroupPermNum GroupPermNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE grouppermission CHANGE UserGroupNum UserGroupNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE hl7msg CHANGE HL7MsgNum HL7MsgNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE hl7msg CHANGE AptNum AptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insfilingcode CHANGE InsFilingCodeNum InsFilingCodeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE insfilingcodesubtype CHANGE InsFilingCodeSubTypeNum InsFilingCodeSubTypeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE insfilingcodesubtype CHANGE InsFilingCodeNum InsFilingCodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE PlanNum PlanNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE Subscriber Subscriber bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE FeeSched FeeSched bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE ClaimFormNum ClaimFormNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE CopayFeeSched CopayFeeSched bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE EmployerNum EmployerNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE CarrierNum CarrierNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE AllowedFeeSched AllowedFeeSched bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE FilingCode FilingCode bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE insplan CHANGE FilingCodeSubtype FilingCodeSubtype bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE journalentry CHANGE JournalEntryNum JournalEntryNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE journalentry CHANGE TransactionNum TransactionNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE journalentry CHANGE AccountNum AccountNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE journalentry CHANGE ReconcileNum ReconcileNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE labcase CHANGE LabCaseNum LabCaseNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE labcase CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE labcase CHANGE LaboratoryNum LaboratoryNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE labcase CHANGE AptNum AptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE labcase CHANGE PlannedAptNum PlannedAptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE labcase CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE laboratory CHANGE LaboratoryNum LaboratoryNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE labturnaround CHANGE LabTurnaroundNum LabTurnaroundNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE labturnaround CHANGE LaboratoryNum LaboratoryNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE letter CHANGE LetterNum LetterNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE lettermerge CHANGE LetterMergeNum LetterMergeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE lettermerge CHANGE Category Category bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE lettermergefield CHANGE FieldNum FieldNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE lettermergefield CHANGE LetterMergeNum LetterMergeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE medication CHANGE MedicationNum MedicationNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE medication CHANGE GenericNum GenericNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE medicationpat CHANGE MedicationPatNum MedicationPatNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE medicationpat CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE medicationpat CHANGE MedicationNum MedicationNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE mount CHANGE MountNum MountNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE mount CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE mount CHANGE DocCategory DocCategory bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE mountdef CHANGE MountDefNum MountDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE mountitem CHANGE MountItemNum MountItemNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE mountitem CHANGE MountNum MountNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE mountitemdef CHANGE MountItemDefNum MountItemDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE mountitemdef CHANGE MountDefNum MountDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE operatory CHANGE OperatoryNum OperatoryNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE operatory CHANGE ProvDentist ProvDentist bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE operatory CHANGE ProvHygienist ProvHygienist bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE operatory CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patfield CHANGE PatFieldNum PatFieldNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE patfield CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patfielddef CHANGE PatFieldDefNum PatFieldDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE PatNum PatNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE Guarantor Guarantor bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE PriProv PriProv bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE SecProv SecProv bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE FeeSched FeeSched bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE BillingType BillingType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE EmployerNum EmployerNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE SiteNum SiteNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patient CHANGE ResponsParty ResponsParty bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patientnote CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patplan CHANGE PatPlanNum PatPlanNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE patplan CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE patplan CHANGE PlanNum PlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payment CHANGE PayNum PayNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE payment CHANGE PayType PayType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payment CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payment CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payment CHANGE DepositNum DepositNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payperiod CHANGE PayPeriodNum PayPeriodNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE payplan CHANGE PayPlanNum PayPlanNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE payplan CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payplan CHANGE Guarantor Guarantor bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payplan CHANGE PlanNum PlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payplancharge CHANGE PayPlanChargeNum PayPlanChargeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE payplancharge CHANGE PayPlanNum PayPlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payplancharge CHANGE Guarantor Guarantor bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payplancharge CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE payplancharge CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE paysplit CHANGE SplitNum SplitNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE paysplit CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE paysplit CHANGE PayNum PayNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE paysplit CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE paysplit CHANGE PayPlanNum PayPlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE paysplit CHANGE ProcNum ProcNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE perioexam CHANGE PerioExamNum PerioExamNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE perioexam CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE perioexam CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE periomeasure CHANGE PerioMeasureNum PerioMeasureNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE periomeasure CHANGE PerioExamNum PerioExamNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE pharmacy CHANGE PharmacyNum PharmacyNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE phonenumber CHANGE PhoneNumberNum PhoneNumberNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE phonenumber CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE plannedappt CHANGE PlannedApptNum PlannedApptNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE plannedappt CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE plannedappt CHANGE AptNum AptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE popup CHANGE PopupNum PopupNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE popup CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE printer CHANGE PrinterNum PrinterNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE printer CHANGE ComputerNum ComputerNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procbutton CHANGE ProcButtonNum ProcButtonNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE procbutton CHANGE Category Category bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procbuttonitem CHANGE ProcButtonItemNum ProcButtonItemNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE procbuttonitem CHANGE ProcButtonNum ProcButtonNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procbuttonitem CHANGE AutoCodeNum AutoCodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procbuttonitem CHANGE CodeNum CodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE proccodenote CHANGE ProcCodeNoteNum ProcCodeNoteNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE proccodenote CHANGE CodeNum CodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE proccodenote CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurecode CHANGE CodeNum CodeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE procedurecode CHANGE ProcCat ProcCat bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE ProcNum ProcNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE AptNum AptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE Priority Priority bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE Dx Dx bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE PlannedAptNum PlannedAptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE ProcNumLab ProcNumLab bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE BillingTypeOne BillingTypeOne bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE BillingTypeTwo BillingTypeTwo bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE CodeNum CodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procedurelog CHANGE SiteNum SiteNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procnote CHANGE ProcNoteNum ProcNoteNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE procnote CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procnote CHANGE ProcNum ProcNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE procnote CHANGE UserNum UserNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE proctp CHANGE ProcTPNum ProcTPNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE proctp CHANGE TreatPlanNum TreatPlanNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE proctp CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE proctp CHANGE ProcNumOrig ProcNumOrig bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE proctp CHANGE Priority Priority bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE program CHANGE ProgramNum ProgramNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE programproperty CHANGE ProgramPropertyNum ProgramPropertyNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE programproperty CHANGE ProgramNum ProgramNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE provider CHANGE ProvNum ProvNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE provider CHANGE FeeSched FeeSched bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE provider CHANGE SchoolClassNum SchoolClassNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE provider CHANGE AnesthProvType AnesthProvType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE providerident CHANGE ProviderIdentNum ProviderIdentNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE providerident CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE question CHANGE QuestionNum QuestionNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE question CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE question CHANGE FormPatNum FormPatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE questiondef CHANGE QuestionDefNum QuestionDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE quickpastecat CHANGE QuickPasteCatNum QuickPasteCatNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE quickpastenote CHANGE QuickPasteNoteNum QuickPasteNoteNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE quickpastenote CHANGE QuickPasteCatNum QuickPasteCatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE recall CHANGE RecallNum RecallNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE recall CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE recall CHANGE RecallStatus RecallStatus bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE recall CHANGE RecallTypeNum RecallTypeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE recalltrigger CHANGE RecallTriggerNum RecallTriggerNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE recalltrigger CHANGE RecallTypeNum RecallTypeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE recalltrigger CHANGE CodeNum CodeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE recalltype CHANGE RecallTypeNum RecallTypeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE reconcile CHANGE ReconcileNum ReconcileNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE reconcile CHANGE AccountNum AccountNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE refattach CHANGE RefAttachNum RefAttachNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE refattach CHANGE ReferralNum ReferralNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE refattach CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE referral CHANGE ReferralNum ReferralNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE referral CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE referral CHANGE Slip Slip bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE registrationkey CHANGE RegistrationKeyNum RegistrationKeyNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE registrationkey CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE repeatcharge CHANGE RepeatChargeNum RepeatChargeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE repeatcharge CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqneeded CHANGE ReqNeededNum ReqNeededNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE reqneeded CHANGE SchoolCourseNum SchoolCourseNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqneeded CHANGE SchoolClassNum SchoolClassNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqstudent CHANGE ReqStudentNum ReqStudentNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE reqstudent CHANGE ReqNeededNum ReqNeededNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqstudent CHANGE SchoolCourseNum SchoolCourseNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqstudent CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqstudent CHANGE AptNum AptNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqstudent CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE reqstudent CHANGE InstructorNum InstructorNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE rxalert CHANGE RxAlertNum RxAlertNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE rxalert CHANGE RxDefNum RxDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE rxalert CHANGE DiseaseDefNum DiseaseDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE rxdef CHANGE RxDefNum RxDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE rxpat CHANGE RxNum RxNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE rxpat CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE rxpat CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE rxpat CHANGE PharmacyNum PharmacyNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE schedule CHANGE ScheduleNum ScheduleNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE schedule CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE schedule CHANGE BlockoutType BlockoutType bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE schedule CHANGE EmployeeNum EmployeeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE scheduleop CHANGE ScheduleOpNum ScheduleOpNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE scheduleop CHANGE ScheduleNum ScheduleNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE scheduleop CHANGE OperatoryNum OperatoryNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE schoolclass CHANGE SchoolClassNum SchoolClassNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE schoolcourse CHANGE SchoolCourseNum SchoolCourseNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE screen CHANGE ScreenNum ScreenNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE screen CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE screen CHANGE ScreenGroupNum ScreenGroupNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE screengroup CHANGE ScreenGroupNum ScreenGroupNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE securitylog CHANGE SecurityLogNum SecurityLogNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE securitylog CHANGE UserNum UserNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE securitylog CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sheet CHANGE SheetNum SheetNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE sheet CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sheetdef CHANGE SheetDefNum SheetDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE sheetfield CHANGE SheetFieldNum SheetFieldNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE sheetfield CHANGE SheetNum SheetNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sheetfielddef CHANGE SheetFieldDefNum SheetFieldDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE sheetfielddef CHANGE SheetDefNum SheetDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sigbutdef CHANGE SigButDefNum SigButDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE sigbutdefelement CHANGE ElementNum ElementNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE sigbutdefelement CHANGE SigButDefNum SigButDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sigbutdefelement CHANGE SigElementDefNum SigElementDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sigelement CHANGE SigElementNum SigElementNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE sigelement CHANGE SigElementDefNum SigElementDefNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sigelement CHANGE SignalNum SignalNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE sigelementdef CHANGE SigElementDefNum SigElementDefNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE `signal` CHANGE SignalNum SignalNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE `signal` CHANGE TaskNum TaskNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE site CHANGE SiteNum SiteNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE statement CHANGE StatementNum StatementNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE statement CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE statement CHANGE DocNum DocNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE supplier CHANGE SupplierNum SupplierNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE supply CHANGE SupplyNum SupplyNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE supply CHANGE SupplierNum SupplierNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE supply CHANGE Category Category bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE supplyneeded CHANGE SupplyNeededNum SupplyNeededNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE supplyorder CHANGE SupplyOrderNum SupplyOrderNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE supplyorder CHANGE SupplierNum SupplierNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE supplyorderitem CHANGE SupplyOrderItemNum SupplyOrderItemNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE supplyorderitem CHANGE SupplyOrderNum SupplyOrderNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE supplyorderitem CHANGE SupplyNum SupplyNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE task CHANGE TaskNum TaskNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE task CHANGE TaskListNum TaskListNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE task CHANGE KeyNum KeyNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE task CHANGE FromNum FromNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE task CHANGE UserNum UserNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE taskancestor CHANGE TaskAncestorNum TaskAncestorNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE taskancestor CHANGE TaskNum TaskNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE taskancestor CHANGE TaskListNum TaskListNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE tasklist CHANGE TaskListNum TaskListNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE tasklist CHANGE Parent Parent bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE tasklist CHANGE FromNum FromNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE tasksubscription CHANGE TaskSubscriptionNum TaskSubscriptionNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE tasksubscription CHANGE UserNum UserNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE tasksubscription CHANGE TaskListNum TaskListNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE terminalactive CHANGE TerminalActiveNum TerminalActiveNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE terminalactive CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE timeadjust CHANGE TimeAdjustNum TimeAdjustNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE timeadjust CHANGE EmployeeNum EmployeeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE toolbutitem CHANGE ToolButItemNum ToolButItemNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE toolbutitem CHANGE ProgramNum ProgramNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE toothinitial CHANGE ToothInitialNum ToothInitialNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE toothinitial CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE transaction CHANGE TransactionNum TransactionNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE transaction CHANGE UserNum UserNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE transaction CHANGE DepositNum DepositNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE transaction CHANGE PayNum PayNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE treatplan CHANGE TreatPlanNum TreatPlanNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE treatplan CHANGE PatNum PatNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE treatplan CHANGE ResponsParty ResponsParty bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE usergroup CHANGE UserGroupNum UserGroupNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE userod CHANGE UserNum UserNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE userod CHANGE UserGroupNum UserGroupNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE userod CHANGE EmployeeNum EmployeeNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE userod CHANGE ClinicNum ClinicNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE userod CHANGE ProvNum ProvNum bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE userod CHANGE TaskListInBox TaskListInBox bigint NOT NULL"; Db.NonQ32(command); command="ALTER TABLE userquery CHANGE QueryNum QueryNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="ALTER TABLE zipcode CHANGE ZipCodeNum ZipCodeNum bigint NOT NULL auto_increment"; Db.NonQ32(command); command="DROP TABLE IF EXISTS replicationserver"; Db.NonQ32(command); command=@"CREATE TABLE replicationserver ( ReplicationServerNum bigint NOT NULL auto_increment, Descript TEXT NOT NULL, ServerId INT unsigned NOT NULL, RangeStart BIGINT NOT NULL, RangeEnd BIGINT NOT NULL, PRIMARY KEY(ReplicationServerNum) )"; Db.NonQ32(command); command="ALTER TABLE claimproc ADD WriteOffEst double NOT NULL"; Db.NonQ(command); command="ALTER TABLE claimproc ADD WriteOffEstOverride double NOT NULL"; Db.NonQ(command); command="UPDATE claimproc SET WriteOffEst = -1"; Db.NonQ(command); command="UPDATE claimproc SET WriteOffEstOverride = -1"; Db.NonQ(command); command="ALTER TABLE paysplit ADD UnearnedType bigint NOT NULL"; Db.NonQ(command); command="INSERT INTO preference (PrefName,ValueString,Comments) VALUES ('RecallMaxNumberReminders','-1','')"; Db.NonQ(command); command="ALTER TABLE recall ADD DisableUntilBalance double NOT NULL"; Db.NonQ(command); command="ALTER TABLE recall ADD DisableUntilDate date NOT NULL default '0001-01-01'"; Db.NonQ(command); command="ALTER TABLE program ADD PluginDllName varchar(255) NOT NULL"; Db.NonQ(command); command="DELETE FROM preference WHERE PrefName = 'DeductibleBeforePercentAsDefault'"; Db.NonQ(command); //We will not delete this pref just in case it's needed later. It's not used anywhere right now. //command = "DELETE FROM preference WHERE PrefName='EnableAnesthMod'"; //We will not delete this pref just in case it's needed later. It's not used anywhere right now. //command="DELETE FROM preference WHERE PrefName='ImageStore'";//this option is no longer supported. //Db.NonQ(command); command="SELECT MAX(ItemOrder) FROM definition WHERE Category=2"; int itemOrder=PIn.Int(Db.GetScalar(command))+1;//eg 7+1 //this should end up with an acceptable autoincrement even if using random primary keys. command="INSERT INTO definition (Category,ItemOrder,ItemName,ItemValue) VALUES (2,"+POut.Int(itemOrder)+",'E-mailed','E-mailed')"; Db.NonQ(command); command="SELECT DefNum FROM definition WHERE Category=2 AND ItemOrder="+POut.Int(itemOrder); string defNumStr=Db.GetScalar(command); command="INSERT INTO preference (PrefName,ValueString) VALUES ('ConfirmStatusEmailed','"+defNumStr+"')"; Db.NonQ(command); command="INSERT INTO preference (PrefName,ValueString) VALUES ('ConfirmEmailSubject','Appointment Confirmation')"; Db.NonQ(command); command="INSERT INTO preference (PrefName,ValueString) VALUES ('ConfirmEmailMessage','[NameF], We would like to confirm your appointment on [date] at [time]')"; Db.NonQ(command); command="ALTER TABLE replicationserver ADD AtoZpath varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE replicationserver ADD UpdateBlocked tinyint NOT NULL"; Db.NonQ(command); try { command="ALTER TABLE task ADD INDEX (KeyNum)"; Db.NonQ(command); } catch { } command="UPDATE preference SET ValueString = '6.8.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To6_8_7(); } private static void To6_8_7() { //duplicated in 6.7 if(FromVersion<new Version("6.8.7.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.8.7"));//No translation in convert script. string command; try { command="ALTER TABLE claimpayment ADD INDEX (DepositNum)"; Db.NonQ(command); command="ALTER TABLE payment ADD INDEX (DepositNum)"; Db.NonQ(command); } catch { //in case any of the indices already exists. } command="UPDATE preference SET ValueString = '6.8.7.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To6_8_11(); } private static void To6_8_11() { //duplicated in 6.6 and 6.7 if(FromVersion<new Version("6.8.11.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.8.11"));//No translation in convert script. string command; //Mediadent version 4 and 5--------------------------------------- command="SELECT COUNT(*) FROM programproperty WHERE PropertyDesc='MediaDent Version 4 or 5'"; if(Db.GetScalar(command)=="0") { command="SELECT ProgramNum FROM program WHERE ProgName='MediaDent'"; long programNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'"+POut.String("MediaDent Version 4 or 5")+"', " +"'5')"; Db.NonQ(command); //add back the image folder command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'"+POut.String("Image Folder")+"', " +"'"+POut.String(@"C:\Mediadent\patients\")+"')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '6.8.11.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To6_8_12(); } private static void To6_8_12() { if(FromVersion<new Version("6.8.12.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.8.12"));//No translation in convert script. string command; //Ewoo_EZDent bridge------------------------------------------------------------------------- command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'EwooEZDent', " +"'EwooEZDent from www.ewoousa.com', " +"'0', " +"'"+POut.String(@"C:\EasyDent4\Edp4\EasyDent4.exe")+"', " +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Long((int)ToolBarsAvail.ChartModule)+"', " +"'EZDent')"; Db.NonQ(command); command="UPDATE preference SET ValueString = '6.8.12.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To6_8_24(); } private static void To6_8_24() { if(FromVersion<new Version("6.8.24.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.8.24"));//No translation in convert script. string command; command="SELECT CodeNum FROM procedurecode WHERE ProcCode='D1204'"; string codeNum1204=Db.GetScalar(command); command="SELECT CodeNum FROM procedurecode WHERE ProcCode='D1203'"; string codeNum1203=Db.GetScalar(command); if(codeNum1203!="" && codeNum1204!="") { command="UPDATE benefit SET CodeNum="+codeNum1203+" WHERE CodeNum="+codeNum1204; Db.NonQ(command); } command="UPDATE preference SET ValueString = '6.8.24.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To6_9_1(); } private static void To6_9_1() { if(FromVersion<new Version("6.9.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.9.1"));//No translation in convert script. string command; //Mountainside Bridge--------------------------------------------------------------------------- command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Mountainside', " +"'Mountainside from www.mountainsidesoftware.com', " +"'0', " +"'', " +"'', " +"'')"; Db.NonQ(command); //Move the HL7 folders from eCW to the pref table command="SELECT PropertyValue FROM programproperty WHERE PropertyDesc='HL7FolderOut'"; string folder=Db.GetScalar(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('HL7FolderOut','"+POut.String(folder)+"')"; Db.NonQ(command); command="DELETE FROM programproperty WHERE PropertyDesc='HL7FolderOut'"; Db.NonQ(command); command="SELECT PropertyValue FROM programproperty WHERE PropertyDesc='HL7FolderIn'"; folder=Db.GetScalar(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('HL7FolderIn','"+POut.String(folder)+"')"; Db.NonQ(command); command="DELETE FROM programproperty WHERE PropertyDesc='HL7FolderIn'"; Db.NonQ(command); //Clinic enhancements---------------------------------------------------------------------------------------- command="ALTER TABLE paysplit ADD ClinicNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE paysplit ADD INDEX (ClinicNum)"; Db.NonQ(command); command="Update payment,paysplit SET paysplit.ClinicNum = payment.ClinicNum WHERE paysplit.PayNum = payment.PayNum"; Db.NonQ(command); command="ALTER TABLE claimproc ADD ClinicNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claimproc ADD INDEX (ClinicNum)"; Db.NonQ(command); command="Update procedurelog,claimproc SET claimproc.ClinicNum = procedurelog.ClinicNum WHERE claimproc.ProcNum = procedurelog.ProcNum"; Db.NonQ(command); //then, for claimprocs that are total payments and not attached to any proc: command="Update claim,claimproc SET claimproc.ClinicNum = claim.ClinicNum WHERE claimproc.ClaimNum = claim.ClaimNum AND claimproc.ProcNum=0"; Db.NonQ(command); command="ALTER TABLE adjustment ADD ClinicNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE adjustment ADD INDEX (ClinicNum)"; Db.NonQ(command); command="ALTER TABLE payplancharge ADD ClinicNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE payplancharge ADD INDEX (ClinicNum)"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PerioColorCAL','-16777011')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PerioColorFurcations','-16777216')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PerioColorFurcationsRed','-7667712')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PerioColorGM','-8388480')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PerioColorMGJ','-29696')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PerioColorProbing','-16744448')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PerioColorProbingRed','-65536')"; Db.NonQ(command); command="ALTER TABLE registrationkey ADD VotesAllotted int NOT NULL"; Db.NonQ(command); command="UPDATE registrationkey SET VotesAllotted =100"; Db.NonQ(command); command="ALTER TABLE apptview ADD OnlySchedBeforeTime time NOT NULL"; Db.NonQ(command); command="ALTER TABLE apptview ADD OnlySchedAfterTime time NOT NULL"; Db.NonQ(command); command="DROP TABLE IF EXISTS automation"; Db.NonQ(command); command=@"CREATE TABLE automation ( AutomationNum bigint NOT NULL auto_increment, Description text NOT NULL, Autotrigger tinyint NOT NULL, ProcCodes text NOT NULL, AutoAction tinyint NOT NULL, SheetNum bigint NOT NULL, CommType bigint NOT NULL, MessageContent text NOT NULL, PRIMARY KEY(AutomationNum) )"; Db.NonQ(command); command="ALTER TABLE sheet ADD Description varchar(255) NOT NULL"; Db.NonQ(command); //for each sheettype, set descriptions for all sheets of that type. for(int i=0;i<Enum.GetNames(typeof(SheetTypeEnum)).Length;i++) { command="UPDATE sheet SET Description= '"+POut.String(Enum.GetNames(typeof(SheetTypeEnum))[i])+"' " +"WHERE SheetType="+POut.Int(i); Db.NonQ(command); } command="UPDATE preference SET ValueString = '6.9.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To6_9_4(); } private static void To6_9_4() { if(FromVersion<new Version("6.9.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.9.4"));//No translation in convert script. string command; command="ALTER TABLE automation CHANGE SheetNum SheetDefNum bigint NOT NULL"; Db.NonQ(command); //Trophy command="SELECT ProgramNum FROM program WHERE ProgName='TrophyEnhanced'"; long programNum=PIn.Long(Db.GetScalar(command)); if(programNum>0) { command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 1 to enable Numbered Mode', " +"'0')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '6.9.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To6_9_10(); } private static void To6_9_10() { if(FromVersion<new Version("6.9.10.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 6.9.10"));//No translation in convert script. string command; command="ALTER TABLE computerpref ADD COLUMN DirectXFormat VARCHAR(255) DEFAULT ''"; Db.NonQ(command); command="UPDATE preference SET ValueString = '6.9.10.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_0_1(); } private static void To7_0_1() { if(FromVersion<new Version("7.0.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.0.1"));//No translation in convert script. string command; command="INSERT INTO preference(PrefName,ValueString) VALUES('InsDefaultShowUCRonClaims','0')"; Db.NonQ(command); command="DROP TABLE IF EXISTS equipment"; Db.NonQ(command); command=@"CREATE TABLE equipment ( EquipmentNum bigint NOT NULL auto_increment, Description text NOT NULL, SerialNumber varchar(255), ModelYear varchar(2), DatePurchased date NOT NULL default '0001-01-01', DateSold date NOT NULL default '0001-01-01', PurchaseCost double NOT NULL, MarketValue double NOT NULL, Location text NOT NULL, DateEntry date NOT NULL default '0001-01-01', PRIMARY KEY(EquipmentNum) )"; Db.NonQ(command); command="ALTER TABLE sheet ADD ShowInTerminal tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE sheetfielddef ADD RadioButtonValue varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE sheetfield ADD RadioButtonValue varchar(255) NOT NULL"; Db.NonQ(command); //add a bunch of indexes to the benefit table to make it faster when there are many similar plans command="ALTER TABLE benefit ADD INDEX(CovCatNum)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(BenefitType)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(Percent)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(MonetaryAmt)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(TimePeriod)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(QuantityQualifier)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(Quantity)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(CodeNum)"; Db.NonQ(command); command="ALTER TABLE benefit ADD INDEX(CoverageLevel)"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.0.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ32(command); } To7_1_1(); } private static void To7_1_1() { if(FromVersion<new Version("7.1.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.1.1"));//No translation in convert script. string command; try { command="ALTER TABLE refattach ADD INDEX (PatNum)"; Db.NonQ(command); } catch {} command="INSERT INTO preference(PrefName,ValueString) VALUES('UpdateShowMsiButtons','0')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('ReportsPPOwriteoffDefaultToProcDate','0')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('ReportsShowPatNum','0')"; Db.NonQ(command); command="ALTER TABLE userod ADD DefaultHidePopups tinyint NOT NULL"; Db.NonQ(command); command="DROP TABLE IF EXISTS taskunread"; Db.NonQ(command); command=@"CREATE TABLE taskunread ( TaskUnreadNum bigint NOT NULL auto_increment, TaskNum bigint NOT NULL, UserNum bigint NOT NULL, PRIMARY KEY (TaskUnreadNum), INDEX(TaskNum), INDEX(UserNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); //MercuryDE clearinghouse. command=@"INSERT INTO clearinghouse(Description,ExportPath,IsDefault,Payors,Eformat, Password,ResponsePath,CommBridge,ClientProgram,ISA05,ISA07, ISA08, ISA15, GS03) VALUES('MercuryDE','"+POut.String(@"C:\MercuryDE\Temp\")+@"','0','','1','','','11','','ZZ','ZZ', '204203105', 'P', '204203105')"; Db.NonQ(command); command="ALTER TABLE clockevent CHANGE TimeEntered TimeEntered1 datetime NOT NULL default '0001-01-01 00:00:00'"; Db.NonQ(command); command="ALTER TABLE clockevent CHANGE TimeDisplayed TimeDisplayed1 datetime NOT NULL default '0001-01-01 00:00:00'"; Db.NonQ(command); command="ALTER TABLE clockevent ADD TimeEntered2 datetime NOT NULL default '0001-01-01 00:00:00'"; Db.NonQ(command); command="ALTER TABLE clockevent ADD TimeDisplayed2 datetime NOT NULL default '0001-01-01 00:00:00'"; Db.NonQ(command); command="SELECT * FROM clockevent WHERE ClockStatus != 2 ORDER BY EmployeeNum,TimeDisplayed1"; DataTable table=Db.GetTable(command); DateTime timeEntered2; DateTime timeDisplayed2; string note; int clockStatus; for(int i=0;i<table.Rows.Count;i++){ if(table.Rows[i]["ClockIn"].ToString()=="0"){//false continue;//only stop on clock-in rows, not clock-out. } if(i==table.Rows.Count-1){//if this is the last row break;//because we always need the next clock-out to actually do anything. } if(table.Rows[i+1]["ClockIn"].ToString()=="1"){//true continue;//if the next row is also a clock-in, then we have two clock-ins in a row. Can't do anything. } if(table.Rows[i]["EmployeeNum"].ToString()!=table.Rows[i+1]["EmployeeNum"].ToString()){//employeeNums don't match continue; } timeEntered2=PIn.DateT(table.Rows[i+1]["TimeEntered1"].ToString());//The time of the second row timeDisplayed2=PIn.DateT(table.Rows[i+1]["TimeDisplayed1"].ToString()); clockStatus=PIn.Int(table.Rows[i+1]["ClockStatus"].ToString()); note=PIn.String(table.Rows[i+1]["Note"].ToString()); command="UPDATE clockevent SET " +"TimeEntered2 = "+POut.DateT(timeEntered2)+", " +"TimeDisplayed2 = "+POut.DateT(timeDisplayed2)+", " +"ClockStatus = "+POut.Int(clockStatus)+", " +"Note = CONCAT(Note,'"+POut.String(note)+"') " +"WHERE ClockEventNum = "+table.Rows[i]["ClockEventNum"].ToString(); Db.NonQ(command); command="DELETE FROM clockevent WHERE ClockEventNum = "+table.Rows[i+1]["ClockEventNum"].ToString(); Db.NonQ(command); } //now, breaks, which are out/in instead of in/out. command="SELECT * FROM clockevent WHERE ClockStatus = 2 ORDER BY EmployeeNum,TimeDisplayed1"; table=Db.GetTable(command); for(int i=0;i<table.Rows.Count;i++){ if(table.Rows[i]["ClockIn"].ToString()=="1"){//true continue;//only stop on clock-out rows, not clock-in. } if(i==table.Rows.Count-1){//if this is the last row break;//because we always need the next clock-in to actually do anything. } if(table.Rows[i+1]["ClockIn"].ToString()=="0"){//false continue;//if the next row is also a clock-out, then we have two clock-outs in a row. Can't do anything. } if(table.Rows[i]["EmployeeNum"].ToString()!=table.Rows[i+1]["EmployeeNum"].ToString()){//employeeNums don't match continue; } timeEntered2=PIn.DateT(table.Rows[i+1]["TimeEntered1"].ToString());//The time of the second row timeDisplayed2=PIn.DateT(table.Rows[i+1]["TimeDisplayed1"].ToString()); //clockStatus=PIn.Int(table.Rows[i+1]["ClockStatus"].ToString()); note=PIn.String(table.Rows[i+1]["Note"].ToString()); command="UPDATE clockevent SET " +"TimeEntered2 = "+POut.DateT(timeEntered2)+", " +"TimeDisplayed2 = "+POut.DateT(timeDisplayed2)+", " //+"ClockStatus = "+POut.Int(clockStatus)+", " +"Note = CONCAT(Note,'"+POut.String(note)+"') " +"WHERE ClockEventNum = "+table.Rows[i]["ClockEventNum"].ToString(); Db.NonQ(command); command="DELETE FROM clockevent WHERE ClockEventNum = "+table.Rows[i+1]["ClockEventNum"].ToString(); Db.NonQ(command); } command="ALTER TABLE clockevent DROP ClockIn"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PasswordsMustBeStrong','0')"; Db.NonQ(command); command="ALTER TABLE userod ADD PasswordIsStrong tinyint NOT NULL"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('SecurityLockDays','0')"; Db.NonQ(command); command="ALTER TABLE laboratory DROP LabSlip"; Db.NonQ(command); command="ALTER TABLE laboratory ADD Slip bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE laboratory ADD Address varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE laboratory ADD City varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE laboratory ADD State varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE laboratory ADD Zip varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE laboratory ADD Email varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE laboratory ADD WirelessPhone varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog ADD HideGraphics tinyint NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.1.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_1_2(); } private static void To7_1_2() { if(FromVersion<new Version("7.1.2.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.1.2"));//No translation in convert script. string command; command="ALTER TABLE provider ADD TaxonomyCodeOverride varchar(255) NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.1.2.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_1_16(); } private static void To7_1_16() { if(FromVersion<new Version("7.1.16.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.1.16"));//No translation in convert script. string command; command="ALTER TABLE etransmessagetext CHANGE MessageText MessageText mediumtext NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.1.16.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_1_18(); } private static void To7_1_18() { if(FromVersion<new Version("7.1.18.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.1.18"));//No translation in convert script. string command; command="INSERT INTO preference(PrefName,ValueString) VALUES('ToothChartMoveMenuToRight','0')"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.1.18.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_1_24(); } private static void To7_1_24() { if(FromVersion<new Version("7.1.24.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.1.24"));//No translation in convert script. string command; command="UPDATE patient SET Guarantor=PatNum WHERE Guarantor=0;"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.1.24.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_1(); } private static void To7_2_1() { if(FromVersion<new Version("7.2.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.1"));//No translation in convert script. string command; //this column was a varchar holding currency amounts. command="ALTER TABLE claimvalcodelog CHANGE ValAmount ValAmount double not null"; Db.NonQ(command); command="ALTER TABLE carrier ADD CanadianEncryptionMethod tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE carrier ADD CanadianTransactionPrefix varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE carrier ADD CanadianSupportedTypes int NOT NULL"; Db.NonQ(command); command="ALTER TABLE canadianclaim DROP EligibilityCode"; Db.NonQ(command); command="ALTER TABLE canadianclaim DROP SchoolName"; Db.NonQ(command); command="ALTER TABLE patient ADD CanadianEligibilityCode tinyint NOT NULL"; Db.NonQ(command); command="DROP TABLE canadianextract"; Db.NonQ(command); command="DROP TABLE canadianclaim"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianMaterialsForwarded varchar(10) NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianReferralProviderNum varchar(20) NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianReferralReason tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianIsInitialLower varchar(5) NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianDateInitialLower date NOT NULL default '0001-01-01'"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianMandProsthMaterial tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianIsInitialUpper varchar(5) NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianDateInitialUpper date NOT NULL default '0001-01-01'"; Db.NonQ(command); command="ALTER TABLE claim ADD CanadianMaxProsthMaterial tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE carrier DROP IsPMP"; Db.NonQ(command); command="ALTER TABLE insplan ADD CanadianPlanFlag varchar(5) NOT NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog ADD CanadianTypeCodes varchar(20) NOT NULL"; Db.NonQ(command); command="UPDATE clearinghouse SET ResponsePath='"+POut.String(@"C:\MercuryDE\Reports\")+"' WHERE ResponsePath='' AND Description='MercuryDE' LIMIT 1"; Db.NonQ(command); command="DROP TABLE IF EXISTS guardian"; Db.NonQ(command); command=@"CREATE TABLE guardian ( GuardianNum bigint NOT NULL auto_increment, PatNumChild bigint NOT NULL, PatNumGuardian bigint NOT NULL, Relationship tinyint NOT NULL, PRIMARY KEY (GuardianNum), INDEX(PatNumChild), INDEX(PatNumGuardian) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="ALTER TABLE apptviewitem ADD ElementAlignment tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE apptview ADD StackBehavUR tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE apptview ADD StackBehavLR tinyint NOT NULL"; Db.NonQ(command); command="DROP TABLE IF EXISTS apptfield"; Db.NonQ(command); command=@"CREATE TABLE apptfield ( ApptFieldNum bigint NOT NULL auto_increment, AptNum bigint NOT NULL, FieldName varchar(255) NOT NULL, FieldValue text NOT NULL, PRIMARY KEY (ApptFieldNum), INDEX(AptNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="DROP TABLE IF EXISTS apptfielddef"; Db.NonQ(command); command=@"CREATE TABLE apptfielddef ( ApptFieldDefNum bigint NOT NULL auto_increment, FieldName varchar(255) NOT NULL, PRIMARY KEY (ApptFieldDefNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); try { command="ALTER TABLE patfield ADD INDEX (PatNum)"; Db.NonQ(command); } catch { //in case the index already exists. } command="ALTER TABLE labcase ADD LabFee double NOT NULL"; Db.NonQ(command); command="ALTER TABLE insplan CHANGE PlanNote PlanNote text NOT NULL"; Db.NonQ(command); command="ALTER TABLE insplan CHANGE BenefitNotes BenefitNotes text NOT NULL"; Db.NonQ(command); command="ALTER TABLE insplan CHANGE SubscNote SubscNote text NOT NULL"; Db.NonQ(command); command="ALTER TABLE apptviewitem ADD ApptFieldDefNum bigint NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.2.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_3(); } private static void To7_2_3() { if(FromVersion<new Version("7.2.3.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.3"));//No translation in convert script. string command; command="ALTER TABLE apptviewitem ADD PatFieldDefNum bigint NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.2.3.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_4(); } private static void To7_2_4() { if(FromVersion<new Version("7.2.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.4"));//No translation in convert script. string command; command="UPDATE apptview SET StackBehavUR=1";//all horiz Db.NonQ(command); command="SELECT ApptViewNum FROM apptview";//all of them. DataTable table=Db.GetTable(command); for(int i=0;i<table.Rows.Count;i++) { command="SELECT COUNT(*) FROM apptviewitem WHERE ApptViewNum="+table.Rows[i]["ApptViewNum"].ToString() +" AND ElementDesc='AssistantAbbr'"; if(Db.GetCount(command)=="0") { command="INSERT INTO apptviewitem (ApptViewNum,ElementDesc,ElementOrder,ElementColor,ElementAlignment) VALUES(" +table.Rows[i]["ApptViewNum"].ToString()+"," +"'AssistantAbbr'," +"0," +"-16777216,"//black +"2)";//LR Db.NonQ(command); } command="SELECT COUNT(*) FROM apptviewitem WHERE ApptViewNum="+table.Rows[i]["ApptViewNum"].ToString() +" AND ElementDesc='ConfirmedColor'"; if(Db.GetCount(command)=="0") { command="INSERT INTO apptviewitem (ApptViewNum,ElementDesc,ElementOrder,ElementColor,ElementAlignment) VALUES(" +table.Rows[i]["ApptViewNum"].ToString()+"," +"'ConfirmedColor'," +"0," +"-16777216," +"1)";//UR Db.NonQ(command); } command="SELECT COUNT(*) FROM apptviewitem WHERE ApptViewNum="+table.Rows[i]["ApptViewNum"].ToString() +" AND ElementDesc='HasIns[I]'"; if(Db.GetCount(command)=="0") { command="INSERT INTO apptviewitem (ApptViewNum,ElementDesc,ElementOrder,ElementColor,ElementAlignment) VALUES(" +table.Rows[i]["ApptViewNum"].ToString()+"," +"'HasIns[I]'," +"1," +"-16777216," +"1)";//UR Db.NonQ(command); } command="SELECT COUNT(*) FROM apptviewitem WHERE ApptViewNum="+table.Rows[i]["ApptViewNum"].ToString() +" AND ElementDesc='InsToSend[!]'"; if(Db.GetCount(command)=="0") { command="INSERT INTO apptviewitem (ApptViewNum,ElementDesc,ElementOrder,ElementColor,ElementAlignment) VALUES(" +table.Rows[i]["ApptViewNum"].ToString()+"," +"'InsToSend[!]'," +"2," +"-65536,"//red +"1)";//UR Db.NonQ(command); } } command="UPDATE preference SET ValueString = '7.2.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_7(); } private static void To7_2_7() { if(FromVersion<new Version("7.2.7.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.7"));//No translation in convert script. string command; command="UPDATE apptviewitem SET ElementColor=-1 WHERE ElementDesc='"+POut.String("MedOrPremed[+]")+"'";//white Db.NonQ(command); command="UPDATE apptviewitem SET ElementColor=-1 WHERE ElementDesc='"+POut.String("HasIns[I]")+"'"; Db.NonQ(command); command="UPDATE apptviewitem SET ElementColor=-1 WHERE ElementDesc='"+POut.String("InsToSend[!]")+"'"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.2.7.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_12(); } private static void To7_2_12() { if(FromVersion<new Version("7.2.12.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.12"));//No translation in convert script. string command; command="INSERT INTO preference(PrefName,ValueString) VALUES('RecallUseEmailIfHasEmailAddress','0')"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.2.12.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_31(); } private static void To7_2_31() { if(FromVersion<new Version("7.2.31.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.31"));//No translation in convert script. string command; //add Sopro bridge: command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Sopro', " +"'Sopro by Acteon www.acteongroup.com', " +"'0', " +"'"+POut.String(@"C:\Program Files\Sopro Imaging\SOPRO Imaging.exe")+"', " +"'', " +"'')"; Db.NonQ(command); command="SELECT ProgramNum FROM program WHERE ProgName='Sopro' LIMIT 1"; long programNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Sopro')"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.2.31.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_36(); } private static void To7_2_36() { if(FromVersion<new Version("7.2.36.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.36"));//No translation in convert script. string command; command="ALTER TABLE hl7msg CHANGE MsgText MsgText MEDIUMTEXT"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.2.36.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_2_38(); } private static void To7_2_38() { if(FromVersion<new Version("7.2.38.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.2.38"));//No translation in convert script. string command; //add Progeny bridge: command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Progeny', " +"'Progeny from www.progenydental.com', " +"'0', " +"'"+POut.String(@"C:\Program Files\Progeny\Progeny Imaging\PIBridge.exe")+"', " +"'', " +"'')"; Db.NonQ(command); command="SELECT ProgramNum FROM program WHERE ProgName='Progeny' LIMIT 1"; long programNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Progeny')"; Db.NonQ32(command); //ProcDate, split off time component----------------------------------------------------------------------- command="ALTER TABLE procedurelog ADD ProcTime time NOT NULL"; Db.NonQ(command); command="UPDATE procedurelog SET ProcTime = time(ProcDate)"; Db.NonQ(command); command="ALTER TABLE procedurelog CHANGE ProcDate ProcDate date NOT NULL default '0001-01-01'"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.2.38.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_3_1(); } private static void To7_3_1() { if(FromVersion<new Version("7.3.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.3.1"));//No translation in convert script. string command; command="ALTER TABLE patient CHANGE SchoolName SchoolName varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE sheet ADD IsWebForm tinyint NOT NULL"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('WebHostSynchServerURL','https://opendentalsoft.com/WebHostSynch/WebHostSynch.asmx')"; Db.NonQ(command); command="ALTER TABLE appointment ADD DateTimeAskedToArrive datetime NOT NULL default '0001-01-01 00:00:00'"; Db.NonQ(command); command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'OrthoPlex', " +"'OrthoPlex from Dentsply GAC', " +"'0', " +"'"+POut.String(@"C:\\Program Files\\GAC\\OrthoPlex v3.20\\OrthoPlex.exe")+"', " +"'-E [PatNum]', " +"'')"; Db.NonQ(command); command="SELECT ProgramNum FROM program WHERE ProgName='OrthoPlex' LIMIT 1"; long programNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int((int)ToolBarsAvail.ChartModule)+"', " +"'OrthoPlex')"; Db.NonQ(command); command="ALTER TABLE patient ADD AskToArriveEarly int NOT NULL"; Db.NonQ(command); command="ALTER TABLE appointment ADD ProcsColored text NOT NULL"; Db.NonQ(command); command="DROP TABLE IF EXISTS procapptcolor"; Db.NonQ(command); command=@"CREATE TABLE procapptcolor ( ProcApptColorNum bigint NOT NULL auto_increment, CodeRange varchar(255) NOT NULL, ColorText int NOT NULL, PRIMARY KEY (ProcApptColorNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="ALTER TABLE procapptcolor ADD ShowPreviousDate tinyint NOT NULL"; Db.NonQ(command); command="DROP TABLE IF EXISTS chartview"; Db.NonQ(command); command=@"CREATE TABLE chartview ( ChartViewNum bigint NOT NULL auto_increment, Description varchar(255) NOT NULL, ItemOrder int NOT NULL, ProcStatuses tinyint NOT NULL, ObjectTypes smallint NOT NULL, ShowProcNotes tinyint NOT NULL, IsAudit tinyint NOT NULL, SelectedTeethOnly tinyint NOT NULL, PRIMARY KEY (ChartViewNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="ALTER TABLE sheetfield ADD RadioButtonGroup varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE sheetfield ADD IsRequired tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE sheetfielddef ADD RadioButtonGroup varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE sheetfielddef ADD IsRequired tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE displayfield ADD ChartViewNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE displayfield ADD INDEX (ChartViewNum)"; Db.NonQ(command); command="DELETE FROM displayfield WHERE Category = 0"; Db.NonQ(command); command="DROP TABLE IF EXISTS procgroupitem"; Db.NonQ(command); command=@"CREATE TABLE procgroupitem ( ProcGroupItemNum bigint NOT NULL auto_increment, ProcNum bigint NOT NULL, GroupNum bigint NOT NULL, PRIMARY KEY (ProcGroupItemNum), INDEX(ProcNum), INDEX(GroupNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="SELECT DefNum FROM definition WHERE Category=11 ORDER BY ItemOrder DESC LIMIT 1"; long procCat=PIn.Long(Db.GetScalar(command)); command=@"INSERT INTO procedurecode (ProcCode,Descript,AbbrDesc,ProcTime,ProcCat, DefaultNote) VALUES('~GRP~','Group Note','GrpNote','" +POut.String("/X/")+"',"+POut.Long(procCat)+",'')"; Db.NonQ(command); //add Orion bridge: command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Orion', " +"'Orion', " +"'0', " +"'', " +"'', " +"'')"; Db.NonQ(command); //add PayConnect bridge: command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'PayConnect', " +"'PayConnect from www.dentalxchange.com', " +"'0', " +"'', " +"'', " +"'No program path or arguments. Usernames and passwords are supplied by dentalxchange.')"; Db.NonQ(command); command="SELECT ProgramNum FROM program WHERE ProgName='PayConnect' LIMIT 1"; programNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Username', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Password', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'PaymentType', " +"'0')"; Db.NonQ(command); //Delete NewPatientForm bridge command="SELECT ProgramNum From program WHERE ProgName='NewPatientForm.com'"; programNum=PIn.Long(Db.GetScalar(command)); if(programNum>0) { command="DELETE FROM program WHERE ProgramNum="+POut.Long(programNum); Db.NonQ(command); command="DELETE FROM toolbutitem WHERE ProgramNum="+POut.Long(programNum); Db.NonQ(command); } command="DROP TABLE IF EXISTS orionproc"; Db.NonQ(command); command=@"CREATE TABLE orionproc ( OrionProcNum bigint NOT NULL auto_increment, ProcNum bigint NOT NULL, DPC tinyint NOT NULL, DateScheduleBy date NOT NULL default '0001-01-01', DateStopClock date NOT NULL default '0001-01-01', Status2 int NOT NULL, IsOnCall tinyint NOT NULL, IsEffectiveComm tinyint NOT NULL, IsRepair tinyint NOT NULL, PRIMARY KEY (OrionProcNum), INDEX(ProcNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="ALTER TABLE commlog ADD Signature text NOT NULL"; Db.NonQ(command); command="ALTER TABLE commlog ADD SigIsTopaz tinyint NOT NULL"; Db.NonQ(command); command="INSERT INTO grouppermission (NewerDays,UserGroupNum,PermType) " //Everyone starts with sheet edit initially. +"SELECT 0,UserGroupNum,"+POut.Int((int)Permissions.SheetEdit)+" " +"FROM usergroup"; Db.NonQ(command); command="ALTER TABLE procedurelog ADD ProcTimeEnd time NOT NULL"; Db.NonQ(command); command="INSERT INTO grouppermission (NewerDays,UserGroupNum,PermType) " //Everyone starts with commlog edit initially. +"SELECT 0,UserGroupNum,"+POut.Int((int)Permissions.CommlogEdit)+" " +"FROM usergroup"; Db.NonQ(command); command="ALTER TABLE patfielddef ADD FieldType tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE patfielddef ADD PickList text NOT NULL"; Db.NonQ(command); command="ALTER TABLE commlog ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE commlog SET DateTStamp=NOW()"; Db.NonQ32(command); command="ALTER TABLE procedurelog ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE procedurelog SET DateTStamp=NOW()"; Db.NonQ32(command); command="ALTER TABLE procedurecode ADD IsMultiVisit tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE chartview ADD OrionStatusFlags int NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.3.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_4_1(); } private static void To7_4_1() { if(FromVersion<new Version("7.4.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.4.1"));//No translation in convert script. string command; command="SELECT TimeAdjustNum,RegHours,OTimeHours FROM timeadjust"; DataTable table=Db.GetTable(command); command="UPDATE timeadjust SET RegHours=0, OTimeHours=0"; Db.NonQ(command); command="ALTER TABLE timeadjust CHANGE RegHours RegHours time NOT NULL default '00:00:00'"; Db.NonQ(command); command="ALTER TABLE timeadjust CHANGE OTimeHours OTimeHours time NOT NULL default '00:00:00'"; Db.NonQ(command); long timeAdjustNum; double regDouble; double oTimeDouble; TimeSpan regSpan; TimeSpan oTimeSpan; for(int i=0;i<table.Rows.Count;i++) { timeAdjustNum=PIn.Long(table.Rows[i]["TimeAdjustNum"].ToString()); regDouble=PIn.Double(table.Rows[i]["RegHours"].ToString()); oTimeDouble=PIn.Double(table.Rows[i]["OTimeHours"].ToString()); regSpan=TimeSpan.FromHours(regDouble); oTimeSpan=TimeSpan.FromHours(oTimeDouble); command="UPDATE timeadjust " +"SET RegHours='"+POut.TSpan(regSpan)+"', " +"OTimeHours='"+POut.TSpan(oTimeSpan)+"' " +"WHERE TimeAdjustNum="+POut.Long(timeAdjustNum); Db.NonQ(command); } command="ALTER TABLE clockevent ADD OTimeHours time NOT NULL"; Db.NonQ(command); command="UPDATE clockevent SET OTimeHours ='-01:00:00'";//default to -1 to indicate no override. Db.NonQ(command); command="ALTER TABLE clockevent ADD OTimeAuto time NOT NULL"; Db.NonQ(command); command="ALTER TABLE clockevent ADD Adjust time NOT NULL"; Db.NonQ(command); command="ALTER TABLE clockevent ADD AdjustAuto time NOT NULL"; Db.NonQ(command); command="ALTER TABLE clockevent ADD AdjustIsOverridden tinyint NOT NULL"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('TimeCardsUseDecimalInsteadOfColon','0')"; Db.NonQ(command); command="DROP TABLE IF EXISTS timecardrule"; Db.NonQ(command); command=@"CREATE TABLE timecardrule ( TimeCardRuleNum bigint NOT NULL auto_increment, EmployeeNum bigint NOT NULL, OverHoursPerDay time NOT NULL, AfterTimeOfDay time NOT NULL, PRIMARY KEY (TimeCardRuleNum), INDEX(EmployeeNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('SecurityLogOffWithWindows','0')"; Db.NonQ(command); command="DROP TABLE IF EXISTS automationcondition"; Db.NonQ(command); command=@"CREATE TABLE automationcondition ( AutomationConditionNum bigint NOT NULL auto_increment, AutomationNum bigint NOT NULL, CompareField tinyint NOT NULL, Comparison tinyint NOT NULL, CompareString varchar(255) NOT NULL, PRIMARY KEY (AutomationConditionNum), INDEX(AutomationNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('TimeCardsMakesAdjustmentsForOverBreaks','0')"; Db.NonQ(command); command="ALTER TABLE timeadjust ADD IsAuto tinyint NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.4.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_4_7(); } private static void To7_4_7() { if(FromVersion<new Version("7.4.7.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.4.7"));//No translation in convert script. string command; try { List<long> aptNums=new List<long>(); Appointment[] aptList=Appointments.GetForPeriod(DateTime.Now.Date,DateTime.MaxValue.AddDays(-10)); for(int i=0;i<aptList.Length;i++) { aptNums.Add(aptList[i].AptNum); } List<Procedure> procsMultApts=Procedures.GetProcsMultApts(aptNums); for(int i=0;i<aptList.Length;i++) { Appointment newApt=aptList[i].Clone(); newApt.ProcDescript=""; Procedure[] procsForOne=Procedures.GetProcsOneApt(aptList[i].AptNum,procsMultApts); string procDescript=""; for(int j=0;j<procsForOne.Length;j++) { ProcedureCode procCode=ProcedureCodes.GetProcCodeFromDb(procsForOne[j].CodeNum); if(j>0) { procDescript+=", "; } switch(procCode.TreatArea.ToString()) { case "Surf"://TreatmentArea.Surf: procDescript+="#"+Tooth.GetToothLabel(procsForOne[j].ToothNum)+"-" +procsForOne[j].Surf+"-";//""#12-MOD-" break; case "Tooth"://TreatmentArea.Tooth: procDescript+="#"+Tooth.GetToothLabel(procsForOne[j].ToothNum)+"-";//"#12-" break; case "Quad"://TreatmentArea.Quad: procDescript+=procsForOne[j].Surf+"-";//"UL-" break; case "Sextant"://TreatmentArea.Sextant: procDescript+="S"+procsForOne[j].Surf+"-";//"S2-" break; case "Arch"://TreatmentArea.Arch: procDescript+=procsForOne[j].Surf+"-";//"U-" break; case "ToothRange"://TreatmentArea.ToothRange: break; default://area 3 or 0 (mouth) break; } procDescript+=procCode.AbbrDesc; } newApt.ProcDescript=procDescript; Appointments.Update(newApt,aptList[i]); } } catch { }//do nothing. Should not have used objects. They are causing failures as the objects change in future versions. command="UPDATE preference SET ValueString = '7.4.7.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_5_1(); } /// <summary>Does nothing if this pref is already present</summary> public static void Set_7_5_17_AutoMerge(YN InsPlanConverstion_7_5_17_AutoMergeYN) { string command="SELECT COUNT(*) FROM preference WHERE PrefName='InsPlanConverstion_7_5_17_AutoMergeYN'"; if(Db.GetCount(command)=="0") { command="INSERT INTO preference(PrefName,ValueString) VALUES('InsPlanConverstion_7_5_17_AutoMergeYN','"+POut.Int((int)InsPlanConverstion_7_5_17_AutoMergeYN)+"')"; Db.NonQ(command); } else { command="UPDATE preference SET ValueString ='"+POut.Int((int)InsPlanConverstion_7_5_17_AutoMergeYN)+"' WHERE PrefName = 'InsPlanConverstion_7_5_17_AutoMergeYN'"; Db.NonQ(command); } } private static void To7_5_1() { if(FromVersion<new Version("7.5.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.5.1"));//No translation in convert script. string command; command="DROP TABLE IF EXISTS inssub"; Db.NonQ(command); command=@"CREATE TABLE inssub ( InsSubNum bigint NOT NULL auto_increment, PlanNum bigint NOT NULL, Subscriber bigint NOT NULL, DateEffective date NOT NULL default '0001-01-01', DateTerm date NOT NULL default '0001-01-01', ReleaseInfo tinyint NOT NULL, AssignBen tinyint NOT NULL, SubscriberID varchar(255) NOT NULL, BenefitNotes text NOT NULL, SubscNote text NOT NULL, OldPlanNum bigint NOT NULL, PRIMARY KEY (InsSubNum), INDEX(PlanNum), INDEX(Subscriber), INDEX(OldPlanNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); command="UPDATE insplan SET TrojanID='' WHERE TrojanID IS NULL";//In a previous version of this script, NULL TrojanIDs caused some insplan values to not carry forward. Db.NonQ(command); command="UPDATE insplan SET GroupNum='' WHERE GroupNum IS NULL"; Db.NonQ(command); command="UPDATE insplan SET GroupName='' WHERE GroupName IS NULL"; Db.NonQ(command); //Master plan for fixing references to plannums throughout the program-------------------------------------- //But many of these only apply to plansShared. //appointment.InsPlan1/2 -- UPDATE InsPlan1/2 //benefit.PlanNum -- DELETE unused //claim.PlanNum/PlanNum2 -- UPDATE PlanNum/2, add claim.InsSubNum/2 //claimproc.PlanNum -- UPDATE PlanNum, add claimproc.InsSubNum //etrans.PlanNum -- UPDATE PlanNum, add etrans.InsSubNum //patplan.PlanNum -- UPDATE PlanNum, add patplan.InsSubNum //payplan.PlanNum -- UPDATE PlanNum, add payplan.InsSubNum command="ALTER TABLE claim ADD InsSubNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD INDEX (InsSubNum)"; Db.NonQ(command); command="ALTER TABLE claim ADD InsSubNum2 bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD INDEX (InsSubNum2)"; Db.NonQ(command); command="ALTER TABLE claimproc ADD InsSubNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claimproc ADD INDEX (InsSubNum)"; Db.NonQ(command); command="ALTER TABLE etrans ADD InsSubNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE etrans ADD INDEX (InsSubNum)"; Db.NonQ(command); command="ALTER TABLE patplan ADD InsSubNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE patplan ADD INDEX (InsSubNum)"; Db.NonQ(command); command="ALTER TABLE payplan ADD InsSubNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE payplan ADD INDEX (InsSubNum)"; Db.NonQ(command); command="SELECT ValueString FROM preference WHERE PrefName = 'InsPlanConverstion_7_5_17_AutoMergeYN'";//This line was added in 7.5.17. bool autoMerge=(Db.GetScalar(command)=="1");//Yes if(autoMerge) {//This option was added in 7.5.17. //Create a temporary table that will hold a copy of all the original plans. command="DROP TABLE IF EXISTS tempinsplan"; Db.NonQ(command); command="CREATE TABLE tempinsplan SELECT * FROM insplan"; Db.NonQ(command); command="ALTER TABLE tempinsplan ADD NewPlanNum bigint NOT NULL";//This new column is the only thing different about this table. Db.NonQ(command); command="ALTER TABLE tempinsplan ADD INDEX (NewPlanNum)"; Db.NonQ(command); command="ALTER TABLE tempinsplan ADD INDEX (PlanNum)"; Db.NonQ(command); command="ALTER TABLE tempinsplan ADD INDEX (Subscriber)"; Db.NonQ(command); command="ALTER TABLE tempinsplan ADD INDEX (CarrierNum)"; Db.NonQ(command); //Create a temporary table that will hold a copy of all the unique plans command="DROP TABLE IF EXISTS tempunique"; Db.NonQ(command); command="CREATE TABLE tempunique SELECT * FROM insplan GROUP BY EmployerNum,GroupName,GroupNum,DivisionNo,CarrierNum,IsMedical,TrojanID,FeeSched"; Db.NonQ(command); command="ALTER TABLE tempunique ADD INDEX (PlanNum)"; Db.NonQ(command); command="ALTER TABLE tempunique ADD INDEX (Subscriber)"; Db.NonQ(command); command="ALTER TABLE tempunique ADD INDEX (CarrierNum)"; Db.NonQ(command); command="UPDATE tempinsplan,tempunique SET tempinsplan.NewPlanNum=tempunique.PlanNum " +"WHERE tempinsplan.EmployerNum=tempunique.EmployerNum " +"AND tempinsplan.GroupName=tempunique.GroupName " +"AND tempinsplan.GroupNum=tempunique.GroupNum " +"AND tempinsplan.DivisionNo=tempunique.DivisionNo " +"AND tempinsplan.CarrierNum=tempunique.CarrierNum " +"AND tempinsplan.IsMedical=tempunique.IsMedical " +"AND tempinsplan.TrojanID=tempunique.TrojanID " +"AND tempinsplan.FeeSched=tempunique.FeeSched"; Db.NonQ(command); //Now, create a series of inssub rows, one for each of the original plans. //But instead of referencing the original planNum, reference the NewPlanNum command="INSERT INTO inssub (PlanNum,Subscriber,DateEffective,DateTerm,ReleaseInfo,AssignBen,SubscriberID,BenefitNotes,SubscNote,OldPlanNum) " +"SELECT NewPlanNum,Subscriber,DateEffective,DateTerm,ReleaseInfo,AssignBen,SubscriberID,BenefitNotes,SubscNote,PlanNum " +"FROM tempinsplan"; Db.NonQ(command); command="DROP TABLE IF EXISTS tempinsplan";//to emphasize that we will not be using it again. Db.NonQ(command); //fix references to plannums throughout the program--------------------------------------------------- //appointment.InsPlan1/2 -- UPDATE InsPlan1/2 command="ALTER TABLE appointment ADD OldInsPlan1 bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE appointment ADD INDEX (OldInsPlan1)"; Db.NonQ(command); command="UPDATE appointment SET OldInsPlan1 = InsPlan1"; Db.NonQ(command); command="ALTER TABLE appointment ADD OldInsPlan2 bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE appointment ADD INDEX (OldInsPlan2)"; Db.NonQ(command); command="UPDATE appointment SET OldInsPlan2 = InsPlan2"; Db.NonQ(command); command="UPDATE appointment SET InsPlan1=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=appointment.OldInsPlan1) WHERE InsPlan1 != 0"; Db.NonQ(command); command="UPDATE appointment SET InsPlan2=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=appointment.OldInsPlan2) WHERE InsPlan2 != 0"; Db.NonQ(command); //benefit.PlanNum -- DELETE unused command="DELETE FROM benefit WHERE PlanNum > 0 AND NOT EXISTS(SELECT * FROM tempunique WHERE tempunique.PlanNum=benefit.PlanNum)"; Db.NonQ(command); //claim.PlanNum/PlanNum2 -- UPDATE PlanNum/2 command="ALTER TABLE claim ADD OldPlanNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD INDEX (OldPlanNum)"; Db.NonQ(command); command="UPDATE claim SET OldPlanNum = PlanNum"; Db.NonQ(command); command="ALTER TABLE claim ADD OldPlanNum2 bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD INDEX (OldPlanNum2)"; Db.NonQ(command); command="UPDATE claim SET OldPlanNum2 = PlanNum2"; Db.NonQ(command); command="UPDATE claim SET PlanNum=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=claim.OldPlanNum) WHERE PlanNum != 0"; Db.NonQ(command); command="UPDATE claim SET PlanNum2=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=claim.OldPlanNum2) WHERE PlanNum2 != 0"; Db.NonQ(command); //claimproc.PlanNum -- UPDATE PlanNum command="ALTER TABLE claimproc ADD OldPlanNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claimproc ADD INDEX (OldPlanNum)"; Db.NonQ(command); command="UPDATE claimproc SET OldPlanNum = PlanNum"; Db.NonQ(command); command="UPDATE claimproc SET PlanNum=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=claimproc.OldPlanNum) WHERE PlanNum != 0"; Db.NonQ(command); //etrans.PlanNum -- UPDATE PlanNum command="ALTER TABLE etrans ADD OldPlanNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE etrans ADD INDEX (OldPlanNum)"; Db.NonQ(command); command="UPDATE etrans SET OldPlanNum = PlanNum"; Db.NonQ(command); command="UPDATE etrans SET PlanNum=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=etrans.OldPlanNum) WHERE PlanNum != 0"; Db.NonQ(command); //patplan.PlanNum -- UPDATE PlanNum command="ALTER TABLE patplan ADD OldPlanNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE patplan ADD INDEX (OldPlanNum)"; Db.NonQ(command); command="UPDATE patplan SET OldPlanNum = PlanNum"; Db.NonQ(command); command="UPDATE patplan SET PlanNum=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=patplan.OldPlanNum) WHERE PlanNum != 0"; Db.NonQ(command); //payplan.PlanNum -- UPDATE PlanNum command="ALTER TABLE payplan ADD OldPlanNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE payplan ADD INDEX (OldPlanNum)"; Db.NonQ(command); command="UPDATE payplan SET OldPlanNum = PlanNum"; Db.NonQ(command); command="UPDATE payplan SET PlanNum=(SELECT PlanNum FROM inssub WHERE inssub.OldPlanNum=payplan.OldPlanNum) WHERE PlanNum != 0"; Db.NonQ(command); //Now, drop all the unused plans------------------------------------------------------------------------------------------- command="DELETE FROM insplan WHERE NOT EXISTS(SELECT * FROM tempunique WHERE tempunique.PlanNum=insplan.PlanNum)"; Db.NonQ(command); //Set all the InsSubNums.-------------------------------------------------------------------------------------------------- //claim.PlanNum/PlanNum2 -- claim.InsSubNum/2 command="UPDATE claim SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.OldPlanNum=claim.OldPlanNum) WHERE PlanNum > 0"; Db.NonQ(command); command="UPDATE claim SET InsSubNum2 = (SELECT InsSubNum FROM inssub WHERE inssub.OldPlanNum=claim.OldPlanNum2) WHERE PlanNum2 > 0"; Db.NonQ(command); //claimproc.PlanNum -- claimproc.InsSubNum command="UPDATE claimproc SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.OldPlanNum=claimproc.OldPlanNum) WHERE PlanNum > 0"; Db.NonQ(command); //etrans.PlanNum -- etrans.InsSubNum command="UPDATE etrans SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.OldPlanNum=etrans.OldPlanNum) WHERE PlanNum > 0"; Db.NonQ(command); //patplan.PlanNum -- patplan.InsSubNum command="UPDATE patplan SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.OldPlanNum=patplan.OldPlanNum) WHERE PlanNum > 0"; Db.NonQ(command); //payplan.PlanNum -- payplan.InsSubNum command="UPDATE payplan SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.OldPlanNum=payplan.OldPlanNum) WHERE PlanNum > 0"; Db.NonQ(command); //Drop temp columns and tables------------------------------------------------------------------------------------------------- command="ALTER TABLE inssub DROP OldPlanNum"; Db.NonQ(command); command="ALTER TABLE appointment DROP OldInsPlan1"; Db.NonQ(command); command="ALTER TABLE appointment DROP OldInsPlan2"; Db.NonQ(command); command="ALTER TABLE claim DROP OldPlanNum"; Db.NonQ(command); command="ALTER TABLE claim DROP OldPlanNum2"; Db.NonQ(command); command="ALTER TABLE claimproc DROP OldPlanNum"; Db.NonQ(command); command="ALTER TABLE etrans DROP OldPlanNum"; Db.NonQ(command); command="ALTER TABLE patplan DROP OldPlanNum"; Db.NonQ(command); command="ALTER TABLE payplan DROP OldPlanNum"; Db.NonQ(command); command="DROP TABLE IF EXISTS tempunique"; Db.NonQ(command); } else {//This option was added in 7.5.17. No combining of plans will happen command="INSERT INTO inssub (PlanNum,Subscriber,DateEffective,DateTerm,ReleaseInfo,AssignBen,SubscriberID,BenefitNotes,SubscNote,OldPlanNum) " +"SELECT PlanNum,Subscriber,DateEffective,DateTerm,ReleaseInfo,AssignBen,SubscriberID,BenefitNotes,SubscNote,PlanNum " +"FROM insplan"; Db.NonQ(command); //Set all InsSubNums---------------------------------------------------------------------------------------------------- //claim.PlanNum/PlanNum2 -- claim.InsSubNum/2 command="UPDATE claim SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.PlanNum=claim.PlanNum) WHERE PlanNum > 0"; Db.NonQ(command); command="UPDATE claim SET InsSubNum2 = (SELECT InsSubNum FROM inssub WHERE inssub.PlanNum=claim.PlanNum2) WHERE PlanNum2 > 0"; Db.NonQ(command); //claimproc.PlanNum -- claimproc.InsSubNum command="UPDATE claimproc SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.PlanNum=claimproc.PlanNum) WHERE PlanNum > 0"; Db.NonQ(command); //etrans.PlanNum -- etrans.InsSubNum command="UPDATE etrans SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.PlanNum=etrans.PlanNum) WHERE PlanNum > 0"; Db.NonQ(command); //patplan.PlanNum -- patplan.InsSubNum command="UPDATE patplan SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.PlanNum=patplan.PlanNum) WHERE PlanNum > 0"; Db.NonQ(command); //payplan.PlanNum -- payplan.InsSubNum command="UPDATE payplan SET InsSubNum = (SELECT InsSubNum FROM inssub WHERE inssub.PlanNum=payplan.PlanNum) WHERE PlanNum > 0"; Db.NonQ(command); } //Final changes to tables----------------------------------------------------------------------------------------------------- command="ALTER TABLE insplan DROP Subscriber"; Db.NonQ(command); command="ALTER TABLE insplan DROP DateEffective"; Db.NonQ(command); command="ALTER TABLE insplan DROP DateTerm"; Db.NonQ(command); command="ALTER TABLE insplan DROP ReleaseInfo"; Db.NonQ(command); command="ALTER TABLE insplan DROP AssignBen"; Db.NonQ(command); command="ALTER TABLE insplan DROP SubscriberID"; Db.NonQ(command); command="ALTER TABLE insplan DROP BenefitNotes"; Db.NonQ(command); command="ALTER TABLE insplan DROP SubscNote"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.5.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_5_4(); } private static void To7_5_4() { if(FromVersion<new Version("7.5.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.5.4"));//No translation in convert script. string command; command="DELETE FROM toolbutitem WHERE ProgramNum=(SELECT p.ProgramNum FROM program p WHERE p.ProgName='PayConnect' LIMIT 1)"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.5.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_5_7(); } private static void To7_5_7() { if(FromVersion<new Version("7.5.7.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.5.7"));//No translation in convert script. string command; command="INSERT INTO preference(PrefName,ValueString) VALUES('SubscriberAllowChangeAlways','0')"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.5.7.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_5_12(); } private static void To7_5_12() { if(FromVersion<new Version("7.5.12.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.5.12"));//No translation in convert script. string command; command="ALTER TABLE inssub CHANGE BenefitNotes BenefitNotes text NOT NULL"; Db.NonQ(command); command="ALTER TABLE inssub CHANGE SubscNote SubscNote text NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.5.12.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_5_16(); } private static void To7_5_16() { if(FromVersion<new Version("7.5.16.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.5.16"));//No translation in convert script. string command; command="ALTER TABLE orionproc ADD DPCpost tinyint NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.5.16.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_6_1(); } private static void To7_6_1() { if(FromVersion<new Version("7.6.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.6.1"));//No translation in convert script. string command; command="UPDATE program SET ProgDesc='PayConnect from www.dentalxchange.com' WHERE ProgName='PayConnect' LIMIT 1"; Db.NonQ(command); command="UPDATE preference SET ValueString = 'https://opendentalsoft.com/WebHostSynch/Sheets.asmx' WHERE PrefName = 'WebHostSynchServerURL'"; Db.NonQ(command); command="ALTER TABLE operatory ADD SetProspective tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE computerpref CHANGE SensorBinned SensorBinned tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE computerpref CHANGE GraphicsDoubleBuffering GraphicsDoubleBuffering tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE computerpref ADD RecentApptView tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE covcat CHANGE DefaultPercent DefaultPercent smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE IntTooth IntTooth smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE ToothValue ToothValue smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE MBvalue MBvalue smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE Bvalue Bvalue smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE DBvalue DBvalue smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE MLvalue MLvalue smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE Lvalue Lvalue smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE periomeasure CHANGE DLvalue DLvalue smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE sigbutdef CHANGE ButtonIndex ButtonIndex smallint NOT NULL"; Db.NonQ(command); command="ALTER TABLE preference DROP PRIMARY KEY"; Db.NonQ(command); command="ALTER TABLE preference ADD COLUMN PrefNum bigint NOT NULL auto_increment FIRST, ADD PRIMARY KEY (PrefNum)"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileSyncIntervalMinutes','0')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileSyncServerURL','https://opendentalsoft.com/WebHostSynch/Mobile.asmx')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileExcludeApptsBeforeDate','2009-12-20')"; Db.NonQ(command); command="DELETE FROM preference WHERE PrefName = 'MobileSyncLastFileNumber'"; Db.NonQ(command); command="DELETE FROM preference WHERE PrefName = 'MobileSyncPath'"; Db.NonQ(command); command="ALTER TABLE county DROP PRIMARY KEY"; Db.NonQ(command); command="ALTER TABLE county ADD COLUMN CountyNum bigint NOT NULL auto_increment FIRST, ADD PRIMARY KEY (CountyNum)"; Db.NonQ(command); command="ALTER TABLE language DROP PRIMARY KEY"; try { Db.NonQ(command); } catch { }//because I don't think there is any primary key for that table. command="ALTER TABLE language ADD COLUMN LanguageNum bigint NOT NULL auto_increment FIRST, ADD PRIMARY KEY (LanguageNum)"; Db.NonQ(command); command="ALTER TABLE languageforeign DROP PRIMARY KEY"; try { Db.NonQ(command); } catch { } command="ALTER TABLE languageforeign ADD COLUMN LanguageForeignNum bigint NOT NULL auto_increment FIRST, ADD PRIMARY KEY (LanguageForeignNum)"; Db.NonQ(command); command="ALTER TABLE school DROP PRIMARY KEY"; Db.NonQ(command); command="ALTER TABLE school ADD COLUMN SchoolNum bigint NOT NULL auto_increment FIRST, ADD PRIMARY KEY (SchoolNum)"; Db.NonQ(command); //DbSchema.AddColumn("SchoolNum",OdDbType.Long); command="ALTER TABLE payment ADD Receipt text NOT NULL"; Db.NonQ(command); command="ALTER TABLE sigelementdef CHANGE ItemOrder ItemOrder smallint NOT NULL"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.6.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_6_2(); } private static void To7_6_2() { if(FromVersion<new Version("7.6.2.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.6.2"));//No translation in convert script. string command; command="ALTER TABLE preference DROP COLUMN PrefNum"; Db.NonQ(command); command="ALTER TABLE preference ADD COLUMN PrefNum bigint NOT NULL auto_increment AFTER ValueString, ADD PRIMARY KEY (PrefNum)"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.6.2.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_6_4(); } private static void To7_6_4() { if(FromVersion<new Version("7.6.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.6.4"));//No translation in convert script. string command; command="INSERT INTO preference(PrefName,ValueString) VALUES('ReportPandIschedProdSubtractsWO','0')"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.6.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_6_10(); } private static void To7_6_10() { if(FromVersion<new Version("7.6.10.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.6.10"));//No translation in convert script. string command; command="SELECT ProgramNum FROM program WHERE ProgName='Xcharge'"; long programNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Username', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Password', " +"'')"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.6.10.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_7_1(); } private static void To7_7_1() { if(FromVersion<new Version("7.7.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.7.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE document ADD RawBase64 mediumtext NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE document ADD RawBase64 clob"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE document ADD Thumbnail text NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE document ADD Thumbnail clob"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxpat ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE rxpat SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxpat ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE rxpat SET DateTStamp = SYSDATE"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileSyncWorkstationName','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MobileSyncWorkstationName','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS tasknote"; Db.NonQ(command); command=@"CREATE TABLE tasknote ( TaskNoteNum bigint NOT NULL auto_increment PRIMARY KEY, TaskNum bigint NOT NULL, UserNum bigint NOT NULL, DateTimeNote datetime NOT NULL DEFAULT '0001-01-01 00:00:00', Note Text NOT NULL, INDEX(TaskNum), INDEX(UserNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE tasknote'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE tasknote ( TaskNoteNum number(20) NOT NULL, TaskNum number(20) NOT NULL, UserNum number(20) NOT NULL, DateTimeNote date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, Note varchar2(4000), CONSTRAINT tasknote_TaskNoteNum PRIMARY KEY (TaskNoteNum) )"; Db.NonQ(command); command=@"CREATE INDEX tasknote_TaskNum ON tasknote (TaskNum)"; Db.NonQ(command); command=@"CREATE INDEX tasknote_UserNum ON tasknote (UserNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('TasksNewTrackedByUser','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'TasksNewTrackedByUser','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ImagesModuleTreeIsCollapsed','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ImagesModuleTreeIsCollapsed','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('TasksShowOpenTickets','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'TasksShowOpenTickets','0')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '7.7.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_8_1(); } private static void To7_8_1() { if(FromVersion<new Version("7.8.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.8.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS creditcard"; Db.NonQ(command); command=@"CREATE TABLE creditcard ( CreditCardNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, Address varchar(255), Zip varchar(255), XChargeToken varchar(255), CCNumberMasked varchar(255), CCExpiration date NOT NULL DEFAULT '0001-01-01', ItemOrder int NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE creditcard'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE creditcard ( CreditCardNum number(20) NOT NULL, PatNum number(20) NOT NULL, Address varchar2(255), Zip varchar2(255), XChargeToken varchar2(255), CCNumberMasked varchar2(255), CCExpiration date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, ItemOrder number(11) NOT NULL, CONSTRAINT creditcard_CreditCardNum PRIMARY KEY (CreditCardNum) )"; Db.NonQ(command); command=@"CREATE INDEX creditcard_PatNum ON creditcard (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO creditcard (PatNum,CCExpiration,CCNumberMasked,ItemOrder) SELECT PatNum,CCExpiration,CCNumber,0 FROM patientnote WHERE CCNumber!=''"; Db.NonQ(command); } else {//oracle command=@"INSERT INTO creditcard (CreditCardNum,PatNum,CCExpiration,CCNumberMasked,ItemOrder) SELECT PatNum,PatNum,CCExpiration,CCNumber,0 FROM patientnote WHERE LENGTH(ccnumber)>0"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patientnote DROP COLUMN CCNumber"; Db.NonQ(command); command="ALTER TABLE patientnote DROP COLUMN CCExpiration"; Db.NonQ(command); } else {//oracle command="ALTER TABLE patientnote DROP (CCNumber, CCExpiration)"; Db.NonQ(command); } //Add PerioEdit permission to all groups------------------------------------------------------ command="SELECT UserGroupNum FROM usergroup"; DataTable table=Db.GetTable(command); long groupNum; if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i][0].ToString()); command="INSERT INTO grouppermission (NewerDays,UserGroupNum,PermType) " +"VALUES(0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.PerioEdit)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i][0].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.PerioEdit)+")"; Db.NonQ32(command); } } //add Cerec bridge: if(DataConnection.DBtype==DatabaseType.MySql) {//NOTE: this chunk of code was realeased with MySQL version only, and then revised to use mySQL or Oracle. The mySQL code was unchanged. command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Cerec', " +"'Cerec from Sirona', " +"'0', " +"'"+POut.String(@"C:\Program Files\Cerec\Cerec system\CerPI.exe")+"', " +"'', " +@"'Cerec v2.6 default install directory is C:\Program Files\Cerec\System\CerPI.exe \r\nCerec v2.8 default install directory is C:\Program Files\Cerec\Cerec system\CerPI.exe')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Cerec')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'Cerec', " +"'Cerec from Sirona', " +"'0', " +"'"+POut.String(@"C:\Program Files\Cerec\Cerec system\CerPI.exe")+"', " +"'', " +@"'Cerec v2.6 default install directory is C:\Program Files\Cerec\System\CerPI.exe \r\nCerec v2.8 default install directory is C:\Program Files\Cerec\Cerec system\CerPI.exe')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum)+1 FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Cerec')"; Db.NonQ32(command); }//End of Cerec Bridge code. This chunk of code works with MySQL, and is unlikely to cause Oracle bugs. if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS school"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE school'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE chartview ADD DatesShowing float NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE chartview ADD DatesShowing number(38,8)"; Db.NonQ(command); command="UPDATE chartview SET DatesShowing = 0 WHERE DatesShowing IS NULL"; Db.NonQ(command); command="ALTER TABLE chartview MODIFY DatesShowing NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD Prognosis bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog ADD INDEX (Prognosis)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurelog ADD Prognosis number(20)"; Db.NonQ(command); command="UPDATE procedurelog SET Prognosis = 0 WHERE Prognosis IS NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog MODIFY Prognosis NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX procedurelog_Prognosis ON procedurelog (Prognosis)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE proctp ADD Prognosis varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE proctp ADD Prognosis varchar2(255)"; Db.NonQ(command); } //Add ProcEditShowFee permission to all groups------------------------------------------------------ command="SELECT UserGroupNum FROM usergroup"; table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i][0].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProcEditShowFee)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i][0].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProcEditShowFee)+")"; Db.NonQ32(command); } } command="UPDATE preference SET ValueString = '7.8.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_8_3(); } private static void To7_8_3() { if(FromVersion<new Version("7.8.3.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.8.3"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileUserName','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MobileUserName','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE proctp ADD Dx varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE proctp ADD Dx varchar2(255)"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '7.8.3.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_8_4(); } private static void To7_8_4() { if(FromVersion<new Version("7.8.4.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.8.4."));//No translation in convert script. string command; //add Patterson Imaging bridge: if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Patterson', " +"'Patterson Imaging from Patterson Dental Supply Inc.', " +"'0', " +"'"+POut.String(@"C:\Program Files\PDI\Shared files\Imaging.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'System path to Patterson Imaging ini', " +"'"+POut.String(@"C:\Program Files\PDI\Shared files\Imaging.ini")+"')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'PattersonImg')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'Patterson', " +"'Patterson Imaging from Patterson Dental Supply Inc.', " +"'0', " +"'"+POut.String(@"C:\Program Files\PDI\Shared files\Imaging.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum)+1 FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'System path to Patterson Imaging ini', " +"'"+POut.String(@"C:\Program Files\PDI\Shared files\Imaging.ini")+"')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'PattersonImg')"; Db.NonQ32(command); }//end Patterson Imaging bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE chartview MODIFY DatesShowing TINYINT NOT NULL"; Db.NonQ(command); } else {//oracle //Does not need to be changed for oracle. } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('MySqlVersion','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MySqlVersion','')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '7.8.4.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_8_5(); } private static void To7_8_5() { if(FromVersion<new Version("7.8.5.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.8.5"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) {//signal is a reserved word in mySQL 5.5 command="DROP TABLE IF EXISTS signalod"; Db.NonQ(command); command="RENAME TABLE `signal` TO signalod"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE signalod'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command="ALTER TABLE signal RENAME TO signalod"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '7.8.5.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_9_1(); } private static void To7_9_1() { if(FromVersion<new Version("7.9.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.9.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CanadaTransRefNum varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CanadaTransRefNum varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CanadaEstTreatStartDate date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CanadaEstTreatStartDate date"; Db.NonQ(command); command="UPDATE claim SET CanadaEstTreatStartDate = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE CanadaEstTreatStartDate IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CanadaEstTreatStartDate NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CanadaInitialPayment double NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CanadaInitialPayment number(38,8)"; Db.NonQ(command); command="UPDATE claim SET CanadaInitialPayment = 0 WHERE CanadaInitialPayment IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CanadaInitialPayment NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CanadaPaymentMode tinyint unsigned NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CanadaPaymentMode number(3)"; Db.NonQ(command); command="UPDATE claim SET CanadaPaymentMode = 0 WHERE CanadaPaymentMode IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CanadaPaymentMode NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CanadaTreatDuration tinyint unsigned NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CanadaTreatDuration number(3)"; Db.NonQ(command); command="UPDATE claim SET CanadaTreatDuration = 0 WHERE CanadaTreatDuration IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CanadaTreatDuration NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CanadaNumAnticipatedPayments tinyint unsigned NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CanadaNumAnticipatedPayments number(3)"; Db.NonQ(command); command="UPDATE claim SET CanadaNumAnticipatedPayments = 0 WHERE CanadaNumAnticipatedPayments IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CanadaNumAnticipatedPayments NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CanadaAnticipatedPayAmount double NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CanadaAnticipatedPayAmount number(38,8)"; Db.NonQ(command); command="UPDATE claim SET CanadaAnticipatedPayAmount = 0 WHERE CanadaAnticipatedPayAmount IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CanadaAnticipatedPayAmount NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE creditcard ADD ChargeAmt double NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE creditcard ADD ChargeAmt number(38,8)"; Db.NonQ(command); command="UPDATE creditcard SET ChargeAmt = 0 WHERE ChargeAmt IS NULL"; Db.NonQ(command); command="ALTER TABLE creditcard MODIFY ChargeAmt NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE creditcard ADD DateStart date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE creditcard ADD DateStart date"; Db.NonQ(command); command="UPDATE creditcard SET DateStart = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateStart IS NULL"; Db.NonQ(command); command="ALTER TABLE creditcard MODIFY DateStart NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE creditcard ADD DateStop date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE creditcard ADD DateStop date"; Db.NonQ(command); command="UPDATE creditcard SET DateStop = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateStop IS NULL"; Db.NonQ(command); command="ALTER TABLE creditcard MODIFY DateStop NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE creditcard ADD Note varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE creditcard ADD Note varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS vitalsign"; Db.NonQ(command); command=@"CREATE TABLE vitalsign ( VitalsignNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, Height float NOT NULL, Weight float NOT NULL, BpSystolic smallint NOT NULL, BpDiastolic smallint NOT NULL, DateTaken date NOT NULL DEFAULT '0001-01-01', INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE vitalsign'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE vitalsign ( VitalsignNum number(20) NOT NULL, PatNum number(20) NOT NULL, Height number(38,8) NOT NULL, Weight number(38,8) NOT NULL, BpSystolic number(11) NOT NULL, BpDiastolic number(11) NOT NULL, DateTaken date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, CONSTRAINT vitalsign_VitalsignNum PRIMARY KEY (VitalsignNum) )"; Db.NonQ(command); command=@"CREATE INDEX vitalsign_PatNum ON vitalsign (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD OnlinePassword varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE patient ADD OnlinePassword varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicationpat ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE medicationpat SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicationpat ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE medicationpat SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicationpat ADD IsDiscontinued tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicationpat ADD IsDiscontinued number(3)"; Db.NonQ(command); command="UPDATE medicationpat SET IsDiscontinued = 0 WHERE IsDiscontinued IS NULL"; Db.NonQ(command); command="ALTER TABLE medicationpat MODIFY IsDiscontinued NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE disease ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE disease SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE disease ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE disease SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } //columns for rxalert---------------------------------------------------------------------------- if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxalert ADD AllergyDefNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE rxalert ADD INDEX (AllergyDefNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxalert ADD AllergyDefNum number(20)"; Db.NonQ(command); command="UPDATE rxalert SET AllergyDefNum = 0 WHERE AllergyDefNum IS NULL"; Db.NonQ(command); command="ALTER TABLE rxalert MODIFY AllergyDefNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX rxalert_AllergyDefNum ON rxalert (AllergyDefNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxalert ADD MedicationNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE rxalert ADD INDEX (MedicationNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxalert ADD MedicationNum number(20)"; Db.NonQ(command); command="UPDATE rxalert SET MedicationNum = 0 WHERE MedicationNum IS NULL"; Db.NonQ(command); command="ALTER TABLE rxalert MODIFY MedicationNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX rxalert_MedicationNum ON rxalert (MedicationNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxalert ADD NotificationMsg varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxalert ADD NotificationMsg varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxpat ADD IsElectQueue tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxpat ADD IsElectQueue number(3)"; Db.NonQ(command); command="UPDATE rxpat SET IsElectQueue = 0 WHERE IsElectQueue IS NULL"; Db.NonQ(command); command="ALTER TABLE rxpat MODIFY IsElectQueue NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('RxSendNewToQueue','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) " +"VALUES((SELECT MAX(PrefNum)+1 FROM preference),'RxSendNewToQueue','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD SmokeStatus tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE patient ADD SmokeStatus number(3)"; Db.NonQ(command); command="UPDATE patient SET SmokeStatus = 0 WHERE SmokeStatus IS NULL"; Db.NonQ(command); command="ALTER TABLE patient MODIFY SmokeStatus NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE canadiannetwork ADD CanadianTransactionPrefix varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE canadiannetwork ADD CanadianTransactionPrefix varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS icd9"; Db.NonQ(command); command=@"CREATE TABLE icd9 ( ICD9Num bigint NOT NULL auto_increment PRIMARY KEY, ICD9Code varchar(255) NOT NULL, Description varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE icd9'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE icd9 ( ICD9Num number(20) NOT NULL, ICD9Code varchar2(255), Description varchar2(255), CONSTRAINT icd9_ICD9Num PRIMARY KEY (ICD9Num) )"; Db.NonQ(command); } //Removed for 13.3 release, will be using code system importer tool instead. //try { // using(StringReader reader=new StringReader(Properties.Resources.icd9)) { // //loop: // command=reader.ReadLine(); // while(command!=null) { // Db.NonQ(command); // command=reader.ReadLine(); // } // } //} //catch(Exception) { }//do nothing if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS medicalorder"; Db.NonQ(command); command=@"CREATE TABLE medicalorder ( MedicalOrderNum bigint NOT NULL auto_increment PRIMARY KEY, MedOrderType tinyint NOT NULL, PatNum bigint NOT NULL, DateTimeOrder datetime NOT NULL DEFAULT '0001-01-01 00:00:00', INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE medicalorder'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE medicalorder ( MedicalOrderNum number(20) NOT NULL, MedOrderType number(3) NOT NULL, PatNum number(20) NOT NULL, DateTimeOrder date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, CONSTRAINT medicalorder_MedicalOrderNum PRIMARY KEY (MedicalOrderNum) )"; Db.NonQ(command); command=@"CREATE INDEX medicalorder_PatNum ON medicalorder (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS allergy"; Db.NonQ(command); command=@"CREATE TABLE allergy ( AllergyNum bigint NOT NULL auto_increment PRIMARY KEY, AllergyDefNum bigint NOT NULL, PatNum bigint NOT NULL, Reaction varchar(255) NOT NULL, StatusIsActive tinyint NOT NULL, DateTStamp timestamp, INDEX(AllergyDefNum), INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE allergy'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE allergy ( AllergyNum number(20) NOT NULL, AllergyDefNum number(20) NOT NULL, PatNum number(20) NOT NULL, Reaction varchar2(255), StatusIsActive number(3) NOT NULL, DateTStamp timestamp, CONSTRAINT allergy_AllergyNum PRIMARY KEY (AllergyNum) )"; Db.NonQ(command); command=@"CREATE INDEX allergy_AllergyDefNum ON allergy (AllergyDefNum)"; Db.NonQ(command); command=@"CREATE INDEX allergy_PatNum ON allergy (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS allergydef"; Db.NonQ(command); command=@"CREATE TABLE allergydef ( AllergyDefNum bigint NOT NULL auto_increment PRIMARY KEY, Description varchar(255) NOT NULL, IsHidden tinyint NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE allergydef'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE allergydef ( AllergyDefNum number(20) NOT NULL, Description varchar2(255), IsHidden number(3) NOT NULL, CONSTRAINT allergydef_AllergyDefNum PRIMARY KEY (AllergyDefNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE disease ADD ICD9Num bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE disease ADD INDEX (ICD9Num)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE disease ADD ICD9Num number(20)"; Db.NonQ(command); command="UPDATE disease SET ICD9Num = 0 WHERE ICD9Num IS NULL"; Db.NonQ(command); command="ALTER TABLE disease MODIFY ICD9Num NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX disease_ICD9Num ON disease (ICD9Num)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE disease ADD ProbStatus tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE disease ADD ProbStatus number(3)"; Db.NonQ(command); command="UPDATE disease SET ProbStatus = 0 WHERE ProbStatus IS NULL"; Db.NonQ(command); command="ALTER TABLE disease MODIFY ProbStatus NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS ehrmeasure"; Db.NonQ(command); command=@"CREATE TABLE ehrmeasure ( EhrMeasureNum bigint NOT NULL auto_increment PRIMARY KEY, MeasureType tinyint NOT NULL, Numerator smallint NOT NULL, Denominator smallint NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE ehrmeasure'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE ehrmeasure ( EhrMeasureNum number(20) NOT NULL, MeasureType number(3) NOT NULL, Numerator number(11) NOT NULL, Denominator number(11) NOT NULL, CONSTRAINT ehrmeasure_EhrMeasureNum PRIMARY KEY (EhrMeasureNum) )"; Db.NonQ(command); } //Add EHR Measures to DB if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(0,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(1,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(2,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(3,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(4,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(5,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(6,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(7,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(8,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(9,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(10,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(11,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(12,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(13,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(14,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(MeasureType,Numerator,Denominator) VALUES(15,-1,-1)"; Db.NonQ(command); } else {//oracle command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES(1,0,-1,-1)";//No rows in table and Oracle returns null so set the first one. Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),1,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),2,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),3,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),4,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),5,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),6,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),7,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),8,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),9,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),10,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),11,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),12,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),13,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),14,-1,-1)"; Db.NonQ(command); command="INSERT INTO ehrmeasure(EhrMeasureNum,MeasureType,Numerator,Denominator) VALUES((SELECT MAX(EhrMeasureNum)+1 FROM ehrmeasure),15,-1,-1)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE allergydef ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE allergydef SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE allergydef ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE allergydef SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE diseasedef ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE diseasedef SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE diseasedef ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE diseasedef SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE icd9 ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE icd9 SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE icd9 ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE icd9 SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medication ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE medication SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medication ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE medication SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS formulary"; Db.NonQ(command); command=@"CREATE TABLE formulary ( FormularyNum bigint NOT NULL auto_increment PRIMARY KEY, Description varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE formulary'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE formulary ( FormularyNum number(20) NOT NULL, Description varchar2(255), CONSTRAINT formulary_FormularyNum PRIMARY KEY (FormularyNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS formularymed"; Db.NonQ(command); command=@"CREATE TABLE formularymed ( FormularyMedNum bigint NOT NULL auto_increment PRIMARY KEY, FormularyNum bigint NOT NULL, MedicationNum bigint NOT NULL, INDEX(FormularyNum), INDEX(MedicationNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE formularymed'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE formularymed ( FormularyMedNum number(20) NOT NULL, FormularyNum number(20) NOT NULL, MedicationNum number(20) NOT NULL, CONSTRAINT formularymed_FormularyMedNum PRIMARY KEY (FormularyMedNum) )"; Db.NonQ(command); command=@"CREATE INDEX formularymed_FormularyNum ON formularymed (FormularyNum)"; Db.NonQ(command); command=@"CREATE INDEX formularymed_MedicationNum ON formularymed (MedicationNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { try { command="ALTER TABLE inssub DROP OldPlanNum"; Db.NonQ(command); } catch { //Some might not have this already so do nothing. //No need to test if column exists for Oracle because column was created in //7.5 which is before Oracle support started so it will never exist. } } //Migrating the diseases to allergies and corresponding Rx alerts. command="SELECT * FROM diseasedef WHERE LOWER(DiseaseName) LIKE '%allerg%'"; DataTable tableDiseaseDef=Db.GetTable(command); for(int i=0;i<tableDiseaseDef.Rows.Count;i++) { command="INSERT INTO allergydef (AllergyDefNum,Description,IsHidden) VALUES(" +POut.Long(PIn.Long(tableDiseaseDef.Rows[i]["DiseaseDefNum"].ToString()))+",'" +POut.String(PIn.String(tableDiseaseDef.Rows[i]["DiseaseName"].ToString()))+"'," +POut.Int(PIn.Int(tableDiseaseDef.Rows[i]["IsHidden"].ToString()))+")"; Db.NonQ(command); command="SELECT * FROM disease WHERE DiseaseDefNum="+POut.Long(PIn.Long(tableDiseaseDef.Rows[i]["DiseaseDefNum"].ToString())); DataTable disease=Db.GetTable(command); for(int j=0;j<disease.Rows.Count;j++) { command="INSERT INTO allergy (AllergyNum,PatNum,AllergyDefNum,Reaction,StatusIsActive) VALUES (" +POut.Long(PIn.Long(disease.Rows[j]["DiseaseNum"].ToString()))+"," +POut.Long(PIn.Long(disease.Rows[j]["PatNum"].ToString()))+"," +POut.Long(PIn.Long(disease.Rows[j]["DiseaseDefNum"].ToString()))+",'" +POut.String(PIn.String(disease.Rows[j]["PatNote"].ToString()))+"',1)"; Db.NonQ(command); command="DELETE FROM disease WHERE DiseaseNum="+POut.Long(PIn.Long(disease.Rows[j]["DiseaseNum"].ToString())); Db.NonQ(command); } command="UPDATE rxalert SET AllergyDefNum="+POut.Long(PIn.Long(tableDiseaseDef.Rows[i]["DiseaseDefNum"].ToString()))+", DiseaseDefNum=0 WHERE DiseaseDefNum=" +POut.Long(PIn.Long(tableDiseaseDef.Rows[i]["DiseaseDefNum"].ToString())); Db.NonQ(command); command="DELETE FROM diseasedef WHERE DiseaseDefNum="+POut.Long(PIn.Long(tableDiseaseDef.Rows[i]["DiseaseDefNum"].ToString())); Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.Oracle) {//Set time stamps to NOW(). command="UPDATE allergy SET DateTStamp=SYSTIMESTAMP"; Db.NonQ(command); command="UPDATE allergydef SET DateTStamp=SYSTIMESTAMP"; Db.NonQ(command); } //Canadian claim carrier default values. command="UPDATE carrier SET CanadianEncryptionMethod=1 WHERE IsCDA=1 AND CanadianEncryptionMethod=0"; Db.NonQ(command); command="UPDATE carrier SET CanadianSupportedTypes=262143 WHERE IsCDA=1 AND CanadianSupportedTypes=0";//All transaction types are allowed for each carrier by default. Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS drugmanufacturer"; Db.NonQ(command); command=@"CREATE TABLE drugmanufacturer ( DrugManufacturerNum bigint NOT NULL auto_increment PRIMARY KEY, ManufacturerName varchar(255) NOT NULL, ManufacturerCode varchar(20) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE drugmanufacturer'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE drugmanufacturer ( DrugManufacturerNum number(20) NOT NULL, ManufacturerName varchar2(255), ManufacturerCode varchar2(20), CONSTRAINT drugmanufacturer_DrugManNum PRIMARY KEY (DrugManufacturerNum) )"; //Changed drugmanufacturer_DrugManufacturerNum to DrugManNum: Max identifier for Oracle is 30 characters. Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS drugunit"; Db.NonQ(command); command=@"CREATE TABLE drugunit ( DrugUnitNum bigint NOT NULL auto_increment PRIMARY KEY, UnitIdentifier varchar(20) NOT NULL, UnitText varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE drugunit'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE drugunit ( DrugUnitNum number(20) NOT NULL, UnitIdentifier varchar2(20), UnitText varchar2(255), CONSTRAINT drugunit_DrugUnitNum PRIMARY KEY (DrugUnitNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS vaccinedef"; Db.NonQ(command); command=@"CREATE TABLE vaccinedef ( VaccineDefNum bigint NOT NULL auto_increment PRIMARY KEY, CVXCode varchar(255) NOT NULL, VaccineName varchar(255) NOT NULL, DrugManufacturerNum bigint NOT NULL, INDEX(DrugManufacturerNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE vaccinedef'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE vaccinedef ( VaccineDefNum number(20) NOT NULL, CVXCode varchar2(255), VaccineName varchar2(255), DrugManufacturerNum number(20) NOT NULL, CONSTRAINT vaccinedef_VaccineDefNum PRIMARY KEY (VaccineDefNum) )"; Db.NonQ(command); command=@"CREATE INDEX vaccinedef_DrugManufacturerNum ON vaccinedef (DrugManufacturerNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS vaccinepat"; Db.NonQ(command); command=@"CREATE TABLE vaccinepat ( VaccinePatNum bigint NOT NULL auto_increment PRIMARY KEY, VaccineDefNum bigint NOT NULL, DateTimeStart date NOT NULL DEFAULT '0001-01-01', DateTimeEnd date NOT NULL DEFAULT '0001-01-01', AdministeredAmt float NOT NULL, DrugUnitNum bigint NOT NULL, LotNumber varchar(255) NOT NULL, INDEX(VaccineDefNum), INDEX(DrugUnitNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE vaccinepat'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE vaccinepat ( VaccinePatNum number(20) NOT NULL, VaccineDefNum number(20) NOT NULL, DateTimeStart date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, DateTimeEnd date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, AdministeredAmt number(38,8) NOT NULL, DrugUnitNum number(20) NOT NULL, LotNumber varchar2(255), CONSTRAINT vaccinepat_VaccinePatNum PRIMARY KEY (VaccinePatNum) )"; Db.NonQ(command); command=@"CREATE INDEX vaccinepat_VaccineDefNum ON vaccinepat (VaccineDefNum)"; Db.NonQ(command); command=@"CREATE INDEX vaccinepat_DrugUnitNum ON vaccinepat (DrugUnitNum)"; Db.NonQ(command); } //eCW bridge enhancements command="SELECT ProgramNum FROM program WHERE ProgName='eClinicalWorks'"; int programNum=PIn.Int(Db.GetScalar(command)); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'FeeSchedulesSetManually', " +"'0')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES((SELECT MAX(ProgramPropertyNum)+1 FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'FeeSchedulesSetManually', " +"'0')"; Db.NonQ32(command); } command="UPDATE preference SET ValueString = '7.9.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_9_2(); } private static void To7_9_2() { if(FromVersion<new Version("7.9.2.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.9.2"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileSynchNewTables79Done','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MobileSynchNewTables79Done','0')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '7.9.2.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_9_8(); } ///<summary>Oracle compatible: 5/24/2011</summary> private static void To7_9_8() { if(FromVersion<new Version("7.9.8.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.9.8"));//No translation in convert script. string command; command=@"UPDATE clearinghouse SET ExportPath='C:\\Program Files\\Renaissance\\dotr\\upload\\' WHERE Description='Renaissance'"; Db.NonQ(command); command="UPDATE preference SET ValueString = '7.9.8.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To7_9_10(); } ///<summary>Oracle compatible: 7/7/2011</summary> private static void To7_9_10() { if(FromVersion<new Version("7.9.10.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 7.9.10"));//No translation in convert script. string command; command="UPDATE payment SET DateEntry=PayDate WHERE DateEntry < "+POut.Date(new DateTime(1880,1,1)); Db.NonQ(command); command="UPDATE preference SET ValueString = '7.9.10.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_1(); } ///<summary>Oracle compatible: 7/8/2011</summary> private static void To11_0_1() { if(FromVersion<new Version("11.0.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS labpanel"; Db.NonQ(command); command=@"CREATE TABLE labpanel ( LabPanelNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, RawMessage text NOT NULL, LabNameAddress varchar(255) NOT NULL, DateTStamp timestamp, SpecimenCondition varchar(255) NOT NULL, SpecimenSource varchar(255) NOT NULL, ServiceId varchar(255) NOT NULL, ServiceName varchar(255) NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE labpanel'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE labpanel ( LabPanelNum number(20) NOT NULL, PatNum number(20) NOT NULL, RawMessage clob, LabNameAddress varchar2(255), DateTStamp timestamp, SpecimenCondition varchar2(255), SpecimenSource varchar2(255), ServiceId varchar2(255), ServiceName varchar2(255), CONSTRAINT labpanel_LabPanelNum PRIMARY KEY (LabPanelNum) )"; Db.NonQ(command); command=@"CREATE INDEX labpanel_PatNum ON labpanel (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS labresult"; Db.NonQ(command); command=@"CREATE TABLE labresult ( LabResultNum bigint NOT NULL auto_increment PRIMARY KEY, LabPanelNum bigint NOT NULL, DateTimeTest datetime NOT NULL DEFAULT '0001-01-01 00:00:00', TestName varchar(255) NOT NULL, DateTStamp timestamp, TestID varchar(255) NOT NULL, ObsValue varchar(255) NOT NULL, ObsUnits varchar(255) NOT NULL, ObsRange varchar(255) NOT NULL, INDEX(LabPanelNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE labresult'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE labresult ( LabResultNum number(20) NOT NULL, LabPanelNum number(20) NOT NULL, DateTimeTest date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, TestName varchar2(255), DateTStamp timestamp, TestID varchar2(255), ObsValue varchar2(255), ObsUnits varchar2(255) NOT NULL, ObsRange varchar2(255) NOT NULL, CONSTRAINT labresult_LabResultNum PRIMARY KEY (LabResultNum) )"; Db.NonQ(command); command=@"CREATE INDEX labresult_LabPanelNum ON labresult (LabPanelNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vaccinepat ADD PatNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE vaccinepat ADD INDEX (PatNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vaccinepat ADD PatNum number(20)"; Db.NonQ(command); command="UPDATE vaccinepat SET PatNum = 0 WHERE PatNum IS NULL"; Db.NonQ(command); command="ALTER TABLE vaccinepat MODIFY PatNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX vaccinepat_PatNum ON vaccinepat (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,Comments) VALUES('EHREmailToAddress','Hidden pref: Email for sending EHR email.')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'EHREmailToAddress','Hidden pref: Email for sending EHR email.')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicalorder ADD Description varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicalorder ADD Description varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vaccinepat MODIFY DateTimeStart DATETIME"; Db.NonQ(command); command="ALTER TABLE vaccinepat MODIFY DateTimeEnd DATETIME"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vaccinepat MODIFY (DateTimeStart DATE);"; Db.NonQ(command); command="ALTER TABLE vaccinepat MODIFY (DateTimeEnd DATE);"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE securitylog ADD CompName varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE securitylog ADD CompName varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference (PrefName, ValueString,Comments) VALUES ('EhrEmergencyNow','0','Boolean. 0 means false. 1 grants emergency access to the family module.')"; Db.NonQ(command); } else{//oracle command="INSERT INTO preference (PrefNum,PrefName, ValueString,Comments) VALUES ((SELECT MAX(PrefNum)+1 FROM preference),'EhrEmergencyNow','0','Boolean. 0 means false. 1 grants emergency access to the family module.')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('SecurityLogOffAfterMinutes','0','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference (PrefNum,PrefName, ValueString,Comments) VALUES ((SELECT MAX(PrefNum)+1 FROM preference),'SecurityLogOffAfterMinutes','0','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD PreferContactConfidential tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE patient ADD PreferContactConfidential number(3)"; Db.NonQ(command); command="UPDATE patient SET PreferContactConfidential = 0 WHERE PreferContactConfidential IS NULL"; Db.NonQ(command); command="ALTER TABLE patient MODIFY PreferContactConfidential NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS reminderrule"; Db.NonQ(command); command=@"CREATE TABLE reminderrule ( ReminderRuleNum bigint NOT NULL auto_increment PRIMARY KEY, ReminderCriterion tinyint NOT NULL, CriterionFK bigint NOT NULL, CriterionValue varchar(255) NOT NULL, Message varchar(255) NOT NULL, INDEX(CriterionFK) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE reminderrule'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE reminderrule ( ReminderRuleNum number(20) NOT NULL, ReminderCriterion number(3) NOT NULL, CriterionFK number(20) NOT NULL, CriterionValue varchar2(255), Message varchar2(255), CONSTRAINT reminderrule_ReminderRuleNum PRIMARY KEY (ReminderRuleNum) )"; Db.NonQ(command); command=@"CREATE INDEX reminderrule_CriterionFK ON reminderrule (CriterionFK)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patplan DROP PlanNum"; Db.NonQ(command); } else {//oracle command="ALTER TABLE patplan DROP COLUMN PlanNum"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('EHREmailFromAddress','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'EHREmailFromAddress','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('EHREmailPOPserver','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'EHREmailPOPserver','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('EHREmailPort','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'EHREmailPort','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('EHREmailPassword','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'EHREmailPassword','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('ProblemsIndicateNone','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ProblemsIndicateNone','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('MedicationsIndicateNone','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MedicationsIndicateNone','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS eduresource"; Db.NonQ(command); command=@"CREATE TABLE eduresource ( EduResourceNum bigint NOT NULL auto_increment PRIMARY KEY, Icd9Num bigint NOT NULL, DiseaseDefNum bigint NOT NULL, MedicationNum bigint NOT NULL, LabResultID varchar(255) NOT NULL, LabResultName varchar(255) NOT NULL, LabResultCompare varchar(255) NOT NULL, ResourceUrl varchar(255) NOT NULL, INDEX(Icd9Num), INDEX(DiseaseDefNum), INDEX(MedicationNum), INDEX(LabResultID) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE eduresource'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE eduresource ( EduResourceNum number(20) NOT NULL, Icd9Num number(20) NOT NULL, DiseaseDefNum number(20) NOT NULL, MedicationNum number(20) NOT NULL, LabResultID varchar2(255), LabResultName varchar2(255), LabResultCompare varchar2(255), ResourceUrl varchar2(255), CONSTRAINT eduresource_EduResourceNum PRIMARY KEY (EduResourceNum) )"; Db.NonQ(command); command=@"CREATE INDEX eduresource_Icd9Num ON eduresource (Icd9Num)"; Db.NonQ(command); command=@"CREATE INDEX eduresource_DiseaseDefNum ON eduresource (DiseaseDefNum)"; Db.NonQ(command); command=@"CREATE INDEX eduresource_MedicationNum ON eduresource (MedicationNum)"; Db.NonQ(command); command=@"CREATE INDEX eduresource_LabResultID ON eduresource (LabResultID)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicalorder ADD IsDiscontinued tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicalorder ADD IsDiscontinued number(3)"; Db.NonQ(command); command="UPDATE medicalorder SET IsDiscontinued = 0 WHERE IsDiscontinued IS NULL"; Db.NonQ(command); command="ALTER TABLE medicalorder MODIFY IsDiscontinued NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('StoreCCtokens','1')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'StoreCCtokens','1')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { //Create a temporary table to hold all of the canadian network information that we know of. command="DROP TABLE IF EXISTS `tempcanadiannetwork`"; Db.NonQ(command); command="CREATE TABLE `tempcanadiannetwork` (" +"`CanadianNetworkNum` bigint(20) NOT NULL auto_increment," +"`Abbrev` varchar(20) default ''," +"`Descript` varchar(255) default ''," +"`CanadianTransactionPrefix` varchar(255) default ''," +"PRIMARY KEY (`CanadianNetworkNum`)" +") ENGINE=MyISAM DEFAULT CHARSET=utf8"; Db.NonQ(command); command="INSERT INTO `tempcanadiannetwork`(`CanadianNetworkNum`,`Abbrev`,`Descript`,`CanadianTransactionPrefix`) VALUES (7,'TELUS B','TELUS Group B','HD* ')"; Db.NonQ(command); command="INSERT INTO `tempcanadiannetwork`(`CanadianNetworkNum`,`Abbrev`,`Descript`,`CanadianTransactionPrefix`) VALUES (8,'CSI','Continovation Services Inc.','CSI ')"; Db.NonQ(command); command="INSERT INTO `tempcanadiannetwork`(`CanadianNetworkNum`,`Abbrev`,`Descript`,`CanadianTransactionPrefix`) VALUES (9,'CDCS','CDCS','CDCS ')"; Db.NonQ(command); command="INSERT INTO `tempcanadiannetwork`(`CanadianNetworkNum`,`Abbrev`,`Descript`,`CanadianTransactionPrefix`) VALUES (10,'TELUS A','TELUS Group A','1111111119 ')"; Db.NonQ(command); command="INSERT INTO `tempcanadiannetwork`(`CanadianNetworkNum`,`Abbrev`,`Descript`,`CanadianTransactionPrefix`) VALUES (11,'MBC','Manitoba Blue Cross','MBC ')"; Db.NonQ(command); command="INSERT INTO `tempcanadiannetwork`(`CanadianNetworkNum`,`Abbrev`,`Descript`,`CanadianTransactionPrefix`) VALUES (12,'PBC','Pacific Blue Cross','PBC ')"; Db.NonQ(command); command="INSERT INTO `tempcanadiannetwork`(`CanadianNetworkNum`,`Abbrev`,`Descript`,`CanadianTransactionPrefix`) VALUES (13,'ABC','Alberta Blue Cross','ABC ')"; Db.NonQ(command); //Create a column to associate already created canadian networks to our temporary canadian network table. command="ALTER TABLE tempcanadiannetwork ADD COLUMN CanadianNetworkNumExisting bigint default 0"; Db.NonQ(command); command="UPDATE tempcanadiannetwork t,canadiannetwork n SET t.CanadianNetworkNumExisting=n.CanadianNetworkNum WHERE TRIM(LOWER(t.Abbrev))=TRIM(LOWER(n.Abbrev))"; Db.NonQ(command); //Create a column to associate our temporary canadian networks to their new primary key in the canadian network table. command="ALTER TABLE tempcanadiannetwork ADD COLUMN CanadianNetworkNumNew bigint default 0"; Db.NonQ(command); command="UPDATE tempcanadiannetwork t " +"SET t.CanadianNetworkNumNew=CASE " +"WHEN t.CanadianNetworkNumExisting<>0 THEN t.CanadianNetworkNumExisting " +"ELSE t.CanadianNetworkNum+(SELECT MAX(n.CanadianNetworkNum) FROM canadiannetwork n) END"; Db.NonQ(command); //Update the live canadiannetwork table and set the CanadianTransactionPrefix to known values for networks that were already in the database. command="UPDATE canadiannetwork n,tempcanadiannetwork t SET n.CanadianTransactionPrefix=t.CanadianTransactionPrefix WHERE n.CanadianNetworkNum=t.CanadianNetworkNumExisting"; Db.NonQ(command); //Add any missing canadian networks from the temporary canadian network table for those networks that are not already present. command="INSERT INTO canadiannetwork (CanadianNetworkNum,Abbrev,Descript,CanadianTransactionPrefix) " +"SELECT CanadianNetworkNumNew,Abbrev,Descript,CanadianTransactionPrefix " +"FROM tempcanadiannetwork " +"WHERE CanadianNetworkNumExisting=0"; Db.NonQ(command); //Remove the CanadianTransactionPrefix column from the carrier table, since it will now be part of the canadiannetwork table. command="ALTER TABLE carrier DROP COLUMN CanadianTransactionPrefix"; Db.NonQ(command); //Create a temporary carrier table to hold all of the most recent canadian carrier information that we know about. command="DROP TABLE IF EXISTS `tempcarriercanada`"; Db.NonQ(command); command="CREATE TABLE `tempcarriercanada` (" +"`CarrierNum` bigint(20) NOT NULL auto_increment," +"`CarrierName` varchar(255) default ''," +"`Address` varchar(255) default ''," +"`Address2` varchar(255) default ''," +"`City` varchar(255) default ''," +"`State` varchar(255) default ''," +"`Zip` varchar(255) default ''," +"`Phone` varchar(255) default ''," +"`ElectID` varchar(255) default ''," +"`NoSendElect` tinyint(1) unsigned NOT NULL default '0'," +"`IsCDA` tinyint(3) unsigned NOT NULL," +"`CDAnetVersion` varchar(100) default ''," +"`CanadianNetworkNum` bigint(20) NOT NULL," +"`IsHidden` tinyint(4) NOT NULL," +"`CanadianEncryptionMethod` tinyint(4) NOT NULL," +"`CanadianSupportedTypes` int(11) NOT NULL," +"PRIMARY KEY (`CarrierNum`)" +") ENGINE=MyISAM DEFAULT CHARSET=utf8"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (1,'Accerta','P.O. Box 310','Station \\'P\\'','Toronto','ON','M5S 2S8','1-800-505-7430','311140',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (2,'ADSC - AB Social Services QuikCard','200 Quikcard Centre','17010 103 Avenue','Edmonton','AB','T5S 1K7','1-800-232-1997','000105',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (3,'AGA Financial Group - Groupe Cloutier','525 René-Lévesque Blvd E 6th Floor','P.O. Box 17100','Quebec','QC','G1K 9E2','1 800 461-0770','610226',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (4,'Association des policières et policiers (APPQ)','1981, Léonard-De Vinci','','Ste-Julie','QC','J3E 1Y9','(450) 922-5414','628112',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (5,'Assumption Life','P. O. Box 160','','Moncton','NB','E1C 8L1','1-800-455-7337','610191',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (6,'Autoben','212 King Street West','Suite 203','Toronto','ON','M5H 1K5','1.866.647.1147','628151',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (7,'Benecaid Health Benefit Solutions (ESI)','185 The West Mall','Suite 1700','Toronto','ON','M9C 5L5','1.877.797.7448','610708',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (8,'Benefits Trust (The)','3800 Steeles Ave. West','Suite #102W','Vaughan','ON','L4L 4G9','1-800-487-2993','610146',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (9,'Beneplan','150 Ferrand Drive','Suite 500','Toronto','ON','M3C 3E5','1-800-387-1670','400008',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (10,'Capitale','525 René-Lévesque Blvd E 6th Floor','P.O. Box 17100','Quebec','QC','G1K 9E2','1 800 461-0770','600502',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (12,'Claimsecure','1 City Centre Drive','Suite 620','Mississauga','ON','L5B 1M2','1-888-479-7587','610099',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (11,'CDCS','P.O. Box 156 Stn. \"B\"','','Sudbury','ON','P3E 4N5','(705) 675-2222','610129',0,1,'04',9,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (13,'Commision de la construction du Quebec (CCQ)','3530, rue Jean-Talon Ouest','','Montréal','QC','H3R 2G3','1 888 842-8282','000036',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (14,'Co-operators (The)','Service Quality Department','130 Macdonell Street','Guelph','ON','N1H 6P8','1-800-265-2662','606258',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (15,'Coughlin & Associates','466 Tremblay Road','','Ottawa','ON','K1G 3R1','1-888-613-1234','610105',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (16,'Cowan Wright Beauchamps','705 Fountain Street North','PO Box 1510','Cambridge','ON','N1R 5T2','1-866-912-6926','610153',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (17,'Desjardins Financial Security','200 des Commandeurs','','Lévis','QC','G6V 6R2','1-866-838-7553','000051',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (18,'Empire Life Insurance Company (The)','259 King Street East','','Kingston','ON','K7L 3A8','1 800 561-1268','000033',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (19,'Equitable Life','One Westmount Road North','P.O. Box 1603, Stn Waterloo','Waterloo','ON','N2J 4C7','1-800-265-4556 x601','000029',0,1,'02',10,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (20,'Esorse Corporation','234 Eglinton Avenue East','Suite 502','Toronto','ON','M4P 1K5','(416)-483-3265','610650',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (21,'FAS Administrators','9707 - 110 Street','9th Floor','Edmonton','AB','T5K 3T4','1-800-770-2998','610614',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (22,'Great West Life Assurance Company (The)','100 Osborne Street North','','Winnipeg','MB','R3C 3A5','204-946-1190','000011',0,1,'02',10,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (23,'Green Shield Canada','8677 Anchor Drive','P.O Box 1606','Windsor','ON','N9A 6W1','1-800-265-5615','000102',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (24,'Group Medical Services (GMS - ESI)','2055 Albert Street','PO Box 1949','Regina','SK','S4P 0E3','1.800.667.3699','610217',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (25,'Group Medical Services (GMS - ESI - Saskatchewan)','2055 Albert Street','PO Box 1949','Regina','SK','S4P 0E3','1.800.667.3699','610218',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (26,'groupSource','1550 - 5th Street SW','Suite 400','Calgary','AB','T2R 1K3','1-800-661-6195','605064',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (27,'Industrial Alliance','1080 Grande Allée West','PO Box 1907, Station Terminus','Quebec City','QC','G1K 7M3','1-800-463-6236','000060',0,1,'02',10,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (28,'Industrial Alliance Pacific Insurance and Financial','2165 Broadway West','P.O. Box 5900','Vancouver','BC','V6B 5H6','(604) 734-1667','000024',0,1,'02',10,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (29,'Internationale Compagnie D\\'assurance vie','142 Heriot','P.O. Box 696','Drummondville','QC','J2B 6W9','1 888 864-6684','610643',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (30,'Johnson Inc.','','','','','','1-877-221-2127','627265',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (31,'Johnston Group','','','','','','800-990-4476','627223',0,1,'02',10,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (32,'Lee-Power & Associates Inc.','616 Cooper St.','','Ottawa','ON','K1R 5J2','(613) 236-9007','627585',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (33,'Manion Wilkins','500 - 21 Four Seasons Place','','Etobicoke','ON','M9B 0A5','1-800-263-5621','610158',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (34,'Manitoba Blue Cross','P.O. Box 1046','','Winnipeg','MB','R3C 2X7','1-800-873-2583','000094',0,1,'04',11,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (35,'Manufacturers Life Insurance Company (The)','500 King Street. N.','P.O. Box 1669','Waterloo','ON','N2J 4Z6','1-888-626-8543','000034',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (36,'Manulife Financial','500 King Street. N.','P.O. Box 1669','Waterloo','ON','N2J 4Z6','1-888-626-8543','610059',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (37,'Maritime Life Assurance Company','500 King Street. N.','P.O. Box 1669','Waterloo','ON','N2J 4Z6','1-888-626-8543','311113',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (38,'Maritime Life Assurance Company','500 King Street. N.','P.O. Box 1669','Waterloo','ON','N2J 4Z6','1-888-626-8543','610070',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (39,'McAteer Group of Companies','45 McIntosh Drive','','Markham','ON','L3R 8C7','(800) 263-3564','000112',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (40,'MDM','MD Management Limited','1870, Alta Vista Drive','Ottawa','ON','K1G 6R7','1 800 267-4022','601052',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (41,'Medavie Blue Cross','644 Main Street','PO Box 220','Moncton','NB','E1C 8L3','1-800-667-4511','610047',0,1,'02',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (42,'NexGenRX','145 The West Mall','P.O. Box 110 U','Toronto','ON','M8Z 5M4','1-866-424-0257','610634',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (43,'NIHB','Health Canada','Address Locator 0900C2','Ottawa','ON','K1A 0K9','1-866-225-0709','610124',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (44,'Nova Scotia Community Services','10 Webster Street','Suite 202','Kentville','NS','B4N 1H7','(902) 679-6715','000109',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (45,'Nova Scotia Medical Services Insurance','1741 Brunswick Street, Suite 110A','PO Box 1535','Halifax','NS','B3J 2Y3','1-877-292-9597','000108',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (46,'Nunatsiavut Government Department of Health','25 Ikajuktauvik Road','P.O. Box 70','Nain','NL','A0P 1L0','(709) 922-2942','610172',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (47,'Pacific Blue Cross','Pacific Blue Cross/ BC Life','PO Box 7000','Vancouver','BC','V6B 4E1','604 419-2300','000064',0,1,'04',12,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (48,'Quikcard','200 Quikcard Centre','17010 103 Avenue','Edmonton','AB','T5S 1K7','(780) 426-7526','000103',0,1,'04',8,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (49,'RWAM Insurance','49 Industrial Drive','','Elmira','ON','N3B 3B1','(519) 669-1632','610616',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (50,'Saskatchewan Blue Cross','516 2nd Avenue N','PO Box 4030','Saskatoon','SK','S7K 3T2','306.244.1192','000096',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (51,'SES Benefits','2800 Skymark Avenue','Suite 307','Mississauga','ON','L4W 5A6','1-888-939-8885','610196',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (52,'SSQ SOCIÉTÉ d\\'assurance-vie inc.','2525 Laurier Boulevard','P.O. Box 10500, Stn Sainte-Foy','Quebec City','QC','G1V 4H6','1-888-900-3457','000079',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (53,'Standard Life Assurance Company (The)','639 - 5th Avenue South West','Suite 1500','Calgary','AB','T2P 0M9','403-296-9477','000020',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (54,'Sun Life of Canada','','','','','','1-877-786-5433','000016',0,1,'02',10,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (55,'Survivance','1555 Girouard Street West','P.O. Box 10,000','Saint-Hyacinthe','QC','J2S 7C8','450 773-6051','000080',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (56,'Syndicat des fonctionnaires municipaux MTL','429, rue de La Gauchetière Est','','Montréal','QC','H2L 2M7','514 842-9463','610677',0,1,'04',7,0,1,262143)"; Db.NonQ(command); command="INSERT INTO `tempcarriercanada`(`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`,`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) VALUES (57,'Wawanesa','900-191 Broadway','','Winnipeg','MB','R3C 3P1','(204) 985-3923','311109',0,1,'02',7,0,1,262143)"; Db.NonQ(command); //Update the CanadianNetworkNum values in the temporary carrier table because the networks in the live canadiannetwork table are different. command="UPDATE tempcarriercanada tc,tempcanadiannetwork tn SET tc.CanadianNetworkNum=tn.CanadianNetworkNumNew WHERE tc.CanadianNetworkNum=tn.CanadianNetworkNum"; Db.NonQ(command); //Clear all CanadianNetworkNum foreign keys from the carrier table so that for those carriers which we cannot match to a network, the users will be notified that no network is associated with the carrier. command="UPDATE carrier c SET c.CanadianNetworkNum=0"; Db.NonQ(command); //Create a column in the temporary carrier table to link up the existing carriers by electronic ID. command="ALTER TABLE tempcarriercanada ADD COLUMN CarrierNumExisting bigint default 0"; Db.NonQ(command); command="UPDATE tempcarriercanada t,carrier c SET t.CarrierNumExisting=c.CarrierNum WHERE c.IsCDA=1 AND t.ElectID=c.ElectID"; Db.NonQ(command); //For those carriers that were already in the live data before this conversion that match a known carrier, update their CanadianNetworkNum to match the temporary canadian network data. command="UPDATE carrier c,tempcarriercanada tc SET c.CanadianNetworkNum=tc.CanadianNetworkNum WHERE c.CarrierNum=tc.CarrierNumExisting"; Db.NonQ(command); //Create a column to figure out what the new carriernums will need to be for the new carriers that we are going to add to the carrier table. command="ALTER TABLE tempcarriercanada ADD COLUMN CarrierNumNew bigint default 0"; Db.NonQ(command); command="UPDATE tempcarriercanada t SET t.CarrierNumNew=CASE WHEN t.CarrierNumExisting<>0 THEN t.CarrierNumExisting ELSE t.CarrierNum+(SELECT MAX(c.CarrierNum) FROM carrier c) END"; Db.NonQ(command); //Add carriers from the temporary carrier table which do not already exist in the live carrier table. //We only want to insert these carriers if in Canada because they are of no use elsewhere. if(CultureInfo.CurrentCulture.Name.EndsWith("CA")) {//Canadian. en-CA or fr-CA command="INSERT INTO carrier (`CarrierNum`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`," +"`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes`) " +"SELECT `CarrierNumNew`,`CarrierName`,`Address`,`Address2`,`City`,`State`,`Zip`,`Phone`,`ElectID`,`NoSendElect`,`IsCDA`," +"`CDAnetVersion`,`CanadianNetworkNum`,`IsHidden`,`CanadianEncryptionMethod`,`CanadianSupportedTypes` " +"FROM tempcarriercanada " +"WHERE CarrierNumExisting=0"; Db.NonQ(command); } command="DROP TABLE IF EXISTS `tempcanadiannetwork`"; Db.NonQ(command); command="DROP TABLE IF EXISTS `tempcarriercanada`"; Db.NonQ(command); } else {//oracle //At this point, there should not be anyone in Canada using Oracle, so these statements have been skipped because they would be a bit of work to create. } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('AllergiesIndicateNone','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'AllergiesIndicateNone','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE provider ADD IsCDAnet tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE provider ADD IsCDAnet number(3)"; Db.NonQ(command); command="UPDATE provider SET IsCDAnet = 0 WHERE IsCDAnet IS NULL"; Db.NonQ(command); command="ALTER TABLE provider MODIFY IsCDAnet NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS ehrmeasureevent"; Db.NonQ(command); command=@"CREATE TABLE ehrmeasureevent ( EhrMeasureEventNum bigint NOT NULL auto_increment PRIMARY KEY, DateTEvent datetime NOT NULL DEFAULT '0001-01-01 00:00:00', EventType tinyint NOT NULL, PatNum bigint NOT NULL, MoreInfo varchar(255) NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE ehrmeasureevent'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE ehrmeasureevent ( EhrMeasureEventNum number(20) NOT NULL, DateTEvent date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, EventType number(3) NOT NULL, PatNum number(20) NOT NULL, MoreInfo varchar2(255), CONSTRAINT ehrmeasureevent_EhrMeasureNum PRIMARY KEY (EhrMeasureEventNum) )"; Db.NonQ(command); command=@"CREATE INDEX ehrmeasureevent_PatNum ON ehrmeasureevent (PatNum)"; Db.NonQ(command); } //EvaSoft link----------------------------------------------------------------------- //This insert statement is compatible with both MySQL and Oracle. command="SELECT MAX(ProgramNum)+1 FROM program"; long programNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'"+POut.Long(programNum)+"'," +"'EvaSoft', " +"'EvaSoft from www.imageworkscorporation.com', " +"'0', " +"'', " +"'', " +"'"+POut.String(@"No command line or path is needed.")+"')"; Db.NonQ(command); //This insert statement is compatible with both MySQL and Oracle. command="SELECT MAX(ProgramPropertyNum)+1 FROM programproperty"; long programPropertyNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programPropertyNum)+"'," +"'"+programNum.ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); //This insert statement is compatible with both MySQL and Oracle. command="SELECT MAX(ToolButItemNum)+1 FROM toolbutitem"; long toolButItemNum=PIn.Long(Db.GetScalar(command)); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(toolButItemNum)+"'," +"'"+programNum.ToString()+"', " +"'"+POut.Int((int)ToolBarsAvail.ChartModule)+"', " +"'EvaSoft')"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE refattach ADD IsTransitionOfCare tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE refattach ADD IsTransitionOfCare number(3)"; Db.NonQ(command); command="UPDATE refattach SET IsTransitionOfCare = 0 WHERE IsTransitionOfCare IS NULL"; Db.NonQ(command); command="ALTER TABLE refattach MODIFY IsTransitionOfCare NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE referral ADD IsDoctor tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE referral ADD IsDoctor number(3)"; Db.NonQ(command); command="UPDATE referral SET IsDoctor = 0 WHERE IsDoctor IS NULL"; Db.NonQ(command); command="ALTER TABLE referral MODIFY IsDoctor NOT NULL"; Db.NonQ(command); } command="UPDATE referral SET IsDoctor=1 WHERE PatNum = 0"; Db.NonQ(command); if(DataConnection.DBtype == DatabaseType.MySql) { command = "ALTER TABLE allergy ADD DateAdverseReaction date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command = "ALTER TABLE allergy ADD DateAdverseReaction date"; Db.NonQ(command); command = "UPDATE allergy SET DateAdverseReaction = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateAdverseReaction IS NULL"; Db.NonQ(command); command = "ALTER TABLE allergy MODIFY DateAdverseReaction NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE pharmacy ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE pharmacy SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE pharmacy ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE pharmacy SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicationpat ADD DateStart date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicationpat ADD DateStart date"; Db.NonQ(command); command="UPDATE medicationpat SET DateStart = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateStart IS NULL"; Db.NonQ(command); command="ALTER TABLE medicationpat MODIFY DateStart NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicationpat ADD DateStop date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicationpat ADD DateStop date"; Db.NonQ(command); command="UPDATE medicationpat SET DateStop = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateStop IS NULL"; Db.NonQ(command); command="ALTER TABLE medicationpat MODIFY DateStop NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="UPDATE medicationpat SET DateStop = CURDATE() WHERE IsDiscontinued=1"; Db.NonQ(command); } else{ command="UPDATE medicationpat SET DateStop = SYSDATE WHERE IsDiscontinued=1"; Db.NonQ(command); } command="ALTER TABLE medicationpat DROP COLUMN IsDiscontinued";//both oracle and mysql Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE allergydef ADD Snomed tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE allergydef ADD Snomed number(3)"; Db.NonQ(command); command="UPDATE allergydef SET Snomed = 0 WHERE Snomed IS NULL"; Db.NonQ(command); command="ALTER TABLE allergydef MODIFY Snomed NOT NULL"; Db.NonQ(command); } //this was supposed to have been deleted: if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE allergydef ADD RxCui bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE allergydef ADD INDEX (RxCui)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE allergydef ADD RxCui number(20)"; Db.NonQ(command); command="UPDATE allergydef SET RxCui = 0 WHERE RxCui IS NULL"; Db.NonQ(command); command="ALTER TABLE allergydef MODIFY RxCui NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX allergydef_RxCui ON allergydef (RxCui)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE labresult ADD AbnormalFlag tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE labresult ADD AbnormalFlag number(3)"; Db.NonQ(command); command="UPDATE labresult SET AbnormalFlag = 0 WHERE AbnormalFlag IS NULL"; Db.NonQ(command); command="ALTER TABLE labresult MODIFY AbnormalFlag NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE disease ADD DateStart date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE disease ADD DateStart date"; Db.NonQ(command); command="UPDATE disease SET DateStart = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateStart IS NULL"; Db.NonQ(command); command="ALTER TABLE disease MODIFY DateStart NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE disease ADD DateStop date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE disease ADD DateStop date"; Db.NonQ(command); command="UPDATE disease SET DateStop = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateStop IS NULL"; Db.NonQ(command); command="ALTER TABLE disease MODIFY DateStop NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxpat ADD SendStatus tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxpat ADD SendStatus number(3)"; Db.NonQ(command); command="UPDATE rxpat SET SendStatus = 0 WHERE SendStatus IS NULL"; Db.NonQ(command); command="ALTER TABLE rxpat MODIFY SendStatus NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE provider ADD EcwID varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE provider ADD EcwID varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE labpanel ADD MedicalOrderNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE labpanel ADD INDEX (MedicalOrderNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE labpanel ADD MedicalOrderNum number(20)"; Db.NonQ(command); command="UPDATE labpanel SET MedicalOrderNum = 0 WHERE MedicalOrderNum IS NULL"; Db.NonQ(command); command="ALTER TABLE labpanel MODIFY MedicalOrderNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX labpanel_MedicalOrderNum ON labpanel (MedicalOrderNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE allergydef ADD MedicationNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE allergydef ADD INDEX (MedicationNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE allergydef ADD MedicationNum number(20)"; Db.NonQ(command); command="UPDATE allergydef SET MedicationNum = 0 WHERE MedicationNum IS NULL"; Db.NonQ(command); command="ALTER TABLE allergydef MODIFY MedicationNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX allergydef_MedicationNum ON allergydef (MedicationNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS orthochart"; Db.NonQ(command); command=@"CREATE TABLE orthochart ( OrthoChartNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, DateService date NOT NULL DEFAULT '0001-01-01', FieldName varchar(255) NOT NULL, FieldValue text NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE orthochart'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE orthochart ( OrthoChartNum number(20) NOT NULL, PatNum number(20) NOT NULL, DateService date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, FieldName varchar2(255), FieldValue varchar2(4000), CONSTRAINT orthochart_OrthoChartNum PRIMARY KEY (OrthoChartNum) )"; Db.NonQ(command); command=@"CREATE INDEX orthochart_PatNum ON orthochart (PatNum)"; Db.NonQ(command); } command="ALTER TABLE rxpat DROP COLUMN IsElectQueue";//both oracle and mysql Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medication ADD RxCui bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE medication ADD INDEX (RxCui)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medication ADD RxCui number(20)"; Db.NonQ(command); command="UPDATE medication SET RxCui = 0 WHERE RxCui IS NULL"; Db.NonQ(command); command="ALTER TABLE medication MODIFY RxCui NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX medication_RxCui ON medication (RxCui)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('ShowFeatureEhr','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ShowFeatureEhr','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE provider ADD EhrKey varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE provider ADD EhrKey varchar2(255)"; Db.NonQ(command); } bool usingECW=true; command="SELECT COUNT(*) FROM program WHERE ProgName='eClinicalWorks' AND Enabled=1"; if(Db.GetCount(command)=="0") { usingECW=false; } if(usingECW) { command="UPDATE provider SET EcwID=Abbr"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS rxnorm"; Db.NonQ(command); command=@"CREATE TABLE rxnorm ( RxNormNum bigint NOT NULL auto_increment PRIMARY KEY, RxCui varchar(255) NOT NULL, MmslCode varchar(255) NOT NULL, Description varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE rxnorm'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE rxnorm ( RxNormNum number(20) NOT NULL, RxCui varchar2(255), MmslCode varchar2(255), Description varchar2(255), CONSTRAINT rxnorm_RxNormNum PRIMARY KEY (RxNormNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS ehrprovkey"; Db.NonQ(command); command=@"CREATE TABLE ehrprovkey ( EhrProvKeyNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, LName varchar(255) NOT NULL, FName varchar(255) NOT NULL, ProvKey varchar(255) NOT NULL, FullTimeEquiv float NOT NULL, Notes text NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE ehrprovkey'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE ehrprovkey ( EhrProvKeyNum number(20) NOT NULL, PatNum number(20) NOT NULL, LName varchar2(255), FName varchar2(255), ProvKey varchar2(255), FullTimeEquiv number(38,8) NOT NULL, Notes varchar2(4000), CONSTRAINT ehrprovkey_EhrProvKeyNum PRIMARY KEY (EhrProvKeyNum) )"; Db.NonQ(command); command=@"CREATE INDEX ehrprovkey_PatNum ON ehrprovkey (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('EhrProvKeyGeneratorPath','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'EhrProvKeyGeneratorPath','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('ApptPrintColumnsPerPage','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ApptPrintColumnsPerPage','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('ApptPrintFontSize','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ApptPrintFontSize','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('ApptPrintTimeStart','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ApptPrintTimeStart','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString,Comments) VALUES('ApptPrintTimeStop','','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString,Comments) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ApptPrintTimeStop','','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE provider ADD StateRxID varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE provider ADD StateRxID varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicalorder ADD ProvNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE medicalorder ADD INDEX (ProvNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicalorder ADD ProvNum number(20)"; Db.NonQ(command); command="UPDATE medicalorder SET ProvNum = 0 WHERE ProvNum IS NULL"; Db.NonQ(command); command="ALTER TABLE medicalorder MODIFY ProvNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX medicalorder_ProvNum ON medicalorder (ProvNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicationpat ADD ProvNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE medicationpat ADD INDEX (ProvNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE medicationpat ADD ProvNum number(20)"; Db.NonQ(command); command="UPDATE medicationpat SET ProvNum = 0 WHERE ProvNum IS NULL"; Db.NonQ(command); command="ALTER TABLE medicationpat MODIFY ProvNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX medicationpat_ProvNum ON medicationpat (ProvNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vitalsign ADD HasFollowupPlan tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vitalsign ADD HasFollowupPlan number(3)"; Db.NonQ(command); command="UPDATE vitalsign SET HasFollowupPlan = 0 WHERE HasFollowupPlan IS NULL"; Db.NonQ(command); command="ALTER TABLE vitalsign MODIFY HasFollowupPlan NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vitalsign ADD IsIneligible tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vitalsign ADD IsIneligible number(3)"; Db.NonQ(command); command="UPDATE vitalsign SET IsIneligible = 0 WHERE IsIneligible IS NULL"; Db.NonQ(command); command="ALTER TABLE vitalsign MODIFY IsIneligible NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vitalsign ADD Documentation text NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vitalsign ADD Documentation varchar2(4000)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE insplan ADD CanadianDiagnosticCode varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE insplan ADD CanadianDiagnosticCode varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE insplan ADD CanadianInstitutionCode varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE insplan ADD CanadianInstitutionCode varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE canadiannetwork ADD CanadianIsRprHandler tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE canadiannetwork ADD CanadianIsRprHandler number(3)"; Db.NonQ(command); command="UPDATE canadiannetwork SET CanadianIsRprHandler = 0 WHERE CanadianIsRprHandler IS NULL"; Db.NonQ(command); command="ALTER TABLE canadiannetwork MODIFY CanadianIsRprHandler NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxdef ADD RxCui bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE rxdef ADD INDEX (RxCui)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxdef ADD RxCui number(20)"; Db.NonQ(command); command="UPDATE rxdef SET RxCui = 0 WHERE RxCui IS NULL"; Db.NonQ(command); command="ALTER TABLE rxdef MODIFY RxCui NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX rxdef_RxCui ON rxdef (RxCui)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxpat ADD RxCui bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE rxpat ADD INDEX (RxCui)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxpat ADD RxCui number(20)"; Db.NonQ(command); command="UPDATE rxpat SET RxCui = 0 WHERE RxCui IS NULL"; Db.NonQ(command); command="ALTER TABLE rxpat MODIFY RxCui NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX rxpat_RxCui ON rxpat (RxCui)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxpat ADD DosageCode varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxpat ADD DosageCode varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE insplan ADD RxBIN varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE insplan ADD RxBIN varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS ehrsummaryccd"; Db.NonQ(command); command=@"CREATE TABLE ehrsummaryccd ( EhrSummaryCcdNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, DateSummary date NOT NULL DEFAULT '0001-01-01', ContentSummary text NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE ehrsummaryccd'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE ehrsummaryccd ( EhrSummaryCcdNum number(20) NOT NULL, PatNum number(20) NOT NULL, DateSummary date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, ContentSummary clob, CONSTRAINT ehrsummaryccd_EhrSummaryCcdNum PRIMARY KEY (EhrSummaryCcdNum) )"; Db.NonQ(command); command=@"CREATE INDEX ehrsummaryccd_PatNum ON ehrsummaryccd (PatNum)"; Db.NonQ(command); } //Add ProcDelete permission to all who had ProcComplEdit------------------------------------------------------ command="SELECT NewerDate,NewerDays,UserGroupNum FROM grouppermission WHERE PermType=10"; DataTable table=Db.GetTable(command); DateTime newerDate; int newerDays; long groupNum; if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { newerDate=PIn.Date(table.Rows[i][0].ToString()); newerDays=PIn.Int(table.Rows[i][1].ToString()); groupNum=PIn.Long(table.Rows[i][2].ToString()); command="INSERT INTO grouppermission (NewerDate,NewerDays,UserGroupNum,PermType) " +"VALUES("+POut.Date(newerDate)+","+POut.Int(newerDays)+","+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProcDelete)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { newerDate=PIn.Date(table.Rows[i][0].ToString()); newerDays=PIn.Int(table.Rows[i][1].ToString()); groupNum=PIn.Long(table.Rows[i][2].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDate,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),"+POut.Date(newerDate)+","+POut.Int(newerDays)+","+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProcDelete)+")"; Db.NonQ32(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vaccinepat ADD NotGiven tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vaccinepat ADD NotGiven number(3)"; Db.NonQ(command); command="UPDATE vaccinepat SET NotGiven = 0 WHERE NotGiven IS NULL"; Db.NonQ(command); command="ALTER TABLE vaccinepat MODIFY NotGiven NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vaccinepat ADD Note text NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vaccinepat ADD Note varchar2(4000)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vitalsign ADD ChildGotNutrition tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vitalsign ADD ChildGotNutrition number(3)"; Db.NonQ(command); command="UPDATE vitalsign SET ChildGotNutrition = 0 WHERE ChildGotNutrition IS NULL"; Db.NonQ(command); command="ALTER TABLE vitalsign MODIFY ChildGotNutrition NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE vitalsign ADD ChildGotPhysCouns tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE vitalsign ADD ChildGotPhysCouns number(3)"; Db.NonQ(command); command="UPDATE vitalsign SET ChildGotPhysCouns = 0 WHERE ChildGotPhysCouns IS NULL"; Db.NonQ(command); command="ALTER TABLE vitalsign MODIFY ChildGotPhysCouns NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="UPDATE icd9 SET ICD9Code=CONCAT(SUBSTR(ICD9Code,1,3),'.',SUBSTR(ICD9Code,4)) WHERE ICD9Code REGEXP '^[VE0-9]{3}[^.]?[0-9]+'"; //explanation of the regular expression: All codes where the first three characters are V, E, or 0-9. The fourth character must not be a period , so [^.]? means zero or more characters that are not a period. And then [0-9]+ indicates 1 or more numbers after that. That's a complicated way of saying that we will not include codes that have already been converted to period format, and that we will not stick a period on codes that are only 3 numbers long. Db.NonQ(command); } else {//oracle command="UPDATE icd9 SET ICD9Code=CONCAT(SUBSTR(ICD9Code,1,3),CONCAT('.',SUBSTR(ICD9Code,4))) WHERE REGEXP_LIKE(ICD9Code, '^[VE0-9]{3}[^.]?[0-9]+')"; //See above for explanation of the regular expression. Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS ehrquarterlykey"; Db.NonQ(command); command=@"CREATE TABLE ehrquarterlykey ( EhrQuarterlyKeyNum bigint NOT NULL auto_increment PRIMARY KEY, YearValue int NOT NULL, QuarterValue int NOT NULL, PracticeName varchar(255) NOT NULL, KeyValue varchar(255) NOT NULL, PatNum bigint NOT NULL, Notes text NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE ehrquarterlykey'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE ehrquarterlykey ( EhrQuarterlyKeyNum number(20) NOT NULL, YearValue number(11) NOT NULL, QuarterValue number(11) NOT NULL, PracticeName varchar2(255), KeyValue varchar2(255), PatNum number(20) NOT NULL, Notes varchar2(4000), CONSTRAINT ehrquarterlykey_EhrQuarterlyKe PRIMARY KEY (EhrQuarterlyKeyNum) )"; Db.NonQ(command); command=@"CREATE INDEX ehrquarterlykey_PatNum ON ehrquarterlykey (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD6' LIMIT 1"; } else {//oracle doesn't have LIMIT command="SELECT * FROM (SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD6') WHERE RowNum<=1"; } DataTable tableClaimFormNum=Db.GetTable(command); if(tableClaimFormNum.Rows.Count>0) { long claimFormNum=PIn.Long(tableClaimFormNum.Rows[0][0].ToString()); command="UPDATE claimformitem SET FieldName='SubscrIDStrict' WHERE FieldName='SubscrID' AND ClaimFormNum="+POut.Long(claimFormNum); Db.NonQ(command); command="UPDATE claimformitem SET FieldName='PatIDFromPatPlan' WHERE FieldName='PatientID-MedicaidOrSSN' AND ClaimFormNum="+POut.Long(claimFormNum); Db.NonQ(command); } command="UPDATE preference SET ValueString = '11.0.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_9(); } ///<summary>Oracle compatible: 10/13/2011</summary> private static void To11_0_9() { if(FromVersion<new Version("11.0.9.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.9"));//No translation in convert script. string command; //ClaimX Clearing House if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO clearinghouse(Description,ExportPath,IsDefault,Payors,Eformat,ResponsePath,CommBridge,ClientProgram,ISA05,ISA07,ISA08,ISA15,GS03) "; command+="VALUES("; command+="'ClaimX'";//Description command+=",'"+POut.String(@"C:\ClaimX\Temp\")+"'";//ExportPath that the X12 is placed into command+=",'0'";//IsDefault command+=",''";//Payors command+=",'1'";//Eformat-1=X12 command+=",''";//ResponsePath command+=",'12'";//CommBridge-12=ClaimX command+=",'"+POut.String(@"C:\ProgramFiles\ClaimX\claimxclient.exe")+"'";//ClientProgram command+=",'30'";//ISA05 command+=",'30'";//ISA07 command+=",'351962405'";//ISA08 command+=",'P'";//ISA15-P=Production, T=Test command+=",'351962405'";//GS03 command+=")"; Db.NonQ(command); } else{//oracle command="INSERT INTO clearinghouse(ClearinghouseNum,Description,ExportPath,IsDefault,Payors,Eformat,ResponsePath,CommBridge,ClientProgram,ISA05,ISA07,ISA08,ISA15,GS03) "; command+="VALUES("; command+="(SELECT MAX(ClearinghouseNum)+1 FROM clearinghouse)"; command+=",'ClaimX'";//Description command+=",'"+POut.String(@"C:\ClaimX\Temp\")+"'";//ExportPath that the X12 is placed into command+=",'0'";//IsDefault command+=",''";//Payors command+=",'1'";//Eformat-1=X12 command+=",''";//ResponsePath command+=",'12'";//CommBridge-12=ClaimX command+=",'"+POut.String(@"C:\ProgramFiles\ClaimX\claimxclient.exe")+"'";//ClientProgram command+=",'30'";//ISA05 command+=",'30'";//ISA07 command+=",'351962405'";//ISA08 command+=",'P'";//ISA15-P=Production, T=Test command+=",'351962405'";//GS03 command+=")"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '11.0.9.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_10(); } ///<summary>Oracle compatible: 10/13/2011</summary> private static void To11_0_10() { if(FromVersion<new Version("11.0.10.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.10"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD6' LIMIT 1"; } else {//oracle doesn't have LIMIT command="SELECT * FROM (SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD6') WHERE RowNum<=1"; } DataTable tableClaimFormNum=Db.GetTable(command); if(tableClaimFormNum.Rows.Count>0) { long claimFormNum=PIn.Long(tableClaimFormNum.Rows[0][0].ToString()); command="INSERT INTO claimformitem (ClaimFormNum,FieldName,XPos,YPos,Width,Height) VALUES ("+POut.Long(claimFormNum)+",'PatientPatNum',494,117,112,16)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormNum,FieldName,XPos,YPos,Width,Height) VALUES ("+POut.Long(claimFormNum)+",'BillingDentistNPI',308,117,103,16)"; Db.NonQ(command); } //It is OK to run the following queries for all of our customers, because if they are not Canadian, then only the Canadian columns will be changed and will then not ever be used. //We do not want to check the region settings here because sometimes Canadian customers forget to set the region correctly on their computer before installing/upgrading. command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=7 WHERE ElectID='311140'";//accerta Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2469,CanadianNetworkNum=8 WHERE ElectID='000105'";//adsc Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='610226'";//aga Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=420,CanadianNetworkNum=7 WHERE ElectID='628112'";//appq Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2468,CanadianNetworkNum=13 WHERE ElectID='000090'";//alberta blue cross Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=0,CanadianNetworkNum=7 WHERE ElectID='610191'";//assumption life Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='628151'";//autoben Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=8 WHERE ElectID='610708'";//benecaid health benefit solutions Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=384,CanadianNetworkNum=7 WHERE ElectID='610146'";//benefits trust Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='400008'";//beneplan Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=0,CanadianNetworkNum=7 WHERE ElectID='600502'";//capitale Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=9 WHERE ElectID='610129'";//cdcs Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=1,CanadianNetworkNum=7 WHERE ElectID='610099'";//claimsecure Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=32,CanadianNetworkNum=7 WHERE ElectID='000036'";//ccq Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=8 WHERE ElectID='606258'";//co-operators Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2464,CanadianNetworkNum=7 WHERE ElectID='610105'";//coughlin & associates Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=8 WHERE ElectID='610153'";//cowan wright beauchamps Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=384,CanadianNetworkNum=8 WHERE ElectID='000051'";//desjardins financial security Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=384,CanadianNetworkNum=7 WHERE ElectID='000033'";//empire life insurance company Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=10 WHERE ElectID='000029'";//equitable life Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=65956,CanadianNetworkNum=7 WHERE ElectID='610650'";//esorse corporation Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='610614'";//fas administrators Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=10 WHERE ElectID='000011'";//great west life assurance company Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=420,CanadianNetworkNum=7 WHERE ElectID='000102'";//green sheild canada Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=8 WHERE ElectID='610217'";//group medical services Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=8 WHERE ElectID='610218'";//group medical services saskatchewan Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=33,CanadianNetworkNum=8 WHERE ElectID='605064'";//groupsource Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=10 WHERE ElectID='000060'";//industrial alliance Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=10 WHERE ElectID='000024'";//industrial alliance pacific insuarnce and financial Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=8 WHERE ElectID='610643'";//internationale campagnie d'assurance vie Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=0,CanadianNetworkNum=7 WHERE ElectID='627265'";//johnson inc. Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=10 WHERE ElectID='627223'";//johnston group Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=0,CanadianNetworkNum=7 WHERE ElectID='627585'";//lee-power & associates Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=7 WHERE ElectID='610158'";//manion wilkins Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2464,CanadianNetworkNum=11 WHERE ElectID='000094'";//manitoba blue cross Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2432,CanadianNetworkNum=8 WHERE ElectID='000114'";//manitoba cleft palate program Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2048,CanadianNetworkNum=8 WHERE ElectID='000113'";//manitoba health Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='000034'";//manufacturers life insurance company Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='610059'";//manulife financial Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='311113'";//maritime life assurance company Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='610070'";//maritime pro Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=417,CanadianNetworkNum=7 WHERE ElectID='601052'";//mdm Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=384,CanadianNetworkNum=7 WHERE ElectID='610047'";//medavie blue cross Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=8 WHERE ElectID='610634'";//nexgenrx Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=8 WHERE ElectID='610124'";//nihb Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2469,CanadianNetworkNum=8 WHERE ElectID='000109'";//nova scotia community services Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2469,CanadianNetworkNum=8 WHERE ElectID='000108'";//nova scotia medical services insurance Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=8 WHERE ElectID='610172'";//nunatsiavut government department of health Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2432,CanadianNetworkNum=12 WHERE ElectID='000064'";//pacific blue cross Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=2469,CanadianNetworkNum=8 WHERE ElectID='000103'";//quickcard Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=384,CanadianNetworkNum=8 WHERE ElectID='610256'";//pbas Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=7 WHERE ElectID='610616'";//rwam insurance Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=0,CanadianNetworkNum=7 WHERE ElectID='000096'";//saskatchewan blue cross Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=7 WHERE ElectID='610196'";//ses benefits Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=0,CanadianNetworkNum=8 WHERE ElectID='000079'";//ssq societe d'assurance-vie inc. Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='000020'";//standard life assurance company Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=10 WHERE ElectID='000016'";//sun life of canada Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=0,CanadianNetworkNum=8 WHERE ElectID='000080'";//survivance Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='04',CanadianSupportedTypes=32,CanadianNetworkNum=8 WHERE ElectID='610677'";//syndicat des fonctionnaires municipaux mtl Db.NonQ(command); command="UPDATE carrier SET CDAnetVersion='02',CanadianSupportedTypes=416,CanadianNetworkNum=7 WHERE ElectID='311109'";//wawanesa Db.NonQ(command); //We only want to insert these carriers if in Canada because they are of no use elsewhere. if(CultureInfo.CurrentCulture.Name.EndsWith("CA")) {//Canadian. en-CA or fr-CA command="SELECT COUNT(*) FROM carrier WHERE ElectID='000090'"; //alberta blue cross if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('Alberta Blue Cross','10009 108th Street NW','','Edmonton','AB','T5J 3C5','1-800-661-6995','000090','0','1','04',13,'0',1,2468)"; Db.NonQ(command); } command="SELECT COUNT(*) FROM carrier WHERE ElectID='000114'"; //manitoba cleft palate program if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('Manitoba Cleft Palate Program','300 Carlton Street','','Winnipeg','MB','R3B 3M9','204-787-4882','000114','0','1','04',8,'0',1,2432)"; Db.NonQ(command); } command="SELECT COUNT(*) FROM carrier WHERE ElectID='000113'"; //manitoba health if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('Manitoba Health','300 Carlton Street','','Winnipeg','MB','R3B 3M9','204-788-2581','000113','0','1','04',8,'0',1,2048)"; Db.NonQ(command); } command="SELECT COUNT(*) FROM carrier WHERE ElectID='610256'"; //pbas if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('PBAS','318-2099 Lougheed Highway','','Port Coquitlam','BC','V3B 1A8','800-952-9932','610256','0','1','04',8,'0',1,384)"; Db.NonQ(command); } } command="UPDATE preference SET ValueString = '11.0.10.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_11(); } ///<summary>Oracle compatible: 10/13/2011</summary> private static void To11_0_11() { if(FromVersion<new Version("11.0.11.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.11"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { //Bug fix for disease column (depricated) being in use. This code is identical to the function run again in 11.0 and is safe to run more than once. bool diseasefieldused=false; bool problemfieldused=false; bool allergyfieldused=false; command="SELECT ItemOrder FROM displayfield WHERE InternalName='Diseases'"; string str=Db.GetScalar(command); int itemOrder=0; if(!String.IsNullOrEmpty(str)) { diseasefieldused=true; itemOrder=PIn.Int(str); } command="SELECT * FROM displayfield WHERE InternalName='Problems'"; if(Db.GetTable(command).Rows.Count>0) { problemfieldused=true; } command="SELECT * FROM displayfield WHERE InternalName='Allergies'"; if(Db.GetTable(command).Rows.Count>0) { allergyfieldused=true; } if(diseasefieldused && !problemfieldused && !allergyfieldused) {//disease is used, problems and allergies are not used command="DELETE FROM displayfield WHERE InternalName='Diseases' AND Category=5"; Db.NonQ(command); command="INSERT INTO displayfield (InternalName,Description,ItemOrder,ColumnWidth,Category) VALUES ('Problems','',"+POut.Int(itemOrder)+",0,5)"; Db.NonQ(command); command="INSERT INTO displayfield (InternalName,Description,ItemOrder,ColumnWidth,Category) VALUES ('Allergies','',"+POut.Int(itemOrder)+",0,5)"; Db.NonQ(command); } } else {//oracle //do nothing } command="UPDATE preference SET ValueString = '11.0.11.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_13(); } ///<summary>Oracle compatible: 10/13/2011</summary> private static void To11_0_13() { if(FromVersion<new Version("11.0.13.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.13"));//No translation in convert script. string command; try {//most users will not have this table command="ALTER TABLE phoneempdefault ADD PhoneExt int NOT NULL"; Db.NonQ(command); command="ALTER TABLE phoneempdefault ADD IsUnavailable tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE phoneempdefault ADD Notes text NOT NULL"; Db.NonQ(command); command="ALTER TABLE phoneempdefault ADD IpAddress varchar(255) NOT NULL"; Db.NonQ(command); command="DROP TABLE phoneoverride"; Db.NonQ(command); } catch { //do nothing } command="UPDATE preference SET ValueString = '11.0.13.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_15(); } ///<summary>Oracle compatible: 10/13/2011</summary> private static void To11_0_15() { if(FromVersion<new Version("11.0.15.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.15"));//No translation in convert script. string command; try {//most users will not have this table command="ALTER TABLE phone ADD ScreenshotPath varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE phone ADD ScreenshotImage mediumtext NOT NULL"; Db.NonQ(command); command="ALTER TABLE phoneempdefault ADD IsPrivateScreen tinyint NOT NULL"; Db.NonQ(command); command="ALTER TABLE phoneempdefault CHANGE IpAddress ComputerName varchar(255) NOT NULL"; Db.NonQ(command); command="ALTER TABLE phoneempdefault CHANGE IsUnavailable StatusOverride tinyint NOT NULL"; Db.NonQ(command); } catch { //do nothing } command="UPDATE preference SET ValueString = '11.0.15.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_24(); } ///<summary>Oracle compatible: 10/13/2011</summary> private static void To11_0_24() { if(FromVersion<new Version("11.0.24.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.24"));//No translation in convert script. string command; command="ALTER TABLE allergydef DROP COLUMN RxCui";//both oracle and mysql Db.NonQ(command); //Primary key was renamed in 6.8.1 on accident. Changing back so generating XML documentation works correctly. if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE insfilingcodesubtype CHANGE InsFilingCodeSubTypeNum InsFilingCodeSubtypeNum BIGINT(20) NOT NULL AUTO_INCREMENT"; Db.NonQ(command); } else {//oracle //No need to change column name in Oracle, strictly affects XML documentation generation. } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE ehrprovkey ADD HasReportAccess tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE ehrprovkey ADD HasReportAccess number(3)"; Db.NonQ(command); command="UPDATE ehrprovkey SET HasReportAccess = 0 WHERE HasReportAccess IS NULL"; Db.NonQ(command); command="ALTER TABLE ehrprovkey MODIFY HasReportAccess NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE provider ADD EhrHasReportAccess tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE provider ADD EhrHasReportAccess number(3)"; Db.NonQ(command); command="UPDATE provider SET EhrHasReportAccess = 0 WHERE EhrHasReportAccess IS NULL"; Db.NonQ(command); command="ALTER TABLE provider MODIFY EhrHasReportAccess NOT NULL"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '11.0.24.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_0_36(); } private static void To11_0_36() { if(FromVersion<new Version("11.0.36.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.0.36"));//No translation in convert script. string command; try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD INDEX procedurelog_ProcNumLab (ProcNumLab)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX procedurelog_ProcNumLab ON procedurelog (ProcNumLab)"; Db.NonQ(command); } } catch { //Oh well, it's just an index. Probably failed because it already exists anyway. } command="UPDATE preference SET ValueString = '11.0.36.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_1_1(); } ///<summary>Oracle compatible: 10/13/2011</summary> private static void To11_1_1() { if(FromVersion<new Version("11.1.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.1.1"));//No translation in convert script. string command; //Set default appt schedule printing preferences. Was released when not finished so can't trust current values. command="UPDATE preference SET ValueString="+POut.DateT(new DateTime(2011,1,1,0,0,0))+" WHERE PrefName='ApptPrintTimeStart'"; Db.NonQ(command); command="UPDATE preference SET ValueString="+POut.DateT(new DateTime(2011,1,1,23,0,0))+" WHERE PrefName='ApptPrintTimeStop'"; Db.NonQ(command); command="UPDATE preference SET ValueString='8' WHERE PrefName='ApptPrintFontSize'"; Db.NonQ(command); command="UPDATE preference SET ValueString='10' WHERE PrefName='ApptPrintColumnsPerPage'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ScannerSuppressDialog','1')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ScannerSuppressDialog','1')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ScannerResolution','150')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ScannerResolution','150')"; Db.NonQ(command); } command="DELETE FROM preference WHERE PrefName = 'ScannerCompressionRadiographs'"; Db.NonQ(command); command="DELETE FROM preference WHERE PrefName = 'ScannerCompressionPhotos'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE payment ADD IsRecurringCC tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE payment ADD IsRecurringCC number(3)"; Db.NonQ(command); command="UPDATE payment SET IsRecurringCC = 0 WHERE IsRecurringCC IS NULL"; Db.NonQ(command); command="ALTER TABLE payment MODIFY IsRecurringCC NOT NULL"; Db.NonQ(command); } //To keep current functionality, set all payments up to this point as recurring charges. command="UPDATE payment SET IsRecurringCC=1"; Db.NonQ(command); try{ if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD INDEX (ProcDate)"; Db.NonQ(command); command="ALTER TABLE paysplit ADD INDEX (DatePay)"; Db.NonQ(command); } else {//oracle command="CREATE INDEX procedurelog_ProcDate ON procedurelog (ProcDate)"; Db.NonQ(command); command="CREATE INDEX paysplit_DatePay ON paysplit (DatePay)"; Db.NonQ(command); } } catch{ } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS dashboardar"; Db.NonQ(command); command=@"CREATE TABLE dashboardar ( DashboardARNum bigint NOT NULL auto_increment PRIMARY KEY, DateCalc date NOT NULL DEFAULT '0001-01-01', BalTotal double NOT NULL, InsEst double NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE dashboardar'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE dashboardar ( DashboardARNum number(20) NOT NULL, DateCalc date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, BalTotal number(38,8) NOT NULL, InsEst number(38,8) NOT NULL, CONSTRAINT dashboardar_DashboardARNum PRIMARY KEY (DashboardARNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ProcCodeListShowHidden','1')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ProcCodeListShowHidden','1')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claimpayment ADD DateIssued date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claimpayment ADD DateIssued date"; Db.NonQ(command); command="UPDATE claimpayment SET DateIssued = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateIssued IS NULL"; Db.NonQ(command); command="ALTER TABLE claimpayment MODIFY DateIssued NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE sheetfield ADD TabOrder int NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE sheetfield ADD TabOrder number(11)"; Db.NonQ(command); command="UPDATE sheetfield SET TabOrder = 0 WHERE TabOrder IS NULL"; Db.NonQ(command); command="ALTER TABLE sheetfield MODIFY TabOrder NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE sheetfielddef ADD TabOrder int NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE sheetfielddef ADD TabOrder number(11)"; Db.NonQ(command); command="UPDATE sheetfielddef SET TabOrder = 0 WHERE TabOrder IS NULL"; Db.NonQ(command); command="ALTER TABLE sheetfielddef MODIFY TabOrder NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS aggpath"; Db.NonQ(command); command=@"CREATE TABLE aggpath ( AggPathNum bigint NOT NULL auto_increment PRIMARY KEY, RemoteURI varchar(255) NOT NULL, RemoteUserName varchar(255) NOT NULL, RemotePassword varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE aggpath'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE aggpath ( AggPathNum number(20) NOT NULL, RemoteURI varchar2(255), RemoteUserName varchar2(255), RemotePassword varchar2(255), CONSTRAINT aggpath_AggPathNum PRIMARY KEY (AggPathNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('AppointmentSearchBehavior','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'AppointmentSearchBehavior','0')"; Db.NonQ(command); } //Insert Apixia Imaging Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Apixia', " +"'Apixia Digital Imaging by Apixia Inc.', " +"'0', " +"'"+POut.String(@"C:\Program Files\Digirex\digirex.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'System path to Apixia Digital Imaging ini file', " +"'"+POut.String(@"C:\Program Files\Digirex\Switch.ini")+"')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Apixia')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'Apixia', " +"'Apixia Digital Imaging by Apixia Inc.', " +"'0', " +"'"+POut.String(@"C:\Program Files\Digirex\digirex.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum)+1 FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'System path to Apixia Digital Imaging ini file', " +"'"+POut.String(@"C:\Program Files\Digirex\Switch.ini")+"')"; Db.NonQ32(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Apixia')"; Db.NonQ32(command); }//end Apixia Imaging bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD PriorAuthorizationNumber varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD PriorAuthorizationNumber varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE provider ADD IsNotPerson tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE provider ADD IsNotPerson number(3)"; Db.NonQ(command); command="UPDATE provider SET IsNotPerson = 0 WHERE IsNotPerson IS NULL"; Db.NonQ(command); command="ALTER TABLE provider MODIFY IsNotPerson NOT NULL"; Db.NonQ(command); } command="UPDATE provider SET IsNotPerson=1 WHERE FName=''"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD SpecialProgramCode tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD SpecialProgramCode number(3)"; Db.NonQ(command); command="UPDATE claim SET SpecialProgramCode = 0 WHERE SpecialProgramCode IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY SpecialProgramCode NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD UniformBillType varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD UniformBillType varchar2(255)"; Db.NonQ(command); } //Add Providers permission to groups with existing Setup permission------------------------------------------------------ command="SELECT DISTINCT UserGroupNum FROM grouppermission WHERE PermType="+POut.Int((int)Permissions.Setup); DataTable table=Db.GetTable(command); long groupNum; if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.Providers)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.Providers)+")"; Db.NonQ32(command); } } //Add ProcedureNote permission to everyone------------------------------------------------------ command="SELECT DISTINCT UserGroupNum FROM grouppermission"; table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProcedureNote)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProcedureNote)+")"; Db.NonQ32(command); } } //Add ReferralAdd permission to everyone------------------------------------------------------ command="SELECT DISTINCT UserGroupNum FROM grouppermission"; table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.ReferralAdd)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.ReferralAdd)+")"; Db.NonQ32(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD MedType tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD MedType number(3)"; Db.NonQ(command); command="UPDATE claim SET MedType = 0 WHERE MedType IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY MedType NOT NULL"; Db.NonQ(command); } command="ALTER TABLE claim DROP COLUMN EFormat"; Db.NonQ(command); command="ALTER TABLE procedurelog DROP COLUMN UnitCode"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ClaimMedTypeIsInstWhenInsPlanIsMedical','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ClaimMedTypeIsInstWhenInsPlanIsMedical','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD DrugUnit tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurelog ADD DrugUnit number(3)"; Db.NonQ(command); command="UPDATE procedurelog SET DrugUnit = 0 WHERE DrugUnit IS NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog MODIFY DrugUnit NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD DrugQty float NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurelog ADD DrugQty number(38,8)"; Db.NonQ(command); command="UPDATE procedurelog SET DrugQty = 0 WHERE DrugQty IS NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog MODIFY DrugQty NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurecode ADD DrugNDC varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurecode ADD DrugNDC varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurecode ADD RevenueCodeDefault varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurecode ADD RevenueCodeDefault varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD AdmissionTypeCode varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD AdmissionTypeCode varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD AdmissionSourceCode varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD AdmissionSourceCode varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD PatientStatusCode varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD PatientStatusCode varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ClearinghouseDefaultDent','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ClearinghouseDefaultDent','0')"; Db.NonQ(command); } //set this new pref with the existing default value from the clearinghouse table command="SELECT ClearinghouseNum FROM clearinghouse WHERE IsDefault=1"; long clearinghouseNum=PIn.Long(Db.GetScalar(command)); command="UPDATE preference SET ValueString="+POut.Long(clearinghouseNum)+" WHERE PrefName='ClearinghouseDefaultDent'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ClearinghouseDefaultMed','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ClearinghouseDefaultMed','0')"; Db.NonQ(command); } command="ALTER TABLE clearinghouse DROP COLUMN IsDefault"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claimpayment ADD IsPartial tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claimpayment ADD IsPartial number(3)"; Db.NonQ(command); command="UPDATE claimpayment SET IsPartial = 0 WHERE IsPartial IS NULL"; Db.NonQ(command); command="ALTER TABLE claimpayment MODIFY IsPartial NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claimproc ADD PaymentRow int NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claimproc ADD PaymentRow number(11)"; Db.NonQ(command); command="UPDATE claimproc SET PaymentRow = 0 WHERE PaymentRow IS NULL"; Db.NonQ(command); command="ALTER TABLE claimproc MODIFY PaymentRow NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD SuperFamily bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE patient ADD INDEX (SuperFamily)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE patient ADD SuperFamily number(20)"; Db.NonQ(command); command="UPDATE patient SET SuperFamily = 0 WHERE SuperFamily IS NULL"; Db.NonQ(command); command="ALTER TABLE patient MODIFY SuperFamily NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX patient_SuperFamily ON patient (SuperFamily)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ShowFeatureSuperfamilies','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ShowFeatureSuperfamilies','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE refattach ADD ProcNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE refattach ADD INDEX (ProcNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE refattach ADD ProcNum number(20)"; Db.NonQ(command); command="UPDATE refattach SET ProcNum = 0 WHERE ProcNum IS NULL"; Db.NonQ(command); command="ALTER TABLE refattach MODIFY ProcNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX refattach_ProcNum ON refattach (ProcNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE refattach ADD DateProcComplete date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE refattach ADD DateProcComplete date"; Db.NonQ(command); command="UPDATE refattach SET DateProcComplete = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateProcComplete IS NULL"; Db.NonQ(command); command="ALTER TABLE refattach MODIFY DateProcComplete NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ProcGroupNoteDoesAggregate','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ProcGroupNoteDoesAggregate','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE statement ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE statement SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE statement ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE statement SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '11.1.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_1_6(); } private static void To11_1_6() { if(FromVersion<new Version("11.1.6.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.1.6"));//No translation in convert script. string command; //We added an index in version 11.0.36 for this column, but some of our customers were already on version 11.1, so we had to add it here as well. try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD INDEX procedurelog_ProcNumLab (ProcNumLab)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX procedurelog_ProcNumLab ON procedurelog (ProcNumLab)"; Db.NonQ(command); } } catch { //Oh well, it's just an index. Probably failed because it already exists anyway. } command="UPDATE preference SET ValueString = '11.1.6.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_1_7(); } private static void To11_1_7() { if(FromVersion<new Version("11.1.7.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.1.7"));//No translation in convert script. string command; command="ALTER TABLE insplan DROP COLUMN DedBeforePerc"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.Oracle) { command="ALTER TABLE insplan MODIFY CanadianPlanFlag NULL"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '11.1.7.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To11_1_9(); } ///<summary>Oracle compatible: 11/17/2011</summary> private static void To11_1_9() { if(FromVersion<new Version("11.1.9.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 11.1.9"));//No translation in convert script. //Update VixWin Bridge string command="Select ProgramNum FROM program WHERE ProgName='VixWin'"; long programNum=PIn.Long(Db.GetScalar(command)); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +POut.Long(programNum)+", " +"'Optional Image Path', " +"'')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum)+1 FROM programproperty)," +POut.Long(programNum)+", " +"'Optional Image Path', " +"'')"; Db.NonQ32(command); } //Insert VixWinBase41 Imaging Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'VixWinBase41', " +"'VixWin(Base41) from www.gendexxray.com', " +"'0', " +"'"+POut.String(@"C:\VixWin\VixWin.exe")+"'," +"'', " +"'This VixWin bridge uses base 41 PatNums.')"; programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +POut.Long(programNum)+", " +"'Image Path', " +"'')";//User will be required to set up image path before using bridge. If they try to use it they will get a warning message and the bridge will fail gracefully. Db.NonQ32(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +POut.Long(programNum)+", " +POut.Int(((int)ToolBarsAvail.ChartModule))+", " +"'VixWinBase41')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'VixWinBase41', " +"'VixWin(Base41) from www.gendexxray.com', " +"'0', " +"'"+POut.String(@"C:\VixWin\VixWin.exe")+"'," +"'', " +"'This VixWin bridge uses base 41 PatNums.')"; programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum)+1 FROM programproperty)," +POut.Long(programNum)+", " +"'Image Path', " +"'')";//User will be required to set up image path before using bridge. If they try to use it they will get a warning message and the bridge will fail gracefully. Db.NonQ32(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +POut.Long(programNum)+", " +POut.Int(((int)ToolBarsAvail.ChartModule))+", " +"'VixWinBase41')"; Db.NonQ32(command); } command="UPDATE preference SET ValueString = '11.1.9.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_0_1(); } ///<summary></summary> private static void To12_0_1() { if(FromVersion<new Version("12.0.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.0.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('BillingEmailSubject','Statement for account [PatNum]')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'BillingEmailSubject','Statement for account [PatNum]')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('BillingEmailBodyText','Statement attached for [nameFL], account number [PatNum]')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'BillingEmailBodyText','Statement attached for [nameFL], account number [PatNum]')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE creditcard ADD PayPlanNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE creditcard ADD INDEX (PayPlanNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE creditcard ADD PayPlanNum number(20)"; Db.NonQ(command); command="UPDATE creditcard SET PayPlanNum = 0 WHERE PayPlanNum IS NULL"; Db.NonQ(command); command="ALTER TABLE creditcard MODIFY PayPlanNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX creditcard_PayPlanNum ON creditcard (PayPlanNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE popup ADD PopupLevel tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE popup ADD PopupLevel number(3)"; Db.NonQ(command); command="UPDATE popup SET PopupLevel = 0 WHERE PopupLevel IS NULL"; Db.NonQ(command); command="ALTER TABLE popup MODIFY PopupLevel NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ChartAddProcNoRefreshGrid','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ChartAddProcNoRefreshGrid','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS eobattach"; Db.NonQ(command); command=@"CREATE TABLE eobattach ( EobAttachNum bigint NOT NULL auto_increment PRIMARY KEY, ClaimPaymentNum bigint NOT NULL, DateTCreated datetime NOT NULL, FileName varchar(255) NOT NULL, RawBase64 text NOT NULL, INDEX(ClaimPaymentNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE eobattach'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE eobattach ( EobAttachNum number(20) NOT NULL, ClaimPaymentNum number(20) NOT NULL, DateTCreated date NOT NULL, FileName varchar2(255), RawBase64 clob, CONSTRAINT eobattach_EobAttachNum PRIMARY KEY (EobAttachNum) )"; Db.NonQ(command); command=@"CREATE INDEX eobattach_ClaimPaymentNum ON eobattach (ClaimPaymentNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE insplan ADD CobRule tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE insplan ADD CobRule number(3)"; Db.NonQ(command); command="UPDATE insplan SET CobRule = 0 WHERE CobRule IS NULL"; Db.NonQ(command); command="ALTER TABLE insplan MODIFY CobRule NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('InsDefaultCobRule','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'InsDefaultCobRule','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileSynchNewTables112Done','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MobileSynchNewTables112Done','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PatientFormsShowConsent','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PatientFormsShowConsent','0')"; Db.NonQ(command); } //Add InsPlanChangeSubsc permission to all groups that had SecurityAdmin permission--------------------------------------------- long groupNum; command="SELECT DISTINCT UserGroupNum " +"FROM grouppermission " +"WHERE PermType="+POut.Int((int)Permissions.SecurityAdmin); DataTable table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.InsPlanChangeSubsc)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.InsPlanChangeSubsc)+")"; Db.NonQ32(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('MedicalFeeUsedForNewProcs','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MedicalFeeUsedForNewProcs','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PracticePayToAddress','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PracticePayToAddress','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PracticePayToAddress2','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PracticePayToAddress2','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PracticePayToCity','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PracticePayToCity','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PracticePayToST','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PracticePayToST','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PracticePayToZip','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PracticePayToZip','')"; Db.NonQ(command); } try{ if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD INDEX (SiteNum)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX patient_SiteNum ON patient (SiteNum)"; Db.NonQ(command); } } catch(Exception ex){} try{ if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claimproc ADD INDEX (Status)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX claimproc_Status ON claimproc (Status)"; Db.NonQ(command); } } catch(Exception ex){} try{ if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD INDEX (PatStatus)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX patient_PatStatus ON patient (PatStatus)"; Db.NonQ(command); } } catch(Exception ex){} try{ if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD INDEX (ClinicNum)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX patient_ClinicNum ON patient (ClinicNum)"; Db.NonQ(command); } } catch(Exception ex){} try{ if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE appointment ADD INDEX (DateTimeArrived)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX appointment_DateTimeArrived ON appointment (DateTimeArrived)"; Db.NonQ(command); } } catch(Exception ex){} if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE apptview ADD ClinicNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE apptview ADD INDEX (ClinicNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE apptview ADD ClinicNum number(20)"; Db.NonQ(command); command="UPDATE apptview SET ClinicNum = 0 WHERE ClinicNum IS NULL"; Db.NonQ(command); command="ALTER TABLE apptview MODIFY ClinicNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX apptview_ClinicNum ON apptview (ClinicNum)"; Db.NonQ(command); } long claimFormNum=0; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO claimform(Description,IsHidden,FontName,FontSize,UniqueID,PrintImages,OffsetX,OffsetY) "+ "VALUES ('UB04',0,'Tahoma',9.75,'OD10',0,0,0)"; claimFormNum=Db.NonQ(command,true); } else {//oracle command="INSERT INTO claimform(ClaimFormNum,Description,IsHidden,FontName,FontSize,UniqueID,PrintImages,OffsetX,OffsetY) "+ "VALUES ((SELECT MAX(ClaimFormNum)+1 FROM claimform),'UB04',0,'Tahoma',9.75,'OD10',0,0,0)"; claimFormNum=Db.NonQ(command,true); } command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'UB04.jpg','','','4','5','860','1120')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','AccidentDate','MMddyyyy','45','164','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','AccidentST','','675','130','30','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentist','','24','14','239','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistAddress','','24','30','239','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistAddress2','','24','46','239','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistCity','','24','63','113','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistNPI','','682','682','151','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistSSNorTIN','','515','64','98','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistST','','145','63','30','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistZip','','183','63','80','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','DateService','MMddyy','685','64','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','DateService','MMddyyyy','132','130','66','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','DateService','MMddyy','615','64','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','DateService','MMddyyyy','460','666','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis1','NoDec','26','880','78','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis2','NoDec','105','881','78','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis3','NoDec','185','881','78','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis4','NoDec','265','881','78','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','116','663','10','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','172','663','10','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','0001','15','664','46','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','9','13','897','9','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedAccidentCode','','15','164','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedAdmissionSourceCode','','255','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedAdmissionTypeCode','','225','130','27','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode18','','345','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode19','','375','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode20','','405','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode21','','435','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode22','','465','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode23','','495','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode24','','525','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode25','','555','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode26','','585','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode27','','615','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedConditionCode28','','645','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAAmtDue','NoDec','654','697','110','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAAssignBen','','425','697','18','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAAuthCode','','15','831','308','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAEmployer','','584','831','249','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAGroupName','','504','764','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAGroupNum','','654','764','179','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAInsuredID','','303','764','199','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAInsuredName','','15','764','257','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAName','','15','697','228','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAOtherProvID','','682','698','151','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAPlanID','','244','697','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsAPriorPmt','NoDec','544','697','101','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsARelation','','274','764','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsARelInfo','','394','697','18','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBAmtDue','NoDec','654','714','110','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBAssignBen','','425','714','18','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBAuthCode','','15','848','308','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBEmployer','','584','848','249','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBGroupName','','504','781','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBGroupNum','','654','781','179','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBInsuredID','','303','781','199','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBInsuredName','','15','781','257','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBName','','15','714','228','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBOtherProvID','','682','715','151','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBPlanID','','244','714','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBPriorPmt','NoDec','544','714','101','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBRelation','','274','781','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsBRelInfo','','394','714','18','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCAmtDue','NoDec','654','732','110','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCAssignBen','','425','732','18','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCAuthCode','','15','864','308','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCEmployer','','584','864','249','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCGroupName','','504','798','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCGroupNum','','654','798','179','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCInsuredID','','303','798','199','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCInsuredName','','15','798','257','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCName','','15','732','228','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCOtherProvID','','682','733','151','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCPlanID','','244','732','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCPriorPmt','NoDec','544','732','101','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCRelation','','274','798','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCRelInfo','','394','732','18','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedInsCrossoverIndicator','','776','53','50','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedPatientStatusCode','','315','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedUniformBillType','','785','30','49','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount39a','NoDec','574','216','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount39b','NoDec','574','232','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount39c','NoDec','574','249','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount39d','NoDec','574','265','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount40a','NoDec','704','216','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount40b','NoDec','704','232','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount40c','NoDec','704','249','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount40d','NoDec','704','265','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount41a','NoDec','833','216','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount41b','NoDec','833','232','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount41c','NoDec','833','249','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValAmount41d','NoDec','833','265','99','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode39a','','445','216','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode39b','','445','232','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode39c','','445','249','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode39d','','445','265','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode40a','','575','216','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode40b','','575','232','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode40c','','575','249','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode40d','','575','265','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode41a','','705','216','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode41b','','705','232','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode41c','','705','249','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MedValCode41d','','705','265','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10CodeAndMods','','311','448','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Date','MMddyyyy','461','448','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Description','','62','448','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Fee','NoDec','704','448','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10RevCode','','15','448','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10UnitQty','','531','448','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1CodeAndMods','','311','299','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Date','MMddyyyy','461','299','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Description','','62','299','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Fee','NoDec','704','299','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1RevCode','','15','299','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1UnitQty','','531','299','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2CodeAndMods','','311','316','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Date','MMddyyyy','461','316','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Description','','62','316','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Fee','NoDec','704','316','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2RevCode','','15','316','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2UnitQty','','531','316','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3CodeAndMods','','311','332','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Date','MMddyyyy','461','332','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Description','','62','332','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Fee','NoDec','704','332','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3RevCode','','15','332','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3UnitQty','','531','332','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4CodeAndMods','','311','349','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Date','MMddyyyy','461','349','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Description','','62','349','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Fee','NoDec','704','349','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4RevCode','','15','349','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4UnitQty','','531','349','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5CodeAndMods','','311','365','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Date','MMddyyyy','461','365','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Description','','62','365','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Fee','NoDec','704','365','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5RevCode','','15','365','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5UnitQty','','531','365','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6CodeAndMods','','311','382','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Date','MMddyyyy','461','382','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Description','','62','382','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Fee','NoDec','704','382','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6RevCode','','15','382','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6UnitQty','','531','382','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7CodeAndMods','','311','398','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Date','MMddyyyy','461','398','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Description','','62','398','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Fee','NoDec','704','398','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7RevCode','','15','398','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7UnitQty','','531','398','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8CodeAndMods','','311','415','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Date','MMddyyyy','461','415','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Description','','62','415','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Fee','NoDec','704','415','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8RevCode','','15','415','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8UnitQty','','531','415','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9CodeAndMods','','311','431','148','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Date','MMddyyyy','461','431','68','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Description','','62','431','247','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Fee','NoDec','704','431','93','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9RevCode','','15','431','45','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9UnitQty','','531','431','77','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientAddress','','426','80','409','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientChartNum','','545','14','238','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientCity','','325','97','319','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientDOB','MMddyyyy','15','130','88','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientFirstMiddleLast','','26','97','287','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientGenderLetter','','105','130','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientST','','655','97','28','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientZip','','695','97','98','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Remarks','','15','1014','238','50')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TotalFee','NoDec','704','666','94','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistFName','','715','982','118','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistLName','','538','982','155','17')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistNPI','','600','966','100','17')"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clearinghouse ADD ISA02 varchar(10) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clearinghouse ADD ISA02 varchar2(10)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clearinghouse ADD ISA04 varchar(10) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clearinghouse ADD ISA04 varchar2(10)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clearinghouse ADD ISA16 varchar(2) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clearinghouse ADD ISA16 varchar2(2)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clearinghouse ADD SeparatorData varchar(2) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clearinghouse ADD SeparatorData varchar2(2)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clearinghouse ADD SeparatorSegment varchar(2) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clearinghouse ADD SeparatorSegment varchar2(2)"; Db.NonQ(command); } //Denti-Cal clearinghouse. if(DataConnection.DBtype==DatabaseType.MySql) { command=@"INSERT INTO clearinghouse(Description,ExportPath,Payors,Eformat,ISA05,SenderTin,ISA07,ISA08,ISA15,Password,ResponsePath,CommBridge,ClientProgram, LastBatchNumber,ModemPort,LoginID,SenderName,SenderTelephone,GS03,ISA02,ISA04,ISA16,SeparatorData,SeparatorSegment) VALUES ('Denti-Cal','"+POut.String(@"C:\Denti-Cal\")+"','','5','ZZ','','ZZ','DENTICAL','P','','','13','',0,0,'','','','DENTICAL','DENTICAL','NONE','22','1D','1C')"; Db.NonQ(command); } else {//oracle command=@"INSERT INTO clearinghouse(ClearinghouseNum,Description,ExportPath,Payors,Eformat,ISA05,SenderTin,ISA07,ISA08,ISA15,Password,ResponsePath,CommBridge,ClientProgram, LastBatchNumber,ModemPort,LoginID,SenderName,SenderTelephone,GS03,ISA02,ISA04,ISA16,SeparatorData,SeparatorSegment) VALUES ((SELECT MAX(ClearinghouseNum+1) FROM clearinghouse),'Denti-Cal','"+POut.String(@"C:\Denti-Cal\")+"','','5','ZZ','','ZZ','DENTICAL','P','','','13','',0,0,'','','','DENTICAL','DENTICAL','NONE','22','1D','1C')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS aggpath"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE aggpath'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); } //IAP bridge was using a hardcoded path. Now we will allow users to use a custom path. //Only update the path if the user doesn't have a custom path already entered. command="SELECT Path FROM program WHERE ProgName='IAP'"; if(Db.GetScalar(command)=="") { command="UPDATE program SET Path='"+POut.String(@"C:\IAPlus\")+"' WHERE ProgName='IAP'"; Db.NonQ(command); } command="UPDATE program SET Note='No buttons are available.' WHERE ProgName='IAP'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS centralconnection"; Db.NonQ(command); command=@"CREATE TABLE centralconnection ( CentralConnectionNum bigint NOT NULL auto_increment PRIMARY KEY, ServerName varchar(255) NOT NULL, DatabaseName varchar(255) NOT NULL, MySqlUser varchar(255) NOT NULL, MySqlPassword varchar(255) NOT NULL, ServiceURI varchar(255) NOT NULL, OdUser varchar(255) NOT NULL, OdPassword varchar(255) NOT NULL, Note text NOT NULL, ItemOrder int NOT NULL, WebServiceIsEcw tinyint NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE centralconnection'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE centralconnection ( CentralConnectionNum number(20) NOT NULL, ServerName varchar2(255), DatabaseName varchar2(255), MySqlUser varchar2(255), MySqlPassword varchar2(255), ServiceURI varchar2(255), OdUser varchar2(255), OdPassword varchar2(255), Note varchar2(255), ItemOrder number(11) NOT NULL, WebServiceIsEcw number(3) NOT NULL, CONSTRAINT centralconnection_CentralConne PRIMARY KEY (CentralConnectionNum) )"; Db.NonQ(command); } //Add the 1500 claim form fields if the claim form does not already exist. The unique ID is OD9. if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9' LIMIT 1"; } else {//oracle doesn't have LIMIT command="SELECT * FROM (SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9') WHERE RowNum<=1"; } DataTable tableClaimFormNum=Db.GetTable(command); if(tableClaimFormNum.Rows.Count==0) { //The 1500 claim form does not exist, so safe to add. claimFormNum=0; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO claimform(Description,IsHidden,FontName,FontSize,UniqueID,PrintImages,OffsetX,OffsetY) "+ "VALUES ('1500',0,'Arial',9,'OD9',1,0,0)"; claimFormNum=Db.NonQ(command,true); } else {//oracle command="INSERT INTO claimform(ClaimFormNum,Description,IsHidden,FontName,FontSize,UniqueID,PrintImages,OffsetX,OffsetY) "+ "VALUES ((SELECT MAX(ClaimFormNum)+1 FROM claimform),'1500',0,'Arial',9,'OD9',1,0,0)"; claimFormNum=Db.NonQ(command,true); } command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'1500.gif','','','-54','13','905','1165')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','AccidentST','','467','396','30','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentist','','531','994','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentist','','256','995','235','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistAddress','','531','1010','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistAddress','','256','1009','235','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistCity','','531','1026','139','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistCity','','256','1023','132','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistNPI','','260','1045','92','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistNPI','','531','1045','92','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistNumIsSSN','','191','961','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistNumIsTIN','','210','961','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistPh123','','680','978','40','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistPh456','','719','978','40','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistPh78910','','759','978','48','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistSSNorTIN','','39','959','131','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistST','','671','1026','30','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistST','','388','1023','28','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistZip','','701','1026','80','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistZip','','416','1023','75','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis1','','52','662','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis2','','52','695','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis3','','324','662','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis4','','325','694','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','EmployerName','','528','394','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','615','763','20','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','615','796','20','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','615','828','20','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','615','862','20','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','615','895','20','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','1','615','929','20','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','GroupNum','','530','327','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsAutoAccident','','370','396','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsFTStudent','','430','295','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsGroupHealthPlan','','329','161','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsMedicaidClaim','','97','162','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsNotAutoAccident','','430','395','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsNotOccupational','','430','362','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsNotOtherAccident','','431','428','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsOccupational','','370','362','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsOtherAccident','','370','428','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsPTStudent','','491','295','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsCarrierName','','36','460','245','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsExists','','540','462','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsGroupNum','','36','358','245','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsNotExists','','591','462','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrDOB','MM dd yyyy','42','397','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrIsFemale','','261','396','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrIsMale','','200','396','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrLastFirst','','36','325','245','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Code','','273','762','55','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1CodeMod1','','340','762','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1CodeMod2','','375','762','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1CodeMod3','','405','762','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1CodeMod4','','434','762','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Date','MM dd yy','32','762','77','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Date','MM dd yy','122','762','78','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Diagnosis','','470','762','35','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Fee','','598','762','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1PlaceNumericCode','','206','762','28','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1TreatProvNPI','','698','762','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Code','','273','796','55','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2CodeMod1','','340','796','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2CodeMod2','','375','796','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2CodeMod3','','405','796','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2CodeMod4','','434','796','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Date','MM dd yy','32','796','77','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Date','MM dd yy','122','796','78','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Diagnosis','','470','796','35','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Fee','','598','796','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2PlaceNumericCode','','205','796','28','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2TreatProvNPI','','698','796','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Code','','273','828','55','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3CodeMod1','','340','827','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3CodeMod2','','375','827','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3CodeMod3','','405','827','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3CodeMod4','','434','827','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Date','MM dd yy','32','829','77','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Date','MM dd yy','121','829','78','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Diagnosis','','470','828','35','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Fee','','598','828','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3PlaceNumericCode','','206','829','28','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3TreatProvNPI','','698','828','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Code','','273','862','55','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4CodeMod1','','340','862','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4CodeMod2','','375','862','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4CodeMod3','','405','862','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4CodeMod4','','434','862','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Date','MM dd yy','32','863','77','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Date','MM dd yy','122','863','78','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Diagnosis','','470','863','35','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Fee','','598','862','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4PlaceNumericCode','','205','863','28','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4TreatProvNPI','','699','862','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Code','','273','895','55','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5CodeMod1','','340','895','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5CodeMod2','','375','895','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5CodeMod3','','405','895','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5CodeMod4','','434','895','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Date','MM dd yy','32','895','77','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Date','MM dd yy','122','895','78','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Diagnosis','','470','895','35','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Fee','','598','895','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5PlaceNumericCode','','205','895','28','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5TreatProvNPI','','699','894','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Code','','273','929','55','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6CodeMod1','','340','929','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6CodeMod2','','375','929','30','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6CodeMod3','','405','929','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6CodeMod4','','434','929','29','16')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Date','MM dd yy','32','929','77','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Date','MM dd yy','122','929','78','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Diagnosis','','470','929','35','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Fee','','598','929','70','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6PlaceNumericCode','','205','929','28','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6TreatProvNPI','','699','928','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientAddress','','37','226','245','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientAssignment','','577','525','210','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientCity','','37','258','200','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientDOB','MM dd yyyy','333','195','95','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientIsFemale','','490','194','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientIsMale','','441','195','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientIsMarried','','430','262','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientIsSingle','','370','262','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientLastFirst','','37','194','245','13')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientPhone','','169','296','120','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientRelease','','78','526','240','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientReleaseDate','MM/dd/yyyy','384','525','113','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientST','','281','259','30','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientZip','','37','293','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsAddress','','419','96','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsAddress2','','419','110','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsCarrierName','','419','82','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsCity','','419','124','140','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsST','','560','124','30','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsZip','','590','124','79','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','ReferringProvNameFL','','32','597','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','ReferringProvNPI','','343','597','150','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsChild','','440','229','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsOther','','490','228','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsSelf','','349','229','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsSpouse','','400','229','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','ShowPreauthorizationIfPreauth','','143','69','200','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrAddress','','530','225','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrCity','','530','260','200','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrDOB','MM dd yyyy','554','363','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrID','','529','161','200','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrIsFemale','','771','362','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrIsMale','','701','362','0','0')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrLastFirst','','530','192','250','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrPhone','','672','293','120','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrST','','760','260','50','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrZip','','531','294','100','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TotalFee','','620','961','75','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistSigDate','','169','1035','74','14')"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistSignature','','27','1020','142','30')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('CentralManagerPassHash','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'CentralManagerPassHash','')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.0.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_0_2(); } ///<summary>This is a helper method for the 12.0.1 and 12.4.12 conversions. Without it, there would be an additional 1200 lines of code.</summary> private static string GetClaimFormItemNum(){ if(DataConnection.DBtype==DatabaseType.Oracle) { return "(SELECT MAX(ClaimFormItemNum)+1 FROM claimformitem)"; } else { //for mysql, this seems to be allowed and will automatically increment. //Should work fine for both autoincrement and regular. return "0"; } } ///<summary>Oracle compatible: 01/04/2012</summary> private static void To12_0_2() { if(FromVersion<new Version("12.0.2.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.0.2"));//No translation in convert script. string command; //Insert MiPACS Imaging Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'MiPACS', " +"'MiPACS Imaging', " +"'0', " +"'"+POut.String(@"C:\Program Files\MiDentView\Cmdlink.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'MiPACS')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'MiPACS', " +"'MiPACS Imaging', " +"'0', " +"'"+POut.String(@"C:\Program Files\MiDentView\Cmdlink.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'MiPACS')"; Db.NonQ32(command); }//end MiPACS Imaging bridge try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE paysplit ADD INDEX (PayPlanNum)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX paysplit_PayPlanNum ON paysplit (PayPlanNum)"; Db.NonQ(command); } } catch(Exception ex) { } command="UPDATE preference SET ValueString = '12.0.2.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_0_5(); } ///<summary>Oracle compatible: 02/02/2012</summary> private static void To12_0_5() { if(FromVersion<new Version("12.0.5.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.0.5"));//No translation in convert script. string command; //Delete duplicate MiPACS Imaging Bridge command="SELECT * FROM program WHERE ProgName='MiPACS'"; DataTable table=Db.GetTable(command); if(table.Rows.Count>1) { long programNum=PIn.Long(table.Rows[1]["ProgramNum"].ToString()); command="DELETE FROM program WHERE ProgramNum="+POut.Long(programNum); Db.NonQ(command); command="DELETE FROM toolbutitem WHERE ProgramNum="+POut.Long(programNum); Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+table.Rows[0]["ProgramNum"].ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); } else {//oracle command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+table.Rows[0]["ProgramNum"].ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); } command="SELECT * FROM program WHERE ProgName='Apixia'"; table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+table.Rows[0]["ProgramNum"].ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '12.0.5.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } else { command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+table.Rows[0]["ProgramNum"].ToString()+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ32(command); command="UPDATE preference SET ValueString = '12.0.5.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } } To12_0_6(); } ///<summary>Oracle compatible: 01/08/2013</summary> private static void To12_0_6() { if(FromVersion<new Version("12.0.6.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.0.6"));//No translation in convert script. string command; //EmdeonMedical clearinghouse. if(DataConnection.DBtype==DatabaseType.MySql) { command=@"INSERT INTO clearinghouse(Description,ExportPath,Payors,Eformat,ISA05,SenderTin,ISA07,ISA08,ISA15,Password,ResponsePath,CommBridge,ClientProgram, LastBatchNumber,ModemPort,LoginID,SenderName,SenderTelephone,GS03,ISA02,ISA04,ISA16,SeparatorData,SeparatorSegment) VALUES ('Emdeon Medical','"+POut.String(@"C:\EmdeonMedical\Claims\")+"','','6','ZZ','','ZZ','133052274','P',''," +"'"+POut.String(@"C:\EmdeonMedical\Reports\")+"','14','',0,0,'','','','133052274','','','','','')"; Db.NonQ(command); } else {//oracle command=@"INSERT INTO clearinghouse(ClearinghouseNum,Description,ExportPath,Payors,Eformat,ISA05,SenderTin,ISA07,ISA08,ISA15,Password,ResponsePath,CommBridge,ClientProgram, LastBatchNumber,ModemPort,LoginID,SenderName,SenderTelephone,GS03,ISA02,ISA04,ISA16,SeparatorData,SeparatorSegment) VALUES ((SELECT MAX(ClearinghouseNum+1) FROM clearinghouse),'Emdeon Medical','"+POut.String(@"C:\EmdeonMedical\Claims\")+"','','6','ZZ','','ZZ','133052274','P',''," +"'"+POut.String(@"C:\EmdeonMedical\Reports\")+"','14','',0,0,'','','','133052274','','','','','')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.0.6.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_1_0(); } ///<summary>Oracle compatible: 01/08/2013</summary> private static void To12_1_0() { if(FromVersion<new Version("12.1.0.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.1.0"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('MobileSynchNewTables121Done','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'MobileSynchNewTables121Done','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('AccountShowPaymentNums','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'AccountShowPaymentNums','0')"; Db.NonQ(command); } try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE insplan ADD INDEX (TrojanID)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX insplan_TrojanID ON insplan (TrojanID)"; Db.NonQ(command); } } catch(Exception ex) { } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE statement ADD IsReceipt tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE statement ADD IsReceipt number(3)"; Db.NonQ(command); command="UPDATE statement SET IsReceipt = 0 WHERE IsReceipt IS NULL"; Db.NonQ(command); command="ALTER TABLE statement MODIFY IsReceipt NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE userod ADD ClinicIsRestricted tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE userod ADD ClinicIsRestricted number(3)"; Db.NonQ(command); command="UPDATE userod SET ClinicIsRestricted = 0 WHERE ClinicIsRestricted IS NULL"; Db.NonQ(command); command="ALTER TABLE userod MODIFY ClinicIsRestricted NOT NULL"; Db.NonQ(command); } command="UPDATE userod SET ClinicIsRestricted = 1 WHERE ClinicNum != 0";//to preserve old ClinicNum behavior. Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('TimeCardOvertimeFirstDayOfWeek','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'TimeCardOvertimeFirstDayOfWeek','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('AccountingSoftware','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'AccountingSoftware','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('QuickBooksCompanyFile','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'QuickBooksCompanyFile','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('QuickBooksDepositAccounts','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'QuickBooksDepositAccounts','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('QuickBooksIncomeAccount','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'QuickBooksIncomeAccount','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ReplicationFailureAtServer_id','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ReplicationFailureAtServer_id','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE replicationserver ADD SlaveMonitor varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE replicationserver ADD SlaveMonitor varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE commlog ADD DateTimeEnd datetime DEFAULT '0001-01-01' NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE commlog ADD DateTimeEnd date"; Db.NonQ(command); command="UPDATE commlog SET DateTimeEnd = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateTimeEnd IS NULL"; Db.NonQ(command); command="ALTER TABLE commlog MODIFY DateTimeEnd NOT NULL"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.1.0.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_1_7(); } ///<summary>Oracle compatible: 01/08/2013</summary> private static void To12_1_7() { if(FromVersion<new Version("12.1.7.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.1.7"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CustomTracking bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE claim ADD INDEX (CustomTracking)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CustomTracking number(20)"; Db.NonQ(command); command="UPDATE claim SET CustomTracking = 0 WHERE CustomTracking IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CustomTracking NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX claim_CustomTracking ON claim (CustomTracking)"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.1.7.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_2_1(); } ///<summary>Oracle compatible: 01/08/2013</summary> private static void To12_2_1() { if(FromVersion<new Version("12.2.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.2.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS custrefentry"; Db.NonQ(command); command=@"CREATE TABLE custrefentry ( CustRefEntryNum bigint NOT NULL auto_increment PRIMARY KEY, PatNumCust bigint NOT NULL, PatNumRef bigint NOT NULL, DateEntry date NOT NULL DEFAULT '0001-01-01', Note varchar(255) NOT NULL, INDEX(PatNumCust), INDEX(PatNumRef) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE custrefentry'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE custrefentry ( CustRefEntryNum number(20) NOT NULL, PatNumCust number(20) NOT NULL, PatNumRef number(20) NOT NULL, DateEntry date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, Note varchar2(255), CONSTRAINT custrefentry_CustRefEntryNum PRIMARY KEY (CustRefEntryNum) )"; Db.NonQ(command); command=@"CREATE INDEX custrefentry_PatNumCust ON custrefentry (PatNumCust)"; Db.NonQ(command); command=@"CREATE INDEX custrefentry_PatNumRef ON custrefentry (PatNumRef)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS custreference"; Db.NonQ(command); command=@"CREATE TABLE custreference ( CustReferenceNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, DateMostRecent date NOT NULL DEFAULT '0001-01-01', Note varchar(255) NOT NULL, IsBadRef tinyint NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE custreference'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE custreference ( CustReferenceNum number(20) NOT NULL, PatNum number(20) NOT NULL, DateMostRecent date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, Note varchar2(255), IsBadRef number(3) NOT NULL, CONSTRAINT custreference_CustReferenceNum PRIMARY KEY (CustReferenceNum) )"; Db.NonQ(command); command=@"CREATE INDEX custreference_PatNum ON custreference (PatNum)"; Db.NonQ(command); } //Create a customer reference object for every customer in the db. if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO custreference (PatNum) SELECT PatNum FROM patient"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE appointment ADD ColorOverride int NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE appointment ADD ColorOverride number(11)"; Db.NonQ(command); command="UPDATE appointment SET ColorOverride = 0 WHERE ColorOverride IS NULL"; Db.NonQ(command); command="ALTER TABLE appointment MODIFY ColorOverride NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD DateResent date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD DateResent date"; Db.NonQ(command); command="UPDATE claim SET DateResent = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateResent IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY DateResent NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD CorrectionType tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD CorrectionType number(3)"; Db.NonQ(command); command="UPDATE claim SET CorrectionType = 0 WHERE CorrectionType IS NULL"; Db.NonQ(command); command="ALTER TABLE claim MODIFY CorrectionType NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD ClaimIdentifier varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD ClaimIdentifier varchar2(255)"; Db.NonQ(command); } command="UPDATE claim SET ClaimIdentifier="+DbHelper.Concat(new string[] {"PatNum","'/'","ClaimNum"}); Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE claim ADD OrigRefNum varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE claim ADD OrigRefNum varchar2(255)"; Db.NonQ(command); } //Add RefAttachDelete permission to everyone------------------------------------------------------ command="SELECT DISTINCT UserGroupNum FROM grouppermission"; DataTable table=Db.GetTable(command); long groupNum; if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.RefAttachDelete)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.RefAttachDelete)+")"; Db.NonQ32(command); } } //Add RefAttachAdd permission to everyone------------------------------------------------------ if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.RefAttachAdd)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.RefAttachAdd)+")"; Db.NonQ32(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE apptfielddef ADD FieldType tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE apptfielddef ADD FieldType number(3)"; Db.NonQ(command); command="UPDATE apptfielddef SET FieldType = 0 WHERE FieldType IS NULL"; Db.NonQ(command); command="ALTER TABLE apptfielddef MODIFY FieldType NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE apptfielddef ADD PickList varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE apptfielddef ADD PickList varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurecode ADD ProvNumDefault bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE procedurecode ADD INDEX (ProvNumDefault)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurecode ADD ProvNumDefault number(20)"; Db.NonQ(command); command="UPDATE procedurecode SET ProvNumDefault = 0 WHERE ProvNumDefault IS NULL"; Db.NonQ(command); command="ALTER TABLE procedurecode MODIFY ProvNumDefault NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX procedurecode_ProvNumDefault ON procedurecode (ProvNumDefault)"; Db.NonQ(command); } //Getting rid of AutoItem from CommLogItem enum. Set all commlogs using AutoItem to None. command="UPDATE commlog SET Mode_=0 WHERE Mode_=5"; Db.NonQ(command); //Getting rid of IsStatementSent from commlog table. command="ALTER TABLE commlog DROP COLUMN IsStatementSent"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE computerpref ADD ScanDocSelectSource tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE computerpref ADD ScanDocSelectSource number(3)"; Db.NonQ(command); command="UPDATE computerpref SET ScanDocSelectSource = 0 WHERE ScanDocSelectSource IS NULL"; Db.NonQ(command); command="ALTER TABLE computerpref MODIFY ScanDocSelectSource NOT NULL"; Db.NonQ(command); } command="UPDATE computerpref SET ScanDocSelectSource = 1";//Default to show select scanner popup. Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE computerpref ADD ScanDocShowOptions tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE computerpref ADD ScanDocShowOptions number(3)"; Db.NonQ(command); command="UPDATE computerpref SET ScanDocShowOptions = 0 WHERE ScanDocShowOptions IS NULL"; Db.NonQ(command); command="ALTER TABLE computerpref MODIFY ScanDocShowOptions NOT NULL"; Db.NonQ(command); } command="UPDATE computerpref SET ScanDocShowOptions = 1";//Default to show scanner options when scanning. Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE computerpref ADD ScanDocDuplex tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE computerpref ADD ScanDocDuplex number(3)"; Db.NonQ(command); command="UPDATE computerpref SET ScanDocDuplex = 0 WHERE ScanDocDuplex IS NULL"; Db.NonQ(command); command="ALTER TABLE computerpref MODIFY ScanDocDuplex NOT NULL"; Db.NonQ(command); } command="UPDATE computerpref SET ScanDocDuplex = 1";//Default to always attempt to scan duplex Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE computerpref ADD ScanDocGrayscale tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE computerpref ADD ScanDocGrayscale number(3)"; Db.NonQ(command); command="UPDATE computerpref SET ScanDocGrayscale = 0 WHERE ScanDocGrayscale IS NULL"; Db.NonQ(command); command="ALTER TABLE computerpref MODIFY ScanDocGrayscale NOT NULL"; Db.NonQ(command); } command="UPDATE computerpref SET ScanDocGrayscale = 1"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE computerpref ADD ScanDocResolution int NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE computerpref ADD ScanDocResolution number(11)"; Db.NonQ(command); command="UPDATE computerpref SET ScanDocResolution = 0 WHERE ScanDocResolution IS NULL"; Db.NonQ(command); command="ALTER TABLE computerpref MODIFY ScanDocResolution NOT NULL"; Db.NonQ(command); } command="SELECT ValueString FROM preference WHERE PrefName='ScannerResolution'"; int scannerRes=PIn.Int(Db.GetScalar(command)); command="UPDATE computerpref SET ScanDocResolution = "+POut.Int(scannerRes); Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE computerpref ADD ScanDocQuality tinyint unsigned NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE computerpref ADD ScanDocQuality number(3)"; Db.NonQ(command); command="UPDATE computerpref SET ScanDocQuality = 0 WHERE ScanDocQuality IS NULL"; Db.NonQ(command); command="ALTER TABLE computerpref MODIFY ScanDocQuality NOT NULL"; Db.NonQ(command); } command="SELECT ValueString FROM preference WHERE PrefName='ScannerCompression'"; int scannerComp=PIn.Int(Db.GetScalar(command)); command="UPDATE computerpref SET ScanDocQuality = "+POut.Int(scannerComp); Db.NonQ(command); command="DELETE FROM preference WHERE PrefName = 'ScannerCompression'"; Db.NonQ(command); command="DELETE FROM preference WHERE PrefName = 'ScannerResolution'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE timecardrule ADD BeforeTimeOfDay time NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE timecardrule ADD BeforeTimeOfDay date"; Db.NonQ(command); command="UPDATE timecardrule SET BeforeTimeOfDay = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE BeforeTimeOfDay IS NULL"; Db.NonQ(command); command="ALTER TABLE timecardrule MODIFY BeforeTimeOfDay NOT NULL"; Db.NonQ(command); } if(CultureInfo.CurrentCulture.Name.EndsWith("CA")) {//Canadian. en-CA or fr-CA command="SELECT CanadianNetworkNum FROM canadiannetwork WHERE Abbrev='CSI' LIMIT 1"; long canadianNetworkNumCSI=PIn.Long(Db.GetScalar(command)); command="SELECT COUNT(*) FROM carrier WHERE ElectID='000116'"; //boilermakers' national benefit plan if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('Boilermakers\\' National Benefit Plan','45 McIntosh Drive','','Markham','ON','L3R 8C7','1-800-668-7547','000116','0','1','04',"+POut.Long(canadianNetworkNumCSI)+",'0',1,384)"; Db.NonQ(command); } command="SELECT COUNT(*) FROM carrier WHERE ElectID='000115'"; //u.a. local 46 dental plan if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('U.A. Local 46 Dental Plan','936 Warden Avenue','','Scarborough','ON','M1L 4C9','1-800-263-3564','000115','0','1','04',"+POut.Long(canadianNetworkNumCSI)+",'0',1,384)"; Db.NonQ(command); } command="SELECT COUNT(*) FROM carrier WHERE ElectID='000110'"; //u.a. local 787 Health Trust Fund Dental Plan if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('U.A. Local 787 Health Trust Fund Dental Plan','419 Deerhurst Drive','','Brampton','ON','L6T 5K3','1-204-985-3940','000110','0','1','04',"+POut.Long(canadianNetworkNumCSI)+",'0',1,384)"; Db.NonQ(command); } } //Insert RayMage Imaging Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'RayMage', " +"'RayMage from www.cefla.com', " +"'0', " +"'"+POut.String(@"C:\Program Files\MyRay\rayMage\rayMage.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'RayMage')"; Db.NonQ(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'RayMage', " +"'RayMage from www.cefla.com', " +"'0', " +"'"+POut.String(@"C:\Program Files\MyRay\rayMage\rayMage.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'RayMage')"; Db.NonQ(command); }//end RayMage Imaging bridge //Insert BioPAK Imaging Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'BioPAK', " +"'BioPAK from www.bioresearchinc.com', " +"'0', " +"'"+POut.String(@"BioPAK.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'BioPAK')"; Db.NonQ(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'BioPAK', " +"'BioPAK from www.bioresearchinc.com', " +"'0', " +"'"+POut.String(@"BioPAK.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'BioPAK')"; Db.NonQ(command); }//end BioPAK Imaging bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE securitylog ADD FKey bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE securitylog ADD INDEX (FKey)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE securitylog ADD FKey number(20)"; Db.NonQ(command); command="UPDATE securitylog SET FKey = 0 WHERE FKey IS NULL"; Db.NonQ(command); command="ALTER TABLE securitylog MODIFY FKey NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX securitylog_FKey ON securitylog (FKey)"; Db.NonQ(command); } //This will be specific to eCW because we don't use IsStandalone anywhere else. command=@"UPDATE programproperty SET PropertyDesc='eClinicalWorksMode' WHERE PropertyDesc='IsStandalone'"; Db.NonQ(command); command="UPDATE preference SET ValueString = '12.2.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_2_17(); } ///<summary>Oracle compatible: 01/08/2013</summary> private static void To12_2_17() { if(FromVersion<new Version("12.2.17.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.2.17"));//No translation in convert script. string command=""; //Add the 1500 claim form field for prior authorization if it does not already exist. The unique ID is OD9. if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9' LIMIT 1"; } else {//oracle doesn't have LIMIT command="SELECT * FROM (SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9') WHERE RowNum<=1"; } long claimFormNum=PIn.Long(Db.GetScalar(command)); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES (0,"+POut.Long(claimFormNum)+",'','PriorAuthString','','528','695','282','14')"; } else { command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ((SELECT MAX(ClaimFormItemNum)+1 FROM claimformitem),"+POut.Long(claimFormNum)+",'','PriorAuthString','','528','695','282','14')"; } Db.NonQ(command); command="UPDATE preference SET ValueString = '12.2.17.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_2_28(); } ///<summary>Oracle compatible: 01/08/2013</summary> private static void To12_2_28() { if(FromVersion<new Version("12.2.28.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.2.28"));//No translation in convert script. string command=""; //Fix medical claim form 1500, P*Date fields printing issue. Fields were too narrow. The unique ID is OD9. if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9' LIMIT 1"; } else {//oracle doesn't have LIMIT command="SELECT * FROM (SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9') WHERE RowNum<=1"; } long claimFormNum=PIn.Long(Db.GetScalar(command)); if(DataConnection.DBtype==DatabaseType.MySql) { command="UPDATE claimformitem SET width = 80 WHERE FieldName LIKE 'P%Date' AND ClaimFormNum = "+claimFormNum; Db.NonQ(command); command="UPDATE claimformitem SET XPos = 206 WHERE FieldName LIKE 'P%PlaceNumericCode' AND ClaimFormNum = "+claimFormNum; Db.NonQ(command); } else { command="UPDATE claimformitem SET width = 80 WHERE FieldName LIKE 'P%Date' AND ClaimFormNum = "+claimFormNum; Db.NonQ(command); command="UPDATE claimformitem SET XPos = 206 WHERE FieldName LIKE 'P%PlaceNumericCode' AND ClaimFormNum = "+claimFormNum; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.2.28.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_3_1(); } //In version 12.2.34, there is an eCW section here. ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_3_1() { if(FromVersion<new Version("12.3.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.3.1"));//No translation in convert script. string command; //Removing Appointment Complete-Time bar, Patient Note Text and Completed Pt. Note Text. command="DELETE FROM definition WHERE Category=17 AND ItemName='Appointment Complete-Time bar'";//Cat 17=AppointmentColors Db.NonQ(command); command="DELETE FROM definition WHERE Category=17 AND ItemName='Patient Note Text'"; Db.NonQ(command); command="DELETE FROM definition WHERE Category=17 AND ItemName='Completed Pt. Note Text'"; Db.NonQ(command); command="DELETE FROM definition WHERE Category=17 AND ItemName='Patient Note - Pt Name'"; Db.NonQ(command); //Fix the ItemOrder of the AppointmentColors category command="UPDATE definition SET ItemOrder=2 WHERE Category=17 AND ItemName='Appointment Complete-Background'"; Db.NonQ(command); command="UPDATE definition SET ItemOrder=3 WHERE Category=17 AND ItemName='Holiday'"; Db.NonQ(command); command="UPDATE definition SET ItemOrder=4 WHERE Category=17 AND ItemName='Blockout Text'"; Db.NonQ(command); command="UPDATE definition SET ItemOrder=5 WHERE Category=17 AND ItemName='Patient Note Background'"; Db.NonQ(command); command="UPDATE definition SET ItemOrder=6 WHERE Category=17 AND ItemName='Completed Pt. Note Background'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('AppointmentTimeIsLocked','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'AppointmentTimeIsLocked','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('RecallAgeAdult','12')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'RecallAgeAdult','12')"; Db.NonQ(command); } try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7msg ADD INDEX (HL7Status)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX hl7msg_HL7Status ON hl7msg (HL7Status)"; Db.NonQ(command); } } catch(Exception ex) { }//ex is needed, or exception won't get caught. if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7msg ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE hl7msg SET DateTStamp = NOW()"; Db.NonQ(command); } else {//oracle command="ALTER TABLE hl7msg ADD DateTStamp timestamp"; Db.NonQ(command); command="UPDATE hl7msg SET DateTStamp = SYSTIMESTAMP"; Db.NonQ(command); } try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7msg ADD INDEX (DateTStamp)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX hl7msg_DateTStamp ON hl7msg (DateTStamp)"; Db.NonQ(command); } } catch(Exception ex) { }//ex is needed, or exception won't get caught. if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('TextMsgOkStatusTreatAsNo','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'TextMsgOkStatusTreatAsNo','0')"; Db.NonQ(command); } command="DELETE FROM preference WHERE PrefName='MedicalEclaimsEnabled'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD TxtMsgOk tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE patient ADD TxtMsgOk number(3)"; Db.NonQ(command); command="UPDATE patient SET TxtMsgOk = 0 WHERE TxtMsgOk IS NULL"; Db.NonQ(command); command="ALTER TABLE patient MODIFY TxtMsgOk NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE programproperty ADD ComputerName varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE programproperty ADD ComputerName varchar2(255)"; Db.NonQ(command); } //Insert CallFire Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'CallFire', " +"'CallFire from www.callfire.com', " +"'0', " +"''," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Key From CallFire', " +"'')"; Db.NonQ(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'CallFire', " +"'CallFire from www.callfire.com', " +"'0', " +"''," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Key From CallFire', " +"'')"; Db.NonQ(command); }//end CallFire bridge //ImageDelete was removed from global lock date. Set the permission dates to the current lock dates. if(DataConnection.DBtype==DatabaseType.MySql) { command=@"UPDATE grouppermission gp,preference pdate,preference pdays SET gp.NewerDate=pdate.ValueString,gp.NewerDays=pdays.ValueString WHERE pdate.PrefName='SecurityLockDate' AND pdays.PrefName='SecurityLockDays' AND gp.PermType=44";//ImageDelete Db.NonQ(command); } else {//oracle command=@"UPDATE grouppermission SET NewerDate=TO_DATE((SELECT ValueString FROM preference WHERE prefname='SecurityLockDate'),'yyyy-mm-dd') ,NewerDays=(SELECT ValueString FROM preference WHERE PrefName='SecurityLockDays') WHERE PermType=44";//ImageDelete Db.NonQ(command); } //Add CarrierAdd permission to everyone------------------------------------------------------ command="SELECT DISTINCT UserGroupNum FROM grouppermission"; DataTable table=Db.GetTable(command); long groupNum; if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+",58)";//CarrierCreate Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+",58)";//CarrierCreate Db.NonQ32(command); } } //Text Message Confirmations-------------------------------------------------------------------------------------------------------------------------------------- if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ConfirmTextMessage','[NameF], we would like to confirm your dental appointment on [date] at [time].')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) " +"VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ConfirmTextMessage','[NameF], we would like to confirm your dental appointment on [date] at [time].')"; Db.NonQ(command); } command="SELECT MAX(ItemOrder) FROM definition WHERE Category="+POut.Int((int)DefCat.ApptConfirmed); int itemOrder=PIn.Int(Db.GetScalar(command))+1;//eg 7+1 long defNumTextMessaged; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO definition(Category,ItemOrder,ItemName,ItemValue) " +"VALUES("+POut.Int((int)DefCat.ApptConfirmed)+","+POut.Int(itemOrder)+",'Texted','Texted')"; defNumTextMessaged=Db.NonQ(command,true); } else {//oracle command="INSERT INTO definition(DefNum,Category,ItemOrder,ItemName,ItemValue) " +"VALUES((SELECT MAX(PrefNum)+1 FROM preference),"+POut.Int((int)DefCat.ApptConfirmed)+","+POut.Int(itemOrder)+",'Texted','Texted')"; defNumTextMessaged=Db.NonQ(command,true); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ConfirmStatusTextMessaged','"+POut.Long(defNumTextMessaged)+"')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ConfirmStatusTextMessaged','"+POut.Long(defNumTextMessaged)+"')"; Db.NonQ(command); } //End Text Message Confirmations---------------------------------------------------------------------------------------------------------------------------------- //add ReportDashbaord permissions to all groups------------------------------------------------------ command="SELECT UserGroupNum FROM usergroup"; table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Long((int)Permissions.GraphicalReports)+")"; Db.NonQ(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Long((int)Permissions.GraphicalReports)+")"; Db.NonQ(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ICD9DefaultForNewProcs','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ICD9DefaultForNewProcs','')"; Db.NonQ(command); } try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE patient ADD INDEX (Email)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX patient_Email ON patient (Email)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE appointment ADD INDEX (AptStatus)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX appointment_AptStatus ON appointment (AptStatus)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE commlog ADD INDEX (CommDateTime)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX commlog_CommDateTime ON commlog (CommDateTime)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE commlog ADD INDEX (CommType)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX commlog_CommType ON commlog (CommType)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE recall ADD INDEX (DatePrevious)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX recall_DatePrevious ON recall (DatePrevious)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE recall ADD INDEX (IsDisabled)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX recall_IsDisabled ON recall (IsDisabled)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE recall ADD INDEX (RecallTypeNum)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX recall_RecallTypeNum ON recall (RecallTypeNum)"; Db.NonQ(command); } } catch(Exception ex) { }//ex is needed, or exception won't get caught. if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS installmentplan"; Db.NonQ(command); command=@"CREATE TABLE installmentplan ( InstallmentPlanNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, DateAgreement date NOT NULL DEFAULT '0001-01-01', DateFirstPayment date NOT NULL DEFAULT '0001-01-01', MonthlyPayment double NOT NULL, APR float NOT NULL, Note varchar(255) NOT NULL, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE installmentplan'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE installmentplan ( InstallmentPlanNum number(20) NOT NULL, PatNum number(20) NOT NULL, DateAgreement date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, DateFirstPayment date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, MonthlyPayment number(38,8) NOT NULL, APR number(38,8) NOT NULL, Note varchar2(255) NOT NULL, CONSTRAINT installmentplan_InstallmentPla PRIMARY KEY (InstallmentPlanNum) )"; Db.NonQ(command); command=@"CREATE INDEX installmentplan_PatNum ON installmentplan (PatNum)"; Db.NonQ(command); } //Insert ClioSoft Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'ClioSoft', " +"'ClioSoft from www.sotaimaging.com', " +"'0', " +"'"+POut.String(@"C:\Program Files (x86)\ClioSoft\ClioSoft.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'ClioSoft')"; Db.NonQ(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'ClioSoft', " +"'ClioSoft from www.sotaimaging.com', " +"'0', " +"'"+POut.String(@"C:\Program Files (x86)\ClioSoft\ClioSoft.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'ClioSoft')"; Db.NonQ(command); }//end ClioSoft bridge //Add AutoNoteQuickNoteEdit permission to everyone------------------------------------------------------ command="SELECT DISTINCT UserGroupNum FROM grouppermission"; table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.AutoNoteQuickNoteEdit)+")"; Db.NonQ32(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.AutoNoteQuickNoteEdit)+")"; Db.NonQ32(command); } } //Insert Tscan Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Tscan', " +"'Tscan from www.tekscan.com', " +"'0', " +"'"+POut.String(@"tscan.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Tscan')"; Db.NonQ(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'Tscan', " +"'Tscan from www.tekscan.com', " +"'0', " +"'"+POut.String(@"tscan.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'Tscan')"; Db.NonQ(command); }//end Tscan bridge command="UPDATE preference SET ValueString = '12.3.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_3_3(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_3_3() { if(FromVersion<new Version("12.3.3.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.3.3"));//No translation in convert script. string command=""; command="UPDATE claimformitem SET FieldName='PayToDentistAddress' WHERE FieldName='BillingDentistAddress'"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='PayToDentistAddress2' WHERE FieldName='BillingDentistAddress2'"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='PayToDentistCity' WHERE FieldName='BillingDentistCity'"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='PayToDentistST' WHERE FieldName='BillingDentistST'"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='PayToDentistZip' WHERE FieldName='BillingDentistZip'"; Db.NonQ(command); command="UPDATE preference SET ValueString = '12.3.3.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_3_6(); } ///<summary>Also in 12.2.34</summary> ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_3_6() { if(FromVersion<new Version("12.3.6.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.3.6"));//No translation in convert script. string command=""; if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ProgramNum FROM program WHERE ProgName='eClinicalWorks'"; int programNum=PIn.Int(Db.GetScalar(command)); command="SELECT COUNT(*) FROM programproperty WHERE ProgramNum="+programNum+" AND PropertyDesc='eCWServer'"; if(Db.GetCount(command)=="0") {//Also added in 12.2 so we need to check to see if it exists command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'eCWServer', " +"'')"; Db.NonQ(command); } command="SELECT COUNT(*) FROM programproperty WHERE ProgramNum="+programNum+" AND PropertyDesc='eCWPort'"; if(Db.GetCount(command)=="0") {//Also added in 12.2 so we need to check to see if it exists command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'eCWPort', " +"'4928')"; Db.NonQ(command); } } else {//oracle //eCW will never use Oracle. } command="UPDATE preference SET ValueString = '12.3.6.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_3_12(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_3_12() { if(FromVersion<new Version("12.3.12.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.3.12"));//No translation in convert script. string command=""; //Sheets created in 12.3 with misc check boxes would have a trailing semicolon. So we will remove the colon for the sheet field def. command="UPDATE sheetfielddef set FieldName='misc' WHERE FieldType=8 AND FieldName='misc:'";//FieldType 8 = CheckBox. Db.NonQ(command); //And remove the colon from all patient forms. command="UPDATE sheetfield SET FieldName='misc' WHERE FieldType=8 AND FieldName='misc:'";//FieldType 8 = CheckBox. Db.NonQ(command); command="UPDATE preference SET ValueString = '12.3.12.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_3_20(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_3_20() { if(FromVersion<new Version("12.3.20.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.3.20"));//No translation in convert script. string command=""; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('RecallExcludeIfAnyFutureAppt','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'RecallExcludeIfAnyFutureAppt','0')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.3.20.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_1(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_4_1() { if(FromVersion<new Version("12.4.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS hl7def"; Db.NonQ(command); command=@"CREATE TABLE hl7def ( HL7DefNum bigint NOT NULL auto_increment PRIMARY KEY, Description varchar(255) NOT NULL, ModeTx tinyint NOT NULL, IncomingFolder varchar(255) NOT NULL, OutgoingFolder varchar(255) NOT NULL, IncomingPort varchar(255) NOT NULL, OutgoingIpPort varchar(255) NOT NULL, FieldSeparator varchar(5) NOT NULL, ComponentSeparator varchar(5) NOT NULL, SubcomponentSeparator varchar(5) NOT NULL, RepetitionSeparator varchar(5) NOT NULL, EscapeCharacter varchar(5) NOT NULL, IsInternal tinyint NOT NULL, InternalType varchar(255) NOT NULL, InternalTypeVersion varchar(50) NOT NULL, IsEnabled tinyint NOT NULL, Note text NOT NULL, HL7Server varchar(255) NOT NULL, HL7ServiceName varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE hl7def'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE hl7def ( HL7DefNum number(20) NOT NULL, Description varchar2(255), ModeTx number(3) NOT NULL, IncomingFolder varchar2(255), OutgoingFolder varchar2(255), IncomingPort varchar2(255), OutgoingIpPort varchar2(255), FieldSeparator varchar2(5), ComponentSeparator varchar2(5), SubcomponentSeparator varchar2(5), RepetitionSeparator varchar2(5), EscapeCharacter varchar2(5), IsInternal number(3) NOT NULL, InternalType varchar2(255), InternalTypeVersion varchar2(50), IsEnabled number(3) NOT NULL, Note clob, HL7Server varchar2(255), HL7ServiceName varchar2(255), CONSTRAINT hl7def_HL7DefNum PRIMARY KEY (HL7DefNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS hl7deffield"; Db.NonQ(command); command=@"CREATE TABLE hl7deffield ( HL7DefFieldNum bigint NOT NULL auto_increment PRIMARY KEY, HL7DefSegmentNum bigint NOT NULL, OrdinalPos int NOT NULL, TableId varchar(255) NOT NULL, DataType varchar(255) NOT NULL, FieldName varchar(255) NOT NULL, FixedText text NOT NULL, INDEX(HL7DefSegmentNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE hl7deffield'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE hl7deffield ( HL7DefFieldNum number(20) NOT NULL, HL7DefSegmentNum number(20) NOT NULL, OrdinalPos number(11) NOT NULL, TableId varchar2(255), DataType varchar2(255), FieldName varchar2(255), FixedText varchar2(2000), CONSTRAINT hl7deffield_HL7DefFieldNum PRIMARY KEY (HL7DefFieldNum) )"; Db.NonQ(command); command=@"CREATE INDEX hl7deffield_HL7DefSegmentNum ON hl7deffield (HL7DefSegmentNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS hl7defmessage"; Db.NonQ(command); command=@"CREATE TABLE hl7defmessage ( HL7DefMessageNum bigint NOT NULL auto_increment PRIMARY KEY, HL7DefNum bigint NOT NULL, MessageType varchar(255) NOT NULL, EventType varchar(255) NOT NULL, InOrOut tinyint NOT NULL, ItemOrder int NOT NULL, Note text NOT NULL, INDEX(HL7DefNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE hl7defmessage'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE hl7defmessage ( HL7DefMessageNum number(20) NOT NULL, HL7DefNum number(20) NOT NULL, MessageType varchar2(255), EventType varchar2(255), InOrOut number(3) NOT NULL, ItemOrder number(11) NOT NULL, Note clob, CONSTRAINT hl7defmessage_HL7DefMessageNum PRIMARY KEY (HL7DefMessageNum) )"; Db.NonQ(command); command=@"CREATE INDEX hl7defmessage_HL7DefNum ON hl7defmessage (HL7DefNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS hl7defsegment"; Db.NonQ(command); command=@"CREATE TABLE hl7defsegment ( HL7DefSegmentNum bigint NOT NULL auto_increment PRIMARY KEY, HL7DefMessageNum bigint NOT NULL, ItemOrder int NOT NULL, CanRepeat tinyint NOT NULL, IsOptional tinyint NOT NULL, SegmentName varchar(255) NOT NULL, Note text NOT NULL, INDEX(HL7DefMessageNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE hl7defsegment'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE hl7defsegment ( HL7DefSegmentNum number(20) NOT NULL, HL7DefMessageNum number(20) NOT NULL, ItemOrder number(11) NOT NULL, CanRepeat number(3) NOT NULL, IsOptional number(3) NOT NULL, SegmentName varchar2(255), Note clob, CONSTRAINT hl7defsegment_HL7DefSegmentNum PRIMARY KEY (HL7DefSegmentNum) )"; Db.NonQ(command); command=@"CREATE INDEX hl7defsegment_HL7DefMessageNum ON hl7defsegment (HL7DefMessageNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE recall ADD DateScheduled date NOT NULL DEFAULT '0001-01-01'"; Db.NonQ(command); } else {//oracle command="ALTER TABLE recall ADD DateScheduled date"; Db.NonQ(command); command="UPDATE recall SET DateScheduled = TO_DATE('0001-01-01','YYYY-MM-DD') WHERE DateScheduled IS NULL"; Db.NonQ(command); command="ALTER TABLE recall MODIFY DateScheduled NOT NULL"; Db.NonQ(command); } try{ if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE recall ADD INDEX (DateScheduled)"; Db.NonQ(command); } else {//oracle command="CREATE INDEX recall_DateScheduled ON recall (DateScheduled)"; Db.NonQ(command); } } catch(Exception ex) { }//ex is needed, or exception won't get caught. DataTable table; if(DataConnection.DBtype==DatabaseType.MySql) { command=@"SELECT recalltrigger.RecallTypeNum,MIN(DATE(appointment.AptDateTime)) AS AptDateTime,recall.PatNum FROM appointment,procedurelog,recalltrigger,recall WHERE appointment.AptNum=procedurelog.AptNum AND procedurelog.CodeNum=recalltrigger.CodeNum AND recall.PatNum=procedurelog.PatNum AND recalltrigger.RecallTypeNum=recall.RecallTypeNum AND (appointment.AptStatus=1 "//Scheduled +"OR appointment.AptStatus=4) "//ASAP +"AND appointment.AptDateTime > CURDATE() " //early this morning +"GROUP BY recalltrigger.RecallTypeNum,recall.PatNum "; table=Db.GetTable(command); for(int i=0;i<table.Rows.Count;i++) { if(table.Rows[i]["RecallTypeNum"].ToString()=="") { continue;//this might happen if there are zero results, but the MIN in the query causes one result row with NULLs. } command=@"UPDATE recall SET recall.DateScheduled="+POut.Date(PIn.Date(table.Rows[i]["AptDateTime"].ToString()))+" " +"WHERE recall.RecallTypeNum="+POut.Long(PIn.Long(table.Rows[i]["RecallTypeNum"].ToString()))+" " +"AND recall.PatNum="+POut.Long(PIn.Long(table.Rows[i]["PatNum"].ToString())); Db.NonQ(command); } } else {//oracle command=@"SELECT recalltrigger.RecallTypeNum,MIN(TO_DATE(appointment.AptDateTime)) AS AptDateTime,recall.PatNum FROM appointment,procedurelog,recalltrigger,recall WHERE appointment.AptNum=procedurelog.AptNum AND procedurelog.CodeNum=recalltrigger.CodeNum AND recall.PatNum=procedurelog.PatNum AND recalltrigger.RecallTypeNum=recall.RecallTypeNum AND (appointment.AptStatus=1 "//Scheduled +"OR appointment.AptStatus=4) "//ASAP +"AND appointment.AptDateTime > SYSDATE " //early this morning +"GROUP BY recalltrigger.RecallTypeNum,recall.PatNum "; table=Db.GetTable(command); for(int i=0;i<table.Rows.Count;i++) { if(table.Rows[i]["RecallTypeNum"].ToString()=="") { continue; } command=@"UPDATE recall SET recall.DateScheduled="+POut.Date(PIn.Date(table.Rows[i]["AptDateTime"].ToString()))+" " +"WHERE recall.RecallTypeNum="+POut.Long(PIn.Long(table.Rows[i]["RecallTypeNum"].ToString()))+" " +"AND recall.PatNum="+POut.Long(PIn.Long(table.Rows[i]["PatNum"].ToString())); Db.NonQ(command); } } //Insert CaptureLink Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'CaptureLink', " +"'CaptureLink from www.henryschein.ca', " +"'0', " +"'"+POut.String(@"C:\Program Files\imaginIT\ImaginIT.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'CaptureLink')"; Db.NonQ(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'CaptureLink', " +"'CaptureLink from www.henryschein.ca', " +"'0', " +"'"+POut.String(@"C:\Program Files\imaginIT\ImaginIT.exe")+"'," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Enter 0 to use PatientNum, or 1 to use ChartNum', " +"'0')"; Db.NonQ(command); command="INSERT INTO toolbutitem (ToolButItemNum,ProgramNum,ToolBar,ButtonText) " +"VALUES (" +"(SELECT MAX(ToolButItemNum)+1 FROM toolbutitem)," +"'"+POut.Long(programNum)+"', " +"'"+POut.Int(((int)ToolBarsAvail.ChartModule))+"', " +"'CaptureLink')"; Db.NonQ(command); }//end CaptureLink bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE deposit ADD Memo varchar(255) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE deposit ADD Memo varchar2(255)"; Db.NonQ(command); } //Insert Divvy Systems/eCards bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'Divvy', " +"'Divvy from www.divvysystems.com', " +"'0', " +"''," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Username', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'Password', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'API Key', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'DesignID for Recall Cards', " +"'')"; Db.NonQ(command); } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'Divvy', " +"'Divvy from www.divvysystems.com', " +"'0', " +"''," +"'', " +"'')"; long programNum=Db.NonQ(command,true); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Username', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'Password', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'API Key', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramPropertyNum,ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"(SELECT MAX(ProgramPropertyNum+1) FROM programproperty)," +"'"+POut.Long(programNum)+"', " +"'DesignID for Recall Cards', " +"'')"; Db.NonQ(command); }//end Divvy Systems/eCards bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('InsDefaultAssignBen','1')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'InsDefaultAssignBen','1')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD UnitQtyType tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurelog ADD UnitQtyType number(3)"; Db.NonQ(command); command="UPDATE procedurelog SET UnitQtyType = 0 WHERE UnitQtyType IS NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog MODIFY UnitQtyType NOT NULL"; Db.NonQ(command); } //Fix medical claim form 1500, unit quantity fields. The unique ID is OD9. if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9' LIMIT 1"; } else {//oracle doesn't have LIMIT command="SELECT * FROM (SELECT ClaimFormNum FROM claimform WHERE UniqueID='OD9') WHERE RowNum<=1"; } long claimFormNum=PIn.Long(Db.GetScalar(command)); command="UPDATE claimformitem SET FieldName='P1UnitQty',FormatString='' WHERE ClaimFormNum="+POut.Long(claimFormNum)+" AND FormatString='1' AND Xpos=615 AND YPos=763"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='P2UnitQty',FormatString='' WHERE ClaimFormNum="+POut.Long(claimFormNum)+" AND FormatString='1' AND Xpos=615 AND YPos=796"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='P3UnitQty',FormatString='' WHERE ClaimFormNum="+POut.Long(claimFormNum)+" AND FormatString='1' AND Xpos=615 AND YPos=828"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='P4UnitQty',FormatString='' WHERE ClaimFormNum="+POut.Long(claimFormNum)+" AND FormatString='1' AND Xpos=615 AND YPos=862"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='P5UnitQty',FormatString='' WHERE ClaimFormNum="+POut.Long(claimFormNum)+" AND FormatString='1' AND Xpos=615 AND YPos=895"; Db.NonQ(command); command="UPDATE claimformitem SET FieldName='P6UnitQty',FormatString='' WHERE ClaimFormNum="+POut.Long(claimFormNum)+" AND FormatString='1' AND Xpos=615 AND YPos=929"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7msg ADD PatNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE hl7msg ADD INDEX (PatNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE hl7msg ADD PatNum number(20)"; Db.NonQ(command); command="UPDATE hl7msg SET PatNum = 0 WHERE PatNum IS NULL"; Db.NonQ(command); command="ALTER TABLE hl7msg MODIFY PatNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX hl7msg_PatNum ON hl7msg (PatNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7msg ADD Note text NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE hl7msg ADD Note varchar2(2000)"; Db.NonQ(command); } //Permission for billing command="SELECT UserGroupNum FROM usergroup"; table=Db.GetTable(command); long groupNum; if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Long((int)Permissions.Billing)+")"; Db.NonQ(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Long((int)Permissions.Billing)+")"; Db.NonQ(command); } } //Add EquipmentSetup permission to all groups that had Setup permission--------------------------------------------- command="SELECT DISTINCT UserGroupNum " +"FROM grouppermission " +"WHERE PermType="+POut.Int((int)Permissions.Setup); table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.EquipmentSetup)+")"; Db.NonQ(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.EquipmentSetup)+")"; Db.NonQ(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ProgramNum FROM program WHERE ProgName='eClinicalWorks'"; int programNum=PIn.Int(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'HL7Server', " +"'')"; Db.NonQ(command); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'HL7ServiceName', " +"'')"; Db.NonQ(command); } else {//oracle //eCW will never use Oracle. } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clockevent ADD AmountBonus double NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clockevent ADD AmountBonus number(38,8)"; Db.NonQ(command); command="UPDATE clockevent SET AmountBonus = 0 WHERE AmountBonus IS NULL"; Db.NonQ(command); command="ALTER TABLE clockevent MODIFY AmountBonus NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clockevent ADD AmountBonusAuto double NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clockevent ADD AmountBonusAuto number(38,8)"; Db.NonQ(command); command="UPDATE clockevent SET AmountBonusAuto = 0 WHERE AmountBonusAuto IS NULL"; Db.NonQ(command); command="ALTER TABLE clockevent MODIFY AmountBonusAuto NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE timecardrule ADD AmtDiff double NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE timecardrule ADD AmtDiff number(38,8)"; Db.NonQ(command); command="UPDATE timecardrule SET AmtDiff = 0 WHERE AmtDiff IS NULL"; Db.NonQ(command); command="ALTER TABLE timecardrule MODIFY AmtDiff NOT NULL"; Db.NonQ(command); } //Negatives should not be part of prefs. Too confusing. But moving to a new pref name is not easy. if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('AtoZfolderUsed','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'AtoZfolderUsed','')"; Db.NonQ(command); } command="SELECT ValueString FROM preference WHERE PrefName='AtoZfolderNotRequired'"; string atozFolderNotRequired=Db.GetScalar(command); if(atozFolderNotRequired=="1") { command="UPDATE preference SET ValueString='0' WHERE PrefName='AtoZfolderUsed'"; Db.NonQ(command); } else {//blank or 0 command="UPDATE preference SET ValueString='1' WHERE PrefName='AtoZfolderUsed'"; Db.NonQ(command); } //command="UPDATE preference SET ValueString='' WHERE PrefName='AtoZfolderNotRequired'";//we can't do this because we need the old value in place during update. command="UPDATE preference SET Comments='Deprecated. Use AtoZfolderUsed instead' WHERE PrefName='AtoZfolderNotRequired'"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS documentmisc"; Db.NonQ(command); command=@"CREATE TABLE documentmisc ( DocMiscNum bigint NOT NULL auto_increment PRIMARY KEY, DateCreated date NOT NULL DEFAULT '0001-01-01', FileName varchar(255) NOT NULL, DocMiscType tinyint NOT NULL, RawBase64 longtext NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE documentmisc'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE documentmisc ( DocMiscNum number(20) NOT NULL, DateCreated date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, FileName varchar2(255), DocMiscType number(3) NOT NULL, RawBase64 clob, CONSTRAINT documentmisc_DocMiscNum PRIMARY KEY (DocMiscNum) )"; Db.NonQ(command); } //Add ProblemEdit permission to all groups that had Setup permission--------------------------------------------- command="SELECT DISTINCT UserGroupNum " +"FROM grouppermission " +"WHERE PermType="+POut.Int((int)Permissions.Setup); table=Db.GetTable(command); if(DataConnection.DBtype==DatabaseType.MySql) { for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (UserGroupNum,PermType) " +"VALUES("+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProblemEdit)+")"; Db.NonQ(command); } } else {//oracle for(int i=0;i<table.Rows.Count;i++) { groupNum=PIn.Long(table.Rows[i]["UserGroupNum"].ToString()); command="INSERT INTO grouppermission (GroupPermNum,NewerDays,UserGroupNum,PermType) " +"VALUES((SELECT MAX(GroupPermNum)+1 FROM grouppermission),0,"+POut.Long(groupNum)+","+POut.Int((int)Permissions.ProblemEdit)+")"; Db.NonQ(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS toothgridcell"; Db.NonQ(command); command=@"CREATE TABLE toothgridcell ( ToothGridCellNum bigint NOT NULL auto_increment PRIMARY KEY, SheetFieldNum bigint NOT NULL, ToothGridColNum bigint NOT NULL, ValueEntered varchar(255) NOT NULL, ToothNum varchar(10) NOT NULL, INDEX(SheetFieldNum), INDEX(ToothGridColNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE toothgridcell'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE toothgridcell ( ToothGridCellNum number(20) NOT NULL, SheetFieldNum number(20) NOT NULL, ToothGridColNum number(20) NOT NULL, ValueEntered varchar2(255), ToothNum varchar2(10), CONSTRAINT toothgridcell_ToothGridCellNum PRIMARY KEY (ToothGridCellNum) )"; Db.NonQ(command); command=@"CREATE INDEX toothgridcell_SheetFieldNum ON toothgridcell (SheetFieldNum)"; Db.NonQ(command); command=@"CREATE INDEX toothgridcell_ToothGridColNum ON toothgridcell (ToothGridColNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS toothgridcol"; Db.NonQ(command); command=@"CREATE TABLE toothgridcol ( ToothGridColNum bigint NOT NULL auto_increment PRIMARY KEY, SheetFieldNum bigint NOT NULL, NameItem varchar(255) NOT NULL, CellType tinyint NOT NULL, ItemOrder smallint NOT NULL, ColumnWidth smallint NOT NULL, CodeNum bigint NOT NULL, ProcStatus tinyint NOT NULL, INDEX(SheetFieldNum), INDEX(CodeNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE toothgridcol'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE toothgridcol ( ToothGridColNum number(20) NOT NULL, SheetFieldNum number(20) NOT NULL, NameItem varchar2(255), CellType number(3) NOT NULL, ItemOrder number(11) NOT NULL, ColumnWidth number(11) NOT NULL, CodeNum number(20) NOT NULL, ProcStatus number(3) NOT NULL, CONSTRAINT toothgridcol_ToothGridColNum PRIMARY KEY (ToothGridColNum) )"; Db.NonQ(command); command=@"CREATE INDEX toothgridcol_SheetFieldNum ON toothgridcol (SheetFieldNum)"; Db.NonQ(command); command=@"CREATE INDEX toothgridcol_CodeNum ON toothgridcol (CodeNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS toothgriddef"; Db.NonQ(command); command=@"CREATE TABLE toothgriddef ( ToothGridDefNum bigint NOT NULL auto_increment PRIMARY KEY, NameInternal varchar(255), NameShowing varchar(255), CellType tinyint NOT NULL, ItemOrder smallint NOT NULL, ColumnWidth smallint NOT NULL, CodeNum bigint NOT NULL, ProcStatus tinyint NOT NULL, INDEX(CodeNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE toothgriddef'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE toothgriddef ( ToothGridDefNum number(20) NOT NULL, NameInternal varchar2(255), NameShowing varchar2(255), CellType number(3) NOT NULL, ItemOrder number(11) NOT NULL, ColumnWidth number(11) NOT NULL, CodeNum number(20) NOT NULL, ProcStatus number(3) NOT NULL, CONSTRAINT toothgriddef_ToothGridDefNum PRIMARY KEY (ToothGridDefNum) )"; Db.NonQ(command); command=@"CREATE INDEX toothgriddef_CodeNum ON toothgriddef (CodeNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE sheetfield ADD ReportableName varchar(255)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE sheetfield ADD ReportableName varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE sheetfielddef ADD ReportableName varchar(255)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE sheetfielddef ADD ReportableName varchar2(255)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE provider ADD StateWhereLicensed varchar(50) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE provider ADD StateWhereLicensed varchar2(50)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PracticeFax','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PracticeFax','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('PublicHealthScreeningUsePat','0')"; Db.NonQ(command); command="INSERT INTO preference(PrefName,ValueString) VALUES('PublicHealthScreeningSheet','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PublicHealthScreeningUsePat','0')"; Db.NonQ(command); command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'PublicHealthScreeningSheet','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clinic ADD Fax varchar(50) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clinic ADD Fax varchar2(50)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS screenpat"; Db.NonQ(command); command=@"CREATE TABLE screenpat ( ScreenPatNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, ScreenGroupNum bigint NOT NULL, SheetNum bigint NOT NULL, INDEX(PatNum), INDEX(ScreenGroupNum), INDEX(SheetNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE screenpat'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE screenpat ( ScreenPatNum number(20) NOT NULL, PatNum number(20) NOT NULL, ScreenGroupNum number(20) NOT NULL, SheetNum number(20) NOT NULL, CONSTRAINT screenpat_ScreenPatNum PRIMARY KEY (ScreenPatNum) )"; Db.NonQ(command); command=@"CREATE INDEX screenpat_PatNum ON screenpat (PatNum)"; Db.NonQ(command); command=@"CREATE INDEX screenpat_ScreenGroupNum ON screenpat (ScreenGroupNum)"; Db.NonQ(command); command=@"CREATE INDEX screenpat_SheetNum ON screenpat (SheetNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE adjustment ADD StatementNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE adjustment ADD INDEX (StatementNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE adjustment ADD StatementNum number(20)"; Db.NonQ(command); command="UPDATE adjustment SET StatementNum = 0 WHERE StatementNum IS NULL"; Db.NonQ(command); command="ALTER TABLE adjustment MODIFY StatementNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX adjustment_StatementNum ON adjustment (StatementNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD StatementNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog ADD INDEX (StatementNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurelog ADD StatementNum number(20)"; Db.NonQ(command); command="UPDATE procedurelog SET StatementNum = 0 WHERE StatementNum IS NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog MODIFY StatementNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX procedurelog_StatementNum ON procedurelog (StatementNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE statement ADD IsInvoice tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE statement ADD IsInvoice number(3)"; Db.NonQ(command); command="UPDATE statement SET IsInvoice = 0 WHERE IsInvoice IS NULL"; Db.NonQ(command); command="ALTER TABLE statement MODIFY IsInvoice NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE statement ADD IsInvoiceCopy tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE statement ADD IsInvoiceCopy number(3)"; Db.NonQ(command); command="UPDATE statement SET IsInvoiceCopy = 0 WHERE IsInvoiceCopy IS NULL"; Db.NonQ(command); command="ALTER TABLE statement MODIFY IsInvoiceCopy NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('BillingDefaultsInvoiceNote','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'BillingDefaultsInvoiceNote','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('NewCropAccountId','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'NewCropAccountId','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('NewCropName','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'NewCropName','')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('NewCropPassword','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'NewCropPassword','')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.4.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_12(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_4_12() { if(FromVersion<new Version("12.4.12.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.12"));//No translation in convert script. string command; //Add the ADA2012 claim form. The unique ID is OD11. long claimFormNum=0; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO claimform(Description,IsHidden,FontName,FontSize,UniqueID,PrintImages,OffsetX,OffsetY) "+ "VALUES ('ADA 2012',0,'Arial',9,'OD11',1,0,0)"; claimFormNum=Db.NonQ(command,true); } else {//oracle command="INSERT INTO claimform(ClaimFormNum,Description,IsHidden,FontName,FontSize,UniqueID,PrintImages,OffsetX,OffsetY) "+ "VALUES ((SELECT MAX(ClaimFormNum)+1 FROM claimform),'ADA 2012',0,'Arial',9,'OD11',1,0,0)"; claimFormNum=Db.NonQ(command,true); } command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9UnitQty','',490,617,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10UnitQty','',490,633,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8UnitQty','',490,601,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7UnitQty','',490,584,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6UnitQty','',490,567,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4UnitQty','',490,533,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5UnitQty','',490,550,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3UnitQty','',490,516,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2UnitQty','',490,499,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1UnitQty','',490,483,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Diagnosis','',440,617,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Diagnosis','',440,633,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Diagnosis','',440,601,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Diagnosis','',440,584,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Diagnosis','',440,567,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Diagnosis','',440,533,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Diagnosis','',440,550,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Diagnosis','',440,516,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Diagnosis','',440,499,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Diagnosis','',440,483,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis4','',610,683,80,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis2','',502,683,80,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis3','',610,666,80,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Diagnosis1','',502,666,80,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PlaceNumericCode','',510,750,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistNPI','',451,981,160,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistNPI','',42,1029,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss17','',333,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingProviderSpecialty','',699,999,130,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss16','',333,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss15','',314,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss13','',274,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss14','',294,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss12','',253,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss11','',234,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss9','',193,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss10','',214,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss8','',174,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss7','',155,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss6','',134,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss5','',113,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss3','',73,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss2','',54,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss1','',34,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss4','',94,667,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TotalFee','',827,683,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Fee','',827,633,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Description','',521,633,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Code','',382,633,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Surface','',322,633,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10ToothNumber','',204,633,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10System','',172,633,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Area','',142,633,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P10Date','MM/dd/yyyy',42,633,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Fee','',827,617,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Description','',521,617,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Code','',382,617,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Surface','',322,617,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9ToothNumber','',204,617,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9System','',172,617,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Area','',142,617,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P9Date','MM/dd/yyyy',42,617,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Fee','',827,601,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Description','',521,601,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Code','',382,601,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Surface','',322,601,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8ToothNumber','',204,601,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8System','',172,601,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Date','MM/dd/yyyy',42,601,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P8Area','',142,601,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Description','',521,584,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Fee','',827,584,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Code','',382,584,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Surface','',322,584,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7ToothNumber','',204,584,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7System','',172,584,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Area','',142,584,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P7Date','MM/dd/yyyy',42,584,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Fee','',827,567,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Code','',382,567,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Description','',521,567,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Surface','',322,567,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6System','',172,567,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6ToothNumber','',204,567,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Date','MM/dd/yyyy',42,567,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P6Area','',142,567,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Fee','',827,550,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Description','',521,550,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Code','',382,550,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Surface','',322,550,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5ToothNumber','',204,550,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5System','',172,550,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Area','',142,550,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P5Date','MM/dd/yyyy',42,550,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Fee','',827,533,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Description','',521,533,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Code','',382,533,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Surface','',322,533,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4ToothNumber','',204,533,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4System','',172,533,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Area','',142,533,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P4Date','MM/dd/yyyy',42,533,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Fee','',827,516,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Description','',521,516,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Code','',382,516,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Surface','',322,516,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3ToothNumber','',204,516,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3System','',172,516,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Area','',142,516,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P3Date','MM/dd/yyyy',42,516,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Description','',521,499,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Fee','',827,499,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Code','',382,499,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2ToothNumber','',204,499,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Surface','',322,499,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2System','',172,499,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Area','',142,499,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P2Date','MM/dd/yyyy',42,499,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Fee','',827,483,59,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Description','',521,483,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Code','',382,483,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Surface','',322,483,54,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1ToothNumber','',204,483,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1System','',172,483,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Area','',142,483,27,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','P1Date','MM/dd/yyyy',42,483,96,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientSSN','',665,416,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientIsFemale','',614,416,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientIsMale','',584,416,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientDOB','MM/dd/yyyy',448,416,90,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientZip','',698,382,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientST','',645,382,40,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientCity','',448,382,185,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientAddress2','',448,366,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientAddress','',448,350,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientLastFirst','',448,334,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsOther','',645,301,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsChild','',555,301,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsSpouse','',495,301,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','RelatIsSelf','',445,301,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','EmployerName','',581,250,230,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrIsFemale','',614,217,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrID','',665,215,120,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','GroupNum','',448,250,95,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrIsMale','',585,217,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrDOB','MM/dd/yyyy',448,215,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrZip','',698,181,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrST','',645,181,40,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrCity','',448,181,185,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrAddress2','',448,165,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrAddress','',448,149,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsZip','',292,416,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsST','',239,416,40,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','SubscrLastFirst','',448,133,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsCity','',42,416,185,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsAddress','',42,400,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsCarrierName','',42,384,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsRelatIsChild','',284,351,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsRelatIsOther','',354,351,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsRelatIsSelf','',174,351,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsRelatIsSpouse','',225,351,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsGroupNum','',42,349,111,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrID','',258,316,130,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrIsFemale','',205,318,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsZip','',300,215,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrIsMale','',174,318,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrDOB','MM/dd/yyyy',42,316,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsExistsMed','',155,251,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsExistsDent','',75,251,0,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsST','',248,215,40,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','OtherInsSubscrLastFirst','',43,283,340,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsAddress2','',85,199,315,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsCity','',85,215,150,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsCarrierName','',85,167,315,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PriInsAddress','',85,183,315,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PreAuthString','',42,116,200,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsEnclosuresAttached','',723,767,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsPreAuth','',195,68,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsStandardClaim','',34,68,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistProviderID','',685,1048,130,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistProviderID','',294,1048,120,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss19','',294,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss18','',314,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss20','',274,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss22','',234,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss21','',253,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss24','',193,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss23','',214,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss25','',174,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss27','',134,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss26','',155,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss28','',113,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss32','',34,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss31','',54,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss30','',73,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Miss29','',94,683,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientRelease','',42,801,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','Remarks','',77,701,708,29)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientReleaseDate','MM/dd/yyyy',298,801,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientAssignment','',42,867,240,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PatientAssignmentDate','MM/dd/yyyy',298,867,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','FixedText','B',504,650,14,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsNotOrtho','',444,798,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsOrtho','',534,798,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','DateOrthoPlaced','MM/dd/yyyy',676,797,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','MonthsOrthoRemaining','',484,830,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsReplacementProsth','',564,833,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsNotReplacementProsth','',534,833,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','DatePriorProsthPlaced','MM/dd/yyyy',676,830,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsOtherAccident','',694,867,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsAutoAccident','',594,866,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','IsOccupational','',444,866,0,0)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','AccidentST','',792,882,35,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','AccidentDate','MM/dd/yyyy',573,882,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentist','',42,947,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PayToDentistAddress2','',42,979,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PayToDentistAddress','',42,963,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PayToDentistST','',239,995,40,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PayToDentistCity','',42,995,185,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','PayToDentistZip','',292,995,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistLicenseNum','',170,1029,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistSSNorTIN','',300,1029,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistPh123','',84,1048,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistPh78910','',164,1048,50,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','BillingDentistPh456','',126,1048,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistSignature','',438,949,245,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistSigDate','MM/dd/yyyy',709,949,100,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistLicense','',699,981,130,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistAddress','',434,1013,350,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistCity','',434,1029,165,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistST','',606,1029,40,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistZip','',658,1029,110,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistPh456','',524,1048,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistPh123','',485,1048,30,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'','TreatingDentistPh78910','',563,1048,40,14)"; Db.NonQ(command); command="INSERT INTO claimformitem (ClaimFormItemNum,ClaimFormNum,ImageFileName,FieldName,FormatString,XPos,YPos,Width,Height) " +"VALUES ("+GetClaimFormItemNum()+","+POut.Long(claimFormNum)+",'ADA2012.gif','','',17,15,815,1063)"; Db.NonQ(command); command="UPDATE preference SET ValueString = '12.4.12.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_14(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_4_14() { if(FromVersion<new Version("12.4.14.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.14"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS erxlog"; Db.NonQ(command); command=@"CREATE TABLE erxlog ( ErxLogNum bigint NOT NULL auto_increment PRIMARY KEY, PatNum bigint NOT NULL, MsgText mediumtext NOT NULL, DateTStamp timestamp, INDEX(PatNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE erxlog'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE erxlog ( ErxLogNum number(20) NOT NULL, PatNum number(20) NOT NULL, MsgText clob, DateTStamp timestamp, CONSTRAINT erxlog_ErxLogNum PRIMARY KEY (ErxLogNum) )"; Db.NonQ(command); command=@"CREATE INDEX erxlog_PatNum ON erxlog (PatNum)"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.4.14.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_22(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_4_22() { if(FromVersion<new Version("12.4.22.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.22"));//No translation in convert script. string command; //Claimstream clearinghouse. if(DataConnection.DBtype==DatabaseType.MySql) { command=@"INSERT INTO clearinghouse(Description,ExportPath,Payors,Eformat,ISA05,SenderTin,ISA07,ISA08,ISA15,Password,ResponsePath,CommBridge,ClientProgram, LastBatchNumber,ModemPort,LoginID,SenderName,SenderTelephone,GS03,ISA02,ISA04,ISA16,SeparatorData,SeparatorSegment) VALUES ('Claimstream','"+POut.String(@"C:\ccd\abc\")+"','000090','3','','','','','','','','15','"+POut.String(@"C:\ccd\abc\ccdws.exe")+"',0,0,'','','','','','','','','')"; Db.NonQ(command); } else {//oracle command=@"INSERT INTO clearinghouse(ClearinghouseNum,Description,ExportPath,Payors,Eformat,ISA05,SenderTin,ISA07,ISA08,ISA15,Password,ResponsePath,CommBridge,ClientProgram, LastBatchNumber,ModemPort,LoginID,SenderName,SenderTelephone,GS03,ISA02,ISA04,ISA16,SeparatorData,SeparatorSegment) VALUES ((SELECT MAX(ClearinghouseNum+1) FROM clearinghouse),'Claimstream','"+POut.String(@"C:\ccd\abc\")+"','000090','3','','','','','','','','15','"+POut.String(@"C:\ccd\abc\ccdws.exe")+"',0,0,'','','','','','','','','')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '12.4.22.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_28(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_4_28() { if(FromVersion<new Version("12.4.28.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.28"));//No translation in convert script. string command; if(CultureInfo.CurrentCulture.Name.EndsWith("US")) {//United States long codeNum=0; string procCode="D1208";//This code is needed for important automation. command="SELECT CodeNum FROM procedurecode WHERE ProcCode='"+POut.String(procCode)+"'"; DataTable dtProcCode=Db.GetTable(command); if(dtProcCode.Rows.Count==0) {//The procedure code does not exist //Make sure the procedure code category exists before inserting the procedure code string procCatDescript="Cleanings"; long defNum=0; command="SELECT DefNum FROM definition WHERE Category="+POut.Long((long)DefCat.ProcCodeCats)+" AND ItemName='"+POut.String(procCatDescript)+"'"; DataTable dtDef=Db.GetTable(command); if(dtDef.Rows.Count==0) { //The procedure code category does not exist, add it if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO definition (Category,ItemName,ItemOrder) " +"VALUES ("+POut.Long((long)DefCat.ProcCodeCats)+",'"+POut.String(procCatDescript)+"',"+POut.Long(DefC.Long[(int)DefCat.ProcCodeCats].Length)+")"; } else {//oracle command="INSERT INTO definition (DefNum,Category,ItemName,ItemOrder) " +"VALUES ((SELECT MAX(DefNum)+1 FROM definition),"+POut.Long((long)DefCat.ProcCodeCats)+",'"+POut.String(procCatDescript)+"',"+POut.Long(DefC.Long[(int)DefCat.ProcCodeCats].Length)+")"; } defNum=Db.NonQ(command,true); } else { //The procedure code category already exists, get the existing defnum defNum=PIn.Long(dtDef.Rows[0][0].ToString()); } //The following variables might be useful if we need to copy this pattern later for adding more codes. string procDescript="topical application of fluoride"; string procAbbrDesc="Flo"; string procTime="/"; long procTreatArea=3; int procNoBillIns=0; int procIsProsth=0; int procIsHygiene=1; int procPaintType=0;//none if(DataConnection.DBtype==DatabaseType.MySql) { command=@"INSERT INTO procedurecode(ProcCode,Descript,AbbrDesc, ProcTime,ProcCat,TreatArea,NoBillIns,IsProsth,IsHygiene,PaintType,DefaultNote,SubstitutionCode) VALUES ('"+POut.String(procCode)+"','"+POut.String(procDescript)+"','"+POut.String(procAbbrDesc)+"'," +"'"+POut.String(procTime)+"','"+POut.Long(defNum)+"',"+POut.Long(procTreatArea)+","+POut.Int(procNoBillIns)+","+POut.Int(procIsProsth)+"," +POut.Int(procIsHygiene)+","+POut.Int(procPaintType)+",'','')"; codeNum=Db.NonQ(command,true); } else {//oracle command=@"INSERT INTO procedurecode(CodeNum,ProcCode,Descript,AbbrDesc, ProcTime,ProcCat,TreatArea,NoBillIns,IsProsth,IsHygiene,PaintType,IsCanadianLab,BaseUnits,SubstOnlyIf,IsMultiVisit,ProvNumDefault,GraphicColor,DefaultNote,SubstitutionCode) VALUES ((SELECT MAX(CodeNum)+1 FROM procedurecode),'"+POut.String(procCode)+"','"+POut.String(procDescript)+"','"+POut.String(procAbbrDesc)+"'," +"'"+POut.String(procTime)+"','"+POut.Long(defNum)+"',"+POut.Long(procTreatArea)+","+POut.Int(procNoBillIns)+","+POut.Int(procIsProsth)+"," +POut.Int(procIsHygiene)+","+POut.Int(procPaintType)+",0,0,0,0,0,0,'','')"; codeNum=Db.NonQ(command,true); } }//end D1208 insert else {//D1208 already exists. codeNum=PIn.Long(dtProcCode.Rows[0][0].ToString()); } //Various references to the old D1203 and D1204 need to be changed to the new D1208. long codeNumD1203=0; command="SELECT CodeNum FROM procedurecode WHERE ProcCode='D1203'"; dtProcCode=Db.GetTable(command); if(dtProcCode.Rows.Count>0) { codeNumD1203=PIn.Long(dtProcCode.Rows[0][0].ToString()); } long codeNumD1204=0; command="SELECT CodeNum FROM procedurecode WHERE ProcCode='D1204'"; dtProcCode=Db.GetTable(command); if(dtProcCode.Rows.Count>0) { codeNumD1204=PIn.Long(dtProcCode.Rows[0][0].ToString()); } //Update benefits to remove the old codes and replace with the new code. We ignore CodeNum=0 in case D1203 or D1204 is not in the database. command="UPDATE benefit SET CodeNum="+POut.Long(codeNum)+" WHERE CodeNum<>0 AND (CodeNum="+POut.Long(codeNumD1203)+" OR CodeNum="+POut.Long(codeNumD1204)+")"; Db.NonQ(command); //Clean up insurance plans with obvious duplicate fluoride benefits (plans that used to have benefits for both D1203 and D1204). command="SELECT DISTINCT PlanNum,CovCatNum,TimePeriod,Quantity,CoverageLevel " +"FROM benefit " +"WHERE BenefitType="+POut.Long((long)InsBenefitType.Limitations)+" AND MonetaryAmt=-1 AND PatPlanNum=0 AND Percent=-1 " +"AND QuantityQualifier="+POut.Long((long)BenefitQuantity.AgeLimit)+" AND CodeNum="+POut.Long(codeNum); DataTable dtBenFlo=Db.GetTable(command); command="DELETE FROM benefit " +"WHERE BenefitType="+POut.Long((long)InsBenefitType.Limitations)+" AND MonetaryAmt=-1 AND PatPlanNum=0 AND Percent=-1 " +"AND QuantityQualifier="+POut.Long((long)BenefitQuantity.AgeLimit)+" AND CodeNum="+POut.Long(codeNum); Db.NonQ(command); for(int i=0;i<dtBenFlo.Rows.Count;i++) { long planNum=PIn.Long(dtBenFlo.Rows[i]["PlanNum"].ToString()); long covCatNum=PIn.Long(dtBenFlo.Rows[i]["CovCatNum"].ToString()); long timePeriod=PIn.Long(dtBenFlo.Rows[i]["TimePeriod"].ToString()); long quantity=PIn.Long(dtBenFlo.Rows[i]["Quantity"].ToString()); long coverageLevel=PIn.Long(dtBenFlo.Rows[i]["CoverageLevel"].ToString()); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO benefit (PlanNum,PatPlanNum,CovCatNum,BenefitType,Percent,MonetaryAmt,TimePeriod," +"QuantityQualifier,Quantity,CodeNum,CoverageLevel) " +"VALUES ("+POut.Long(planNum)+",0,"+POut.Long(covCatNum)+","+POut.Long((long)InsBenefitType.Limitations)+",-1,-1,"+POut.Long(timePeriod) +","+POut.Long((long)BenefitQuantity.AgeLimit)+","+POut.Long(quantity)+","+POut.Long(codeNum)+","+POut.Long(coverageLevel)+")"; Db.NonQ(command); } else {//oracle command="INSERT INTO benefit (BenefitNum,PlanNum,PatPlanNum,CovCatNum,BenefitType,Percent,MonetaryAmt,TimePeriod," +"QuantityQualifier,Quantity,CodeNum,CoverageLevel) " +"VALUES ((SELECT MAX(BenefitNum)+1 FROM benefit),"+POut.Long(planNum)+",0,"+POut.Long(covCatNum)+","+POut.Long((long)InsBenefitType.Limitations)+",-1,-1,"+POut.Long(timePeriod) +","+POut.Long((long)BenefitQuantity.AgeLimit)+","+POut.Long(quantity)+","+POut.Long(codeNum)+","+POut.Long(coverageLevel)+")"; Db.NonQ(command); } }//end benefit inserts //Update recall triggers with new fluoride code. command="UPDATE recalltrigger SET CodeNum="+POut.Long(codeNum)+" WHERE CodeNum<>0 AND (CodeNum="+POut.Long(codeNumD1203)+" OR CodeNum="+POut.Long(codeNumD1204)+")"; Db.NonQ(command); //Update the fluoride procedures on the recall triggers. command="SELECT * FROM recalltype";//Should only be a handful of results. DataTable dtRecallType=Db.GetTable(command); for(int i=0;i<dtRecallType.Rows.Count;i++) { string procs=PIn.String(dtRecallType.Rows[i]["Procedures"].ToString()); string procsNew=procs.Replace("D1203","D1208").Replace("D1204","D1208"); if(procs!=procsNew) { long recallTypeNum=PIn.Long(dtRecallType.Rows[i]["RecallTypeNum"].ToString()); command="UPDATE recalltype SET Procedures='"+POut.String(procsNew)+"' WHERE RecallTypeNum="+POut.Long(recallTypeNum); Db.NonQ(command); } } }//end United States update command="UPDATE preference SET ValueString = '12.4.28.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_30(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_4_30() { if(FromVersion<new Version("12.4.30.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.30"));//No translation in convert script. string command; if(CultureInfo.CurrentCulture.Name.EndsWith("US")) {//United States //Move depricated codes to the Obsolete procedure code category. //Make sure the procedure code category exists before moving the procedure codes. string procCatDescript="Obsolete"; long defNum=0; command="SELECT DefNum FROM definition WHERE Category="+POut.Long((long)DefCat.ProcCodeCats)+" AND ItemName='"+POut.String(procCatDescript)+"'"; DataTable dtDef=Db.GetTable(command); if(dtDef.Rows.Count==0) { //The procedure code category does not exist, add it if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO definition (Category,ItemName,ItemOrder) " +"VALUES ("+POut.Long((long)DefCat.ProcCodeCats)+",'"+POut.String(procCatDescript)+"',"+POut.Long(DefC.Long[(int)DefCat.ProcCodeCats].Length)+")"; } else {//oracle command="INSERT INTO definition (DefNum,Category,ItemName,ItemOrder) " +"VALUES ((SELECT MAX(DefNum)+1 FROM definition),"+POut.Long((long)DefCat.ProcCodeCats)+",'"+POut.String(procCatDescript)+"',"+POut.Long(DefC.Long[(int)DefCat.ProcCodeCats].Length)+")"; } defNum=Db.NonQ(command,true); } else { //The procedure code category already exists, get the existing defnum defNum=PIn.Long(dtDef.Rows[0][0].ToString()); } string[] cdtCodesDeleted=new string[] { "D0360","D0362","D1203","D1204", "D4271","D6254","D6795","D6970", "D6972","D6973","D6976","D6977" }; for(int i=0;i<cdtCodesDeleted.Length;i++) { string procCode=cdtCodesDeleted[i]; command="SELECT CodeNum FROM procedurecode WHERE ProcCode='"+POut.String(procCode)+"'"; DataTable dtProcCode=Db.GetTable(command); if(dtProcCode.Rows.Count==0) { //The procedure code does not exist in this database. continue;//Do not try to move it. } long codeNum=PIn.Long(dtProcCode.Rows[0][0].ToString()); command="UPDATE procedurecode SET ProcCat="+POut.Long(defNum)+" WHERE CodeNum="+POut.Long(codeNum); Db.NonQ(command); } }//end United States update command="UPDATE preference SET ValueString = '12.4.30.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_32(); } ///<summary>Oracle compatible: 01/09/2013</summary> private static void To12_4_32() { if(FromVersion<new Version("12.4.32.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.32"));//No translation in convert script. string command; if(CultureInfo.CurrentCulture.Name.EndsWith("US")) {//United States long codeNumD1203=0; command="SELECT CodeNum FROM procedurecode WHERE ProcCode='D1203'"; DataTable dtProcCode=Db.GetTable(command); if(dtProcCode.Rows.Count>0) { codeNumD1203=PIn.Long(dtProcCode.Rows[0][0].ToString()); } long codeNumD1204=0; command="SELECT CodeNum FROM procedurecode WHERE ProcCode='D1204'"; dtProcCode=Db.GetTable(command); if(dtProcCode.Rows.Count>0) { codeNumD1204=PIn.Long(dtProcCode.Rows[0][0].ToString()); } long codeNumD1208=0; command="SELECT CodeNum FROM procedurecode WHERE ProcCode='D1208'"; dtProcCode=Db.GetTable(command); if(dtProcCode.Rows.Count>0) { codeNumD1208=PIn.Long(dtProcCode.Rows[0][0].ToString()); } //Change the procedures on currently scheduled appointments to show D1208 instead of D1203/4. command="UPDATE procedurelog " +"SET CodeNum="+POut.Long(codeNumD1208)+" " +"WHERE ProcStatus="+POut.Long((long)ProcStat.TP)+" AND CodeNum<>0 AND (CodeNum="+POut.Long(codeNumD1203)+" OR CodeNum="+POut.Long(codeNumD1204)+")"; Db.NonQ(command); //Appt procs quick add, change the flouride code to D1208 instead of D1203/4. command="SELECT DefNum,ItemValue FROM definition WHERE Category="+POut.Long((long)DefCat.ApptProcsQuickAdd);//A short list, so just get them all. DataTable dtApptProcsQuickAdd=Db.GetTable(command); for(int i=0;i<dtApptProcsQuickAdd.Rows.Count;i++) { string procs=PIn.String(dtApptProcsQuickAdd.Rows[i]["ItemValue"].ToString()); string procs1208=procs.Replace("D1203","D1208").Replace("D1204","D1208"); if(procs==procs1208) { continue; //There were no D1203 and no D1204. } long defNum=PIn.Long(dtApptProcsQuickAdd.Rows[i]["DefNum"].ToString()); command="UPDATE definition SET ItemValue='"+POut.String(procs1208)+"' WHERE DefNum="+POut.Long(defNum); Db.NonQ(command); } //proc buttons, change flouride to D1208 instead of D1203/4. We don't care about possible duplicates because they are highly unlikely. command="UPDATE procbuttonitem SET CodeNum="+POut.Long(codeNumD1208)+" WHERE CodeNum<>0 AND (CodeNum="+POut.Long(codeNumD1203)+" OR CodeNum="+POut.Long(codeNumD1204)+")"; Db.NonQ(command); }//end United States update command="UPDATE preference SET ValueString = '12.4.32.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To12_4_38(); } ///<summary>Oracle compatible: 02/23/2013</summary> private static void To12_4_38() { if(FromVersion<new Version("12.4.38.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 12.4.38"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.Oracle) { //skip. Too hard for too little benefit. } else { //The code below synchronizes recall.DateScheduled for all patients. There was a bug, that necessitated doing this. //This is essentially a copy of the code from Recalls.SynchScheduledApptFull(). //Clear out DateScheduled column for all pats before changing command="UPDATE recall SET recall.DateScheduled="+POut.Date(DateTime.MinValue); Db.NonQ(command); //get all active patients with future scheduled appointments that have a procedure attached which is a recall trigger procedure command="SELECT DISTINCT patient.PatNum " +"FROM patient " +"INNER JOIN appointment ON appointment.PatNum=patient.PatNum AND AptDateTime>CURDATE() AND (AptStatus=1 OR AptStatus=4) " +"INNER JOIN procedurelog ON procedurelog.AptNum=appointment.AptNum " +"INNER JOIN recalltrigger ON recalltrigger.CodeNum=procedurelog.CodeNum " +"WHERE PatStatus=0"; DataTable tablePats=Db.GetTable(command); for(int p=0;p<tablePats.Rows.Count;p++) { //Get table of future appointment dates with recall type for this patient, where a procedure is attached that is a recall trigger procedure command=@"SELECT recalltrigger.RecallTypeNum,MIN(DATE(appointment.AptDateTime)) AS AptDateTime FROM appointment,procedurelog,recalltrigger,recall WHERE appointment.AptNum=procedurelog.AptNum AND appointment.PatNum="+POut.Long(PIn.Long(tablePats.Rows[p][0].ToString()))+@" AND procedurelog.CodeNum=recalltrigger.CodeNum AND recall.PatNum=appointment.PatNum AND recalltrigger.RecallTypeNum=recall.RecallTypeNum AND (appointment.AptStatus=1 "//Scheduled +"OR appointment.AptStatus=4) "//ASAP +"AND appointment.AptDateTime>CURDATE() "//early this morning +"GROUP BY recalltrigger.RecallTypeNum"; DataTable tableSchedDate=Db.GetTable(command); //Update the recalls for this patient with DATE(AptDateTime) where there is a future appointment with recall proc on it for(int i=0;i<tableSchedDate.Rows.Count;i++) { if(tableSchedDate.Rows[i]["RecallTypeNum"].ToString()=="") { continue; } command=@"UPDATE recall SET recall.DateScheduled="+POut.Date(PIn.Date(tableSchedDate.Rows[i]["AptDateTime"].ToString()))+" " +"WHERE recall.RecallTypeNum="+POut.Long(PIn.Long(tableSchedDate.Rows[i]["RecallTypeNum"].ToString()))+" " +"AND recall.PatNum="+POut.Long(PIn.Long(tablePats.Rows[p][0].ToString()))+" "; Db.NonQ(command); } } } command="UPDATE preference SET ValueString = '12.4.38.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_1_1(); } ///<summary>Oracle compatible: 02/23/2013</summary> private static void To13_1_1() { if(FromVersion<new Version("13.1.1.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 13.1.1"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clockevent CHANGE AmountBonus AmountBonus double NOT NULL default -1"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clockevent MODIFY (AmountBonus NUMBER(38,8) DEFAULT '-1')";//Column is already NOT NULL. Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clockevent CHANGE AmountBonusAuto AmountBonusAuto double NOT NULL default -1"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clockevent MODIFY (AmountBonusAuto NUMBER(38,8) DEFAULT '-1')";//Column is already NOT NULL. Db.NonQ(command); } command="SELECT ValueString FROM preference WHERE PrefName='StatementShowNotes'"; string prefStatementShowNotes=Db.GetScalar(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('StatementShowAdjNotes','"+prefStatementShowNotes+"')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'StatementShowAdjNotes','"+prefStatementShowNotes+"')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ProcLockingIsAllowed','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ProcLockingIsAllowed','0')"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE procedurelog ADD IsLocked tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE procedurelog ADD IsLocked number(3)"; Db.NonQ(command); command="UPDATE procedurelog SET IsLocked = 0 WHERE IsLocked IS NULL"; Db.NonQ(command); command="ALTER TABLE procedurelog MODIFY IsLocked NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7def ADD ShowDemographics tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE hl7def ADD ShowDemographics number(3)"; Db.NonQ(command); command="UPDATE hl7def SET ShowDemographics = 0 WHERE ShowDemographics IS NULL"; Db.NonQ(command); command="ALTER TABLE hl7def MODIFY ShowDemographics NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7def ADD ShowAppts tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE hl7def ADD ShowAppts number(3)"; Db.NonQ(command); command="UPDATE hl7def SET ShowAppts = 0 WHERE ShowAppts IS NULL"; Db.NonQ(command); command="ALTER TABLE hl7def MODIFY ShowAppts NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE hl7def ADD ShowAccount tinyint NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE hl7def ADD ShowAccount number(3)"; Db.NonQ(command); command="UPDATE hl7def SET ShowAccount = 0 WHERE ShowAccount IS NULL"; Db.NonQ(command); command="ALTER TABLE hl7def MODIFY ShowAccount NOT NULL"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS dictcustom"; Db.NonQ(command); command=@"CREATE TABLE dictcustom ( DictCustomNum bigint NOT NULL auto_increment PRIMARY KEY, WordText varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE dictcustom'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE dictcustom ( DictCustomNum number(20) NOT NULL, WordText varchar2(255), CONSTRAINT dictcustom_DictCustomNum PRIMARY KEY (DictCustomNum) )"; Db.NonQ(command); } if(CultureInfo.CurrentCulture.Name.EndsWith("CA")) {//Canadian. en-CA or fr-CA command="SELECT CanadianNetworkNum FROM canadiannetwork WHERE Abbrev='CSI' LIMIT 1"; long canadianNetworkNumCSI=PIn.Long(Db.GetScalar(command)); command="SELECT COUNT(*) FROM carrier WHERE ElectID='000118'"; //local 1030 health benefit plan if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('Local 1030 Health Benefit Plan','45 McIntosh Drive','','Markham','ON','L3R 8C7','1-800-263-3564','000118','0','1','04',"+POut.Long(canadianNetworkNumCSI)+",'0',1,1944)"; Db.NonQ(command); } command="SELECT COUNT(*) FROM carrier WHERE ElectID='000119'"; //sheet metal workers local 30 benefit plan if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('Sheet Metal Workers Local 30 Benefit Plan','45 McIntosh Drive','','Markham','ON','L3R 8C7','1-800-263-3564','000119','0','1','04',"+POut.Long(canadianNetworkNumCSI)+",'0',1,1944)"; Db.NonQ(command); } command="SELECT COUNT(*) FROM carrier WHERE ElectID='000120'"; //the building union of canada health benefit if(Db.GetCount(command)=="0") { command="INSERT INTO carrier (CarrierName,Address,Address2,City,State,Zip,Phone,ElectID,NoSendElect,IsCDA,CDAnetVersion,CanadianNetworkNum,IsHidden,CanadianEncryptionMethod,CanadianSupportedTypes) VALUES "+ "('The Building Union of Canada Health Benefit','45 McIntosh Drive','','Markham','ON','L3R 8C7','1-800-263-3564','000120','0','1','04',"+POut.Long(canadianNetworkNumCSI)+",'0',1,1944)"; Db.NonQ(command); } } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS wikipage"; Db.NonQ(command); command=@"CREATE TABLE wikipage ( WikiPageNum bigint NOT NULL auto_increment PRIMARY KEY, UserNum bigint NOT NULL, PageTitle varchar(255) NOT NULL, KeyWords varchar(255) NOT NULL, PageContent MEDIUMTEXT NOT NULL, DateTimeSaved datetime NOT NULL DEFAULT '0001-01-01 00:00:00', INDEX(UserNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE wikipage'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE wikipage ( WikiPageNum number(20) NOT NULL, UserNum number(20) NOT NULL, PageTitle varchar2(255), KeyWords varchar2(255), PageContent clob, DateTimeSaved date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, CONSTRAINT wikipage_WikiPageNum PRIMARY KEY (WikiPageNum) )"; Db.NonQ(command); command=@"CREATE INDEX wikipage_UserNum ON wikipage (UserNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS wikipagehist"; Db.NonQ(command); command=@"CREATE TABLE wikipagehist ( WikiPageNum bigint NOT NULL auto_increment PRIMARY KEY, UserNum bigint NOT NULL, PageTitle varchar(255) NOT NULL, PageContent MEDIUMTEXT NOT NULL, DateTimeSaved datetime NOT NULL DEFAULT '0001-01-01 00:00:00', IsDeleted tinyint NOT NULL, INDEX(UserNum) ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE wikipagehist'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE wikipagehist ( WikiPageNum number(20) NOT NULL, UserNum number(20) NOT NULL, PageTitle varchar2(255), PageContent clob, DateTimeSaved date DEFAULT TO_DATE('0001-01-01','YYYY-MM-DD') NOT NULL, IsDeleted number(3) NOT NULL, CONSTRAINT wikipagehist_WikiPageNum PRIMARY KEY (WikiPageNum) )"; Db.NonQ(command); command=@"CREATE INDEX wikipagehist_UserNum ON wikipagehist (UserNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS emailaddress"; Db.NonQ(command); command=@"CREATE TABLE emailaddress ( EmailAddressNum bigint NOT NULL auto_increment PRIMARY KEY, SMTPserver varchar(255) NOT NULL, EmailUsername varchar(255) NOT NULL, EmailPassword varchar(255) NOT NULL, ServerPort int NOT NULL, UseSSL tinyint NOT NULL, SenderAddress varchar(255) NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE emailaddress'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE emailaddress ( EmailAddressNum number(20) NOT NULL, SMTPserver varchar2(255), EmailUsername varchar2(255), EmailPassword varchar2(255), ServerPort number(11) NOT NULL, UseSSL number(3) NOT NULL, SenderAddress varchar2(255), CONSTRAINT emailaddress_EmailAddressNum PRIMARY KEY (EmailAddressNum) )"; Db.NonQ(command); } //Jason: Talked with Ryan and these are going to be the only two pages in this table. Oracle requires a PK, so manually setting PK's of 1 and 2. //todo: edit these 2 starting wikipages command="INSERT INTO wikipage (WikiPageNum,UserNum,PageTitle,KeyWords,PageContent,DateTimeSaved) VALUES(" +"1,"//Oracle requires PK to be not null and does not have auto incrementing. Simply hard code the PK here. +"0,"//no usernum set for the first 2 pages +"'_Master'," +"''," +"'"+POut.String(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""> <head> <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" /> <style type=""text/css""> <!-- *{ border: 0px; margin: 0px; } body{ margin: 3px; font-size: 9pt; font-family: arial,sans-serif; } p{ margin-top: 0px; margin-bottom: 0px; } h1, h1 a{ font-size:20pt; color:#005677; } h2, h2 a { font-size:16pt; color:#005677; } h3, h3 a { font-size:12pt; color:#005677; } ul{ list-style-position: inside;/*This puts the bullets inside the div rect instead of outside*/ } ol{ list-style-position: inside; } ul .ListItemContent{ position: relative; left: -5px;/*Tightens up the spacing between bullets and text*/ } ol .ListItemContent{ position: relative; left: -1px;/*Tightens up the spacing between numbers and text*/ } a{ color:rgb(68,81,199);/*same blue color as wikipedia*/ text-decoration:none; } a:hover{ text-decoration:underline; } table, th, td, tr { border-collapse:collapse; border:1px solid #999999; padding:2px; } .PageNotExists, a.PageNotExists { border-bottom:1px dashed #000000; } a.PageNotExists:hover { border-bottom:1px solid #000000; text-decoration:none; } .keywords, a.keywords:hover { color:#000000; background-color:#eeeeee; } --> </style> </head> @@@body@@@ </html>")+"',"; if(DataConnection.DBtype==DatabaseType.Oracle) { command+="SYSDATE"; } else{ command+="NOW()"; } command+=")"; Db.NonQ(command); //blank home page command="INSERT INTO wikipage (WikiPageNum,UserNum,PageTitle,KeyWords,PageContent,DateTimeSaved) VALUES(" +"2,"//Oracle requires PK to be not null and does not have auto incrementing. Simply hard code the PK here. +"0," +"'Home'," +"''," +"'Home',"; if(DataConnection.DBtype==DatabaseType.Oracle) { command+="SYSDATE"; } else { command+="NOW()"; } command+=")"; Db.NonQ(command); if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('EmailDefaultAddressNum','')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'EmailDefaultAddressNum','')"; Db.NonQ(command); } string emailUsername=Db.GetScalar("SELECT ValueString FROM preference WHERE PrefName='EmailUsername'"); if(emailUsername!="") { string emailPassword=Db.GetScalar("SELECT ValueString FROM preference WHERE PrefName='EmailPassword'"); string senderAddress=Db.GetScalar("SELECT ValueString FROM preference WHERE PrefName='EmailSenderAddress'"); int serverPort=PIn.Int(Db.GetScalar("SELECT ValueString FROM preference WHERE PrefName='EmailPort'").ToString()); string smtpServer=Db.GetScalar("SELECT ValueString FROM preference WHERE PrefName='EmailSMTPServer'"); bool useSSL=PIn.Bool(Db.GetScalar("SELECT ValueString FROM preference WHERE PrefName='EmailUseSSL'")); command="INSERT INTO emailaddress(EmailPassword,EmailUsername,SenderAddress,ServerPort,SMTPServer,UseSSL) " +"VALUES('"+POut.String(emailPassword)+"','"+POut.String(emailUsername)+"','"+POut.String(senderAddress)+"'," +POut.Int(serverPort)+",'"+POut.String(smtpServer)+"',"+POut.Bool(useSSL)+")"; long defaultEmailAddressNum=Db.NonQ(command,true); command="UPDATE preference SET ValueString = "+POut.Long(defaultEmailAddressNum)+" WHERE PrefName = 'EmailDefaultAddressNum'"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE clinic ADD EmailAddressNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE clinic ADD INDEX (EmailAddressNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE clinic ADD EmailAddressNum number(20)"; Db.NonQ(command); command="UPDATE clinic SET EmailAddressNum = 0 WHERE EmailAddressNum IS NULL"; Db.NonQ(command); command="ALTER TABLE clinic MODIFY EmailAddressNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX clinic_EmailAddressNum ON clinic (EmailAddressNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE toothgriddef ADD SheetFieldDefNum bigint NOT NULL"; Db.NonQ(command); command="ALTER TABLE toothgriddef ADD INDEX (SheetFieldDefNum)"; Db.NonQ(command); } else {//oracle command="ALTER TABLE toothgriddef ADD SheetFieldDefNum number(20)"; Db.NonQ(command); command="UPDATE toothgriddef SET SheetFieldDefNum = 0 WHERE SheetFieldDefNum IS NULL"; Db.NonQ(command); command="ALTER TABLE toothgriddef MODIFY SheetFieldDefNum NOT NULL"; Db.NonQ(command); command=@"CREATE INDEX toothgriddef_SheetFieldDefNum ON toothgriddef (SheetFieldDefNum)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('ElectronicRxDateStartedUsing131',"+DbHelper.Now()+")"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'ElectronicRxDateStartedUsing131',"+DbHelper.Now()+")"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE rxpat ADD NewCropGuid varchar(40) NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE rxpat ADD NewCropGuid varchar2(40)"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE payment CHANGE PayNote PayNote TEXT NOT NULL"; Db.NonQ(command); } else {//oracle command="ALTER TABLE payment MODIFY (PayNote varchar2(4000) NOT NULL)"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '13.1.1.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_1_3(); } ///<summary>Oracle compatible: 02/23/2013</summary> private static void To13_1_3() { if(FromVersion<new Version("13.1.3.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 13.1.3"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('SpellCheckIsEnabled','1')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'SpellCheckIsEnabled','1')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '13.1.3.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_1_14(); } ///<summary>Oracle compatible: 05/16/2013</summary> private static void To13_1_14() { if(FromVersion<new Version("13.1.14.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 13.1.14"));//No translation in convert script. string command; command="UPDATE preference SET ValueString = "+DbHelper.Now()+" WHERE PrefName = 'ElectronicRxDateStartedUsing131'"; Db.NonQ(command); command="UPDATE preference SET ValueString = '13.1.14.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_1_19(); } ///<summary>Oracle compatible: 05/16/2013</summary> private static void To13_1_19() { if(FromVersion<new Version("13.1.19.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 13.1.19"));//No translation in convert script. string command; try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE adjustment ADD INDEX (ProcNum)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX adjustment_ProcNum ON adjustment (ProcNum)"; Db.NonQ(command); } } catch(Exception ex) { }//ex is needed, or exception won't get caught. if(DataConnection.DBtype==DatabaseType.MySql) { command="DROP TABLE IF EXISTS wikilistheaderwidth"; Db.NonQ(command); command=@"CREATE TABLE wikilistheaderwidth ( WikiListHeaderWidthNum bigint NOT NULL auto_increment PRIMARY KEY, ListName varchar(255) NOT NULL, ColName varchar(255) NOT NULL, ColWidth int NOT NULL ) DEFAULT CHARSET=utf8"; Db.NonQ(command); } else {//oracle //WikiLists Not Supported in Oracle. but we're still adding this table here for consistency of the schema. Also, we might turn on this feature for Oracle some day. command="BEGIN EXECUTE IMMEDIATE 'DROP TABLE wikilistheaderwidth'; EXCEPTION WHEN OTHERS THEN NULL; END;"; Db.NonQ(command); command=@"CREATE TABLE wikilistheaderwidth ( WikiListHeaderWidthNum number(20) NOT NULL, ListName varchar2(255), ColName varchar2(255), ColWidth number(11) NOT NULL, CONSTRAINT wikilistheaderwidth_WikiListHe PRIMARY KEY (WikiListHeaderWidthNum) )"; Db.NonQ(command); } if(DataConnection.DBtype==DatabaseType.MySql) { command="SELECT ProgramNum FROM program WHERE ProgName='eClinicalWorks'"; int programNum=PIn.Int(Db.GetScalar(command)); command="INSERT INTO programproperty (ProgramNum,PropertyDesc,PropertyValue" +") VALUES(" +"'"+POut.Long(programNum)+"', " +"'MedicalPanelUrl', " +"'')"; Db.NonQ(command); } else {//oracle //eCW will never use Oracle. } command="UPDATE preference SET ValueString = '13.1.19.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_1_32(); } private static void To13_1_32() { if(FromVersion<new Version("13.1.32.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 13.1.32"));//No translation in convert script. string command; try { if(DataConnection.DBtype==DatabaseType.MySql) { command="ALTER TABLE medicationpat ADD INDEX (PatNum)"; Db.NonQ(command); } else {//oracle command=@"CREATE INDEX medicationpat_PatNum ON medicationpat (PatNum)"; Db.NonQ(command); } } catch(Exception ex) { }//ex is needed, or exception won't get caught. command="UPDATE preference SET ValueString = '13.1.32.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_1_33(); } private static void To13_1_33() { if(FromVersion<new Version("13.1.33.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 13.1.33"));//No translation in convert script. string command; bool isNewCropEnabled=false; command="SELECT ValueString FROM preference WHERE PrefName='NewCropAccountId'"; if(Db.GetScalar(command)!="") { isNewCropEnabled=true; } //Insert NewCrop Bridge if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO program (ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"'NewCrop'," +"'NewCrop electronic Rx'," +"'"+POut.Bool(isNewCropEnabled)+"',"//The enabled status of the NewCrop bridge is synchronous with the NewCropAccountId preference. If disabled later, then the NewCropAccountId will also be cleared. +"'',"//No program path. +"'',"//No command line, because not program path. +"'NewCrop only works for the United States and its territories, including Puerto Rico. Disable if you are located elsewhere.')"; Db.NonQ(command);//No programproperties, because we only need the Enabled checkbox. } else {//oracle command="INSERT INTO program (ProgramNum,ProgName,ProgDesc,Enabled,Path,CommandLine,Note" +") VALUES(" +"(SELECT MAX(ProgramNum)+1 FROM program)," +"'NewCrop'," +"'NewCrop electronic Rx'," +"'"+POut.Bool(isNewCropEnabled)+"',"//The enabled status of the NewCrop bridge is synchronous with the NewCropAccountId preference. If disabled later, then the NewCropAccountId will also be cleared. +"'',"//No program path. +"'',"//No command line, because not program path. +"'NewCrop only works for the United States and its territories, including Puerto Rico. Disable if you are located elsewhere.')"; Db.NonQ(command);//No programproperties, because we only need the Enabled checkbox. }//end NewCrop bridge command="UPDATE preference SET ValueString = '13.1.33.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_1_38(); } private static void To13_1_38() { if(FromVersion<new Version("13.1.38.0")) { ODEvent.Fire(new ODEventArgs("ConvertDatabases","Upgrading database to version: 13.1.38"));//No translation in convert script. string command; if(DataConnection.DBtype==DatabaseType.MySql) { command="INSERT INTO preference(PrefName,ValueString) VALUES('BillingElectSaveHistory','0')"; Db.NonQ(command); } else {//oracle command="INSERT INTO preference(PrefNum,PrefName,ValueString) VALUES((SELECT MAX(PrefNum)+1 FROM preference),'BillingElectSaveHistory','0')"; Db.NonQ(command); } command="UPDATE preference SET ValueString = '13.1.38.0' WHERE PrefName = 'DataBaseVersion'"; Db.NonQ(command); } To13_2_1(); } } }
gpl-3.0
wyozi/wmc
lua/wmcproviders/twitch.lua
1102
wyozimc.AddProvider({ Name = "Twitch Stream", UrlPatterns = { "^https?://www.twitch.tv/([%a%d]*)", "^https?://twitch.tv/([%a%d]*)", }, QueryMeta = function(udata, callback, failCallback) local channel = udata.Matches[1] local url = string.format("https://api.twitch.tv/kraken/channels/%s", channel) wyozimc.Debug("Fetching Twitch meta for channel " .. channel) http.Fetch(url, function(result, size) if size == 0 then failCallback("HTTP request failed (size = 0)") return end local data = {} data["URL"] = "http://www.twitch.tv/" .. channel local jsontbl = util.JSONToTable(result) if jsontbl then data.Title = jsontbl.display_name .. ": " .. jsontbl.status data.Duration = -1 else data.Title = "ERROR" data.Duration = -1 end callback(data) end) end, PlayInMediaType = function(mtype, play_data) local data = play_data.udata mtype.html:OpenURL(string.format("http://wyozi.github.io/wmc/players/twitch.html?channel=%s", wyozimc.JSEscape(data.Matches[1]))) end, ParseUData = function(udata) end, MediaType = "web", })
gpl-3.0
optimizationBenchmarking/utils-base
src/main/java/org/optimizationBenchmarking/utils/collections/lists/package-info.java
103
/** * Some simple list utilities. */ package org.optimizationBenchmarking.utils.collections.lists;
gpl-3.0
ligovirgo/gwdetchar
gwdetchar/omega/config.py
15875
# coding=utf-8 # Copyright (C) Duncan Macleod (2015) # # This file is part of the GW DetChar python package. # # GW DetChar is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # GW DetChar is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GW DetChar. If not, see <http://www.gnu.org/licenses/>. """ ################################# How to write a configuration file ################################# :mod:`gwdetchar.omega` can be used to process an arbitrary list of channels, including primary gravitational wave strain channels and auxiliary sensors, with arbitrary units and sample rates. Channels can be organized in contextual blocks using an INI-formatted configuration file that must be passed at runtime, which must include processing options for individual blocks. In a given block, the following keywords are supported: Keywords -------- ======================= ====================================================== ``name`` The full name of this channel block, which will appear as a section header on the output page (optional) ``parent`` The `blockkey` of a section that the current block should appear on the output page with (optional) ``q-range`` Range of quality factors (or Q) to search (required) ``frequency-range`` Range of frequencies to search (required) ``resample`` A sample rate (in Hz) to resample the input data to, must be different from the original sample rate (optional) ``frametype`` The type of frame files to read data from (will be superceded by `source`, required if `source` is not specified) ``source`` Path to a LAL-format cache pointing to frame files ``state-flag`` A data quality flag to require to be active before processing this block (can be superceded by passing ``--ignore-state-flags`` on the command-line; optional) ``duration`` The duration of data to process in this block (required) ``fftlength`` The FFT length to use in computing an ASD for whitening with an overlap of `fftlength/2` (required) ``search`` Duration (seconds) of search time window (optional) ``max-mismatch`` The maximum mismatch in time-frequency tiles (optional) ``snr-threshold`` Threshold on SNR for plotting eventgrams (optional) ``dt`` Maximum acceptable time delay from the primary channel (optional) ``always-plot`` Always analyze this block regardless of channel significance (optional; will be superceded by `state-flag` unless `--ignore-state-flags` is passed) ``plot-time-durations`` Time-axis durations of omega scan plots (required) ``channels`` Full list of channels which appear in this block (required) ======================= ====================================================== If cross-correlation will be implemented, the user will also need to specify a block whose blockkey is ``primary`` that includes only one ``channel`` and options for ``f-low`` (a high-pass corner frequency) and ``matched-filter-length``. State flags are always ignored for the primary. An example using many of the above options would look something like this: .. code-block:: ini [primary] ; the primary channel, which will be used as a matched-filter f-low = 4.0 resample = 4096 frametype = L1_HOFT_C00 duration = 64 fftlength = 8 matched-filter-length = 2 channel = L1:GDS-CALIB_STRAIN [GW] ; name of this block, which contains h(t) name = Gravitational Wave Strain q-range = 3.3166,150.0 frequency-range = 4.0,2048 resample = 4096 frametype = L1_HOFT_C00 state-flag = L1:DMT-GRD_ISC_LOCK_NOMINAL:1 duration = 64 fftlength = 8 max-mismatch = 0.2 snr-threshold = 5 always-plot = True plot-time-durations = 1,4,16 channels = L1:GDS-CALIB_STRAIN [CAL] ; a sub-block of channels with different options, but which should appear ; together with the block `GW` on the output page parent = GW q-range = 3.3166,150 frequency-range = 4.0,Inf resample = 4096 frametype = L1_R state-flag = L1:DMT-GRD_ISC_LOCK_NOMINAL:1 duration = 64 fftlength = 8 max-mismatch = 0.35 snr-threshold = 5.5 always-plot = True plot-time-durations = 1,4,16 channels = L1:CAL-DELTAL_EXTERNAL_DQ .. note:: The `blockkey` will appear in the navbar to identify channel blocks on the output page, with a scrollable dropdown list of channels in that block for ease of navigation. The `primary` block will only be used to design a matched-filter. To process this channel during the omega scan, it must be included again in a subsequent block. If running on a LIGO Data Grid (LDG) computer cluster, the `~detchar` account houses default configurations organized by subsystem. """ import sys import ast import os.path import configparser import numpy from gwpy.detector import Channel from .. import const from ..io.html import FancyPlot if sys.version_info < (3, 7): from collections import OrderedDict __author__ = 'Alex Urban <alexander.urban@ligo.org>' __credits__ = 'Duncan Macleod <duncan.macleod@ligo.org>' # -- define parser ------------------------------------------------------------ class OmegaConfigParser(configparser.ConfigParser): """Custom configuration parser for :mod:`gwdetchar.omega` Parameters ---------- ifo : `str`, optional prefix of the interferometer to use, defaults to `None` defaults : `dict`, optional dictionary of default values to pass to the parser, default: ``{}`` **kwargs : `dict`, optional additional keyword arguments to pass to `ConfigParser` Methods ------- read: parse a list of INI-format configuration files get_channel_blocks: retrieve an ordered dictionary of contextual channel blocks, as organized in the source configuration """ def __init__(self, ifo=None, defaults=dict(), **kwargs): if ifo is not None: defaults.setdefault('IFO', ifo) configparser.ConfigParser.__init__(self, defaults=defaults, **kwargs) def read(self, filenames): readok = configparser.ConfigParser.read(self, filenames) for f in filenames: if f not in readok: raise IOError("Cannot read file %r" % f) return readok read.__doc__ = configparser.ConfigParser.read.__doc__ def get_channel_blocks(self): """Retrieve an ordered dictionary of channel blocks These blocks are organized contextually by the user, since they are read in and preserved from the source configuration. """ # retrieve an ordered dictionary of channel blocks if sys.version_info >= (3, 7): # python 3.7+ return {s: OmegaChannelList(s, **self[s]) for s in self.sections()} else: return OrderedDict([(s, OmegaChannelList(s, **dict(self.items(s)))) for s in self.sections()]) # -- utilities ---------------------------------------------------------------- def get_default_configuration(ifo, gpstime): """Retrieve a default configuration file stored locally Parameters ---------- ifo : `str` interferometer ID string, e.g. `'L1'` gpstime : `float` time of analysis in GPS second format """ # find epoch epoch = const.gps_epoch(gpstime, default=const.latest_epoch()) # find and parse configuration file if ifo == 'Network': return [os.path.expanduser( '~detchar/etc/omega/{epoch}/Network.ini'.format(epoch=epoch))] else: return [os.path.expanduser( '~detchar/etc/omega/{epoch}/{obs}-{ifo}_R-selected.ini'.format( epoch=epoch, obs=ifo[0], ifo=ifo))] def get_fancyplots(channel, plottype, duration, caption=None): """Construct FancyPlot objects for output HTML pages Parameters ---------- channel : `str` the name of the channel plottype : `str` the type of plot, e.g. 'raw_timeseries' duration : `str` duration of the plot, in seconds caption : `str`, optional a caption to render in the fancybox """ plotdir = 'plots' chan = channel.replace('-', '_').replace(':', '-') filename = '%s/%s-%s-%s.png' % (plotdir, chan, plottype, duration) if not caption: caption = os.path.basename(filename) return FancyPlot(filename, caption) # -- channel list objects ----------------------------------------------------- class OmegaChannel(Channel): """Customized `Channel` object for omega scan analyses Parameters ---------- channelname : `str` name of this channel, e.g. `L1:GDS-CALIB_STRAIN` section : `str` configuration section to which this channel belongs params : `dict` parameters set in a configuration file """ def __init__(self, channelname, section, **params): self.name = channelname frametype = params.get('frametype', None) super(OmegaChannel, self).__init__( channelname, frametype=frametype) if section != 'primary': self.qrange = tuple( [float(s) for s in params.get('q-range').split(',')]) self.frange = tuple( [float(s) for s in params.get('frequency-range').split(',')]) self.mismatch = float(params.get('max-mismatch', 0.2)) self.snrthresh = float(params.get('snr-threshold', 5.5)) self.always_plot = ast.literal_eval( params.get('always-plot', 'False')) self.pranges = [int(t) for t in params.get('plot-time-durations', None).split(',')] self.plots = {} for plottype in ['timeseries_raw', 'timeseries_highpassed', 'timeseries_whitened', 'qscan_highpassed', 'qscan_whitened', 'qscan_autoscaled', 'eventgram_highpassed', 'eventgram_whitened', 'eventgram_autoscaled']: self.plots[plottype] = [get_fancyplots(self.name, plottype, t) for t in self.pranges] self.section = section self.params = params.copy() def save_loudest_tile_features(self, qgram, correlate=None, gps=0, dt=0.1): """Store properties of the loudest time-frequency tile Parameters ---------- channel : `OmegaChannel` `OmegaChannel` object corresponding to this data stream qgram : `~gwpy.signal.qtransform.QGram` output of a Q-transform on whitened input correlate : `~gwpy.timeseries.TimeSeries`, optional output of a single phase matched-filter, or `None` if not requested gps : `float`, optional GPS time (seconds) of suspected transient, used only if `correlate` is not `None`, default: 0 dt : `float`, optional maximum acceptable time delay (seconds) between the primary and `self`, used only if `correlate` is not `None`, default: 0.1 Notes ----- Attributes stored in-place include `Q`, `energy`, `snr`, `t`, and `f`, all corresponding to the loudest time-frequency tile contained in `qgram`. If `correlate` is not `None` then the maximum correlation amplitude, relative time delay, and standard deviation are stored as attributes `corr`, `delay`, and `stdev`, respectively. """ # save parameters self.Q = numpy.around(qgram.plane.q, 1) self.energy = numpy.around(qgram.peak['energy'], 1) self.snr = numpy.around(qgram.peak['snr'], 1) self.t = numpy.around(qgram.peak['time'], 3) self.f = numpy.around(qgram.peak['frequency'], 1) if correlate is not None: stdev = correlate.std().value corr = correlate.abs().crop(gps - dt, gps + dt) self.corr = numpy.around(corr.max().value, 1) self.stdev = stdev # used to reject high glitch rates delay = (corr.t0 + corr.argmax() * corr.dt).value - gps self.delay = int(delay * 1000) # convert to ms def load_loudest_tile_features(self, table, correlated=False): """Load properties of the loudest time-frequency tile from a table Parameters ---------- table : `~gwpy.table.Table` table of properties of the loudest time-frequency tile correlated : `bool`, optional boolean switch to determine if cross-correlation properties are included, default: `False` Notes ----- Attributes stored in-place include `Q`, `energy`, `snr`, `t`, and `f`, all corresponding to the columns contained in `table`. If `correlated` is not `None` then the maximum correlation amplitude, relative time delay, and standard deviation are stored as attributes `corr`, `delay`, and `stdev`, respectively. """ # save parameters self.Q = table['Q'] self.energy = table['Energy'] self.snr = table['SNR'] self.t = table['Central Time'] self.f = table['Central Frequency (Hz)'] if correlated: self.corr = table['Correlation'] self.stdev = table['Standard Deviation'] self.delay = table['Delay (ms)'] class OmegaChannelList(object): """A conceptual list of `OmegaChannel` objects with common signal processing settings Parameters ---------- key : `str` the unique identifier for this list, e.g. `'CAL'` for calibration channels params : `dict` parameters set in a configuration file """ def __init__(self, key, **params): self.key = key self.parent = params.get('parent', None) self.name = params.get('name', None) self.duration = int(params.get('duration', 32)) self.fftlength = int(params.get('fftlength', 2)) self.resample = int(params.get('resample', 0)) self.source = params.get('source', None) self.frametype = params.get('frametype', None) section = self.parent if self.parent else self.key if key == 'primary': self.length = float(params.get('matched-filter-length')) self.flow = float(params.get('f-low', 4)) channelname = params.get('channel').strip() self.channel = OmegaChannel(channelname, section, **params) else: self.flag = params.get('state-flag', None) self.search = float(params.get('search', 0.5)) self.dt = float(params.get('dt', 0.1)) chans = params.get('channels', None).strip().split('\n') self.channels = [OmegaChannel(c, section, **params) for c in chans] self.params = params.copy()
gpl-3.0
mwolf76/gnuSMV
src/cmd/commands/select_trace.hh
1801
/** * @file SELECT_TRACE.hh * @brief Command-interpreter subsystem related classes and definitions. * * This header file contains the handler interface for the `select-trace` * command. * * Copyright (C) 2012 Marco Pensallorto < marco AT pensallorto DOT gmail DOT com > * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * **/ #ifndef SELECT_TRACE_CMD_H #define SELECT_TRACE_CMD_H #include <cmd/command.hh> #include <witness/witness.hh> namespace cmd { class SelectTrace : public Command { /* the trace id */ pchar f_trace_id; public: void set_trace_id(pconst_char trace_id); inline pconst_char trace_id() const { return f_trace_id; } SelectTrace (Interpreter& owner); virtual ~SelectTrace(); utils::Variant virtual operator()(); }; typedef SelectTrace* SelectTrace_ptr; class SelectTraceTopic : public CommandTopic { public: SelectTraceTopic(Interpreter& owner); virtual ~SelectTraceTopic(); void virtual usage(); }; } // namespace cmd #endif /* SELECT_TRACE_CMD_H */
gpl-3.0
leetmaa/KMCLib
c++/src/matcher.cpp
22062
/* Copyright (c) 2012-2014 Mikael Leetmaa This file is part of the KMCLib project distributed under the terms of the GNU General Public License version 3, see <http://www.gnu.org/licenses/>. */ /*! \file matcher.cpp * \brief File for the implementation code of the Matcher class. */ #include <cstdio> #include <algorithm> #include <cstdlib> #include "matcher.h" #include "matchlist.h" #include "process.h" #include "interactions.h" #include "latticemap.h" #include "configuration.h" #include "latticemap.h" #include "hash.h" #include "mpicommons.h" #include "mpiroutines.h" // ----------------------------------------------------------------------------- // Matcher::Matcher(const size_t & sites, const size_t & processes) : rate_table_(), inverse_table_(sites, std::vector<bool>(processes, false)) { // NOTHING HERE YET } // ----------------------------------------------------------------------------- // void Matcher::calculateMatching(Interactions & interactions, Configuration & configuration, const LatticeMap & lattice_map, const std::vector<int> & indices) { // PERFORMME: What happens in this function is // highly performance critical. // Build the list of indices and processes to match. std::vector<std::pair<int,int> > index_process_to_match; for(size_t i = 0; i < indices.size(); ++i) { // Get the index. const int index = indices[i]; bool use_index = false; // Get the basis site. const int basis_site = lattice_map.basisSiteFromIndex(index); // For each process, check if we should try to match. for (size_t j = 0; j < interactions.processes().size(); ++j) { // Check if the basis site is listed. const std::vector<int> & process_basis_sites = (*interactions.processes()[j]).basisSites(); if ( std::find(process_basis_sites.begin(), process_basis_sites.end(), basis_site) != process_basis_sites.end() ) { // This is a potential match. index_process_to_match.push_back(std::pair<int,int>(index,j)); use_index = true; } } // Update the configuration match list for this index if it will be used. if (use_index) { configuration.updateMatchList(index); } } // Generate the lists of tasks. std::vector<RemoveTask> remove_tasks; std::vector<RateTask> update_tasks; std::vector<RateTask> add_tasks; matchIndicesWithProcesses(index_process_to_match, interactions, configuration, remove_tasks, update_tasks, add_tasks); // Calculate the new rates if needed. if (interactions.useCustomRates()) { // Create a common task list for getting a good load balance. std::vector<RateTask> global_tasks; std::vector<ratekey> global_keys; std::vector<int> global_process_numbers; // Find out which tasks are allready calculated and stored. std::vector<int> add_task_indices; for (size_t i = 0; i < add_tasks.size(); ++i) { // Calculate the key. const Process & process = (*interactions.processes()[add_tasks[i].process]); const int index = add_tasks[i].index; const ratekey key = hashCustomRateInput(index, process, configuration); // Check if the key has a stored value. if (rate_table_.stored(key) != -1) { add_tasks[i].rate = rate_table_.retrieve(key); } else { global_tasks.push_back(add_tasks[i]); global_keys.push_back(key); global_process_numbers.push_back(process.processNumber()); add_task_indices.push_back(i); } } // The same procedure for the update tasks. std::vector<int> update_task_indices; for (size_t i = 0; i < update_tasks.size(); ++i) { // Calculate the key. const Process & process = (*interactions.processes()[update_tasks[i].process]); const int index = update_tasks[i].index; const ratekey key = hashCustomRateInput(index, process, configuration); // Check if the key has a stored value. if (rate_table_.stored(key) != -1) { update_tasks[i].rate = rate_table_.retrieve(key); } else { global_tasks.push_back(update_tasks[i]); global_keys.push_back(key); global_process_numbers.push_back(process.processNumber()); update_task_indices.push_back(i); } } // ------------------------------------------------------------------------ // Here comes the MPI parallelism // ------------------------------------------------------------------------ // Split up the tasks. std::vector<RateTask> local_tasks = splitOverProcesses(global_tasks); std::vector<double> local_tasks_rates(local_tasks.size(), 0.0); // Update in parallel. updateRates(local_tasks_rates, local_tasks, interactions, configuration); // Join the results. const std::vector<double> global_tasks_rates = joinOverProcesses(local_tasks_rates); // ------------------------------------------------------------------------ // Copy the results over to the tasks vectors. for (size_t i = 0; i < add_task_indices.size(); ++i) { const int index = add_task_indices[i]; add_tasks[index].rate = global_tasks_rates[i]; } const size_t offset = add_task_indices.size(); for (size_t i = 0; i < update_task_indices.size(); ++i) { const int index = update_task_indices[i]; update_tasks[index].rate = global_tasks_rates[offset + i]; } // Store the calculated key value pairs. for (size_t i = 0; i < global_tasks_rates.size(); ++i) { // But only if the procees can safely be cached. const int process_number = global_process_numbers[i]; if ((*interactions.processes()[process_number]).cacheRate()) { const ratekey key = global_keys[i]; const double rate = global_tasks_rates[i]; rate_table_.store(key, rate); } } } // Update the processes. updateProcesses(remove_tasks, update_tasks, add_tasks, interactions); // DONE } // ----------------------------------------------------------------------------- // void Matcher::matchIndicesWithProcesses(const std::vector<std::pair<int,int> > & index_process_to_match, const Interactions & interactions, const Configuration & configuration, std::vector<RemoveTask> & remove_tasks, std::vector<RateTask> & update_tasks, std::vector<RateTask> & add_tasks) const { // Setup local variables for running in parallel. std::vector< std::pair<int,int> > local_index_process_to_match = \ splitOverProcesses(index_process_to_match); // These are the local task types to fill with matching restults. const int n_local_tasks = local_index_process_to_match.size(); std::vector<int> local_task_types(n_local_tasks, 0); // Loop over pairs to match. for (size_t i = 0; i < local_index_process_to_match.size(); ++i) { // Get the process and index to match. const int index = local_index_process_to_match[i].first; const int p_idx = local_index_process_to_match[i].second; Process & process = (*interactions.processes()[p_idx]); // Perform the matching. const bool in_list = inverse_table_[index][p_idx]; // ML: const bool is_match = whateverMatch(process.processMatchList(), configuration.configMatchList(index)); // Determine what to do with this pair of processes and indices. if (!is_match && in_list) { // If no match and previous match - remove. local_task_types[i] = 1; } else if (is_match && in_list) { // If match and previous match - update the rate. local_task_types[i] = 2; } else if (is_match && !in_list) { // If match and not previous match - add. local_task_types[i] = 3; } } // Join the result - parallel. const std::vector<int> task_types = joinOverProcesses(local_task_types); // Loop again (not in parallel) and add the tasks to the taks vectors. const size_t n_tasks = index_process_to_match.size(); for (size_t i = 0; i < n_tasks; ++i) { const int index = index_process_to_match[i].first; const int p_idx = index_process_to_match[i].second; const Process & process = (*interactions.processes()[p_idx]); // If no match and previous match - remove. if (task_types[i] == 1) { RemoveTask t; t.index = index; t.process = p_idx; remove_tasks.push_back(t); } else if (task_types[i] == 2 || task_types[i] == 3) { // Get the multiplicity. const double m = multiplicity(process.processMatchList(), configuration.configMatchList(index)); RateTask t; t.index = index; t.process = p_idx; t.rate = process.rateConstant(); t.multiplicity = m; // If match and previous match - update the rate. if (task_types[i] == 2) { update_tasks.push_back(t); } // If match and not previous match - add. else if (task_types[i] == 3) { add_tasks.push_back(t); } } } // DONE } // ----------------------------------------------------------------------------- // bool Matcher::isMatch(const ProcessBucketMatchList & process_match_list, const ConfigBucketMatchList & index_match_list) const { return whateverMatch(process_match_list, index_match_list); /* if (index_match_list.size() < process_match_list.size()) { return false; } // Iterators to the match list entries. ProcessBucketMatchList::const_iterator it1 = process_match_list.begin(); ConfigBucketMatchList::const_iterator it2 = index_match_list.begin(); // Loop over the process match list and compare. for( ; it1 != process_match_list.end(); ++it1, ++it2) { if ((*it1) != (*it2)) { return false; } } // All match, return true. return true; */ } // ----------------------------------------------------------------------------- // void Matcher::printMatchLists(const ProcessBucketMatchList & process_match_list, const ConfigBucketMatchList & index_match_list) const { printf("\n\n PROCESS match list INDEX match list\n"); printf("size %16lu %16lu\n", process_match_list.size(), index_match_list.size()); // Iterators to the match list entries. ProcessBucketMatchList::const_iterator it1 = process_match_list.begin(); ConfigBucketMatchList::const_iterator it2 = index_match_list.begin(); // Loop over the process match list and compare. int step = 0; for( ; it1 != process_match_list.end(); ++it1, ++it2) { printf("%5i:", step); printf(" distance:"); printf("%13f", (*it1).distance); printf("%13f\n", (*it2).distance); printf(" [ "); for (int i = 0; i < (*it1).match_types.size(); ++i) { printf("%i ", (*it1).match_types[i]); } printf(" ]"); printf(" [ "); for (int i = 0; i < (*it2).match_types.size(); ++i) { printf("%i ", (*it2).match_types[i]); } printf(" ]\n"); ++step; if (!(*it1).match(*it2)) { printf("break at step %i\n", step); break; } } } // ----------------------------------------------------------------------------- // void Matcher::printMatchLists(const ConfigBucketMatchList & process_match_list, const ConfigBucketMatchList & index_match_list) const { printf("\n\n PROCESS match list INDEX match list\n"); printf("size %16lu %16lu\n", process_match_list.size(), index_match_list.size()); // Iterators to the match list entries. ConfigBucketMatchList::const_iterator it1 = process_match_list.begin(); ConfigBucketMatchList::const_iterator it2 = index_match_list.begin(); // Loop over the process match list and compare. int step = 0; for( ; it1 != process_match_list.end(); ++it1, ++it2) { printf("%5i:", step); printf(" distance:"); printf("%13f", (*it1).distance); printf("%13f\n", (*it2).distance); printf(" [ "); for (int i = 0; i < (*it1).match_types.size(); ++i) { printf("%i ", (*it1).match_types[i]); } printf(" ]"); printf(" [ "); for (int i = 0; i < (*it2).match_types.size(); ++i) { printf("%i ", (*it2).match_types[i]); } printf(" ]\n"); ++step; } } // ----------------------------------------------------------------------------- // void Matcher::printMatchList(const ConfigBucketMatchList & index_match_list) const { printf("\n\n INDEX match list\n"); printf("size %16lu\n", index_match_list.size()); // Iterators to the match list entries. ConfigBucketMatchList::const_iterator it2 = index_match_list.begin(); // Loop over the process match list and compare. int step = 0; for( ; it2 != index_match_list.end(); ++it2) { printf("%5i:", step); printf(" distance:"); printf("%13f\n", (*it2).distance); printf(" [ "); for (int i = 0; i < (*it2).match_types.size(); ++i) { printf("%i ", (*it2).match_types[i]); } printf(" ]\n"); ++step; } } // ----------------------------------------------------------------------------- // void Matcher::updateProcesses(const std::vector<RemoveTask> & remove_tasks, const std::vector<RateTask> & update_tasks, const std::vector<RateTask> & add_tasks, Interactions & interactions) { // This could perhaps be OpenMP parallelized. // Remove. for (size_t i = 0; i < remove_tasks.size(); ++i) { const int index = remove_tasks[i].index; const int p_idx = remove_tasks[i].process; interactions.processes()[p_idx]->removeSite(index); inverse_table_[index][p_idx] = false; } // Update. for (size_t i = 0; i < update_tasks.size(); ++i) { const int index = update_tasks[i].index; const int p_idx = update_tasks[i].process; const double rate = update_tasks[i].rate; interactions.processes()[p_idx]->removeSite(index); interactions.processes()[p_idx]->addSite(index, rate); } // Add. for (size_t i = 0; i < add_tasks.size(); ++i) { const int index = add_tasks[i].index; const int p_idx = add_tasks[i].process; const double rate = add_tasks[i].rate; interactions.processes()[p_idx]->addSite(index, rate); inverse_table_[index][p_idx] = true; } } // ----------------------------------------------------------------------------- // void Matcher::updateRates(std::vector<double> & new_rates, const std::vector<RateTask> & tasks, const Interactions & interactions, const Configuration & configuration) { // Use the backendCallBack function on the RateCalculator stored on the // interactions object, to get an updated rate for each process. const RateCalculator & rate_calculator = interactions.rateCalculator(); for (size_t i = 0; i < tasks.size(); ++i) { // Get the rate process to use. const Process & process = (*interactions.processes()[tasks[i].process]); // Get the coordinate index. const int index = tasks[i].index; // Calculate the new rate. new_rates[i] = updateSingleRate(index, process, configuration, rate_calculator); } } // ----------------------------------------------------------------------------- // double Matcher::updateSingleRate(const int index, const Process & process, const Configuration & configuration, const RateCalculator & rate_calculator) const { // Get the match lists. const ProcessBucketMatchList & process_match_list = process.processMatchList(); const ConfigBucketMatchList & config_match_list = configuration.configMatchList(index); // We will also need the elements. const std::vector<std::vector<std::string> > & elements = configuration.elements(); const std::vector<TypeBucket> & types = configuration.types(); // Get cutoff distance from the process. const double cutoff = process.cutoff(); ConfigBucketMatchList::const_iterator it1 = config_match_list.begin(); int len = 0; while ( (*it1).distance <= cutoff && it1 != config_match_list.end()) { ++it1; ++len; } const size_t distance = it1 - config_match_list.begin(); // Allocate memory for the numpy geometry and copy the data over. std::vector<double> numpy_geo(len*3); std::vector<std::string> types_before(distance); std::vector<TypeBucket> occupations(distance); for (size_t i = 0; i < distance; ++i) { const Coordinate coord(config_match_list[i].x, config_match_list[i].y, config_match_list[i].z); numpy_geo[3*i] = coord.x(); numpy_geo[3*i+1] = coord.y(); numpy_geo[3*i+2] = coord.z(); const int idx = config_match_list[i].index; types_before[i] = elements[idx][0]; occupations[i] = types[idx]; } // Types after the process. std::vector<std::string> types_after = types_before; std::vector<TypeBucket> update(len, TypeBucket(occupations[0].size())); // Loop over the process match list and update the types_after vector. for (size_t i = 0; i < process_match_list.size(); ++i) { const TypeBucket & update_types = process_match_list[i].update_types; // Save the update types in the full update vector. update[i] = update_types; // PERFORMME: This should be handeled more efficiently. // Check that the update type is not 'zero'. int sum = 0; for (int j = 0; j < update_types.size(); ++j) { sum += std::abs(update_types[j]); } if ( sum != 0 && !(update_types == 0) ) { // For non-buckets only. for (int j = 0; j < update_types.size(); ++j) { // Taking the first only. if (update_types[j] == 1) { types_after[i] = configuration.typeName(j); break; } } } } // Calculate the rate using the provided rate calculator. const double rate_constant = process.rateConstant(); const int process_number = process.processNumber(); const double global_x = configuration.coordinates()[index].x(); const double global_y = configuration.coordinates()[index].y(); const double global_z = configuration.coordinates()[index].z(); // Determine if we should use the buckets interface or not. if (!process.bucketProcess()) { return rate_calculator.backendRateCallback(numpy_geo, len, types_before, types_after, rate_constant, process_number, global_x, global_y, global_z); } else { return rate_calculator.backendRateCallbackBuckets(numpy_geo, len, occupations, update, configuration.typeNames(), rate_constant, process_number, global_x, global_y, global_z); } }
gpl-3.0
OsirisSPS/osiris-sps
client/src/plugins/python/wrappers/ixmlserializable.pypp.hpp
231
// This file has been generated by Py++. #ifndef IXMLSerializable_hpp__pyplusplus_wrapper #define IXMLSerializable_hpp__pyplusplus_wrapper void register_IXMLSerializable_class(); #endif//IXMLSerializable_hpp__pyplusplus_wrapper
gpl-3.0
hyperized/ansible
test/units/galaxy/test_collection_install.py
31437
# -*- coding: utf-8 -*- # Copyright: (c) 2019, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import copy import json import os import pytest import re import shutil import tarfile import yaml from io import BytesIO, StringIO from units.compat.mock import MagicMock import ansible.module_utils.six.moves.urllib.error as urllib_error from ansible import context from ansible.cli.galaxy import GalaxyCLI from ansible.errors import AnsibleError from ansible.galaxy import collection, api from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.utils import context_objects as co from ansible.utils.display import Display def call_galaxy_cli(args): orig = co.GlobalCLIArgs._Singleton__instance co.GlobalCLIArgs._Singleton__instance = None try: GalaxyCLI(args=['ansible-galaxy', 'collection'] + args).run() finally: co.GlobalCLIArgs._Singleton__instance = orig def artifact_json(namespace, name, version, dependencies, server): json_str = json.dumps({ 'artifact': { 'filename': '%s-%s-%s.tar.gz' % (namespace, name, version), 'sha256': '2d76f3b8c4bab1072848107fb3914c345f71a12a1722f25c08f5d3f51f4ab5fd', 'size': 1234, }, 'download_url': '%s/download/%s-%s-%s.tar.gz' % (server, namespace, name, version), 'metadata': { 'namespace': namespace, 'name': name, 'dependencies': dependencies, }, 'version': version }) return to_text(json_str) def artifact_versions_json(namespace, name, versions, galaxy_api, available_api_versions=None): results = [] available_api_versions = available_api_versions or {} api_version = 'v2' if 'v3' in available_api_versions: api_version = 'v3' for version in versions: results.append({ 'href': '%s/api/%s/%s/%s/versions/%s/' % (galaxy_api.api_server, api_version, namespace, name, version), 'version': version, }) if api_version == 'v2': json_str = json.dumps({ 'count': len(versions), 'next': None, 'previous': None, 'results': results }) if api_version == 'v3': response = {'meta': {'count': len(versions)}, 'data': results, 'links': {'first': None, 'last': None, 'next': None, 'previous': None}, } json_str = json.dumps(response) return to_text(json_str) def error_json(galaxy_api, errors_to_return=None, available_api_versions=None): errors_to_return = errors_to_return or [] available_api_versions = available_api_versions or {} response = {} api_version = 'v2' if 'v3' in available_api_versions: api_version = 'v3' if api_version == 'v2': assert len(errors_to_return) <= 1 if errors_to_return: response = errors_to_return[0] if api_version == 'v3': response['errors'] = errors_to_return json_str = json.dumps(response) return to_text(json_str) @pytest.fixture(autouse='function') def reset_cli_args(): co.GlobalCLIArgs._Singleton__instance = None yield co.GlobalCLIArgs._Singleton__instance = None @pytest.fixture() def collection_artifact(request, tmp_path_factory): test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input')) namespace = 'ansible_namespace' collection = 'collection' skeleton_path = os.path.join(os.path.dirname(os.path.split(__file__)[0]), 'cli', 'test_data', 'collection_skeleton') collection_path = os.path.join(test_dir, namespace, collection) call_galaxy_cli(['init', '%s.%s' % (namespace, collection), '-c', '--init-path', test_dir, '--collection-skeleton', skeleton_path]) dependencies = getattr(request, 'param', None) if dependencies: galaxy_yml = os.path.join(collection_path, 'galaxy.yml') with open(galaxy_yml, 'rb+') as galaxy_obj: existing_yaml = yaml.safe_load(galaxy_obj) existing_yaml['dependencies'] = dependencies galaxy_obj.seek(0) galaxy_obj.write(to_bytes(yaml.safe_dump(existing_yaml))) galaxy_obj.truncate() call_galaxy_cli(['build', collection_path, '--output-path', test_dir]) collection_tar = os.path.join(test_dir, '%s-%s-0.1.0.tar.gz' % (namespace, collection)) return to_bytes(collection_path), to_bytes(collection_tar) @pytest.fixture() def galaxy_server(): context.CLIARGS._store = {'ignore_certs': False} galaxy_api = api.GalaxyAPI(None, 'test_server', 'https://galaxy.ansible.com') return galaxy_api def test_build_requirement_from_path(collection_artifact): actual = collection.CollectionRequirement.from_path(collection_artifact[0], True) assert actual.namespace == u'ansible_namespace' assert actual.name == u'collection' assert actual.b_path == collection_artifact[0] assert actual.api is None assert actual.skip is True assert actual.versions == set([u'*']) assert actual.latest_version == u'*' assert actual.dependencies == {} def test_build_requirement_from_path_with_manifest(collection_artifact): manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json') manifest_value = json.dumps({ 'collection_info': { 'namespace': 'namespace', 'name': 'name', 'version': '1.1.1', 'dependencies': { 'ansible_namespace.collection': '*' } } }) with open(manifest_path, 'wb') as manifest_obj: manifest_obj.write(to_bytes(manifest_value)) actual = collection.CollectionRequirement.from_path(collection_artifact[0], True) # While the folder name suggests a different collection, we treat MANIFEST.json as the source of truth. assert actual.namespace == u'namespace' assert actual.name == u'name' assert actual.b_path == collection_artifact[0] assert actual.api is None assert actual.skip is True assert actual.versions == set([u'1.1.1']) assert actual.latest_version == u'1.1.1' assert actual.dependencies == {'ansible_namespace.collection': '*'} def test_build_requirement_from_path_invalid_manifest(collection_artifact): manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json') with open(manifest_path, 'wb') as manifest_obj: manifest_obj.write(b"not json") expected = "Collection file at '%s' does not contain a valid json string." % to_native(manifest_path) with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement.from_path(collection_artifact[0], True) def test_build_requirement_from_tar(collection_artifact): actual = collection.CollectionRequirement.from_tar(collection_artifact[1], True, True) assert actual.namespace == u'ansible_namespace' assert actual.name == u'collection' assert actual.b_path == collection_artifact[1] assert actual.api is None assert actual.skip is False assert actual.versions == set([u'0.1.0']) assert actual.latest_version == u'0.1.0' assert actual.dependencies == {} def test_build_requirement_from_tar_fail_not_tar(tmp_path_factory): test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input')) test_file = os.path.join(test_dir, b'fake.tar.gz') with open(test_file, 'wb') as test_obj: test_obj.write(b"\x00\x01\x02\x03") expected = "Collection artifact at '%s' is not a valid tar file." % to_native(test_file) with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement.from_tar(test_file, True, True) def test_build_requirement_from_tar_no_manifest(tmp_path_factory): test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input')) json_data = to_bytes(json.dumps( { 'files': [], 'format': 1, } )) tar_path = os.path.join(test_dir, b'ansible-collections.tar.gz') with tarfile.open(tar_path, 'w:gz') as tfile: b_io = BytesIO(json_data) tar_info = tarfile.TarInfo('FILES.json') tar_info.size = len(json_data) tar_info.mode = 0o0644 tfile.addfile(tarinfo=tar_info, fileobj=b_io) expected = "Collection at '%s' does not contain the required file MANIFEST.json." % to_native(tar_path) with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement.from_tar(tar_path, True, True) def test_build_requirement_from_tar_no_files(tmp_path_factory): test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input')) json_data = to_bytes(json.dumps( { 'collection_info': {}, } )) tar_path = os.path.join(test_dir, b'ansible-collections.tar.gz') with tarfile.open(tar_path, 'w:gz') as tfile: b_io = BytesIO(json_data) tar_info = tarfile.TarInfo('MANIFEST.json') tar_info.size = len(json_data) tar_info.mode = 0o0644 tfile.addfile(tarinfo=tar_info, fileobj=b_io) expected = "Collection at '%s' does not contain the required file FILES.json." % to_native(tar_path) with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement.from_tar(tar_path, True, True) def test_build_requirement_from_tar_invalid_manifest(tmp_path_factory): test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input')) json_data = b"not a json" tar_path = os.path.join(test_dir, b'ansible-collections.tar.gz') with tarfile.open(tar_path, 'w:gz') as tfile: b_io = BytesIO(json_data) tar_info = tarfile.TarInfo('MANIFEST.json') tar_info.size = len(json_data) tar_info.mode = 0o0644 tfile.addfile(tarinfo=tar_info, fileobj=b_io) expected = "Collection tar file member MANIFEST.json does not contain a valid json string." with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement.from_tar(tar_path, True, True) def test_build_requirement_from_name(galaxy_server, monkeypatch): mock_get_versions = MagicMock() mock_get_versions.return_value = ['2.1.9', '2.1.10'] monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions) actual = collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server], '*', True, True) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.b_path is None assert actual.api == galaxy_server assert actual.skip is False assert actual.versions == set([u'2.1.9', u'2.1.10']) assert actual.latest_version == u'2.1.10' assert actual.dependencies is None assert mock_get_versions.call_count == 1 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection') def test_build_requirement_from_name_with_prerelease(galaxy_server, monkeypatch): mock_get_versions = MagicMock() mock_get_versions.return_value = ['1.0.1', '2.0.1-beta.1', '2.0.1'] monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions) actual = collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server], '*', True, True) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.b_path is None assert actual.api == galaxy_server assert actual.skip is False assert actual.versions == set([u'1.0.1', u'2.0.1']) assert actual.latest_version == u'2.0.1' assert actual.dependencies is None assert mock_get_versions.call_count == 1 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection') def test_build_requirment_from_name_with_prerelease_explicit(galaxy_server, monkeypatch): mock_get_info = MagicMock() mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.1-beta.1', None, None, {}) monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info) actual = collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server], '2.0.1-beta.1', True, True) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.b_path is None assert actual.api == galaxy_server assert actual.skip is False assert actual.versions == set([u'2.0.1-beta.1']) assert actual.latest_version == u'2.0.1-beta.1' assert actual.dependencies == {} assert mock_get_info.call_count == 1 assert mock_get_info.mock_calls[0][1] == ('namespace', 'collection', '2.0.1-beta.1') def test_build_requirement_from_name_second_server(galaxy_server, monkeypatch): mock_get_versions = MagicMock() mock_get_versions.return_value = ['1.0.1', '1.0.2', '1.0.3'] monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions) broken_server = copy.copy(galaxy_server) broken_server.api_server = 'https://broken.com/' mock_404 = MagicMock() mock_404.side_effect = api.GalaxyError(urllib_error.HTTPError('https://galaxy.server.com', 404, 'msg', {}, StringIO()), "custom msg") monkeypatch.setattr(broken_server, 'get_collection_versions', mock_404) actual = collection.CollectionRequirement.from_name('namespace.collection', [broken_server, galaxy_server], '>1.0.1', False, True) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.b_path is None # assert actual.api == galaxy_server assert actual.skip is False assert actual.versions == set([u'1.0.2', u'1.0.3']) assert actual.latest_version == u'1.0.3' assert actual.dependencies is None assert mock_404.call_count == 1 assert mock_404.mock_calls[0][1] == ('namespace', 'collection') assert mock_get_versions.call_count == 1 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection') def test_build_requirement_from_name_missing(galaxy_server, monkeypatch): mock_open = MagicMock() mock_open.side_effect = api.GalaxyError(urllib_error.HTTPError('https://galaxy.server.com', 404, 'msg', {}, StringIO()), "") monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_open) expected = "Failed to find collection namespace.collection:*" with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server, galaxy_server], '*', False, True) def test_build_requirement_from_name_401_unauthorized(galaxy_server, monkeypatch): mock_open = MagicMock() mock_open.side_effect = api.GalaxyError(urllib_error.HTTPError('https://galaxy.server.com', 401, 'msg', {}, StringIO()), "error") monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_open) expected = "error (HTTP Code: 401, Message: Unknown error returned by Galaxy server.)" with pytest.raises(api.GalaxyError, match=re.escape(expected)): collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server, galaxy_server], '*', False) def test_build_requirement_from_name_single_version(galaxy_server, monkeypatch): mock_get_info = MagicMock() mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.0', None, None, {}) monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info) actual = collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server], '2.0.0', True, True) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.b_path is None assert actual.api == galaxy_server assert actual.skip is False assert actual.versions == set([u'2.0.0']) assert actual.latest_version == u'2.0.0' assert actual.dependencies == {} assert mock_get_info.call_count == 1 assert mock_get_info.mock_calls[0][1] == ('namespace', 'collection', '2.0.0') def test_build_requirement_from_name_multiple_versions_one_match(galaxy_server, monkeypatch): mock_get_versions = MagicMock() mock_get_versions.return_value = ['2.0.0', '2.0.1', '2.0.2'] monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions) mock_get_info = MagicMock() mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.1', None, None, {}) monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info) actual = collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server], '>=2.0.1,<2.0.2', True, True) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.b_path is None assert actual.api == galaxy_server assert actual.skip is False assert actual.versions == set([u'2.0.1']) assert actual.latest_version == u'2.0.1' assert actual.dependencies == {} assert mock_get_versions.call_count == 1 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection') assert mock_get_info.call_count == 1 assert mock_get_info.mock_calls[0][1] == ('namespace', 'collection', '2.0.1') def test_build_requirement_from_name_multiple_version_results(galaxy_server, monkeypatch): mock_get_versions = MagicMock() mock_get_versions.return_value = ['2.0.0', '2.0.1', '2.0.2', '2.0.3', '2.0.4', '2.0.5'] monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions) actual = collection.CollectionRequirement.from_name('namespace.collection', [galaxy_server], '!=2.0.2', True, True) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.b_path is None assert actual.api == galaxy_server assert actual.skip is False assert actual.versions == set([u'2.0.0', u'2.0.1', u'2.0.3', u'2.0.4', u'2.0.5']) assert actual.latest_version == u'2.0.5' assert actual.dependencies is None assert mock_get_versions.call_count == 1 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection') @pytest.mark.parametrize('versions, requirement, expected_filter, expected_latest', [ [['1.0.0', '1.0.1'], '*', ['1.0.0', '1.0.1'], '1.0.1'], [['1.0.0', '1.0.5', '1.1.0'], '>1.0.0,<1.1.0', ['1.0.5'], '1.0.5'], [['1.0.0', '1.0.5', '1.1.0'], '>1.0.0,<=1.0.5', ['1.0.5'], '1.0.5'], [['1.0.0', '1.0.5', '1.1.0'], '>=1.1.0', ['1.1.0'], '1.1.0'], [['1.0.0', '1.0.5', '1.1.0'], '!=1.1.0', ['1.0.0', '1.0.5'], '1.0.5'], [['1.0.0', '1.0.5', '1.1.0'], '==1.0.5', ['1.0.5'], '1.0.5'], [['1.0.0', '1.0.5', '1.1.0'], '1.0.5', ['1.0.5'], '1.0.5'], [['1.0.0', '2.0.0', '3.0.0'], '>=2', ['2.0.0', '3.0.0'], '3.0.0'], ]) def test_add_collection_requirements(versions, requirement, expected_filter, expected_latest): req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', versions, requirement, False) assert req.versions == set(expected_filter) assert req.latest_version == expected_latest def test_add_collection_requirement_to_unknown_installed_version(): req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False, skip=True) expected = "Cannot meet requirement namespace.name:1.0.0 as it is already installed at version 'unknown'." with pytest.raises(AnsibleError, match=expected): req.add_requirement(str(req), '1.0.0') def test_add_collection_wildcard_requirement_to_unknown_installed_version(): req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False, skip=True) req.add_requirement(str(req), '*') assert req.versions == set('*') assert req.latest_version == '*' def test_add_collection_requirement_with_conflict(galaxy_server): expected = "Cannot meet requirement ==1.0.2 for dependency namespace.name from source '%s'. Available versions " \ "before last requirement added: 1.0.0, 1.0.1\n" \ "Requirements from:\n" \ "\tbase - 'namespace.name:==1.0.2'" % galaxy_server.api_server with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement('namespace', 'name', None, galaxy_server, ['1.0.0', '1.0.1'], '==1.0.2', False) def test_add_requirement_to_existing_collection_with_conflict(galaxy_server): req = collection.CollectionRequirement('namespace', 'name', None, galaxy_server, ['1.0.0', '1.0.1'], '*', False) expected = "Cannot meet dependency requirement 'namespace.name:1.0.2' for collection namespace.collection2 from " \ "source '%s'. Available versions before last requirement added: 1.0.0, 1.0.1\n" \ "Requirements from:\n" \ "\tbase - 'namespace.name:*'\n" \ "\tnamespace.collection2 - 'namespace.name:1.0.2'" % galaxy_server.api_server with pytest.raises(AnsibleError, match=re.escape(expected)): req.add_requirement('namespace.collection2', '1.0.2') def test_add_requirement_to_installed_collection_with_conflict(): source = 'https://galaxy.ansible.com' req = collection.CollectionRequirement('namespace', 'name', None, source, ['1.0.0', '1.0.1'], '*', False, skip=True) expected = "Cannot meet requirement namespace.name:1.0.2 as it is already installed at version '1.0.1'. " \ "Use --force to overwrite" with pytest.raises(AnsibleError, match=re.escape(expected)): req.add_requirement(None, '1.0.2') def test_add_requirement_to_installed_collection_with_conflict_as_dep(): source = 'https://galaxy.ansible.com' req = collection.CollectionRequirement('namespace', 'name', None, source, ['1.0.0', '1.0.1'], '*', False, skip=True) expected = "Cannot meet requirement namespace.name:1.0.2 as it is already installed at version '1.0.1'. " \ "Use --force-with-deps to overwrite" with pytest.raises(AnsibleError, match=re.escape(expected)): req.add_requirement('namespace.collection2', '1.0.2') def test_install_skipped_collection(monkeypatch): mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) req = collection.CollectionRequirement('namespace', 'name', None, 'source', ['1.0.0'], '*', False, skip=True) req.install(None, None) assert mock_display.call_count == 1 assert mock_display.mock_calls[0][1][0] == "Skipping 'namespace.name' as it is already installed" def test_install_collection(collection_artifact, monkeypatch): mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) collection_tar = collection_artifact[1] output_path = os.path.join(os.path.split(collection_tar)[0], b'output') collection_path = os.path.join(output_path, b'ansible_namespace', b'collection') os.makedirs(os.path.join(collection_path, b'delete_me')) # Create a folder to verify the install cleans out the dir temp_path = os.path.join(os.path.split(collection_tar)[0], b'temp') os.makedirs(temp_path) req = collection.CollectionRequirement.from_tar(collection_tar, True, True) req.install(to_text(output_path), temp_path) # Ensure the temp directory is empty, nothing is left behind assert os.listdir(temp_path) == [] actual_files = os.listdir(collection_path) actual_files.sort() assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles'] assert mock_display.call_count == 1 assert mock_display.mock_calls[0][1][0] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" \ % to_text(collection_path) def test_install_collection_with_download(galaxy_server, collection_artifact, monkeypatch): collection_tar = collection_artifact[1] output_path = os.path.join(os.path.split(collection_tar)[0], b'output') collection_path = os.path.join(output_path, b'ansible_namespace', b'collection') mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) mock_download = MagicMock() mock_download.return_value = collection_tar monkeypatch.setattr(collection, '_download_file', mock_download) temp_path = os.path.join(os.path.split(collection_tar)[0], b'temp') os.makedirs(temp_path) meta = api.CollectionVersionMetadata('ansible_namespace', 'collection', '0.1.0', 'https://downloadme.com', 'myhash', {}) req = collection.CollectionRequirement('ansible_namespace', 'collection', None, galaxy_server, ['0.1.0'], '*', False, metadata=meta) req.install(to_text(output_path), temp_path) # Ensure the temp directory is empty, nothing is left behind assert os.listdir(temp_path) == [] actual_files = os.listdir(collection_path) actual_files.sort() assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles'] assert mock_display.call_count == 1 assert mock_display.mock_calls[0][1][0] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" \ % to_text(collection_path) assert mock_download.call_count == 1 assert mock_download.mock_calls[0][1][0] == 'https://downloadme.com' assert mock_download.mock_calls[0][1][1] == temp_path assert mock_download.mock_calls[0][1][2] == 'myhash' assert mock_download.mock_calls[0][1][3] is True def test_install_collections_from_tar(collection_artifact, monkeypatch): collection_path, collection_tar = collection_artifact temp_path = os.path.split(collection_tar)[0] shutil.rmtree(collection_path) mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) collection.install_collections([(to_text(collection_tar), '*', None,)], to_text(temp_path), [u'https://galaxy.ansible.com'], True, False, False, False, False) assert os.path.isdir(collection_path) actual_files = os.listdir(collection_path) actual_files.sort() assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles'] with open(os.path.join(collection_path, b'MANIFEST.json'), 'rb') as manifest_obj: actual_manifest = json.loads(to_text(manifest_obj.read())) assert actual_manifest['collection_info']['namespace'] == 'ansible_namespace' assert actual_manifest['collection_info']['name'] == 'collection' assert actual_manifest['collection_info']['version'] == '0.1.0' # Filter out the progress cursor display calls. display_msgs = [m[1][0] for m in mock_display.mock_calls if 'newline' not in m[2]] assert len(display_msgs) == 3 assert display_msgs[0] == "Process install dependency map" assert display_msgs[1] == "Starting collection install process" assert display_msgs[2] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" % to_text(collection_path) def test_install_collections_existing_without_force(collection_artifact, monkeypatch): collection_path, collection_tar = collection_artifact temp_path = os.path.split(collection_tar)[0] mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) # If we don't delete collection_path it will think the original build skeleton is installed so we expect a skip collection.install_collections([(to_text(collection_tar), '*', None,)], to_text(temp_path), [u'https://galaxy.ansible.com'], True, False, False, False, False) assert os.path.isdir(collection_path) actual_files = os.listdir(collection_path) actual_files.sort() assert actual_files == [b'README.md', b'docs', b'galaxy.yml', b'playbooks', b'plugins', b'roles'] # Filter out the progress cursor display calls. display_msgs = [m[1][0] for m in mock_display.mock_calls if 'newline' not in m[2]] assert len(display_msgs) == 4 # Msg1 is the warning about not MANIFEST.json, cannot really check message as it has line breaks which varies based # on the path size assert display_msgs[1] == "Process install dependency map" assert display_msgs[2] == "Starting collection install process" assert display_msgs[3] == "Skipping 'ansible_namespace.collection' as it is already installed" # Makes sure we don't get stuck in some recursive loop @pytest.mark.parametrize('collection_artifact', [ {'ansible_namespace.collection': '>=0.0.1'}, ], indirect=True) def test_install_collection_with_circular_dependency(collection_artifact, monkeypatch): collection_path, collection_tar = collection_artifact temp_path = os.path.split(collection_tar)[0] shutil.rmtree(collection_path) mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) collection.install_collections([(to_text(collection_tar), '*', None,)], to_text(temp_path), [u'https://galaxy.ansible.com'], True, False, False, False, False) assert os.path.isdir(collection_path) actual_files = os.listdir(collection_path) actual_files.sort() assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles'] with open(os.path.join(collection_path, b'MANIFEST.json'), 'rb') as manifest_obj: actual_manifest = json.loads(to_text(manifest_obj.read())) assert actual_manifest['collection_info']['namespace'] == 'ansible_namespace' assert actual_manifest['collection_info']['name'] == 'collection' assert actual_manifest['collection_info']['version'] == '0.1.0' # Filter out the progress cursor display calls. display_msgs = [m[1][0] for m in mock_display.mock_calls if 'newline' not in m[2]] assert len(display_msgs) == 3 assert display_msgs[0] == "Process install dependency map" assert display_msgs[1] == "Starting collection install process" assert display_msgs[2] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" % to_text(collection_path)
gpl-3.0
ivanamihalek/tcga
icgc/icgc_utils/mysql.py
10309
import MySQLdb, sys, os # # This source code is part of icgc, an ICGC processing pipeline. # # Icgc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Icgc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see<http://www.gnu.org/licenses/>. # # Contact: ivana.mihalek@gmail.com # ######## def set_autoincrement(cursor, db_name, table_name, column): # what should be the next value for column qry = "select max({}) from {}.{}".format(column, db_name, table_name) new_column_value = 1 ret = search_db (cursor, qry, verbose=False) if ret and ret[0][0]: new_column_value += ret[0][0] qry = "alter table {}.{} set auto_increment={}".format(db_name, table_name, new_column_value) search_db (cursor, qry, verbose=False) qry = "alter table {}.{} modify column {} int not null auto_increment".format(db_name, table_name, column) rows = search_db (cursor, qry, verbose=False) if (rows): print(rows) exit() ######## def check_null (variable): if variable is None: return None if (type(variable) is str and variable=="None"): return None return variable ######## def switch_to_db (cursor, db_name): qry = "use %s" % db_name rows = search_db (cursor, qry, verbose=False) if (rows): print(rows) return False return True ######## def get_table_size(cursor, db_name, tables, as_list = False): table_size = [] if as_list else {} for table in tables: qry = "select count(1) from %s.%s" % (db_name,table) ret = search_db (cursor, qry, verbose=True) size = 0 if ret and ret[0] and type(ret[0][0])==int: size = ret[0][0] if as_list: table_size.append(size) else: table_size[table] = size return table_size ######## def val2mysqlval(value): if value is None: return "null " elif type(value) is str: return "\'%s\'" % value return "{}".format(value) ######## def store_without_checking(cursor, table, fields, verbose=False, database=None, ignore=False): qry = "insert " # if we use INSERT IGNORE, the duplication attempt is ignored if ignore: qry += "ignore " qry += "%s.%s "%(database,table) if database else "%s "%table qry += "(" qry += ",".join(fields.keys()) qry += ")" qry += " values " qry += "(" qry += ",".join([val2mysqlval(v) for v in fields.values()]) qry += ")" rows = search_db (cursor, qry, verbose) if verbose: print("qry:",qry,"\n", "rows:", rows) if rows: rows = search_db (cursor, qry, verbose=True) print(rows) return -1 rows = search_db (cursor, "select last_insert_id()" ) try: row_id = int(rows[0][0]) except: row_id = -1 return row_id ######## def store_or_update (cursor, table, fixed_fields, update_fields, verbose=False, primary_key='id'): conditions = " and ".join(["{}={}".format(k,val2mysqlval(v)) for k,v in fixed_fields.items()]) # check if the row exists qry = "select %s from %s where %s " % (primary_key, table, conditions) rows = search_db (cursor, qry, verbose) exists = rows and (type(rows[0][0]) is int) row_id = -1 if exists: row_id = rows[0][0] if verbose: print("\n".join(["", qry, "exists? {}".format(exists), str(row_id)])) if exists and not update_fields: return row_id if exists: # if it exists, update if verbose: print("exists; updating") qry = "update %s set " % table qry += ",".join(["{}={}".format(k,val2mysqlval(v)) for k,v in update_fields.items()]) qry += " where %s " % conditions else: # if not, make a new one if verbose: print("does not exist; making new one") qry = "insert into %s " % table keys = list(fixed_fields.keys()) vals = list(fixed_fields.values()) if update_fields: keys += list(update_fields.keys()) vals += list(update_fields.values()) qry += "(" + ",".join(keys) + ")" qry += " values " qry += "(" + ",".join([val2mysqlval(v) for v in vals]) + ")" rows = search_db (cursor, qry, verbose) if verbose: print("qry:",qry,"\n", "rows:", rows) # if there is a return, it is an error msg if rows: rows = search_db (cursor, qry, verbose=True) print(rows[0]) return -1 if row_id==-1: rows = search_db (cursor, "select last_insert_id()" ) try: row_id = int(rows[0][0]) except: row_id = -1 return row_id ######################################### def create_index (cursor, db_name, index_name, table, columns, verbose=False): if not switch_to_db (cursor, db_name): return False # check whether this index exists already qry = "show index from %s where key_name like '%s'" % ( table, index_name) rows = error_intolerant_search(cursor, qry) if (rows):return True # columns is a list of columns that we want to have indexed qry = "create index %s on %s (%s)" % (index_name, table, ",".join(columns)) rows = error_intolerant_search(cursor, qry) if (rows): return False return True ######################################### def get_column_names (cursor, db_name, table_name): qry = "select c.column_name from information_schema.columns c " qry += "where c.table_schema='%s' and c.table_name='%s'" % (db_name, table_name) rows = search_db (cursor, qry, verbose=False) if (rows): if ( 'Error' in rows[0]): rows = search_db (cursor, qry, verbose=True) return False else: return [row[0] for row in rows] else: return False ######################################### def column_exists (cursor, db_name, table_name, column_name): if not switch_to_db (cursor, db_name): return False qry = "show columns from "+ table_name + " like '%s'" % column_name rows = search_db (cursor, qry, verbose=False) if (rows): if ( 'Error' in rows[0]): return False else: return True else: return False ######################################### def add_column(cursor, db_name, table_name, column_name, col_type, default=None, after_col=None): if not column_exists (cursor, db_name, table_name, column_name): qry = "alter table %s.%s add %s %s " %(db_name, table_name, column_name, col_type) if default: qry += "default %s " % default if after_col: qry += "after %s" % after_col error_intolerant_search(cursor,qry) return ######################################### def add_boolean_column(cursor, db_name, table_name, column_name): return add_column(cursor, db_name, table_name, column_name, 'boolean', '0') ######################################### def add_float_column(cursor, db_name, table_name, column_name): return add_column(cursor, db_name, table_name, column_name, 'float', '0.0') ######################################### def entry_exists(cursor, db_name, table_name, column_name, column_value): qry = "select 1 from %s.%s where %s=%s" % (db_name, table_name, column_name, column_value) rows = search_db (cursor, qry, verbose=False) if rows: return True else: return False ######################################### def check_table_exists (cursor, db_name, table_name): if not switch_to_db (cursor, db_name): return False qry = "show tables like '%s'" % table_name rows = search_db (cursor, qry, verbose=False) if (rows): if ( 'Error' in rows[0]): return False else: return True else: return False ############ def check_and_drop(cursor, db_name, table): search_db(cursor, "drop table if exists %s.%s"% (db_name, table)) return ######################################### def table_create_time (cursor, db_name, table_name): qry = "select create_time from information_schema.tables where " qry += "table_schema = '%s' " % db_name qry += "and table_name = '%s' " % table_name rows = search_db (cursor, qry, verbose=False) if (not rows or 'Error' in rows[0]): search_db (cursor, qry, verbose=True) return "" else: return rows[0][0] import warnings ####### def search_db(cursor, qry, verbose=False): warnings.filterwarnings('ignore', category=MySQLdb.Warning) try: cursor.execute(qry) except MySQLdb.Error as e: if verbose: print("Error running cursor.execute() for qry:\n%s\n%s" % (qry, e.args[1])) return [["Error"], e.args] except MySQLdb.Warning as e: # this does not work for me - therefore filterwarnings if verbose: print("Warning running cursor.execute() for qry:\n%s\n%s" % (qry, e.args[1])) return [["Warning"], e.args] try: rows = cursor.fetchall() except MySQLdb.Error as e: if verbose: print("Error running cursor.fetchall() for qry:\n%s\n%s" % (qry, e.args[1])) return [["Error"], e.args] if len(rows) == 0: if verbose: print("No return for query:\n%s" % qry) return False # since python3 fetchall returns bytes inst of str in some random fashion # not clear what's going on # here is a rather useless issue page on github # https://github.com/PyMySQL/mysqlclient-python/issues/145#issuecomment-283936456 rows_clean = [] for row in rows: rows_clean.append([r.decode('utf-8') if type(r)==bytes else r for r in row]) return rows_clean ######################################### def error_intolerant_search(cursor, qry): ret = search_db(cursor, qry) if not ret: return ret if type(ret[0][0])==str and 'error' in ret[0][0].lower(): search_db(cursor, qry, verbose=True) exit() return ret ######################################### def hard_landing_search(cursor, qry): ret = search_db(cursor, qry) if not ret or (type(ret[0][0])==str and 'error' in ret[0][0].lower()): search_db(cursor, qry, verbose=True) exit() return ret ######## def connect_to_mysql (conf_file): try: mysql_conn_handle = MySQLdb.connect(read_default_file=conf_file) except MySQLdb.Error as e: print("Error connecting to mysql (%s) " % (e.args[1])) sys.exit(1) return mysql_conn_handle ######## def connect_to_db (db_name, user=None, passwd=None): try: if not user is None: db = MySQLdb.connect(user=user, passwd=passwd, db=db_name) else: db = MySQLdb.connect(user="root", db=db_name) except MySQLdb.Error as e: print("Error connecting to %s: %d %s" % (db_name, e.args[0], e.args[1])) exit(1) return db
gpl-3.0
x-tools/xtools-rebirth
src/AppBundle/Repository/SimpleEditCounterRepository.php
2971
<?php /** * This file contains only the SimpleEditCounterRepository class. */ declare(strict_types = 1); namespace AppBundle\Repository; use AppBundle\Model\Project; use AppBundle\Model\User; /** * SimpleEditCounterRepository is responsible for retrieving data * from the database for the Simple Edit Counter tool. * @codeCoverageIgnore */ class SimpleEditCounterRepository extends Repository { /** * Execute and return results of the query used for the Simple Edit Counter. * @param Project $project * @param User $user * @param int|string $namespace Namespace ID or 'all' for all namespaces. * @param int|false $start Unix timestamp. * @param int|false $end Unix timestamp. * @return string[] Counts, each row with keys 'source' and 'value'. */ public function fetchData(Project $project, User $user, $namespace = 'all', $start = false, $end = false): array { $cacheKey = $this->getCacheKey(func_get_args(), 'simple_editcount'); if ($this->cache->hasItem($cacheKey)) { return $this->cache->getItem($cacheKey)->get(); } $userTable = $project->getTableName('user'); $pageTable = $project->getTableName('page'); $archiveTable = $project->getTableName('archive'); $revisionTable = $project->getTableName('revision'); $userGroupsTable = $project->getTableName('user_groups'); $arDateConditions = $this->getDateConditions($start, $end, null, 'ar_timestamp'); $revDateConditions = $this->getDateConditions($start, $end); $revNamespaceJoinSql = 'all' === $namespace ? '' : "JOIN $pageTable ON rev_page = page_id"; $revNamespaceWhereSql = 'all' === $namespace ? '' : "AND page_namespace = $namespace"; $arNamespaceWhereSql = 'all' === $namespace ? '' : "AND ar_namespace = $namespace"; $sql = "SELECT 'id' AS source, user_id as value FROM $userTable WHERE user_name = :username UNION SELECT 'arch' AS source, COUNT(*) AS value FROM $archiveTable WHERE ar_user_text = :username $arNamespaceWhereSql $arDateConditions UNION SELECT 'rev' AS source, COUNT(*) AS value FROM $revisionTable $revNamespaceJoinSql WHERE rev_user_text = :username $revNamespaceWhereSql $revDateConditions UNION SELECT 'groups' AS source, ug_group AS value FROM $userGroupsTable JOIN $userTable ON user_id = ug_user WHERE user_name = :username"; $result = $this->executeProjectsQuery($sql, ['username' => $user->getUsername()])->fetchAll(); // Cache and return. return $this->setCache($cacheKey, $result); } }
gpl-3.0
Archerpe/aries
src/main/java/com/andy/design_patterns/combined/djview/HeartModel.java
2154
package com.andy.design_patterns.combined.djview; import java.util.*; public class HeartModel implements HeartModelInterface, Runnable { ArrayList<BeatObserver> beatObservers = new ArrayList<BeatObserver>(); ArrayList<BPMObserver> bpmObservers = new ArrayList<BPMObserver>(); int time = 1000; int bpm = 90; Random random = new Random(System.currentTimeMillis()); Thread thread; public HeartModel() { thread = new Thread(this); thread.start(); } public void run() { int lastrate = -1; for (; ; ) { int change = random.nextInt(10); if (random.nextInt(2) == 0) { change = 0 - change; } int rate = 60000 / (time + change); if (rate < 120 && rate > 50) { time += change; notifyBeatObservers(); if (rate != lastrate) { lastrate = rate; notifyBPMObservers(); } } try { Thread.sleep(time); } catch (Exception e) { } } } public int getHeartRate() { return 60000 / time; } public void registerObserver(BeatObserver o) { beatObservers.add(o); } public void removeObserver(BeatObserver o) { int i = beatObservers.indexOf(o); if (i >= 0) { beatObservers.remove(i); } } public void notifyBeatObservers() { for (int i = 0; i < beatObservers.size(); i++) { BeatObserver observer = (BeatObserver) beatObservers.get(i); observer.updateBeat(); } } public void registerObserver(BPMObserver o) { bpmObservers.add(o); } public void removeObserver(BPMObserver o) { int i = bpmObservers.indexOf(o); if (i >= 0) { bpmObservers.remove(i); } } public void notifyBPMObservers() { for (int i = 0; i < bpmObservers.size(); i++) { BPMObserver observer = (BPMObserver) bpmObservers.get(i); observer.updateBPM(); } } }
gpl-3.0
Thecarisma/powertext
Power Text/src/com/power/text/rtextarea/RegExReplaceInfo.java
2097
/* * 02/19/2006 * * RegExReplaceInfo.java - Information about a regex text match. * * This library is distributed under a modified BSD license. See the included * RSyntaxTextArea.License.txt file for details. */ package com.power.text.rtextarea; /** * Information on how to implement a regular expression "replace" operation. * * @author Robert Futrell * @version 1.0 */ class RegExReplaceInfo { private String matchedText; private int startIndex; private int endIndex; private String replacement; /** * Constructor. * * @param matchedText The text that matched the regular expression. * @param start The start index of the matched text in the * <code>CharSequence</code> searched. * @param end The end index of the matched text in the * <code>CharSequence</code> searched. * @param replacement The text to replace the matched text with. This * string has any matched groups and character escapes replaced. */ RegExReplaceInfo(String matchedText, int start, int end, String replacement) { this.matchedText = matchedText; this.startIndex = start; this.endIndex = end; this.replacement = replacement; } /** * Returns the end index of the matched text. * * @return The end index of the matched text in the document searched. * @see #getMatchedText() * @see #getEndIndex() */ public int getEndIndex() { return endIndex; } /** * Returns the text that matched the regular expression. * * @return The matched text. */ public String getMatchedText() { return matchedText; } /** * Returns the string to replaced the matched text with. * * @return The string to replace the matched text with. */ public String getReplacement() { return replacement; } /** * Returns the start index of the matched text. * * @return The start index of the matched text in the document searched. * @see #getMatchedText() * @see #getEndIndex() */ public int getStartIndex() { return startIndex; } }
gpl-3.0
mojca/gecko
core/remotecontrolpanel.cpp
12125
/* Copyright 2011 Bastian Loeher, Roland Wirth This file is part of GECKO. GECKO is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GECKO is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "remotecontrolpanel.h" #include "runmanager.h" #include <QLabel> #include <QLineEdit> #include <QDateTimeEdit> #include <QTextEdit> #include <QGroupBox> #include <QComboBox> #include <QPushButton> #include <QGridLayout> #include <QMessageBox> #include <QTimer> #include <iostream> Q_DECLARE_METATYPE (QHostAddress); RemoteControlPanel::RemoteControlPanel (QWidget *parent) : QWidget (parent) , remoteUpdateTimer (new QTimer (this)) , geckoremote (new GeckoRemote (43256)) // "GECKO" on phone keyboard { setAccessibleName (tr ("Remote Control")); remoteUpdateTimer->setInterval (1000); connect (remoteUpdateTimer, SIGNAL(timeout()), geckoremote, SLOT(startUpdate())); createUI (); } RemoteControlPanel::~RemoteControlPanel () { remoteUpdateTimer->stop(); } void RemoteControlPanel::createUI () { QWidget* remoteControl = new QGroupBox(tr("Remote Control")); remoteControl->setAccessibleName(tr("Remote Control")); QGridLayout* layout = new QGridLayout(); QLabel* runNameLabel = new QLabel(tr("Remote Run name:")); remoteRunNameEdit = new QLineEdit(); QLabel* ipAddressLabel = new QLabel(tr("Remote address:")); remoteIpAddressEdit = new QComboBox(this); //remoteIpAddressEdit->setPlaceholderText("0.0.0.0"); // QT 4.7 remoteIpAddressEdit->setInsertPolicy(QComboBox::InsertAlphabetically); remoteIpAddressEdit->setEditable(true); remoteDiscoverButton = new QPushButton(tr("Discover...")); QLabel* stateLabel = new QLabel(tr("Remote state:")); remoteStateEdit = new QLineEdit(); remoteStateEdit->setReadOnly(true); remoteUpdateButton = new QPushButton(tr("Update")); remoteConnectButton = new QPushButton(tr("Connect")); QGroupBox* box1 = new QGroupBox(tr("Remote Timing:")); QGridLayout* box1l = new QGridLayout(); QLabel* runStartTimeLabel = new QLabel(tr("Start:")); QLabel* runStopTimeLabel = new QLabel(tr("Stop:")); remoteStartTimeEdit = new QDateTimeEdit(); remoteStopTimeEdit = new QDateTimeEdit(); remoteStartTimeEdit->setDisplayFormat("dd.MM. yyyy hh:mm:ss"); remoteStopTimeEdit->setDisplayFormat("dd.MM. yyyy hh:mm:ss"); remoteStartTimeEdit->setReadOnly(true); remoteStopTimeEdit->setReadOnly(true); box1l->addWidget(runStartTimeLabel,0,0,1,1); box1l->addWidget(runStopTimeLabel,1,0,1,1); box1l->addWidget(remoteStartTimeEdit,0,1,1,1); box1l->addWidget(remoteStopTimeEdit,1,1,1,1); box1l->setColumnStretch(1, 1); box1->setLayout(box1l); QGroupBox* box2 = new QGroupBox(tr("Remote Events:")); QGridLayout* box2l = new QGridLayout(); QLabel* nofEventsLabel = new QLabel(tr("Events:")); QLabel* eventsPerSecondLabel = new QLabel(tr("Ev/s:")); remoteNofEventsEdit = new QLineEdit(0); remoteNofEventsEdit->setReadOnly(true); remoteEventsPerSecondEdit = new QLineEdit(0); remoteEventsPerSecondEdit->setReadOnly(true); box2l->addWidget(nofEventsLabel,0,0,1,1); box2l->addWidget(eventsPerSecondLabel,1,0,1,1); box2l->addWidget(remoteNofEventsEdit,0,1,1,1); box2l->addWidget(remoteEventsPerSecondEdit,1,1,1,1); box2->setLayout(box2l); remoteRunStartButton = new QPushButton(tr("Start Remote Run")); remoteRunStartButton->setMinimumHeight(60); connect(remoteRunStartButton,SIGNAL(clicked()), SLOT(remoteRunStartClicked())); connect(remoteConnectButton, SIGNAL(clicked()), SLOT(remoteConnectClicked())); remoteRunNameButton = new QPushButton(tr("Change")); connect(remoteRunNameButton,SIGNAL(clicked()),this,SLOT(remoteRunNameButtonClicked())); connect(remoteRunNameEdit, SIGNAL(textChanged(QString)), RunManager::ptr (), SLOT(setRemoteRunName(QString))); connect(remoteDiscoverButton, SIGNAL(clicked()), geckoremote, SLOT(startDiscover())); connect(remoteUpdateButton, SIGNAL(clicked()), geckoremote, SLOT(startUpdate())); connect(remoteIpAddressEdit,SIGNAL(currentIndexChanged(int)),SLOT(remoteIpAddressChanged(int))); connect(remoteIpAddressEdit->lineEdit(),SIGNAL(editingFinished()),SLOT(remoteIpAddressTextChanged())); QGroupBox* box3 = new QGroupBox(tr("Remote Notes:")); QGridLayout* box3l = new QGridLayout(); remoteRunInfoEdit = new QTextEdit(); box3l->addWidget(remoteRunInfoEdit,0,0,1,1); box3->setLayout(box3l); QGroupBox* box4 = new QGroupBox(tr("Remote Load:")); QGridLayout* box4l = new QGridLayout(); QLabel* cpuLabel = new QLabel(tr("CPU:")); QLabel* netLabel = new QLabel(tr("Net:")); remoteCpuEdit = new QLineEdit(); remoteNetEdit = new QLineEdit(); remoteCpuEdit->setReadOnly(true); remoteNetEdit->setReadOnly(true); box4l->addWidget(cpuLabel,0,0,1,1); box4l->addWidget(remoteCpuEdit,0,1,1,1); box4l->addWidget(netLabel,1,0,1,1); box4l->addWidget(remoteNetEdit,1,1,1,1); box4->setLayout(box4l); int row = 0; layout->addWidget(ipAddressLabel, row,0,1,1); layout->addWidget(remoteIpAddressEdit, row,1,1,2); layout->addWidget(remoteDiscoverButton, row,3,1,1); row++; layout->addWidget(remoteConnectButton, row,3,1,1); row++; layout->addWidget(stateLabel, row,0,1,1); layout->addWidget(remoteStateEdit, row,1,1,2); layout->addWidget(remoteUpdateButton, row,3,1,1); row++; layout->addWidget(runNameLabel, row,0,1,1); layout->addWidget(remoteRunNameEdit, row,1,1,2); layout->addWidget(remoteRunNameButton, row,3,1,1); row++; layout->addWidget(box1, row,0,1,2); layout->addWidget(box2, row,2,1,2); row++; layout->addWidget(box3, row,0,2,3); layout->addWidget(remoteRunStartButton, row,3,1,1); row++; layout->addWidget(box4, row,3,1,1); layout->setColumnStretch (0, 0); layout->setColumnStretch (1, 1); layout->setColumnStretch (2, 1); layout->setColumnStretch (3, 0); remoteRunStartButton->setEnabled(false); remoteRunNameButton->setEnabled(false); remoteRunInfoEdit->setEnabled(false); remoteRunNameEdit->setEnabled(false); remoteControl->setLayout(layout); (new QGridLayout (this))->addWidget (remoteControl); } void RemoteControlPanel::remoteRunStartClicked() { if(geckoremote->getRemoteState ().running == false) { geckoremote->startRemoteRun (); } else { geckoremote->stopRemoteRun (); } } void RemoteControlPanel::remoteConnectClicked() { if(geckoremote->isConnected () == false) { geckoremote->connectRemote (); } else { geckoremote->disconnectRemote (); } } void RemoteControlPanel::setCurrentRemoteAddress(QHostAddress newAddress) { geckoremote->setRemote (newAddress); std::cout << "Changed current remote address to " << newAddress.toString().toStdString() << std::endl; } void RemoteControlPanel::remoteIpAddressChanged(int idx) { if(idx != -1) { QVariant var = remoteIpAddressEdit->itemData(idx); setCurrentRemoteAddress(var.value<QHostAddress>()); } } void RemoteControlPanel::remoteIpAddressTextChanged() { QString newIp = remoteIpAddressEdit->lineEdit()->text(); QHostAddress newAddr (newIp); if(!newAddr.isNull () && remoteIpAddressEdit->findData (QVariant::fromValue (newAddr)) == -1) { remoteIpAddressEdit->addItem(newAddr.toString(),QVariant::fromValue (newAddr)); } } void RemoteControlPanel::discoveredRemote (QHostAddress remote) { if (remoteIpAddressEdit->findData (QVariant::fromValue (remote)) == -1) { remoteIpAddressEdit->addItem(remote.toString (), QVariant::fromValue (remote)); } } void RemoteControlPanel::remoteUpdateComplete () { const RemoteGeckoState &gs = geckoremote->getRemoteState (); remoteStateEdit->setText ( (QStringList () << (gs.running ? tr ("running") : tr ("not running")) << (gs.controlled ? tr ("remote controlled") : tr ("not remote controlled"))).join (tr(", "))); remoteRunNameEdit->setText (gs.runname); remoteStartTimeEdit->setDateTime (gs.starttime); remoteStopTimeEdit->setDateTime (gs.stoptime); remoteNofEventsEdit->setText (QString::number (gs.nofevents)); remoteEventsPerSecondEdit->setText (QString::number (gs.eventrate, 'f', 2)); remoteRunInfoEdit->setText (gs.runinfo); remoteCpuEdit->setText (tr("%1 %%").arg (gs.cpuload)); } void RemoteControlPanel::remoteConnected (QHostAddress controller) { if (!controller.isNull ()) { QMessageBox::warning (this, tr ("Gecko"), tr ("Connect failed! Remote already controlled by %1.").arg (controller.toString ()), QMessageBox::Ok); return; } else { geckoremote->startUpdate (); remoteUpdateTimer->start (); remoteConnectButton->setText(tr("Disconnect")); remoteRunStartButton->setEnabled(true); remoteRunNameButton->setEnabled(true); remoteRunInfoEdit->setEnabled(true); remoteRunNameEdit->setEnabled(true); } } void RemoteControlPanel::remoteDisconnected (QHostAddress controller) { if (!controller.isNull ()) { QMessageBox::warning (this, tr ("Gecko"), tr ("Disconnect failed! Remote already controlled by %1.").arg (controller.toString ()), QMessageBox::Ok); return; } else { geckoremote->startUpdate (); remoteUpdateTimer->stop (); remoteConnectButton->setText (tr ("Connect")); remoteRunStartButton->setEnabled (false); remoteRunNameButton->setEnabled (false); remoteRunInfoEdit->setEnabled (false); remoteRunNameEdit->setEnabled (false); } } void RemoteControlPanel::remoteStarted (GeckoRemote::StartStopResult res) { switch (res) { case GeckoRemote::Ok: break; case GeckoRemote::NotContr: QMessageBox::warning (this, tr ("Gecko"), tr ("Start failed! Remote is controlled by %1.") .arg (geckoremote->getRemoteState ().controller.toString ()), QMessageBox::Ok); break; case GeckoRemote::Already: QMessageBox::warning (this, tr ("Gecko"), tr ("Start failed! Remote is already running.") .arg (geckoremote->getRemoteState ().controller.toString ()), QMessageBox::Ok); break; } } void RemoteControlPanel::remoteStopped (GeckoRemote::StartStopResult res) { switch (res) { case GeckoRemote::Ok: break; case GeckoRemote::NotContr: QMessageBox::warning (this, tr ("Gecko"), tr ("Stop failed! Remote is controlled by %1.") .arg (geckoremote->getRemoteState ().controller.toString ()), QMessageBox::Ok); break; case GeckoRemote::Already: QMessageBox::warning (this, tr ("Gecko"), tr ("Stop failed! Remote is not running.") .arg (geckoremote->getRemoteState ().controller.toString ()), QMessageBox::Ok); break; } }
gpl-3.0
aylusltd/NGN
bin/CLI.js
4023
#!/usr/bin/env node var path = require('path'), fs = require('fs'), optimist = require('optimist'), exec = require('child_process').exec, user = require('./lib/permissions'), pkg = require(path.join(process.mainModule.paths[0],'..','..','package.json')); require('colors'); // AVAILABLE CLI OPTIONS var base = { 'init': 'Initialize a project directory for use with NGN.', 'add': 'Add an NGN feature.', 'remove': 'Remove an NGN feature.', 'update': 'Update the NGN installation', 'uninstall': 'Remove NGN completely.', /* 'start': 'Start the NGN manager or a process.', 'stop': 'Stop the manager or a process.', 'create': 'Create a custom class, API, process, or documentation.', */ 'version':'List the version of NGN installed on the system.', 'help':'View help for a specific command.' //'mechanic': 'Open the NGN Mechanic shell.', //'repair': 'Repair an existing NGN installation.', }; var shortcuts = { 'v': 'version', 'h': 'help' }; var opts = {}; for(var o in base){ opts[o] = base[o]; } // Optional CLI Options var opt = { 'ngn-dev': { 'develop': 'Auto-restart processes when the file changes. (Dev Tool)', } } // Add optional CLI options if they're installed. for (var mod in opt){ if (fs.existsSync(path.join(__dirname,'..','..','ngn-dev'))){ for (var m in opt[mod]){ opts[m] = opt[mod][m]; } } } // Placeholder for the selected command var cmd = null; // CLI REQUIREMENTS // Make sure at least one command option is selected. var minOptions = function(argv){ if (argv._.length > 0){ cmd = argv._[0]; argv[cmd] = argv._[1] || true; return true; } for (var term in opts){ if (argv.hasOwnProperty(term)){ cmd = term; return true; } } for (var _term in argv){ if (_term !== '_' && _term !== '$0'){ cmd = _term; break; } } optimist.describe(opts); if (cmd == null){ throw(''); } if (cmd in shortcuts){ cmd = shortcuts[cmd]; return true; } throw('"'+cmd+'" is not a valid option.'); }; var priv = function(){ if (!user.isElevatedUser()){ throw('Insufficient privileges to run this command.\nPlease run this command '+(require('os').platform() == 'win32' ? 'with and admin account' : 'as root (or sudo)')+'.'); } }; // Make sure the command option has the appropriate parameters which // are required to run. var validOption = function(argv){ switch (cmd.trim().toLowerCase()){ case 'uninstall': priv(); return true; case 'update': priv(); return true; case 'remove': case 'add': priv(); if (typeof argv[cmd] == 'boolean'){ argv[cmd] = ''; } break; // Make sure the CLI knows what it needs to create case 'create': if (argv[cmd] === true || ['class','docs','api'].indexOf(argv[cmd].trim().toLowerCase()) < 0){ throw('"'+(argv[cmd] === true ? 'Blank' : argv[cmd])+'" is not a valid "create" option. Valid options are:\n - class\n - api'); } break; case 'start': case 'stop': return true; // All other options do not require additional parameters, or they // are not valid. default: // If the command options object contains the command, it is // recognized and processing continues. if (opts.hasOwnProperty(cmd)) { return true; } // If the command is not recognized, the list of valid commands // is described and the usage/error is displayed. optimist.describe(opts); throw('"'+cmd+'" is not a valid option.'); } return true; }; // ARGUMENTS var argv = optimist .usage('Usage: ngn <option>') .wrap(80) .check(minOptions) .check(validOption) .argv, p = require('path'), cwd = process.cwd(), root = p.dirname(process.mainModule.filename); // Include the appropriate command if (cmd in base){ require(require('path').join(__dirname,'commands',cmd)); } else { for (var pkg in opt){ if (opt[pkg][cmd] !== undefined){ require(require('path').join(__dirname,'..','..',pkg))[cmd](); break; } } } return;
gpl-3.0
WilleamZhao/wechat
src/main/java/com/sourcod/wechat/model/MessageModel.java
5430
package com.sourcod.wechat.model; import java.io.Serializable; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * 消息Model类 * * @author willeam * @time 2016-12-07 09:55:19 * */ @XStreamAlias("xml") public class MessageModel implements Serializable{ /** * */ private static final long serialVersionUID = -7176575843990000883L; /** * */ @XStreamAlias("ToUserName") private String ToUserName; // 接收方帐号(收到的OpenID) @XStreamAlias("FromUserName") private String FromUserName; // 开发者微信号 @XStreamAlias("CreateTime") private String CreateTime; // 消息创建时间 (整型) @XStreamAlias("MsgType") private String MsgType; // music @XStreamAlias("Content") private String Content; // 回复的消息内容 @XStreamAlias("MsgId") private String MsgId; // 消息id,64位整型 @XStreamAlias("Format") private String Format; // 语音格式,如amr,speex等 @XStreamAlias("Location_X") private String Location_X; // 地理位置维度 @XStreamAlias("Location_Y") private String Location_Y; // 地理位置经度 @XStreamAlias("Scale") private String Scale; // 地图缩放大小 @XStreamAlias("Label") private String Label; // 地理位置信息 @XStreamAlias("MediaId") private String MediaId; // 上传多媒体文件,得到的id @XStreamAlias("Title") private String Title; // 标题 @XStreamAlias("Description") private String Description; // 描述 @XStreamAlias("MusicURL") private String MusicURL; // 音乐链接 @XStreamAlias("HQMusicUrl") private String HQMusicUrl; // 高质量音乐链接,WIFI环境优先使用该链接播放音乐 @XStreamAlias("ThumbMediaId") private String ThumbMediaId; // 上传多媒体文件,得到的id @XStreamAlias("ArticleCount") private String ArticleCount; // 图文消息个数,限制为10条以内 @XStreamAlias("Articles") private String Articles; // 多条图文消息信息 @XStreamAlias("PicUrl") private String PicUrl; // 图片链接 @XStreamAlias("Url") private String Url; // 点击图文消息跳转链接 @XStreamAlias("Encrypt") private String Encrypt; // 密文 @XStreamAlias("Event") private String Event; // 事件类型,subscribe(订阅)、unsubscribe(取消订阅) @XStreamAlias("EventKey") private String EventKey; private String MenuId; public String getToUserName() { return ToUserName; } public void setToUserName(String toUserName) { ToUserName = toUserName; } public String getFromUserName() { return FromUserName; } public void setFromUserName(String fromUserName) { FromUserName = fromUserName; } public String getCreateTime() { return CreateTime; } public void setCreateTime(String createTime) { CreateTime = createTime; } public String getMsgType() { return MsgType; } public void setMsgType(String msgType) { MsgType = msgType; } public String getContent() { return Content; } public void setContent(String content) { Content = content; } public String getMediaId() { return MediaId; } public void setMediaId(String mediaId) { MediaId = mediaId; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getDescription() { return Description; } public void setDescription(String description) { Description = description; } public String getMusicURL() { return MusicURL; } public void setMusicURL(String musicURL) { MusicURL = musicURL; } public String getHQMusicUrl() { return HQMusicUrl; } public void setHQMusicUrl(String hQMusicUrl) { HQMusicUrl = hQMusicUrl; } public String getThumbMediaId() { return ThumbMediaId; } public void setThumbMediaId(String thumbMediaId) { ThumbMediaId = thumbMediaId; } public String getArticleCount() { return ArticleCount; } public void setArticleCount(String articleCount) { ArticleCount = articleCount; } public String getArticles() { return Articles; } public void setArticles(String articles) { Articles = articles; } public String getPicUrl() { return PicUrl; } public void setPicUrl(String picUrl) { PicUrl = picUrl; } public String getUrl() { return Url; } public void setUrl(String url) { Url = url; } public String getMsgId() { return MsgId; } public void setMsgId(String msgId) { MsgId = msgId; } public String getFormat() { return Format; } public void setFormat(String format) { Format = format; } public String getLocation_X() { return Location_X; } public void setLocation_X(String location_X) { Location_X = location_X; } public String getLocation_Y() { return Location_Y; } public void setLocation_Y(String location_Y) { Location_Y = location_Y; } public String getScale() { return Scale; } public void setScale(String scale) { Scale = scale; } public String getLabel() { return Label; } public void setLabel(String label) { Label = label; } public String getEncrypt() { return Encrypt; } public void setEncrypt(String encrypt) { Encrypt = encrypt; } public String getEvent() { return Event; } public void setEvent(String event) { Event = event; } public String getEventKey() { return EventKey; } public void setEventKey(String eventKey) { EventKey = eventKey; } public String getMenuId() { return MenuId; } public void setMenuId(String menuId) { MenuId = menuId; } }
gpl-3.0
gunnarfloetteroed/java
experimental/src/main/java/stockholm/ihop4/tollzonepassagedata/SizeAnalysisHandler.java
1846
/* * Copyright 2018 Gunnar Flötteröd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * contact: gunnar.flotterod@gmail.com * */ package stockholm.ihop4.tollzonepassagedata; /** * * @author Gunnar Flötteröd * */ class SizeAnalysisHandler extends AbstractTollZonePassageDataHandler { private final int[] relevantIdentifiedVehiclesPerMeterLengthClass; private final int[] identifiedVehiclesPerMeterLengthClass; SizeAnalysisHandler(final int[] relevantIdentifiedVehiclesPerMeterLengthClass, final int[] identifiedVehiclesPerMeterLengthClass) { this.relevantIdentifiedVehiclesPerMeterLengthClass = relevantIdentifiedVehiclesPerMeterLengthClass; this.identifiedVehiclesPerMeterLengthClass = identifiedVehiclesPerMeterLengthClass; } @Override protected void processFields() { final int lengthClass = super.vehicleLength_cm / 100; if ((lengthClass < 0) || (lengthClass >= this.identifiedVehiclesPerMeterLengthClass.length)) { return; } if (super.containsRegisterData) { this.identifiedVehiclesPerMeterLengthClass[lengthClass]++; if (super.registerDataFeasible) { this.relevantIdentifiedVehiclesPerMeterLengthClass[lengthClass]++; } } } }
gpl-3.0
wikimedia/phabricator-extensions-Sprint
src/conduit/SprintManiphestConduitAPIMethod.php
9939
<?php abstract class SprintManiphestConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass( 'PhabricatorManiphestApplication'); } protected function defineErrorTypes() { return array( 'ERR-INVALID-PARAMETER' => pht('Missing or malformed parameter.'), ); } protected function buildTaskInfoDictionary(ManiphestTask $task) { $results = $this->buildTaskInfoDictionaries(array($task)); return idx($results, $task->getPHID()); } protected function getTaskFields($is_new) { $fields = array(); if (!$is_new) { $fields += array( 'id' => 'optional int', 'phid' => 'optional int', ); } $fields += array( 'title' => $is_new ? 'required string' : 'optional string', 'description' => 'optional string', 'ownerPHID' => 'optional phid', 'viewPolicy' => 'optional phid or policy string', 'editPolicy' => 'optional phid or policy string', 'ccPHIDs' => 'optional list<phid>', 'priority' => 'optional int', 'projectPHIDs' => 'optional list<phid>', 'auxiliary' => 'optional dict', 'points' => 'optional int' ); if (!$is_new) { $fields += array( 'status' => 'optional string', 'comments' => 'optional string', ); } return $fields; } protected function applyRequest( ManiphestTask $task, ConduitAPIRequest $request, $is_new) { $changes = array(); if ($is_new) { $task->setTitle((string)$request->getValue('title')); $task->setDescription((string)$request->getValue('description')); $changes[ManiphestTransaction::TYPE_STATUS] = ManiphestTaskStatus::getDefaultStatus(); $changes[PhabricatorTransactions::TYPE_SUBSCRIBERS] = array('+' => array($request->getUser()->getPHID())); } else { $comments = $request->getValue('comments'); if (!$is_new && $comments !== null) { $changes[PhabricatorTransactions::TYPE_COMMENT] = null; } $title = $request->getValue('title'); if ($title !== null) { $changes[ManiphestTransaction::TYPE_TITLE] = $title; } $desc = $request->getValue('description'); if ($desc !== null) { $changes[ManiphestTransaction::TYPE_DESCRIPTION] = $desc; } $status = $request->getValue('status'); if ($status !== null) { $valid_statuses = ManiphestTaskStatus::getTaskStatusMap(); if (!isset($valid_statuses[$status])) { throw id(new ConduitException('ERR-INVALID-PARAMETER')) ->setErrorDescription(pht('Status set to invalid value.')); } $changes[ManiphestTransaction::TYPE_STATUS] = $status; } } $priority = $request->getValue('priority'); if ($priority !== null) { $valid_priorities = ManiphestTaskPriority::getTaskPriorityMap(); if (!isset($valid_priorities[$priority])) { throw id(new ConduitException('ERR-INVALID-PARAMETER')) ->setErrorDescription(pht('Priority set to invalid value.')); } $changes[ManiphestTransaction::TYPE_PRIORITY] = $priority; } $owner_phid = $request->getValue('ownerPHID'); if ($owner_phid !== null) { $this->validatePHIDList( array($owner_phid), PhabricatorPeopleUserPHIDType::TYPECONST, 'ownerPHID'); $changes[ManiphestTransaction::TYPE_OWNER] = $owner_phid; } $ccs = $request->getValue('ccPHIDs'); if ($ccs !== null) { $changes[PhabricatorTransactions::TYPE_SUBSCRIBERS] = array('=' => array_fuse($ccs)); } $transactions = array(); $view_policy = $request->getValue('viewPolicy'); if ($view_policy !== null) { $transactions[] = id(new ManiphestTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY) ->setNewValue($view_policy); } $edit_policy = $request->getValue('editPolicy'); if ($edit_policy !== null) { $transactions[] = id(new ManiphestTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY) ->setNewValue($edit_policy); } $project_phids = $request->getValue('projectPHIDs'); if ($project_phids !== null) { $this->validatePHIDList( $project_phids, PhabricatorProjectProjectPHIDType::TYPECONST, 'projectPHIDS'); $project_type = PhabricatorProjectObjectHasProjectEdgeType::EDGECONST; $transactions[] = id(new ManiphestTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDGE) ->setMetadataValue('edge:type', $project_type) ->setNewValue( array( '=' => array_fuse($project_phids), )); } $template = new ManiphestTransaction(); foreach ($changes as $type => $value) { $transaction = clone $template; $transaction->setTransactionType($type); if ($type == PhabricatorTransactions::TYPE_COMMENT) { $transaction->attachComment( id(new ManiphestTransactionComment()) ->setContent($comments)); } else { $transaction->setNewValue($value); } $transactions[] = $transaction; } $field_list = PhabricatorCustomField::getObjectFields( $task, PhabricatorCustomField::ROLE_EDIT); $field_list->readFieldsFromStorage($task); $auxiliary = $request->getValue('auxiliary'); if ($auxiliary) { foreach ($field_list->getFields() as $key => $field) { if (!array_key_exists($key, $auxiliary)) { continue; } $transaction = clone $template; $transaction->setTransactionType( PhabricatorTransactions::TYPE_CUSTOMFIELD); $transaction->setMetadataValue('customfield:key', $key); $transaction->setOldValue( $field->getOldValueForApplicationTransactions()); $transaction->setNewValue($auxiliary[$key]); $transactions[] = $transaction; } } if (!$transactions) { return; } $content_source = PhabricatorContentSource::newForSource( PhabricatorContentSource::SOURCE_CONDUIT, array()); $editor = id(new ManiphestTransactionEditor()) ->setActor($request->getUser()) ->setContentSource($content_source) ->setContinueOnNoEffect(true); if (!$is_new) { $editor->setContinueOnMissingFields(true); } $editor->applyTransactions($task, $transactions); // reload the task now that we've done all the fun stuff return id(new ManiphestTaskQuery()) ->setViewer($request->getUser()) ->withPHIDs(array($task->getPHID())) ->needSubscriberPHIDs(true) ->needProjectPHIDs(true) ->executeOne(); } protected function buildTaskInfoDictionaries(array $tasks) { assert_instances_of($tasks, 'ManiphestTask'); if (!$tasks) { return array(); } $task_phids = mpull($tasks, 'getPHID'); $all_deps = id(new PhabricatorEdgeQuery()) ->withSourcePHIDs($task_phids) ->withEdgeTypes(array(ManiphestTaskDependsOnTaskEdgeType::EDGECONST)); $all_deps->execute(); $result = array(); foreach ($tasks as $task) { // TODO: Batch this get as CustomField gets cleaned up. $field_list = PhabricatorCustomField::getObjectFields( $task, PhabricatorCustomField::ROLE_EDIT); $field_list->readFieldsFromStorage($task); $auxiliary = mpull( $field_list->getFields(), 'getValueForStorage', 'getFieldKey'); $task_deps = $all_deps->getDestinationPHIDs( array($task->getPHID()), array(ManiphestTaskDependsOnTaskEdgeType::EDGECONST)); $result[$task->getPHID()] = array( 'id' => $task->getID(), 'phid' => $task->getPHID(), 'points' => $task->getPoints(), 'authorPHID' => $task->getAuthorPHID(), 'ownerPHID' => $task->getOwnerPHID(), 'ccPHIDs' => $task->getSubscriberPHIDs(), 'status' => $task->getStatus(), 'statusName' => ManiphestTaskStatus::getTaskStatusName( $task->getStatus()), 'isClosed' => $task->isClosed(), 'priority' => ManiphestTaskPriority::getTaskPriorityName( $task->getPriority()), 'priorityColor' => ManiphestTaskPriority::getTaskPriorityColor( $task->getPriority()), 'title' => $task->getTitle(), 'description' => $task->getDescription(), 'projectPHIDs' => $task->getProjectPHIDs(), 'uri' => PhabricatorEnv::getProductionURI('/T'.$task->getID()), 'auxiliary' => $auxiliary, 'objectName' => 'T'.$task->getID(), 'dateCreated' => $task->getDateCreated(), 'dateModified' => $task->getDateModified(), 'dependsOnTaskPHIDs' => $task_deps, ); } return $result; } /** * NOTE: This is a temporary stop gap since its easy to make malformed tasks. * Long-term, the values set in @{method:defineParamTypes} will be used to * validate data implicitly within the larger Conduit application. * * TODO: Remove this in favor of generalized Conduit hotness. */ private function validatePHIDList(array $phid_list, $phid_type, $field) { $phid_groups = phid_group_by_type($phid_list); unset($phid_groups[$phid_type]); if (!empty($phid_groups)) { throw id(new ConduitException('ERR-INVALID-PARAMETER')) ->setErrorDescription( pht( 'One or more PHIDs were invalid for %s.', $field)); } return true; } }
gpl-3.0
UWHealth/markdown-documentation-generator
lib/templating.js
2689
/* jshint node: true */ /* jshint esnext: true*/ "use strict"; var _sg = require('./globals'); var listFiles = require('./log'); var handlebars = require('handlebars'); var helpers = require('./swag.js'); var fs = require('fs-extra'); var path = require('path'); /** * Try user-provided Handlebars partials to ensure they are files that can be read * * @param {string} file * @param {string} name * @returns {string} file content */ function checkPartial(file, name) { try { listFiles(_sg.brand('Partial: ') + path.relative(_sg.root, file), false, 3); return fs.readFileSync(file, 'utf8'); } catch(err) { console.error(_sg.error(_sg.logPre + 'Could not read ' + name + ' Partial: ' + file)); return; } } /** * Run through Handlebars to create HTML * * @param {object} json * @returns {string} html */ module.exports = function(json, options) { //Register Swag helpers helpers.registerHelpers(handlebars); findPathPartials(_sg.templateSource, options.templateFile); //Run through partials, check if they exist, and register them for(var partial in options.handlebarsPartials) { if ({}.hasOwnProperty.call(options.handlebarsPartials, partial)) { checkAndRegisterPartial( partial, path.resolve(_sg.root, options.handlebarsPartials[partial]) ); } } // Adding '#styleguide .hljs pre' to highlight css, to override common used styling for 'pre' // var highlightSource = _sg.highlightSource.replace('.hljs {', '#styleguide .hljs pre, .hljs {'); handlebars.registerPartial("highlight", _sg.highlightSource); handlebars.registerPartial("theme", _sg.themeSource); try { var template = handlebars.compile(_sg.templateSource); var html = template(json); return html; } catch(err) { console.error(_sg.logPre + _sg.error(new Error("Error compiling template"))); console.error(err); process.exit(1); } }; function findPathPartials(template, templatePath) { const regex = /{{>\s*['"]?((\.|\/)[a-zA-Z\/\.\-_]*)['"]? *}}/g; let matches; let partialsFound = {}; while((matches = regex.exec(template)) !== null) { checkAndRegisterPartial( matches[1], path.resolve(path.dirname(templatePath), matches[1]) ) } } function checkAndRegisterPartial(partial, partialPath) { const currentPartial = checkPartial(partialPath, partial); // Check for nested partials findPathPartials(currentPartial, partialPath); handlebars.registerPartial(partial, currentPartial); }
gpl-3.0