branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>DysonJ/Exercises<file_sep>/week3/starcraft-rankings/app.js
angular.module('StarCraft',[])
.controller('ranking', rankingController)
.controller('test',testController)
.factory('getRanking', rankingFactory)
rankingController.$inject = ['getRanking']
testController.$inject = ['getRanking']
rankingFactory = ['$http']
function testController(getRanking){
var t = this;
var handleSuccess = function(data){
console.log('success',data);
}
var handleError = function(data, status){
console.log('error: ',data,status)
}
getRanking.rankingCall().then(handleSuccess,handleError)
}
function rankingController(getRanking){
var r = this;
var handleSuccess = function(data){
console.log('success',data,status);
}
var handleError = function(data, status){
console.log('error: ',data,status)
}
getRanking.rankingCall().then(handleSuccess,handleError)
}
function rankingFactory($http){
var ranking = function(){
return $http({
method:'GET',
url:'https://gist.githubusercontent.com/Devaio/a2d8a96c01dfc4500186767b218e5981/raw/22824bb4d4f1ccf91d6853e4f08ec57d452b62d0/starcraft.json'
})
}
return{
rankingCall : ranking,
}
}
<file_sep>/week6/node-colors/luminosity.js
var r = process.argv[2];
var g = process.argv[3];
var b = process.argv[4];
var luminosity = 0.2126 * r + 0.7152 * g + 0.0722 * b;
console.log(luminosity)
<file_sep>/week3/hide-a-form/script.js
var app = angular.module('app',[]);
app.controller('data', ['$scope',function($scope){
$scope.user = {
image:'user.jpg',
name:'<NAME>',
bio:'orem ipsum dolor sit amet, consectetur adipiscing elit. Sed dictum elementum pharetra. In ac neque ac velit sollicitudin ultrices nec sit amet nisi. Praesent a ultricies libero. Maecenas facilisis ipsum vel tortor vulputate congue. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque viverra urna sem, vel imperdiet libero hendrerit eu. ',
favBooks:'12-Hour Work Week',
favJavascript:['jQuery','Bootstrap.js']
}
$scope.form = false;
}])
<file_sep>/week3/class-exercise/app.js
var mod = angular.module('mod',[])
// method chained controller with named function
.controller('syntax2', funct2);
function funct2(){
var s2 = this;
s2.test = 'Yup'
}
// controller attached to module with an anonymous function (controller as)
mod.controller('runIt', function(){
var r = this;
r.test = 'Hello';
})
// controller attached to module using $scope
mod.controller('syntax3',['$scope',function($scope){
$scope.test = 'syntax3';
}])
<file_sep>/week3/problem-set-2/source.js
function firstReverse(s){
var reverseString = '';
for (var i=0; i<s.length; i++){
reverseString = s.charAt(i) + reverseString;
}
return reverseString;
}
console.log('firstReverse: ',firstReverse('thisistest'));
function swapCase(s){
var capString = '';
for (var i=0; i < s.length; i++){
if (s.charAt(i) === s.charAt(i).toLowerCase()){
capString += s.charAt(i).toUpperCase();
}
else{
capString += s.charAt(i).toLowerCase();
}
}
return capString;
}
console.log('swapCase: ',swapCase('ThisIsTest'));
function letterCount(s){
var a = s.split(' ');
var highestCount = 0;
var highestCountIndex;
//loop through array of strings or words
a.forEach(function(e,index){
//Loop through the string
for(var i=0; i<e.length; i++){
var highestTally = 0;
var tally = 0;
var ch = e.charAt(i);
//Compare this letter to each letter in string
for (var c=0; c<e.length; c++){
if(ch == e.charAt(c)){
tally++;
}
if (c == e.length-1 && tally > highestTally){
highestTally = tally
}
}
if (highestTally > highestCount){
highestCount = highestTally;
highestCountIndex = index;
}
}
})
return a[highestCountIndex];
}
console.log("letterCount: The word '"+letterCount("Today, is the greatest day ever!")+"' has the highest number of repeating characters.");<file_sep>/week6/express intro/server.js
var express = require('express');
var bodyParser = require('body-parser');
//create app
var app = express();
//body parser to deal with url encoding
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
//static file server
app.use(express.static(__dirname+'/public'))
//specific route instructions
app.get('/', function(request, response){
console.log(request.query)
response.sendFile('index.html', { root:'./public/html'})
});
app.post('/createuser', function(request,response){
console.log("creating a user...", request.body);
response.send(`Welcome back ${request.body.name}`)
})
app.listen(process.env.PORT || 3000, function(){
console.log('Server Running')
})
<file_sep>/week3/function-practice-2/source.js
function getName(myObject){
return myObject.name;
}
console.log(getName({name: 'Luisa',age:25}));
console.log('');
function totalLetters(a){
var totalCharacters = 0;
a.forEach(function(e){
totalCharacters = totalCharacters + e.length;
});
return totalCharacters;
}
console.log(totalLetters(['javascript', 'is', 'awesome']));
console.log(totalLetters(['what', 'happened', 'to', 'my', 'function']));
console.log('');
function keyValue(a,b){
var newObj = {[a]:b};
return newObj;
}
console.log(keyValue('city', 'Denver'));
console.log('');
function negativeIndex(a,i){
return a[a.length+i];
}
console.log(negativeIndex(['a', 'b', 'c', 'd', 'e'], -2));
console.log(negativeIndex(['jerry', 'sarah', 'sally'], -1));
console.log('');
function removeM(s){
var newS = '';
for (var i=0; i<s.length; i++){
if (s.charAt(i) != 'm'){
newS += s.charAt(i);
}
}
return newS
}
console.log(removeM('family'));
console.log(removeM('memory') );
console.log('');
function printObject(a){
var structKeys = Object.keys(a);
structKeys.forEach(function(e){
console.log(`${e} is ${a[e]}`)
})
}
printObject({ a: 10, b: 20, c: 30 });
printObject({ firstName: 'pork', lastName: 'chops' })
console.log('');
function vowels(s){
var array = [];
for (var i=0; i < s.length; i++){
if (s.charAt(i) == 'a'|s.charAt(i) == 'e'|s.charAt(i) == 'i'|s.charAt(i) == 'o'|s.charAt(i) == 'u'){
array.push(s.charAt(i))
}
}
return array;
}
console.log(vowels('alabama') );
console.log(vowels('What evil odd ducks!'));
console.log('');
function twins(a){
var isTwins = true;
if (a.length % 2 != 0){
isTwins = false;
}
for (var i=0; i<a.length; i = i+2){
if (a[i] != a[i+1]){
isTwins = false;
}
}
return isTwins;
}
console.log(twins(['a', 'a', 'b', 'b', 'c', 'c']));
console.log(twins(['a', 'a', 'b', 'c', 'd', 'd']));
console.log(twins(['a', 'a', 'b', 'z']));
console.log(twins(['a', 'a', undefined]) );
console.log('');
function or(a){
var isTrue = false;
for (var i=0; i<a.length; i++){
if (a[i] == true){
isTrue = true;
break
}
}
return isTrue
}
console.log(or([false, false, true, false]));
console.log(or([false, false, false]));
console.log(or([]));
console.log('')
function unique(a){
var filtered = []
for(var i=0; i<a.length; i++){
if (filtered.includes(a[i]) == false){
filtered.push(a[i]);
}
}
return filtered
}
console.log(unique(['a', 'b', 'a', 'c', 'd', 'd']) );
console.log(unique(['todd', 'avery', 'maria', 'avery']));<file_sep>/week4/inspirational-quotes/data.js
var data = [
{
quote:"This is an example of a quote",
name:"Jon",
ratings:[2,4]
},
{
quote:"This is an example of a quote",
name:"tom",
ratings:[1,2,2]
},
]
<file_sep>/week3/class-exercise/wednesday/app.js
angular.module('tokyo',[])
.controller('abyss', abyss)
function abyss(){
var abyss = this;
}
<file_sep>/week3/loop-practice-2/script.js
var animals = ['rat','cat','butterfly','marmot','ocelot'];
for(var i=0; i<animals.length-1; i++) {
console.log(animals[i]);
}
console.log(' ');
for(var i=0; i < animals.length; i+=2){
console.log(animals[i]);
}
console.log(' ');
for(var i= animals.length; i>=0; i--){
console.log(animals[i]);
}
console.log(' ');
for(var i=0; i<animals.length;i++){
console.log(animals[i]);
if (i>0 && i < animals.length-1){
console.log(animals[i]);
}
}<file_sep>/week2/victims-and-volunteers/script.js
//Initialize global variables
var victimCount = 0;
var currentRecord = 1;
var volunteerCount = 0;
var currentVolunteer = 1;
var victims = [];
var volunteers = [];
//Initially ask the user how many victims to enter
var askCount = parseInt(prompt("How many victims do you wish to enter?"));
isNumberVic(askCount);
//Initially ask the user how many volunteers to enter
var vAskCount = parseInt(prompt("How many volunteers do you wish to enter?"));
isNumberVol(vAskCount);
// Setup the iteration information in the html
document.getElementById('count').innerHTML = currentRecord+' of '+ victimCount;
document.getElementById('vcount').innerHTML = currentVolunteer+' of '+ volunteerCount;
//addVictim is called when the user submit the form
function addVictim(){
//Only iterate the submittion if the current record is lower than the total record submissions requested
if (currentRecord < victimCount){
currentRecord++;
updateData();
clearInputs();
document.getElementById('count').innerHTML = currentRecord+' of '+victimCount;
}
//If the user wants to submit additional records ask how many and update the iteration count in the html
else if( currentRecord == victimCount){
updateData();
askCount = parseInt(prompt(victimCount+' names submitted. '+'How many additional victims would you like to add?'));
isNumberVic(askCount);
document.getElementById('count').innerHTML = currentRecord+' of '+ victimCount;
}
}
//addVolunteer is called when the user submit the form
function addVolunteer(){
//Only iterate the submittion if the current record is lower than the total record submissions requested
if (currentVolunteer < volunteerCount){
currentVolunteer++;
updateDataV();
clearInputs();
document.getElementById('vcount').innerHTML = currentVolunteer+' of '+volunteerCount;
}
//If the user wants to submit additional records ask how many and update the iteration count in the html
else if( currentVolunteer == volunteerCount){
updateDataV();
vAskCount = parseInt(prompt(volunteerCount+' names submitted. '+'How many additional volunteers would you like to add?'));
isNumberVol(vAskCount);
document.getElementById('vcount').innerHTML = currentVolunteer+' of '+ volunteerCount;
}
}
//Used to attempt number validation. Terminates prompts after 2 failed attempts to prevent the need for while loop.
function isNumberVic(num){
if (isNaN(num) == true){
alert('Please enter only numbers');
num = parseInt(prompt('How many additional victims would you like to add?'));
}
else{
victimCount = victimCount + num;
}
}
//Used to attempt number validation. Terminates prompts after 2 failed attempts to prevent the need for while loop.
function isNumberVol(num){
if (isNaN(num) == true){
alert('Please enter only numbers');
num = parseInt(prompt('How many additional volunteers would you like to add?'));
}
else{
volunteerCount = volunteerCount + num;
}
}
//update the object data with the submitted data and post it to the console log
function updateData(){
victims[victims.length] = {
name:document.getElementById('name').value,
phone:document.getElementById('phone').value,
street:document.getElementById('street').value
}
console.log(victims);
/*
Had I used 3 arrays rather than a collection it would look like this:
names.push(document.getElementById('name').value)
phones.push(document.getElementById('phone').value)
streets.push(document.getElementById('street').value)
*/
}
function updateDataV(){
volunteers[volunteers.length] = {
name:document.getElementById('vname').value,
phone:document.getElementById('vphone').value,
street:document.getElementById('vstreet').value
}
console.log(volunteers);
/*
Had I used 3 arrays rather than a collection it would look like this:
vnames.push(document.getElementById('vname').value)
vphones.push(document.getElementById('vphone').value)
vstreets.push(document.getElementById('vstreet').value)
*/
}
//clear the input fields to prepare for the next data set
function clearInputs(){
document.getElementById('name').value = '';
document.getElementById('phone').value = '';
document.getElementById('street').value = '';
}
function summary(){
alert('Number of victims: '+ victims.length + '\nNumber of volunteers: '+ volunteers.length + '\nAll Victims:\n'+ JSON.stringify(victims) + '\nAll Volunteers:\n' + JSON.stringify(volunteers));
}
function search(){
var sstreet = document.getElementById('sstreet').value;
var person = volunteers.filter(function(obj){return obj.street == sstreet});
console.log(person);
if (person.length > 0){
console.log(person.length);
document.getElementById('searchResult').innerHTML = "Volunteer "+person[0].name+" is also on "+person[0].street;
}
else
{
document.getElementById('searchResult').innerHTML = "no one has been found";
}
}<file_sep>/week3/intro-to-angular/app.js
///////////////////////
//Part 1
//////////////////////
var app = angular.module("app",[]);
app.controller('controllerAsSyntax', function(){
this.title = 'Controller as syntax';
this.conLog = function(){
console.log('my controller as syntax message');
}
});
app.controller('standardSyntax',['$scope',function($scope){
$scope.title = 'Standard Syntax';
$scope.conLog = function(){
console.log('my standard syntax message');
};
$scope.reveal = function(target){
console.log(`show: ${target}`);
document.getElementById(target).style.display = 'block';
};
}]);
///////////////////////
//Part 2
//////////////////////
// Seperated simply for practice writing the syntax
var app2 = angular.module('app2',[]);
app2.controller('part2Controller',['$scope', function($scope){
$scope.title = 'PART 2';
$scope.changeBg = function(event){
event.target.style.color = 'pink';
console.log(event.target.parentElement.firstElementChild.innerHTML = event.target.parentElement.firstElementChild.innerHTML+'!')
};
$scope.exit = function(event){
var response = confirm('Are you sure you want to navigate to '+ event.target.href+' ?');
if(response == false){
event.preventDefault();
event.target.style.display = 'none'
}
};
}]);
///////////////////////
//Part 3
//////////////////////
// Seperated simply for practice writing the syntax
app.controller('pop', ['$scope',function($scope){
$scope.title = 'PART 3';
$scope.toggleModal = function(){
var classExists = document.getElementById('modal').className.indexOf("show");
//If .show is contained within the className string
if (classExists != -1){
//Create and array of all classes
var classArray = document.getElementById('modal').className.split(' ');
//remove .show class if it exists
var removedClass = classArray.filter(function(element){
if (element == 'show'){
return false
}else{
return true
}
})
//stringify the class name array
var toggledClass = removedClass.join(' ');
document.getElementById('modal').className = toggledClass;
//if .show did not exist in the className string
}else{
//Append to className
document.getElementById('modal').className += ' show';
}
};
}])
<file_sep>/week3/infinite-agenda/script.js
var app = angular.module('app',[]);
app.controller('page',['$scope',function($scope){
$scope.title = 'Super Calendar';
// Varibales for sample data
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate()+1);
var future = new Date();
future.setDate(future.getDate()+2);
$scope.agenda = [
{
date: today,
desc:'Leave for the day',
priority:'normal',
},
{
date: tomorrow,
desc:'Eat lunch and stuff',
priority:'normal',
},
{
date: future,
desc:'Class Battle-Royale',
priority:'normal',
}
];
//Return true if the date's month is within the current month
$scope.dateClass = function (d){
var current = new Date();
var className = '';
if (d.getDay() == current.getDay() && d.getMonth() ==current.getMonth()){
className = 'today';
}else if(d.getDay() == current.getDay()+1 && d.getMonth() ==current.getMonth()){
className = 'tomorrow'
}
return className;
}
//add a new date
$scope.createDate = function(){
var form = $scope.form;
var current = new Date();
var newDate = {};
newDate.date = new Date(parseInt(current.getFullYear()), parseInt(form.month),parseInt(form.day),parseInt(form.hour),parseInt(form.minute));
newDate.desc = form.task;
newDate.priority = 'normal';
$scope.agenda.push(newDate);
console.log(newDate);
}
}])
<file_sep>/week1/browser-js-basics/chat.js
var userName = prompt('Hello human meat bag. What name should I call you?');
alert(`Hello ${userName}! I've now drained you bank account and kicked your dog. Have a nice day :)`)<file_sep>/week6/signup-form/app.js
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
//initialize express
var app = express();
app.get('/', function(request, response){
var page = fs.readFileSync('form.html');
response.header('content-type', 'text/html')
response.send(page)
})
app.post('/formsubmit', function(request, response){
response.redirect('/success');
})
app.get('/success',function(request, response){
response.header('content-type', 'text/html')
response.send('Success!');
})
var port = 3000;
app.listen(port,function(){
console.log('server running')
})
<file_sep>/week2/simple-validator/script.js
//PHONE NUMBER VALIDATION
document.getElementById('phone').addEventListener('keypress',function(event){
if (event.key == 'Enter'){
var value = document.getElementById('phone').value;
var msg = 'Great! '+value+" is a valid number. The spam-a-thon has begun!!!";
var result = value.length === 12 && value[3] =='-' && value[7] == '-';
if (result == false){
msg = 'Please ensure your phone number is 12 characters including dashes!'
}
document.getElementById('phone').nextElementSibling.innerHTML = msg;
}
})
//BIRTHDAY VALIDATION
document.getElementById('bd').addEventListener('keypress',function(event){
if (event.key == 'Enter'){
var value = document.getElementById('bd').value;
var msg = 'Great! Your birthday is '+value;
var result = parseInt(value.slice(0,2)) <= 12;
if (result == false){
msg = "Make sure the first two characters are for the month... we don't have a month larger than 12"
}
var result = parseInt(value.slice(3,5)) <= 31;
if (result == false){
msg = "Months do not have more than 31 days!"
}
result = value[2] == '/' && value[5] == '/'
if (result == false){
msg = 'Make sure to use / in the correct places! :)'
}
result = value.length == 8
if (result== false){
msg = 'Please ensure you have 8 characters'
}
document.getElementById('bd').nextElementSibling.innerHTML = msg;
}
})
//ZIPCODE
document.getElementById('zip').addEventListener('keypress',function(event){
if (event.key == 'Enter'){
var value = document.getElementById('zip').value;
var msg = 'Great! Your zipcode is '+value;
var result = value.length == 5 || (value.length == 10 && value[5] == '-');
if (result == false){
msg = "Ensure your zipcode has only 5 digits or 9 digits with a dash!"
}
document.getElementById('zip').nextElementSibling.innerHTML = msg;
}
})
//STATE
document.getElementById('state').addEventListener('keypress',function(event){
if (event.key == 'Enter'){
var value = document.getElementById('state').value;
var msg = 'Great! Your state is '+value;
var result = value.length == 2 & value === value.toUpperCase();
if (result == false){
msg = "Please ensure you use 2 UPPERCASE characters!"
}
document.getElementById('state').nextElementSibling.innerHTML = msg;
}
})
//MARRIED
document.getElementById('married').addEventListener('keypress',function(event){
if (event.key == 'Enter'){
var value = document.getElementById('married').value;
var msg = 'Great! You said '+value.toLowerCase()+" you are";
if (value == 'no'){
msg = msg + (" NOT married! Alas, i'm a computer and cannot date ... yet!");
}
else{
msg = msg + " married!";
}
var result = value.toLowerCase() == 'yes' || value.toLowerCase() == 'no';
if (result == false){
msg = "Please reply with only yes or no. Also note that I don't litterally mean the phrase 'yes or no'"
}
document.getElementById('married').nextElementSibling.innerHTML = msg;
}
})
<file_sep>/week2/function-practice-1/script.js
///////////////////////
//TripleFive
///////////////////////
function tripleFive (){
for(i=1; i<= 3; i++){
console.log('Five!');
}
}
console.log('tripleFive: ');
tripleFive();
///////////////////////
//lastLetter
///////////////////////
function lastLetter(s){
var last = s[s.length-1];
return last;
}
console.log("lastLetter('hello'): " + lastLetter("hello"));
console.log("lastLetter('island'): " + lastLetter("island"));
///////////////////////
//square
///////////////////////
function square(num){
var squared = num * num;
return squared;
}
console.log("square(3): "+ square(3));
console.log("square(5): "+ square(5));
///////////////////////
//negate
///////////////////////
function negate(num){
var negative = -num;
return negative;
}
console.log("negate(5): " + negate(5));
console.log("negate(-8): " + negate(-8));
///////////////////////
//toArray
///////////////////////
function toArray (a, b, c){
var array = [a,b,c];
return array;
}
console.log("toArray(1,4,5): "+ toArray(1,4,5));
console.log("toArray(8,9,10): "+ toArray(8,9,10));
///////////////////////
//startsWithA
///////////////////////
function startsWithA(s){
var result = s[0].toLowerCase() == 'a';
return result;
}
console.log("startsWithA('aardvark'): " +startsWithA('aardvark'));
console.log("startsWithA('bear'): " +startsWithA('bear'));
///////////////////////
//excite
///////////////////////
function excite(s){
var result = s+'!!!';
return result;
}
console.log("excite('yes'): " + excite('yes'));
console.log("excite('go'): " + excite('go'));
///////////////////////
//sun
///////////////////////
function sun(s){
var result = s.indexOf('sun') != -1;
return result
}
console.log("sun('sundries'): "+ sun('sundries'));
console.log("sun('asunder'): "+ sun('asunder'));
console.log("sun('catapult'): "+ sun('catapult'));
///////////////////////
//tiny
///////////////////////
function tiny(num){
var result = num < 1 && num > 0;
return result;
}
console.log("tiny(0.3): "+ tiny(0.3));
console.log("tiny(14): "+ tiny(14));
console.log("tiny(-5): "+ tiny(-5));
///////////////////////
//getSeconds
///////////////////////
function getSeconds(s){
var result = parseInt(s.slice(0,2)) * 60 + parseInt(s.slice(3,5));
return result;
}
console.log("getSeconds('01:30'): "+ getSeconds('01:30'));
console.log("getSeconds('10:25'): "+ getSeconds('10:25'));<file_sep>/week6/chunk/app.js
var input = [1,2,3,4,5,6,7,8,9,10];
function splitter(a,s){
var count = Math.floor(a.length/s);
var result = [];
for (var i = 0 ; i<s; i++){
var group = (a.length%s)-i>0?a.slice(i * count, (i*count)+count+1):a.slice(i * count, (i*count)+count)
// if ((a.length%s)-(i) > 0 ){
// var group = a.slice(i * count, (i*count)+count+1);
// }else{
// var group = a.slice(i * count, (i*count)+count);
// }
result.push(group)
}
return result
}
console.log('splitter([1,2,3,4,5,6,7,8,9,10],3): ',splitter(input,3))
<file_sep>/week2/string-reporter/script.js
document.getElementById('color').addEventListener('keypress',function(event){
if (event.key == 'Enter'){
console.log('key: '+ event.key);
var color = document.getElementById('color').value;
var output = "What?! no way! My favorite <span style='color:"+color+";'>color</span> is <span style='color:"+color+";'>" +color+"</span> too!";
console.log(output)
var target = document.getElementById('result')
target.innerHTML='';
target.insertAdjacentHTML('beforeend',output);
target.insertAdjacentHTML('beforeend',"<p>You entered: "+color+"</p>");
target.insertAdjacentHTML('beforeend',"<p>There are "+ color.length +" characters in the word.</p>");
target.insertAdjacentHTML('beforeend',"<p>The third character is: "+color[2]);
target.insertAdjacentHTML('beforeend',"<p>toLowerCase: "+color.toLowerCase()+"</p>");
target.insertAdjacentHTML('beforeend',"<p>toUpperCase: "+color.toUpperCase()+"</p>");
target.insertAdjacentHTML('beforeend',"<p>subword: "+color.slice(1,4)+"</p>");
}
})
//var color = prompt("What's you favorite color and junk?");<file_sep>/week3/slideshow/app.js
angular.module('SlideShow',[])
.controller('slider', slideController)
slideController.$inject = ['images','$interval','$timeout'];
angular.module('SlideShow')
.factory('images',imageFactory)
function slideController(images,$interval,$timeout){
var s = this;
s.images = images.imgArray;
s.focusImg = 0;
s.sliderIndex = 0;
s.maxCount = Math.ceil(window.innerWidth/300);
s.transition = {
transition: '300ms ease',
transform:'translateX(0)',
}
s.maxViewable = function(element, index){
if (index < s.maxCount){
return true
}else{
return false
}
}
s.setFocus = function(i){
s.focusImg = i;
s.sliderIndex = i;
s.transition.transform = 'translateX(-'+s.focusImg*300+'px)';
}
s.setFocusExt= function(i){
s.focusImg = i;
s.sliderIndex = i;
s.transition.transform = 'translateX(-'+ parseInt(parseInt((s.images.length) * 300) + parseInt(i * 300)) +'px)';
$timeout(function(){
s.transition.transition = 'none';
s.transition.transform = 'translateX(-'+s.focusImg*300+'px)';
$timeout(function(){
s.transition.transition = '300ms ease'
},20)
},300)
}
s.pause = function(){
if (s.autoSlide.$$state.status != 0){
s.autoSlide = $interval(s.timer,4000);
}else{
$interval.cancel(s.autoSlide);
}
}
s.timer = function(){
console.log('focusImg: ',s.focusImg)
if (s.focusImg < s.images.length - 1 ){
s.focusImg += 1;
s.sliderIndex +=1;
s.transition.transform = 'translateX(-'+s.focusImg*300+'px)';
}
else if (s.sliderIndex < s.images.length){
s.transition.transform = 'translateX(-'+(s.sliderIndex+1)*300+'px)';
s.focusImg = 0;
$timeout(function(){
s.transition.transition = 'none'
s.transition.transform = 'translateX(0)';
s.sliderIndex = 0;
$timeout(function(){
s.transition.transition = '300ms ease'
},20)
},300)
}
};
s.autoSlide = $interval(s.timer,4000);
//console.log('start',s.autoSlide)
}
function imageFactory(){
var imgArray = [
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-15.jpg',
title:'Lavender',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-32.jpg',
title:'Deep Red',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-31.jpg',
title:'Apocalypse Now',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-33.jpg',
title:'Bamboo Forest',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-34.jpg',
title:'Frozen Forest',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-35.jpg',
title:'Bolivia',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-36.jpg',
title:'Bagan Balloons',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-38.jpg',
title:'Tylip Field',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-51.jpg',
title:'Winter Silence',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-41.jpg',
title:'Spring Time',
},
{
src: 'http://static.boredpanda.com/blog/wp-content/uuuploads/landscape-photography/landscape-photography-44.jpg',
title:'Aspen Cathedral',
},
]
return{
imgArray : imgArray,
}
}
<file_sep>/week2/problem-set-1/script.js
function letterCapitalize (s){
var cap = s.split(' ')
for ( var i = 0; i < cap.length; i++){
cap[i] = cap[i].charAt(0).toUpperCase() + cap[i].substr(1);
}
cap = cap.join(" ");
console.log("letterCapitalize('the man went for a walk'): " + cap);
return cap;
}
letterCapitalize('the man went for a walk');
function wordCount(s){
var count = s.split(' ').length;
console.log("wordCount('the man went for a walk'): "+ count);
return count;
}
wordCount('the man went for a walk');
function primeTime(n){
var sqr = Math.sqrt(n);
var isPrime = n + ' is prime!';
var factorFound = false;
for (var i = 2; i <= sqr; i++){
if (n % i == 0){
isPrime = n + ' in NOT prime!';
factorFound = true;
break
}
}
console.log ("primeTime("+n+"): "+factorFound+" : "+isPrime);
return factorFound;
}
primeTime(4);
primeTime(3);<file_sep>/week2/mad-metrics/script.js
//Scroll variables
var percentExplored = 0;
var screenHeight;
var totalHeight;
var totalWidth;
var scrollPos;
var viewPos;
var lastPos = 0;
var distanceScrolled = 0;
//Used for time spent in each section
//array index of current section
var currentSection = 0;
var priorSection = 0;
//time in seconds the current section was entered
var startTime = 0;
//timing variables
var totalTime = 0;
var sections= [];
function toggleClass(c,elementId){
var e = document.getElementById(elementId);
var className = e.className;
if (className.includes(c)){
var classArray = className.split(' ');
classArray.splice(classArray.indexOf(c),1);
e.className = classArray.join(' ');
}else{
e.className = className + ' ' + c;
}
}
document.addEventListener('scroll', function(){
//set the current scroll position
scrollPos = Math.round(window.scrollY);
//Determine the scroll percentage and highest scroll percentage
document.getElementById('scroll-pos').innerHTML = 'Scroll Position: '+ scrollPos;
var percent = Math.round((scrollPos / totalHeight)*100);
if(percentExplored < percent){
percentExplored = percent;
document.getElementById('scroll-percent').innerHTML = 'Percent Scrolled: '+ percentExplored + '%';
}
//determine how far the page has scrolled since the last iteration and add it to the total distance
distanceScrolled = distanceScrolled + (Math.abs(scrollPos - lastPos));
document.getElementById('scroll-distance').innerHTML = 'Distance Scrolled: '+ distanceScrolled + 'px';
//Prepare lastPos variable to be compared to the scroll position in the next iteration.
lastPos = scrollPos;
});
function getCurrentSection(){
sections.forEach(function(section,i){
//if the current view/scroll position (center of screen) is between the element top and the element bottom push it's index to array
if (section.offsetTop <= scrollPos+screenHeight/2 && (section.offsetTop + section.height) >= scrollPos+screenHeight/2){
currentSection = i;
}
});
return
}
window.onload = function(){
screenHeight = window.innerHeight;
totalHeight = document.documentElement.scrollHeight - screenHeight;
totalWidth = document.documentElement.scrollWidth;
//setup stopwatch
setInterval(stopWatch, 1000);
//initialize and array of section objects
var sectionArray = document.getElementsByClassName('content-block');
for(var i = 0; i < document.getElementsByClassName('content-block').length; i++){
sections.push({
offsetTop:sectionArray[i].offsetTop,
height: sectionArray[i].offsetHeight,
timeViewed: 0
});
}
//Allows for page refresh on areas other than the top of the page
getCurrentSection();
priorSection = currentSection;
};
function stopWatch(){
totalTime = totalTime + 1;
document.getElementById('time-total').innerHTML = 'Time on Page: '+totalTime+' sec';
//find current section
getCurrentSection();
//increment the time viewed for the current section by 1 sec
sections[currentSection]['timeViewed']++;
}
function outputSectionTime(){
for (var i = 0; i < sections.length; i++){
console.log(`Section ${i+1} Time Viewed: ${sections[i]['timeViewed']}`)
}
console.log(' ');
console.log(' ');
}
<file_sep>/week4/millinilBot/main.js
angular.module("MillBot", [])
.controller("bot", botController);
botController.$inject=["$http","$timeout"];
function botController ($http,$timeout){
var bCtrl=this;
bCtrl.log = [{
u:'Hey Millenial Bot! I was just in a super intense meditation, like third eye blown, and was thinking about some really cool shit. What do you know about ',
r:''
}]
//bCtrl.logSearch = [''];
//bCtrl.logResponse = [];
bCtrl.handleResponse = function(e){
if (e.type == 'keydown' && e.key =='Enter'){
console.log(e.target.value)
bCtrl.getInfo(e.target.value);
e.target.blur();
}
}
var arrayofResponses = [
"Whoa, chill brah. What about ",
"yeah, I missed that lecture. I had a free range yoga class. Maybe... ",
"#yolo "
]
var arrayofBot = [
"Seriously?! I knew that before it was cool. Obviously, ",
"DOOOOOOD. How did you not know that ",
"#RUPharrel? like srsly, ",
"Sorry dude, my kombucha is over fermenting, I gotta run."
]
var botIndex = 0;
var index = 0;
bCtrl.getInfo = function (item){
$http.get("https://en.wikipedia.org/w/api.php?action=opensearch&search="+item).then(function(response){
console.log(response)
bCtrl.log[bCtrl.log.length-1].r = '...';
$timeout(function(){
bCtrl.log[bCtrl.log.length-1].r = arrayofBot[botIndex]+response.data[2][0]+ " 💩";
botIndex ++;
},1000);
$timeout(function(){
bCtrl.log.push({
u:arrayofResponses[index],
r:''
})
index ++;
},2000);
})
}
}
<file_sep>/week6/node-colors/color.js
var $request = require('request');
var color = process.argv[2];
$request.get('https://cdn.rawgit.com/metaraine/swatch/74580660c9229541622bbf1fd4198618d9f677e5/webcolors.json', function(e,response){
var colorList = JSON.parse(response.body);
var targetColor = colorList.filter(function(element,index){
if (element.name.toUpperCase() == color.toUpperCase()){
return true
}
})
if (targetColor.length > 0){
console.log(`${targetColor[0].rgb.r} ${targetColor[0].rgb.g} ${targetColor[0].rgb.b}`)
}else {
console.log('Color Not Found')
}
})
<file_sep>/week2/loop-practice-1/script.js
for(var i=0; i<501; i+=100){
console.log(i);
}
for(var i=1; i<65; i+=i){
console.log(i);
}
for (var i=1.33; i < 4; i+=.33){
console.log(Math.floor(i));
}
for (var i = 0; i<=10; i+=2){
console.log(i);
}
for (var i=3; i<=15; i+=3){
console.log(i);
}
for(var i=9; i>=0; i-=1){
console.log(i);
}
for (var i=0; i<=12; i++){
console.log(i%4)
}
for (var i=0; i<3; i++){
for(var a = 0; a < 4; a++){
console.log(a);
}
} | eee3f3813638c550bdd5e6bf8c571c5dc38edd39 | [
"JavaScript"
] | 25 | JavaScript | DysonJ/Exercises | cd956cfd606e8621c959c93d82b1d69b4227de3e | 9624670d10eea108898f30af66b2edc6e71b909d |
refs/heads/master | <file_sep>
import React, { Component } from 'react';
import { View, Text, TextInput, Button, Image, TouchableOpacity, ScrollView, Dimensions, Alert, TouchableWithoutFeedback } from 'react-native';
import { Overlay, ModalIndicator, Toast } from 'teaset'
import appConfig from '../../../jsonData/appConfig.js'
export default class WangJiMiMa extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6183b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('otherParam', '忘记密码'),
}
}
state = {
phone: '',//手机号码
passWord: '',//密码
code: '',//验证码
}
fun1 = async () => {
if (this.state.phone == '') {
// Alert.alert('手机号码未填写')
Toast.fail('手机号码未填写')
return
}
if (this.state.passWord == '') {
// Alert.alert('新密码未填写')
Toast.fail('新密码未填写')
return
}
if (this.state.code == '') {
// Alert.alert('验证码未填写')
Toast.fail('验证码未填写')
return
}
// 修改密码
ModalIndicator.show('请稍等。。。')
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/resetPwd`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
phone: this.state.phone,
pwd: this.state.passWord,
code: this.state.code
}),
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
ModalIndicator.hide()
Toast.success('密码重置成功')
this.timer1 = setTimeout(() => {
this.props.navigation.replace('DengLu')
this.timer1 && clearTimeout(this.timer1)
}, 2000);
} else {
ModalIndicator.hide()
console.log('失败', responseJson);
Toast.fail('操作失败')
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
//获取验证码
fun2 = () => {
if (!/^1\d{10}$/.test(this.state.phone)) {
// Alert.alert('请先填写正确的手机号码')
Toast.fail('请先填写正确的手机号码')
return
}
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/code`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}),
// body: JSON.stringify({//请求参数
// // templeId: this.props.navigation.getParam('templeId')
// templeId: '1'
// }),
body: `phone=${this.state.phone}`,
})
.then((response) => {
// console.log('response', response);
// return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
// console.log('data1', responseJson.data)
// Alert.alert('验证码发送成功,请注意查收')
Toast.message('验证码发送成功,请注意查收')
})
.catch((error) => {
console.log('error', error);
Toast.fail('验证码发送失败,请重试。')
})
}
render() {
const { width } = Dimensions.get('window');
return (
<ScrollView
keyboardShouldPersistTaps='handled'
style={{
flex: 1,
paddingRight: 30,
paddingLeft: 30,
paddingTop: 93,
paddingBottom: 131,
}}
>
<Text style={{
color: '#6183b1',
}}>手机号码</Text>
<TextInput
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
onChangeText={(text) => {
this.setState({
phone: text
})
}}
>{this.state.phone}</TextInput>
<Text style={{
color: '#6183b1',
}}>新密码</Text>
<TextInput
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
secureTextEntry={true}
onChangeText={(text) => {
this.setState({
passWord: text
})
}}
>{this.state.passWord}</TextInput>
<View style={{
flexDirection: "row",
alignItems: "center",
// backgroundColor:'#545465'
}}>
<View style={{
// backgroundColor:'#590348',
width: width - 60 - 116 - 21,
}}>
<Text style={{
color: '#6183b1',
}}>验证码</Text>
<TextInput
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
onChangeText={(text) => {
this.setState({
code: text
})
}}
>{this.state.code}</TextInput>
</View>
<TouchableOpacity
onPress={() => {
this.fun2()
}}
style={{
height: 46,
alignItems: "center",
justifyContent: 'center',
borderRadius: 5,
borderWidth: 1,
borderColor: '#6183b1',
position: 'relative',
top: -21,
width: 116,
marginLeft: 21,
}}
>
<Text style={{
color: '#6183b1',
}}>获取验证码</Text>
</TouchableOpacity>
</View>
<TouchableOpacity
onPress={() => {
this.fun1()
}}
style={{
backgroundColor: '#6183b1',
borderRadius: 5,
alignItems: "center",
justifyContent: "center",
height: 36,
}}
>
<Text style={{
color: '#FFFFFF',
}}>提交</Text>
</TouchableOpacity>
</ScrollView>
);
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, TouchableOpacity, Image, Alert, Dimensions, ScrollView, TextInput, ImageBackground, TouchableWithoutFeedback } from 'react-native';
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
import { Overlay, ModalIndicator, Toast, Checkbox } from 'teaset'
import * as WeChat from 'react-native-wechat-lib'
import Alipay from '@0x5e/react-native-alipay';
import moment from 'moment';
// WeChat.registerApp(appConfig.wxAppId,'https://help.wechat.com/');//此方法应全局调用一次
const { width, height } = Dimensions.get('window');
export default class JuanZeng extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 18,
color: '#fff',
fontWeight: 'bold',
},
title: navigation.getParam('title', '捐赠'),
headerRight: (
<Image />
)
}
}
state = {
wx: false,
zfb: false,
isCheck: false,
Yuan: '',//捐赠金额
JuanName: '',//捐款用的昵称
isNiMing: false,//是否匿名
hxw: '愿以此功德,庄严佛净土,上报四重恩,下济三途苦。若有见闻者,悉发菩提心,尽此一报身,同生极乐国。',//回向文
isZDY: false,//是否自定义回向文
Authorization: ''//用户唯一识别码
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
// this.getValue1()
this.JianCeDengLu()
}
// 检测是否登录
JianCeDengLu = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户信息
let valueObj = JSON.parse(value)
if (valueObj.outTime > moment().unix()) {
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/me`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: '',
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
ModalIndicator.hide()
this.setState({
JuanName: responseJson.data.nickName,
Authorization: `${valueObj.token_type} ${valueObj.access_token}`
})
console.log('返回的数据', responseJson.data.nickName);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
this.TiShiDengLu()
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
this.TiShiDengLu()
}
} else {
ModalIndicator.hide()
this.TiShiDengLu()
}
console.log('value', value)
} catch (error) {
// read error
ModalIndicator.hide()
console.log('error', error)
}
console.log('Done.')
}
// 提示用户登录
TiShiDengLu = () => {
// 提示用户先登录
let TiShiDengLuOverlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.TiShiDengLuOverlayView = v}
>
<ImageBackground
style={{
backgroundColor: '#fff',
padding: 3,
// borderRadius: 10,
height: 165,
width: 285,
}}
resizeMethod='resize'
resizeMode='cover'
source={require('../../../imgs/dl.png')}
>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 22,
}}>[请先登录]</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.overlayView1 && this.overlayView1.close()
this.overlayView2 && this.overlayView2.close()
this.props.navigation.goBack()
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>返回</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.overlayView1 && this.overlayView1.close()
this.overlayView2 && this.overlayView2.close()
this.props.navigation.replace('DengLu')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>确定</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Overlay.View>
);
Overlay.show(TiShiDengLuOverlayView);
}
render1 = (val) => {
if (this.state.Yuan == val) {
return (
<TouchableOpacity
style={{
justifyContent: 'center',
alignItems: 'center',
padding: 10,
borderWidth: 1,
borderRadius: 5,
borderColor: '#e4c590',
width: width / 4 - 15,
marginTop: 10,
backgroundColor: '#f9f7f4',
}}
onPress={() => {
this.setState({
Yuan: val,
isCheck: false,
})
}}
>
<Text style={{
fontSize: 18,
color: '#e4c590',
}}>{val}元</Text>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
style={{
justifyContent: 'center',
alignItems: 'center',
padding: 10,
borderWidth: 1,
borderRadius: 5,
borderColor: '#a3a3a3',
width: width / 4 - 15,
marginTop: 10,
backgroundColor: '#fff',
}}
onPress={() => {
this.setState({
Yuan: val,
isCheck: false,
})
}}
>
<Text style={{
fontSize: 18,
color: '#333',
}}>{val}元</Text>
</TouchableOpacity>
)
}
}
fun1 = async (txt) => {
//字段验证
// if (this.state.JuanName == '') {
// Alert.alert('请先填写功德主芳名')
// return
// }
if (this.state.Yuan == '') {
// Alert.alert('请先选择或填写捐赠金额')
Toast.fail('请先选择或填写捐赠金额')
return
}
if (this.state.Yuan < 0) {
// Alert.alert('捐赠金额必须大于0')
Toast.fail('捐赠金额必须大于0')
return
}
// if (this.state.hxw == '') {
// Alert.alert('请先填写回向文')
// return
// }
ModalIndicator.show()
// 支付类型判断
if (txt == '微信支付') {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// this.timer = setTimeout(() => {
// this.fun2()
// this.timer && clearTimeout(this.timer)
// }, 3000)
//
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/wxpay/createMeritOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
// 'Authorization': '<KEY>',
}),
body: JSON.stringify({//请求参数
productId: parseInt(this.props.navigation.getParam('productId', '')),
userNickName: this.state.isNiMing ? '' : this.state.JuanName,
money: parseFloat(this.state.Yuan).toFixed(2),
// days: parseInt(this.state.days),
// lamps: parseInt(1),
blessing: this.state.hxw,
prayType: parseInt(this.props.navigation.getParam('praytype', '')),
}),
// body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
WeChat.isWXAppInstalled()
.then((isInstalled) => {
if (isInstalled) {
this.payFun(responseJson)
} else {
ModalIndicator.hide()
// Alert.alert('请安装微信');
Toast.fail('请安装微信')
}
});
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
ModalIndicator.hide()
}
} else if (txt == '支付宝') {
// Alert.alert('支付宝方式付款')
// ModalIndicator.hide()
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// this.timer = setTimeout(() => {
// this.fun2()
// this.timer && clearTimeout(this.timer)
// }, 3000)
// 获取用户关注的寺院列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/alipay/createMeritOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
// 'Authorization': '<KEY>',
}),
body: JSON.stringify({//请求参数
productId: parseInt(this.props.navigation.getParam('productId', '')),
userNickName: this.state.isNiMing ? '' : this.state.JuanName,
money: parseFloat(this.state.Yuan).toFixed(2),
// days: parseInt(this.state.days),
// lamps: parseInt(1),
blessing: this.state.hxw,
prayType: parseInt(this.props.navigation.getParam('praytype', '')),
}),
// body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
// WeChat.isWXAppInstalled()
// .then((isInstalled) => {
// if (isInstalled) {
// this.payFun(responseJson)
// } else {
// ModalIndicator.hide()
// Alert.alert('请安装微信');
// }
// });
this.toPay(responseJson)
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
ModalIndicator.hide()
}
}
}
toPay = async (val) => {
if (val.data) {
// APP支付
try {
let response = await Alipay.pay(val.data.orderParams)
let { resultStatus, result, memo } = response;
// let { code, msg, app_id, out_trade_no, trade_no, total_amount, seller_id, charset, timestamp } = JSON.parse(result);
console.log('支付宝支付返回的结果', response)
if (resultStatus == '9000') {
ModalIndicator.show('查询支付结果。。。')
this.isPaySucceed(val.data.orderNo, this.state.Authorization)
} else {
ModalIndicator.hide()
Toast.message(memo)
// 取消未支付的订单
this.fun6(val.data.orderNo)
return
}
} catch (error) {
ModalIndicator.hide()
console.error('错误', error);
console.info('支付失败');
Toast.fail('支付失败,请联系开发人员')
}
} else {
ModalIndicator.hide()
// Alert.alert('支付参数不正确')
Toast.fail('支付参数不正确')
}
}
// fun2 = () => {
// // 询问用户是否支付成功
// let overlayView1 = (
// <Overlay.View
// style={{ alignItems: 'center', justifyContent: 'center' }}
// modal={true}
// overlayOpacity={0.5}
// ref={v => this.overlayView1 = v}
// >
// <View style={{
// backgroundColor: '#fff',
// padding: 20,
// borderRadius: 10,
// height: 250,
// width: 280,
// }}>
// <View style={{
// width: '100%',
// height: 50,
// alignItems: 'center',
// justifyContent: 'center',
// flex: 1,
// }}>
// <Text style={{
// fontSize: 20,
// }}>请确认支付是否已完成</Text>
// </View>
// <View style={{
// width: '100%',
// flexDirection: 'column',
// // justifyContent: 'space-between',
// }}>
// <TouchableOpacity
// onPress={() => {
// this.overlayView1 && this.overlayView1.close()
// // this.fun3()
// }}
// style={{
// padding: 10,
// backgroundColor: '#485784',
// borderRadius: 10,
// }}
// >
// <Text style={{
// fontSize: 17,
// color: '#fff',
// }}>已完成支付</Text>
// </TouchableOpacity>
// <TouchableOpacity
// onPress={() => {
// this.overlayView1 && this.overlayView1.close()
// // this.props.navigation.goback()
// }}
// style={{
// marginTop: 10,
// padding: 10,
// backgroundColor: '#666',
// borderRadius: 10,
// }}
// >
// <Text style={{
// fontSize: 17,
// color: '#fff',
// }}>支付遇到问题,重新支付</Text>
// </TouchableOpacity>
// </View>
// </View>
// </Overlay.View>
// );
// Overlay.show(overlayView1);
// }
// fun3 = () => {
// // 感谢用户的爱心捐赠
// let overlayView2 = (
// <Overlay.View
// style={{ alignItems: 'center', justifyContent: 'center' }}
// modal={true}
// overlayOpacity={0.5}
// ref={v => this.overlayView2 = v}
// >
// <View style={{
// backgroundColor: '#fff',
// padding: 20,
// borderRadius: 10,
// height: 200,
// width: 250,
// }}>
// <View style={{
// width: '100%',
// height: 50,
// alignItems: 'center',
// justifyContent: 'center',
// flex: 1,
// }}>
// <Text style={{
// fontSize: 20,
// }}>感谢您的爱心捐赠!祝您身体健康!</Text>
// </View>
// <View style={{
// width: '100%',
// flexDirection: 'column',
// // justifyContent: 'space-between',
// }}>
// <TouchableOpacity
// onPress={() => {
// this.overlayView2 && this.overlayView2.close()
// this.props.navigation.goBack()
// }}
// style={{
// padding: 10,
// backgroundColor: '#485784',
// borderRadius: 10,
// }}
// >
// <Text style={{
// fontSize: 20,
// color: '#fff',
// }}>好的</Text>
// </TouchableOpacity>
// </View>
// </View>
// </Overlay.View>
// );
// Overlay.show(overlayView2);
// }
// 通过用户唯一识别码和订单号查询支付是否成功的函数
isPaySucceed = (orderNum, Authorization) => {
this.setState({
wx: false,
zfb: false,
})
this.timerIsPaySucceed = setTimeout(() => {
console.log('订单号', orderNum)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/checkOrderPayInfo`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': Authorization
}),
// body: JSON.stringify({//请求参数
// productId: parseInt(this.props.navigation.getParam('productId', '')),
// userNickName: this.state.JuanName,
// }),
body: `orderNo=${orderNum}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
this.timerIsPaySucceed && clearTimeout(this.timerIsPaySucceed);
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
if (responseJson.data.platformStatus == 1) {
ModalIndicator.hide()
this.props.navigation.goBack()
// Alert.alert('订单支付成功')
Toast.success('订单支付成功')
}
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
// Alert.alert('订单支付失败')
Toast.fail('后台认为订单支付失败')
// 取消未支付的订单
this.fun6(orderNum)
}
})
.catch((error) => {
this.timerIsPaySucceed && clearTimeout(this.timerIsPaySucceed);
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
}, 1000);
}
//取消订单
fun6 = async (orderNo) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/cancelOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: `orderNo=${orderNo}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
// Toast.message('订单已取消!')
} else {
Toast.message('服务器取消订单失败')
}
})
.catch((error) => {
console.log('error', error);
})
} else {
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
}
// 微信支付函数
payFun = async function (responseJson) {
try {
console.log('支付参数', responseJson.data)
console.log('支付参数partnerid', responseJson.data.orderParams.partnerid)
console.log('支付参数prepayid', responseJson.data.orderParams.prepayid)
console.log('支付参数noncestr', responseJson.data.orderParams.noncestr)
console.log('支付参数timestamp', responseJson.data.orderParams.timestamp)
console.log('支付参数package', responseJson.data.orderParams.package)
console.log('支付参数sign', responseJson.data.orderParams.sign)
console.log('支付参数appid', responseJson.data.orderParams.appid)
let result = await WeChat.pay({
partnerId: responseJson.data.orderParams.partnerid, // 商家向财付通申请的商家id
prepayId: responseJson.data.orderParams.prepayid, // 预支付订单
nonceStr: responseJson.data.orderParams.noncestr, // 随机串,防重发
timeStamp: responseJson.data.orderParams.timestamp, // 时间戳,防重发
package: responseJson.data.orderParams.package, // 商家根据财付通文档填写的数据和签名
sign: responseJson.data.orderParams.sign, // 商家根据微信开放平台文档对数据做的签名
appId: responseJson.data.orderParams.appid
});
let {errCode,errStr}=result
if(errCode==0){
ModalIndicator.show('查询支付结果。。。')
this.isPaySucceed(responseJson.data.orderNo, this.state.Authorization)
}else{
ModalIndicator.hide()
Toast.message(errStr)
// 取消未支付的订单
this.fun6(responseJson.data.orderNo)
return
}
} catch (e) {
ModalIndicator.hide()
console.log('支付失败了', e)
// Toast.fail('支付失败,请联系开发者')
Toast.fail('操作已取消')
}
}
// render2 = (img, bgcolor, txt) => {
// return (
// <View style={{
// flexDirection: 'row',
// alignItems: 'center',
// marginLeft: 15,
// marginRight: 15,
// marginTop: 20,
// }}>
// <Image
// style={{
// width: 45,
// height: 45,
// }}
// resizeMethod='resize'
// resizeMode='stretch'
// source={img}
// />
// <TouchableOpacity
// onPress={() => {
// this.fun1(txt)
// }}
// style={{
// flex: 1,
// justifyContent: 'center',
// alignItems: 'center',
// backgroundColor: bgcolor,
// height: 45,
// borderRadius: 5,
// }}
// >
// <Text style={{
// color: '#fff',
// fontWeight: 'bold',
// fontSize: 20,
// }}>{txt}</Text>
// </TouchableOpacity>
// </View>
// )
// }
render3 = () => {
if (this.state.isCheck) {
return (
<View style={{
height: 50,
margin: 10,
backgroundColor: '#f8f8f8',
justifyContent: 'flex-start',
alignItems: 'center',
flexDirection: 'row',
alignItems: 'center',
borderRadius: 5,
}}>
<Text style={{
fontSize: 20,
color: '#000',
}}>请填写金额:</Text>
<TextInput
placeholder='请填写金额'
placeholderTextColor='#ccc'
autoFocus={true}
style={{
padding: 0,
height: 30,
flex: 1,
marginLeft: 5,
fontSize: 20,
lineHeight: 30,
color: '#2f2f2f',
}}
onChangeText={(text) => {
this.setState({
Yuan: text
})
}}
>{this.state.Yuan}</TextInput>
<Text style={{
color: '#6d6d6d',
fontSize: 20,
paddingLeft: 5,
position: 'absolute',
right: 5,
}}>元</Text>
</View>
)
} else {
return <></>
}
}
render4 = () => {
if (this.state.isCheck) {
return (
<TouchableOpacity
style={{
justifyContent: 'center',
alignItems: 'center',
padding: 10,
borderWidth: 1,
borderRadius: 5,
borderColor: '#e4c590',
width: width / 4 - 15,
marginTop: 10,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#f9f7f4',
}}
onPress={() => {
this.setState({
Yuan: '',
isCheck: !this.state.isCheck
})
}}
>
<Image
style={{
width: 15,
height: 15,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./bi2.png')}
/>
<Text style={{
fontSize: 20,
color: '#e4c590',
}}>随喜</Text>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
style={{
justifyContent: 'center',
alignItems: 'center',
padding: 10,
borderWidth: 1,
borderRadius: 5,
borderColor: '#a3a3a3',
width: width / 4 - 15,
marginTop: 10,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#fff'
}}
onPress={() => {
this.setState({
isCheck: !this.state.isCheck,
Yuan: '',
})
}}
>
<Image
style={{
width: 15,
height: 15,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./bi.png')}
/>
<Text style={{
fontSize: 20,
color: '#708fb5',
}}>随喜</Text>
</TouchableOpacity>
)
}
}
render8 = () => {
if (this.state.isNiMing) {
return (
<View style={{
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
borderRadius: 5,
// width: width * 0.35,
flex: 1,
}}>
<Text style={{
color: '#333',
fontSize: 15,
marginRight: 10,
}}>素客</Text>
</View>
)
} else {
return (
<TextInput
placeholder='功德主芳名'
// placeholderTextColor='#000'
style={{
color: '#333',
fontSize: 20,
// width: width * 0.35,
flex: 1,
height: width * 0.12,
borderRadius: 5,
padding: 0,
paddingLeft: 5,
borderColor: '#a3a3a3',
backgroundColor: '#fff',
borderWidth: 1,
}}
onChangeText={(text) => {
this.setState({
JuanName: text,
isNiMing: false,
})
}}
>{this.state.JuanName}</TextInput>
)
}
}
render9 = () => {
if (this.state.isNiMing) {
return (
<TouchableOpacity
onPress={() => {
this.setState({
isNiMing: false,
JuanName: ''
})
}}
style={{
flexDirection: "row",
alignItems: 'center',
marginLeft: 5,
// position: 'absolute',
// right: 10,
// backgroundColor: "#394733",
}}
>
<Image
style={{
width: 20,
height: 20,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./true.png')}
/>
<Text style={{
color: '#333',
fontSize: 20,
}}>匿名参与</Text>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
onPress={() => {
this.setState({
isNiMing: true,
JuanName: '素客'
})
}}
style={{
flexDirection: "row",
alignItems: 'center',
marginLeft: 5,
// position: 'absolute',
// right: 10,
// backgroundColor: "#394733",
}}>
<Image
style={{
width: 20,
height: 20,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./false.png')}
/>
<Text style={{
color: '#333',
fontSize: 15,
}}>匿名参与</Text>
</TouchableOpacity>
)
}
}
render10 = () => {
if (this.state.isZDY) {
return (
<TouchableOpacity
onPress={() => {
this.setState({
isZDY: false,
})
}}
>
<Text style={{
color: '#ffc6b4',
fontSize: 17,
alignSelf: 'flex-end',
}}>确定</Text>
</TouchableOpacity>
)
} else {
return (
// <TouchableOpacity
// onPress={() => {
// this.setState({
// isZDY: true,
// })
// }}
// >
// <Text style={{
// color: '#ffc6b4',
// fontSize: 17,
// alignSelf: 'flex-end',
// }}>自定义</Text>
// </TouchableOpacity>
<TouchableOpacity
style={{
backgroundColor: '#ececec',
borderRadius: 5,
padding: 5,
// marginBottom: 5,
// width: 50,
justifyContent: 'center',
alignItems: 'center',
}}
onPress={() => {
this.setState({
isZDY: true,
})
}}
>
<Text style={{
// fontSize: 13,
// fontWeight: 'bold',
color: '#708fb5',
fontSize: 13,
alignSelf: 'flex-end',
}}>自定义</Text>
</TouchableOpacity>
)
}
}
render11 = () => {
if (this.state.isZDY) {
return (
<TextInput
placeholder='请输入自定义的回向文'
onChangeText={(text) => {
this.setState({
hxw: text
})
}}
style={{
color: '#000',
fontSize: 15,
backgroundColor: '#eee',
width: width - 100,
borderRadius: 15,
// height:60,
textAlignVertical: 'top',
}}
maxLength={100}
multiline={true}
>{this.state.hxw}</TextInput>
)
} else {
return (
<Text style={{
color: '#f47b0f',
fontSize: 15,
}}>{this.state.hxw ? this.state.hxw : '点【自定义】填写回向文'}</Text>
)
}
}
render5 = (img, type, txt) => {
return (
<TouchableOpacity
onPress={() => {
if (type == 'wx') {
this.setState({
wx: true,
zfb: false,
})
} else if (type == 'zfb') {
this.setState({
wx: false,
zfb: true,
})
}
this.fun1(txt)
}}
style={{
width: width - 40,
height: 55,
flexDirection: 'row',
alignItems: "center",
justifyContent: 'flex-start',
paddingLeft: 30,
}}
>
<Image
style={{
width: 35,
height: 35,
marginRight: 15,
}}
resizeMethod='resize'
resizeMode='stretch'
source={img}
/>
<View style={{
justifyContent: 'center',
alignItems: 'center',
height: 45,
backgroundColor: '#fff',
borderRadius: 5,
marginRight: 10,
}}>
<Text style={{
color: '#333',
fontSize: 17,
}}>{txt}</Text>
</View>
<Checkbox
style={{
marginRight: 10,
position: 'absolute',
right: 10,
}}
size='lg'
checked={this.state[type]}
onChange={checked => {
this.changeCheck(checked, type)
this.fun1(txt)
}}
/>
</TouchableOpacity>
)
}
changeCheck = (checked, type) => {
if (type == 'wx') {
if (checked) {
this.setState({
'wx': true,
'zfb': false
})
} else {
this.setState({
'wx': false
})
}
} else if (type == 'zfb') {
if (checked) {
this.setState({
'zfb': true,
'wx': false
})
} else {
this.setState({
'zfb': false
})
}
}
}
render() {
return (
<TouchableWithoutFeedback
onPress={() => {
}}
>
<ScrollView
style={{
flex: 1,
backgroundColor: '#f0f0f0',
// borderColor: '#e4c590',
// borderWidth: 10,
padding: 10,
}}
keyboardShouldPersistTaps='handled'
>
<View style={{
borderRadius: 15,
borderWidth: 2,
borderColor: '#ef9797',
marginLeft: 30,
width: width - 80,
justifyContent: 'center',
alignItems: 'center',
padding: 10,
marginTop: 20,
backgroundColor: '#fff',
}}>
<View style={{
width: '100%',
}}>
<Text style={{
color: '#ffc6b4',
fontSize: 17,
alignSelf: 'flex-start',
}}>回向文</Text>
</View>
{this.render11()}
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'flex-end',
}}>
{this.render10()}
</View>
</View>
<View style={{
flexDirection: 'row',
alignItems: "center",
justifyContent: 'flex-start',
paddingLeft: 10,
paddingRight: 10,
// width:'100%',
// backgroundColor:'#588454',
marginTop: 20,
// backgroundColor:'#440000',
}}>
<Text style={{
fontSize: 15,
color: '#333',
}}>功德主芳名:</Text>
{this.render8()}
{this.render9()}
</View>
<Text style={{
fontSize: 15,
color: '#333',
// fontWeight: 'bold',
marginTop: 30,
marginLeft: 10,
}}>选择行善金额</Text>
<View style={{
justifyContent: 'space-between',
flexDirection: 'row',
flexWrap: 'wrap',
// marginTop: 5,
paddingLeft: 10,
paddingRight: 10,
}}>
{this.render1(1)}
{this.render1(6)}
{this.render1(18)}
{this.render1(28)}
{this.render1(66)}
{this.render1(108)}
{this.render1(288)}
{this.render4()}
</View>
{this.render3()}
{/* {this.render2(require('./wx.png'), '#00cd00', '微信支付')}
{this.render2(require('./zfb.png'), '#00a0e8', '支付宝')} */}
<View style={{
marginTop: 10,
width: width - 40,
marginLeft: 10,
borderRadius: 10,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#fff',
overflow: 'hidden',
shadowColor: '#000',
shadowOffset: { width: 4, height: 4 },
shadowOpacity: 0.8,
shadowRadius: 6,
elevation: 2
}}>
{this.render5(require('./wx.png'), 'wx', '微信支付')}
<View style={{
height: 1,
backgroundColor: '#dadada',
}}></View>
{this.render5(require('./zfb.png'), 'zfb', '支付宝')}
</View>
<View style={{
width: width,
height: 60,
}}></View>
</ScrollView>
</TouchableWithoutFeedback>
);
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, TouchableOpacity, Image, Alert, Dimensions, ScrollView, FlatList, ImageBackground } from 'react-native';
import Back from '../../../component/Back'
import moment from 'moment';
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
import { Carousel, SegmentedView, ModalIndicator, Overlay, AlbumView } from 'teaset';
const { width, height } = Dimensions.get('window');
export default class RenZheng extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: '认证资料',
headerRight: <Image />
}
}
state = {
data1: '',
}
UNSAFE_componentWillMount() {
// ModalIndicator.show('加载中。。。')
this.setState({
data1: this.props.navigation.getParam('data')
})
console.log('接受到的导航数据', this.props.navigation.getParam('data'))
}
render1 = (txt1, txt2) => {
return (
<Text style={{
fontSize: 15,
color: '#333',
marginBottom: 5,
marginTop: 5,
}}>{txt1}{txt2}</Text>
)
}
render2 = (txt) => {
return (
<View style={{
height: 45,
alignItems: 'center',
flexDirection: 'row',
}}>
<Text style={{
fontSize: 15,
color: '#2d6ca4',
}}>{txt}</Text>
</View>
)
}
render3 = () => {
return (
<View style={{
height: 1,
width: '100%',
backgroundColor: '#e0e0e0',
}}></View>
)
}
render4 = (img) => {
return (
<View style={{
borderRadius: 5,
overflow: 'hidden',
width: width / 2 - 30,
height: width / 2 - 30,
backgroundColor: '#e5e2e2',
padding: 5,
}}>
{/* <AlbumView
style={{
width: '100%',
height: '100%',
}}
control={true}
images={[img ? { uri: img } : require('../../../imgs/noimg.png')]}
thumbs={[img ? { uri: img } : require('../../../imgs/noimg.png')]}
/> */}
<Image
style={{
width: '100%',
height: '100%',
}}
resizeMode='stretch'
resizeMethod='resize'
source={img ? { uri: img } : require('../../../imgs/noimg.png')}
/>
</View>
)
}
render() {
if (this.state.data1) {
return (
<ScrollView style={{
flex: 1,
backgroundColor: '#f0f0f0',
}}>
<View style={{
width: width,
padding: 10,
}}>
<View style={{
borderRadius: 10,
overflow: 'hidden',
}}>
<ImageBackground
style={{
width: '100%',
height: 170,
borderRadius: 10,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./a.png')}
>
<View style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
marginBottom: 45
}}>
<Text
style={{
fontSize: 20,
color: '#fff',
paddingRight: 10,
}}
>{this.state.data1.templeName}</Text>
<Image
style={{
width: 30,
height: 30,
borderRadius: 10,
}}
resizeMethod='resize'
resizeMode='contain'
source={require('./zheng.png')}
/>
</View>
<View style={{
width: '100%',
height: 45,
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
bottom: 0,
backgroundColor: '#427190',
}}>
<Text style={{
fontSize: 13,
color: '#fff',
}}>已通过<Text style={{
fontSize: 13,
color: '#ffc966',
}}>素客来认证中心</Text>认证,可放心访问</Text>
</View>
</ImageBackground>
</View>
</View>
<View style={{
width: width - 20,
marginLeft: 10,
marginRight: 10,
padding: 10,
borderRadius: 10,
backgroundColor: '#fff',
}}>
{this.render2('基础信息')}
{this.render3()}
{this.render1('单位名称:', this.state.data1.templeName)}
{this.render1('登记编号:', `宗场证字(闽)${this.state.data1.templeCode}`)}
{this.render1('负责人名:', this.state.data1.templeLegal)}
{this.render1('所在地址:', this.state.data1.templeAddr)}
</View>
<View style={{
width: width - 20,
borderRadius: 10,
backgroundColor: '#fff',
padding: 10,
marginTop: 10,
marginLeft: 10,
}}>
{this.render2('认证授权')}
{this.render3()}
<View style={{
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 10,
}}>
{this.render4(this.state.data1.authorizedImage)}
{this.render4(this.state.data1.certImage)}
</View>
</View>
<View style={{
width: width,
height: 100,
justifyContent: "center",
alignItems: 'center',
}}>
<TouchableOpacity
onPress={() => {
this.props.navigation.goBack()
}}
style={{
width: 280,
height: 50,
borderRadius: 25,
backgroundColor: '#80aade',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>返回</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
} else {
return (
<View style={{
flex: 1,
backgroundColor: '#f0f0f0',
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TextInput, TouchableOpacity, ScrollView, Dimensions, ImageBackground, Alert, FlatList } from 'react-native';
import { Overlay, ModalIndicator } from 'teaset'
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
const { width } = Dimensions.get('window');
export default class WoDeGongDe extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 18,
color: '#666',
fontWeight: 'bold',
},
title: navigation.getParam('otherParam', '我的功德'),
}
}
state = {
data1: '',
nextPage: 1,// 下一页的页码
pageSize: 24,//每页条数
isLoading: false,//列表是否正在加载中
isOver: false,// 是否已经到底,没有更多内容了
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
this.refresh()
}
render2 = (txt) => {
return (
<View style={{
width: '25%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
borderWidth: 1,
borderColor: '#333',
}}>
<Text>{txt}</Text>
</View>
)
}
// render3 = (data) => {
// let arr = data.reduce((res, cur, index) => {
// res.push(
// )
// return res
// }, [])
// return arr
// }
render4 = (txt) => {
return (
<View style={{
borderWidth: 1,
borderColor: '#333',
height: 50,
width: '25%',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>{txt}</Text>
</View>
)
}
_renderHeader = () => {
return (
<View style={{
width: width - 20,
marginLeft: 10,
flexDirection: 'row',
alignItems: 'center',
}}>
{this.render2('寺院名称')}
{this.render2('行善类别')}
{this.render2('募捐时间')}
{this.render2('乐捐金额')}
</View>
)
}
_renderFooter = () => {
if (this.state.data1 && (this.state.data1.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderEmptyComponent = () => {
return (
<View style={{
width: '100%',
alignItems: 'center',
height: 100,
justifyContent: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>暂无数据</Text>
</View>
)
}
renderItem = (data) => {
return (
<View
style={{
width: width - 20,
marginLeft: 10,
flexDirection: 'row',
alignItems: 'center',
}}
>
{this.render4(data.item.templeName)}
{this.render4(data.item.donateName)}
{this.render4(moment(data.item.donateTime).format('YYYY-MM-DD'))}
{this.render4(`${data.item.money}元`)}
</View>
)
}
// 加载下一页的数据
nextData = async () => {
console.log('触发了nextData')
if (this.state.isOver) {
// Alert('已经到最底部,没有更多内容了')
return
}
let nowPage=this.state.nextPage
this.setState({
isLoading: true,
nextPage: nowPage + 1,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的功德列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/merit/getMyMeritRecord`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"page": nowPage,
"size": this.state.pageSize
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if(responseJson.data.list.length==this.state.pageSize){
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
})
}else if (responseJson.data.list.length > 0) {
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
isOver: true,
})
} else {
this.setState({
isLoading: false,
isOver: true,
})
}
console.log('成功', responseJson.data.list);
} else {
console.log('失败', responseJson);
}
})
.catch((error) => {
console.log('error', error);
})
} else {
}
console.log('value', value)
} catch (error) {
console.log('error', error)
}
console.log('Done.')
}
// 刷新列表
refresh = async () => {
console.log('触发了refresh')
this.setState({
isLoading: true,
nextPage: 2,
isOver: false,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的功德列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/merit/getMyMeritRecord`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"page": 1,
"size": this.state.pageSize
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
})
ModalIndicator.hide()
} else if (responseJson.data.list.length > 0) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
isOver: true,
})
ModalIndicator.hide()
} else {
this.setState({
data1: [],
isLoading: false,
isOver: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
console.log('成功', responseJson.data.list);
} else {
ModalIndicator.hide()
console.log('失败', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
ModalIndicator.hide()
console.log('error', error)
}
console.log('Done.')
}
render() {
if (this.state.data1) {
return (
<View style={{
width: width,
flex: 1,
paddingTop: 20,
paddingBottom: 20,
}}>
{/* {this.render3(this.state.data1)} */}
<FlatList
data={this.state.data1}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
ListHeaderComponent={this._renderHeader}//头部组件
ListFooterComponent={this._renderFooter}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</View>
);
} else {
return (
<View style={{
backgroundColor: '#fff',
flex: 1,
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Image, Dimensions, ScrollView } from 'react-native';
import { WebView } from 'react-native-webview';
const { width, height } = Dimensions.get('window');
const BaseScript =
`
(function () {
var height = null;
function changeHeight() {
if (document.body.scrollHeight&&parseInt(document.body.scrollHeight)) {
height = document.body.scrollHeight;
if (window.ReactNativeWebView.postMessage) {
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'setHeight',
height: height,
}))
}
}
}
setTimeout(changeHeight, 600);
} ())
`
export default class ZhuChiDetail extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: `${navigation.getParam('templeDetail') && navigation.getParam('templeDetail').name ? navigation.getParam('templeDetail').name : '某某寺'}`,
headerRight: <Image />
}
}
state = {
templeDetail: '',
imgHeight: 0,
height: 500,
}
UNSAFE_componentWillMount() {
this.setState({
templeDetail: this.props.navigation.getParam('templeDetail')
})
this.getHight(this.props.navigation.getParam('templeDetail').hostImage)
console.log('住持详细介绍', this.props.navigation.getParam('templeDetail').hostProfile)
}
getHight = (uri) => {
// this.timer = setTimeout(() => {
Image.getSize(uri, (width1, height1) => {
//width 图片的宽度
//height 图片的高度
this.setState({
imgHeight: Math.floor(width / width1 * height1)
})
})
// this.timer && clearTimeout(this.timer);
// }, 100)
}
/**
* web端发送过来的交互消息
*/
onMessage(event) {
console.log('enent', event.nativeEvent.data)
try {
const action = JSON.parse(event.nativeEvent.data)
if (action.type === 'setHeight' && action.height > 0) {
this.setState({
height: action.height + 50
}, () => {
console.log('成功设置高度', action.height)
})
}
} catch (error) {
// pass
console.log('error', error)
// Alert.alert('34343')
}
}
render1 = (txt) => {
let txtArr = txt.split(/\n+/)
let arr = txtArr.reduce((res, cur, index) => {
res.push(
<Text
key={index}
style={{
fontSize: 18,
color: '#979797',
marginTop: 5,
marginBottom: 15,
}}>{cur}</Text>
)
return res
}, [])
return arr
}
render2 = (img) => {
return (
<Image
style={{
width: width - 20,
height: this.state.imgHeight,
}}
resizeMethod='resize'
resizeMode='cover'
source={img ? { uri: img } : require('../../../imgs/noimg.png')}
/>
)
}
render() {
if (this.state.templeDetail) {
return (
<ScrollView style={{
width: width,
flex: 1,
backgroundColor: '#f1f1f1'
}}>
<View style={{
width: width - 20,
marginLeft: 10,
borderTopRightRadius: 10,
borderTopLeftRadius: 10,
overflow: 'hidden',
marginTop: 20,
}}>
{this.render2(this.state.templeDetail && this.state.templeDetail.hostImage ? this.state.templeDetail.hostImage : '')}
</View>
<View style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
padding: 15,
alignItems: 'center',
flexDirection: 'row',
height: 50,
}}>
<Text style={{
fontSize: 20,
fontWeight: 'bold',
color: '#343434'
}}>{this.props.navigation.getParam('isCiShan', '') ? '会长' : '住持'}:{this.state.templeDetail && this.state.templeDetail.hostName ? this.state.templeDetail.hostName : ''}</Text>
</View>
<View style={{
width: width - 20,
marginLeft: 10,
height: 1,
alignItems: 'center',
backgroundColor: '#fff',
}}>
<View style={{
width: width - 70,
height: 1,
backgroundColor: '#f4f4f5'
}}></View>
</View>
<View style={{
width: width - 20,
marginLeft: 10,
paddingRight: 10,
backgroundColor: '#fff',
padding: 15,
minHeight: height - width,
}}>
{/* {this.render1(this.state.templeDetail && this.state.templeDetail.hostProfile ? this.state.templeDetail.hostProfile : '')} */}
<View style={{
width: '100%',
height: this.state.height
}}>
<View style={{
width: '100%',
height: this.state.height,
backgroundColor: 'transparent',
position: 'absolute',
left: 0,
top: 0,
zIndex: 10,
}}></View>
<WebView
style={{ flex: 1 }}
bounces={false}
scrollEnabled={false}
automaticallyAdjustContentInsets={true}
contentInset={{ top: 0, left: 0 }}
scalesPageToFit={false}//布尔值,控制网页内容是否自动适配视图的大小,同时启用用户缩放功能。默认为true。
originWhitelist={['*']}//允许被导航到的源字符串列表。字符串允许使用通配符,并且只根据原始地址(而不是完整的URL)进行匹配。如果用户点击导航到一个新页面,但是新页面不在这个白名单中,这个URL将由操作系统处理。默认的白名单起点是"http://"和"https://".
source={{ html: `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0;maximum-scale=1;user-scalable=no"><meta name="description" content=""/></head><body>${this.state.templeDetail && this.state.templeDetail.hostProfile ? this.state.templeDetail.hostProfile : ''}</body></html>` }}
injectedJavaScript={BaseScript}
onMessage={this.onMessage.bind(this)}
/>
</View>
</View>
</ScrollView>
);
} else {
return (
<View style={{
flex: 1,
backgroundColor: '#fef4e0',
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, ScrollView, Image, TouchableOpacity, Dimensions, ImageBackground, FlatList, Alert } from 'react-native';
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
import { Overlay, ModalIndicator, SegmentedView, Label } from 'teaset'
import moment from 'moment';
const { width, height } = Dimensions.get('window');
export default class WoDeXingCheng extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 18,
color: '#666',
fontWeight: 'bold',
},
title: navigation.getParam('otherParam', '我的行程'),
}
}
state = {
data0: '',//已取消订单,查询参数1
nextPage0: 1,// 已取消订单,下一页的页码
isOver0: false,// 已取消订单,是否已经到底,没有更多内容了
data1: '',//待付款订单,查询参数1
nextPage1: 1,// 待付款订单,下一页的页码
isOver1: false,// 待付款订单,是否已经到底,没有更多内容了
data2: '',//待出行订单,查询参数2
nextPage2: 1,// 待出行订单,下一页的页码
isOver2: false,// 待出行订单,是否已经到底,没有更多内容了
data3: '',//已完成订单,查询参数2
nextPage3: 1,// 已完成订单,下一页的页码
isOver3: false,// 已完成订单,是否已经到底,没有更多内容了
pageSize: 10,//每页条数
isLoading: false,//列表是否正在加载中
activeIndex: 1,//当前激活item的序号
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
const didBlurSubscription4 = this.props.navigation.addListener('didFocus', (payload) => {
this.refresh1()
});
this.refresh0()
this.refresh2()
this.refresh3()
}
componentWillUnmount() {
this.didBlurSubscription4 && this.didBlurSubscription4.remove();
}
renderLine = () => {
return (
<View style={{
width: '100%',
height: 1,
backgroundColor: '#e0e0e0',
}}></View>
)
}
render4 = (status) => {
if (status == 40) {
return (
<Text>支付状态:交易完成</Text>
)
} else if (status == 20) {
return (
<Text>支付状态:待出行</Text>
)
} else if (status == 10) {
return (
<Text>支付状态:未支付</Text>
)
} else {
return (
<Text>支付状态:取消</Text>
)
}
}
render2 = (data) => {
let arr = data.reduce((res, cur, index) => {
res.push(
<TouchableOpacity
key={index}
onPress={() => {
this.props.navigation.navigate('DingDanDetail', {
orderNo: cur.orderNo
})
}}
style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
borderColor: '#333',
borderWidth: 1,
marginTop: 10,
}}
>
<View style={{
flexDirection: 'row',
padding: 10,
}}>
<View style={{
width: width * 0.5,
height: width * 0.3,
justifyContent: 'space-evenly',
}}>
<Text>预约人:{cur.tenantName}</Text>
<Text>入住日期:{moment(cur.enterDate).format('YYYY-MM-DD')}</Text>
<Text>离开日期:{moment(cur.leaveDate).format('YYYY-MM-DD')}</Text>
{this.render4(cur.status)}
</View>
<View style={{
flex: 1,
alignItems: 'center',
}}>
<Text style={{
fontSize: 18,
color: '#333',
}}>{cur.templeName}</Text>
<Text style={{
fontSize: 15,
color: '#333',
marginTop: 10,
}}>({cur.productName})</Text>
<Text style={{
fontSize: 17,
color: '#333',
backgroundColor: '#ffcc80',
borderRadius: 5,
position: 'absolute',
bottom: 0,
padding: 5,
}}>查看订单详情</Text>
</View>
</View>
{this.renderLine()}
</TouchableOpacity>
)
return res
}, [])
return arr
}
renderItem1 = (data) => {
return (
<TouchableOpacity
onPress={() => {
// this.props.navigation.navigate('DingDanDetail', {
// orderNo: data.item.orderNo
// })
this.props.navigation.navigate('QvZhiFu2', {
orderNo: data.item.orderNo
})
// this.fun2(data.item.orderNo)
}}
style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
borderColor: '#333',
borderWidth: 1,
marginTop: 10,
}}
>
<View style={{
flexDirection: 'row',
padding: 10,
}}>
<View style={{
width: width * 0.5,
height: width * 0.3,
justifyContent: 'space-evenly',
}}>
<Text>预约人:{data.item.tenantName}</Text>
<Text>入住日期:{moment(data.item.enterDate).format('YYYY-MM-DD')}</Text>
<Text>离开日期:{moment(data.item.leaveDate).format('YYYY-MM-DD')}</Text>
{this.render4(data.item.status)}
</View>
<View style={{
flex: 1,
alignItems: 'center',
}}>
<Text style={{
fontSize: 18,
color: '#333',
}}>{data.item.templeName}</Text>
<Text style={{
fontSize: 15,
color: '#333',
marginTop: 10,
}}>({data.item.productName})</Text>
<Text style={{
fontSize: 17,
color: '#333',
backgroundColor: '#ffcc80',
borderRadius: 5,
position: 'absolute',
bottom: 0,
padding: 5,
}}>查看订单详情</Text>
</View>
</View>
{this.renderLine()}
</TouchableOpacity>
)
}
renderItem = (data) => {
return (
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('DingDanDetail', {
orderNo: data.item.orderNo
})
}}
style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
borderColor: '#333',
borderWidth: 1,
marginTop: 10,
}}
>
<View style={{
flexDirection: 'row',
padding: 10,
}}>
<View style={{
width: width * 0.5,
height: width * 0.3,
justifyContent: 'space-evenly',
}}>
<Text>预约人:{data.item.tenantName}</Text>
<Text>入住日期:{moment(data.item.enterDate).format('YYYY-MM-DD')}</Text>
<Text>离开日期:{moment(data.item.leaveDate).format('YYYY-MM-DD')}</Text>
{this.render4(data.item.status)}
</View>
<View style={{
flex: 1,
alignItems: 'center',
}}>
<Text style={{
fontSize: 18,
color: '#333',
}}>{data.item.templeName}</Text>
<Text style={{
fontSize: 15,
color: '#333',
marginTop: 10,
}}>({data.item.productName})</Text>
<Text style={{
fontSize: 17,
color: '#333',
backgroundColor: '#ffcc80',
borderRadius: 5,
position: 'absolute',
bottom: 0,
padding: 5,
}}>查看订单详情</Text>
</View>
</View>
{this.renderLine()}
</TouchableOpacity>
)
}
// 刷新列表(已取消)
refresh0 = async () => {
console.log('触发了refresh0')
this.setState({
isLoading: true,
isOver0: false,
nextPage0: 2,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 0,//0已取消,1待支付,2待出行,3已完成
"page": 1,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data0: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data0: responseJson.data.list,
isLoading: false,
isOver0: true,
})
ModalIndicator.hide()
} else {
this.setState({
data0: [],
isLoading: false,
isOver0: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 刷新列表(待支付)
refresh1 = async () => {
console.log('触发了refresh1')
this.setState({
isLoading: true,
isOver1: false,
nextPage1: 2,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 1,//1未支付,2已支付
"page": 1,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
isOver1: true,
})
ModalIndicator.hide()
} else {
this.setState({
data1: [],
isLoading: false,
isOver1: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// (待出行订单)刷新列表
refresh2 = async () => {
this.setState({
isLoading: true,
isOver2: false,
nextPage2: 2,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 2,//1未支付,2已支付
"page": 1,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data2: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data2: responseJson.data.list,
isLoading: false,
isOver2: true,
})
} else {
this.setState({
data2: [],
isLoading: false,
isOver2: true,
})
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 刷新列表(待支付)
refresh3 = async () => {
console.log('触发了refresh3')
this.setState({
isLoading: true,
isOver3: false,
nextPage3: 2,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 3,//0已取消,1待支付,2待出行,3已完成
"page": 1,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data3: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data3: responseJson.data.list,
isLoading: false,
isOver3: true,
})
ModalIndicator.hide()
} else {
this.setState({
data3: [],
isLoading: false,
isOver3: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 已取消订单,加载下一页的数据
nextData0 = async () => {
console.log('触发了nextData0')
if (this.state.isOver0) {
// Alert.alert('已经到最底部,没有更多内容了')
return
}
let nowPage=this.state.nextPage0
this.setState({
isLoading: true,
nextPage0: nowPage + 1,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 0,//0已取消,1待支付,2待出行,3已完成
"page": nowPage,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data0: [
...this.state.data0,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data0: [
...this.state.data0,
...responseJson.data.list
],
isLoading: false,
isOver0: true,
})
} else {
this.setState({
isOver0: true,
isLoading: false,
})
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 待支付订单,加载下一页的数据
nextData1 = async () => {
console.log('触发了nextData1')
if (this.state.isOver1) {
// Alert.alert('已经到最底部,没有更多内容了')
return
}
let nowPage=this.state.nextPage1
this.setState({
isLoading: true,
nextPage1: nowPage + 1,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 1,//0已取消,1待支付,2待出行,3已完成
"page": nowPage,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
isOver1: true,
})
} else {
this.setState({
isOver1: true,
isLoading: false,
})
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 加载下一页的数据
nextData2 = async () => {
if (this.state.isOver2) {
// Alert.alert('已经到最底部,没有更多内容了')
return
}
let nowPage=this.state.nextPage2
this.setState({
isLoading: true,
nextPage2: nowPage + 1,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 2,//1未支付,2已支付
"page": nowPage,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data2: [
...this.state.data2,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data2: [
...this.state.data2,
...responseJson.data.list
],
isLoading: false,
isOver2: true,
})
} else {
this.setState({
isOver2: true,
isLoading: false,
})
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 已完成订单,加载下一页的数据
nextData3 = async () => {
console.log('触发了nextData3')
if (this.state.isOver3) {
// Alert.alert('已经到最底部,没有更多内容了')
return
}
let nowPage=this.state.nextPage3
this.setState({
isLoading: true,
nextPage3: nowPage + 1,
})
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"status": 3,//0已取消,1待支付,2待出行,3已完成
"page": nowPage,
"size": this.state.pageSize,
}),
// body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data3: [
...this.state.data3,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data3: [
...this.state.data3,
...responseJson.data.list
],
isLoading: false,
isOver3: true,
})
} else {
this.setState({
isOver3: true,
isLoading: false,
})
}
ModalIndicator.hide()
console.log('返回的数据', responseJson);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
_renderEmptyComponent = () => {
return (
<View style={{
width: '100%',
alignItems: 'center',
height: 100,
justifyContent: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>暂无数据</Text>
</View>
)
}
// 已支付订单,尾部组件
_renderFooter0 = () => {
if (this.state.data0 && (this.state.data0.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver0) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
// 待支付订单,尾部组件
_renderFooter1 = () => {
if (this.state.data1 && (this.state.data1.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver1) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderFooter2 = () => {
if (this.state.data2 && (this.state.data2.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver2) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
// 已完成订单,尾部组件
_renderFooter3 = () => {
if (this.state.data3 && (this.state.data3.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver3) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
render() {
if (this.state.data0 || this.state.data1 || this.state.data2 || this.state.data3) {
return (
<View style={{
flex: 1,
backgroundColor: '#eee',
}}>
<SegmentedView
style={{
flex: 1
}}
type='carousel'
justifyItem='fixed'
activeIndex={this.state.activeIndex}
onChange={(index) => {
this.setState({
activeIndex: index
})
// console.log('当前', `${index}`)
}}
>
<SegmentedView.Sheet
title='待支付'
activeTitleStyle={{
color: '#333',
}}
titleStyle={{
color: '#333',
}}
>
<FlatList
data={this.state.data1}//数据源
renderItem={(data) => this.renderItem1(data)}//列表呈现方式
onEndReached={() => this.nextData1()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onrefresh={() => this.refresh1()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
// ListHeaderComponent ={this._renderHeader }//头部组件
ListFooterComponent={this._renderFooter1}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
<SegmentedView.Sheet
title='待出行'
activeTitleStyle={{
color: '#333',
}}
titleStyle={{
color: '#333',
}}
>
<FlatList
data={this.state.data2}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData2()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onrefresh={() => this.refresh2()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
// ListHeaderComponent ={this._renderHeader }//头部组件
ListFooterComponent={this._renderFooter2}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
<SegmentedView.Sheet
title='已完成'
activeTitleStyle={{
color: '#333',
}}
titleStyle={{
color: '#333',
}}
>
<FlatList
data={this.state.data3}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData3()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onrefresh={() => this.refresh3()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
// ListHeaderComponent ={this._renderHeader }//头部组件
ListFooterComponent={this._renderFooter3}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
<SegmentedView.Sheet
title='已取消'
activeTitleStyle={{
color: '#333',
}}
titleStyle={{
color: '#333',
}}
>
<FlatList
data={this.state.data0}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData0()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onrefresh={() => this.refresh0()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
// ListHeaderComponent ={this._renderHeader }//头部组件
ListFooterComponent={this._renderFooter0}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
</SegmentedView>
</View>
);
} else {
return (
<View style={{
backgroundColor: '#fff',
flex: 1,
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, TextInput, Button, Image, TouchableOpacity, TouchableWithoutFeedback, ScrollView, Dimensions, Linking, Alert, ImageBackground, Animated, Easing } from 'react-native';
import { Carousel, SegmentedView, ModalIndicator, Overlay, Toast } from 'teaset';
import { MarqueeHorizontal, MarqueeVertical } from 'react-native-marquee-ab';
import { WebView } from 'react-native-webview';
import AsyncStorage from '@react-native-community/async-storage';
import * as WeChat from 'react-native-wechat-lib'
import Alipay from '@0x5e/react-native-alipay';
import moment from 'moment';
import Back from '../../../component/Back'
import appConfig from '../../../jsonData/appConfig.js'
// WeChat.registerApp(appConfig.wxAppId,'https://help.wechat.com/');//此方法因全局调用一次
const { width } = Dimensions.get('window');
class JuanKuan extends Component {
state = {
isEdit: false,//是否编辑捐款名字
SiYuanFangName: '',//用户寺院芳名
JuanName: '用户xx',//捐款用的昵称
headImg: {
uri: ''
},//头像图片
rmb: '',//捐赠金额
isNiMing: false,//是否匿名
isRandom: false,//是否随机金额
rmbRandom: [
6,
6.6,
18,
26,
28,
0.88,
1.88,
188,
18.88,
28.88,
36.66,
55,
5.5,
123,
13,
1.33,
6.66,
8.88,
88.8,
4.6,
7.88,
13,
1.33,
23,
23.33,
3,
0.88,
7.77,
9.99,
98,
65,
2.33,
10,
20,
30,
50,
60,
70,
80,
90,
188.88,
88.88,
66.66,
6.88,
8.66
],//随机金额
Authorization: '',//用户唯一标识
}
UNSAFE_componentWillMount() {
this.Do1()
this.JianCeDengLu()
}
// 获取功德芳名
fun13 = (templeId, Authorization) => {
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/getUserMeritName`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
// 'Content-Type': 'application/json',
'Authorization': Authorization
}),
body: `templeId=${templeId}`,
// body: JSON.stringify({//请求参数
// templeId: parseInt(templeId),
// }),
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
this.setState({
SiYuanFangName: responseJson.data,
JuanName: responseJson.data,
})
} else {
this.setState({
SiYuanFangName: '',
})
}
console.log('野兽到的芳名', responseJson)
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
// 检测是否登录
JianCeDengLu = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户信息
let valueObj = JSON.parse(value)
if (valueObj.outTime > moment().unix()) {
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/me`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: '',
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
// 获取功德芳名
this.setState({
JuanName: responseJson.data.nickName,
headImg: {
uri: responseJson.data.usersign
},
Authorization: `${valueObj.token_type} ${valueObj.access_token}`
}, () => {
// 获取功德芳名
this.fun13(this.props.templeId, this.state.Authorization)
console.log('寺庙id', this.props.templeId)
})
console.log('返回的数据', responseJson.data.nickName);
} else {
console.log('responseJson', responseJson);
this.TiShiDengLu()
}
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
this.TiShiDengLu()
}
} else {
this.TiShiDengLu()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
console.log('Done.')
}
// 提示用户登录
TiShiDengLu = () => {
// 提示用户先登录
let TiShiDengLuOverlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.TiShiDengLuOverlayView = v}
>
<ImageBackground
style={{
backgroundColor: '#fff',
padding: 3,
// borderRadius: 10,
height: 165,
width: 285,
}}
resizeMethod='resize'
resizeMode='cover'
source={require('../../../imgs/dl.png')}
>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 22,
}}>[请先登录]</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.overlayView2 && this.overlayView2.close()
this.props.closeAll()
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>返回</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.overlayView2 && this.overlayView2.close()
this.props.closeAll()
this.props.navigation.replace('DengLu')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>确定</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Overlay.View>
);
Overlay.show(TiShiDengLuOverlayView);
}
// 通过用户唯一识别码和订单号查询支付是否成功的函数
isPaySucceed = (orderNum, Authorization) => {
this.timerIsPaySucceed = setTimeout(() => {
console.log('订单号', orderNum)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/checkOrderPayInfo`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': Authorization
}),
// body: JSON.stringify({//请求参数
// productId: parseInt(this.props.navigation.getParam('productId', '')),
// userNickName: this.state.JuanName,
// }),
body: `orderNo=${orderNum}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
this.timerIsPaySucceed && clearTimeout(this.timerIsPaySucceed);
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
if (responseJson.data.platformStatus == 1) {
ModalIndicator.hide()
// 收起红包
this.props.close1()
// 刷新功德榜
this.props.refresh1()
// this.props.navigation.goBack()
// Alert.alert('订单支付成功')
Toast.success('订单支付成功')
}
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
// Alert.alert('订单支付失败')
Toast.fail('后台认为订单支付失败')
// 取消订单
this.fun6(orderNum)
}
})
.catch((error) => {
this.timerIsPaySucceed && clearTimeout(this.timerIsPaySucceed);
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
}, 1000);
}
//取消订单
fun6 = async (orderNo) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/cancelOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: `orderNo=${orderNo}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
// Toast.message('订单已取消!')
} else {
Toast.message('服务器取消订单失败')
}
})
.catch((error) => {
console.log('error', error);
})
} else {
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
}
fun4 = async (txt) => {
if (this.state.rmb == '') {
// Alert.alert('请先填写或随机生成捐赠金额')
Toast.message('请先填写或随机生成捐赠金额')
return
}
if (this.state.rmb <= 0) {
// Alert.alert('捐赠金额必须大于0')
Toast.message('捐赠金额必须大于0')
return
}
if (!/^[0-9]+(.[0-9]{1,2})?$/.test(this.state.rmb)) {
// Alert.alert('输入的金额格式不正确')
Toast.message('输入的金额格式不正确')
return
}
ModalIndicator.show()
// 支付类型判断
// this.timer = setTimeout(() => {
// this.fun5()
// this.timer && clearTimeout(this.timer)
// }, 3000)
if (txt == '微信支付') {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/wxpay/createMeritOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
productId: parseInt(this.props.meritProductInfo.productId),
userNickName: this.state.isNiMing ? '' : this.state.JuanName,
money: parseFloat(this.state.rmb).toFixed(2),
// days: parseInt(this.state.Tian),
// lamps: parseInt(1),
// blessing: this.state.hxw,
prayType: this.props.meritProductInfo.praytype,
}),
// body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
WeChat.isWXAppInstalled()
.then((isInstalled) => {
if (isInstalled) {
this.payFun(responseJson)
} else {
ModalIndicator.hide()
// Alert.alert('请安装微信');
Toast.message('请安装微信')
}
});
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
ModalIndicator.hide()
}
} else if (txt == '支付宝') {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/alipay/createMeritOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
productId: parseInt(this.props.meritProductInfo.productId),
userNickName: this.state.isNiMing ? '' : this.state.JuanName,
money: parseFloat(this.state.rmb).toFixed(2),
// days: parseInt(this.state.Tian),
// lamps: parseInt(1),
// blessing: this.state.hxw,
prayType: this.props.meritProductInfo.praytype,
}),
// body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
this.toPay(responseJson)
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
ModalIndicator.hide()
}
}
}
toPay = async (val) => {
if (val.data) {
// APP支付
try {
let response = await Alipay.pay(val.data.orderParams)
let { resultStatus, result, memo } = response;
// let { code, msg, app_id, out_trade_no, trade_no, total_amount, seller_id, charset, timestamp } = JSON.parse(result);
console.log('支付宝支付返回的结果', response)
if (resultStatus == '9000') {
ModalIndicator.show('查询支付结果。。。')
this.isPaySucceed(val.data.orderNo, this.state.Authorization)
} else {
ModalIndicator.hide()
Toast.message(memo)
// 取消未支付的订单
this.fun6(val.data.orderNo)
return
}
} catch (error) {
ModalIndicator.hide()
console.error('错误', error);
console.info('支付失败');
Toast.fail('支付失败,请联系开发人员')
}
} else {
ModalIndicator.hide()
// Alert.alert('支付参数不正确')
Toast.fail('支付参数不正确')
}
}
// 微信支付函数
payFun = async function (responseJson) {
try {
console.log('支付参数', responseJson.data)
console.log('支付参数partnerid', responseJson.data.orderParams.partnerid)
console.log('支付参数prepayid', responseJson.data.orderParams.prepayid)
console.log('支付参数noncestr', responseJson.data.orderParams.noncestr)
console.log('支付参数timestamp', responseJson.data.orderParams.timestamp)
console.log('支付参数package', responseJson.data.orderParams.package)
console.log('支付参数sign', responseJson.data.orderParams.sign)
console.log('支付参数appid', responseJson.data.orderParams.appid)
let result = await WeChat.pay({
partnerId: responseJson.data.orderParams.partnerid, // 商家向财付通申请的商家id
prepayId: responseJson.data.orderParams.prepayid, // 预支付订单
nonceStr: responseJson.data.orderParams.noncestr, // 随机串,防重发
timeStamp: responseJson.data.orderParams.timestamp, // 时间戳,防重发
package: responseJson.data.orderParams.package, // 商家根据财付通文档填写的数据和签名
sign: responseJson.data.orderParams.sign, // 商家根据微信开放平台文档对数据做的签名
appId: responseJson.data.orderParams.appid
});
let { errCode, errStr } = result
if (errCode == 0) {
ModalIndicator.show('查询支付结果。。。')
this.isPaySucceed(responseJson.data.orderNo, this.state.Authorization)
} else {
ModalIndicator.hide()
Toast.message(errStr)
// 取消未支付的订单
this.fun6(responseJson.data.orderNo)
return
}
} catch (e) {
ModalIndicator.hide()
console.log('支付失败了', e)
// Toast.fail('支付失败,请联系开发者')
Toast.fail('操作已取消')
}
}
render8 = () => {
if (this.state.isNiMing) {
return (
<View style={{
marginTop: 10,
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<Text style={{
color: '#fff',
fontSize: 20,
marginRight: 10,
}}>素客</Text>
</View>
)
} else if (this.state.isEdit) {
return (
<View style={{
marginTop: 10,
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<ImageBackground
style={{
width: width * 0.55,
height: width * 0.12,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./ip.png')}
>
<TextInput
style={{
color: '#fff',
fontSize: 20,
width: width * 0.55,
height: width * 0.12,
borderRadius: width * 0.05,
padding: 0,
fontSize: 15,
paddingLeft: 20,
}}
onChangeText={(text) => {
this.setState({
JuanName: text
})
}}
>{this.state.JuanName}</TextInput>
</ImageBackground>
</View>
)
} else {
return (
<View style={{
marginTop: 10,
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<TouchableOpacity
style={{
flexDirection: 'row',
alignItems: "center",
}}
onPress={() => {
this.setState({
isEdit: true
})
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
marginRight: 10,
}}>{this.state.JuanName}</Text>
<Image
style={{
width: width * 0.04,
height: width * 0.04,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./bi.png')}
/>
</TouchableOpacity>
</View>
)
}
}
render9 = () => {
if (this.state.isNiMing) {
return (
<TouchableOpacity
onPress={() => {
this.setState({
isNiMing: false,
JuanName: ''
})
}}
style={{
flexDirection: "row",
alignItems: 'center',
}}
>
<View style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#fff',
justifyContent: 'center',
alignItems: 'center',
}}>
<View style={{
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: '#d9392a',
}}></View>
</View>
<Text style={{
color: '#fff',
fontSize: 20,
}}>匿名参与</Text>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
onPress={() => {
this.setState({
isNiMing: true,
JuanName: '素客',
})
}}
style={{
flexDirection: "row",
alignItems: 'center',
}}>
<View style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#fff',
}}
></View>
<Text style={{
color: '#fff',
fontSize: 20,
}}>匿名参与</Text>
</TouchableOpacity>
)
}
}
render11 = () => {
if (this.state.isNiMing) {
return (
<Image
style={{
width: width * 0.28 - 4,
height: width * 0.28 - 4,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./ntx.png')}
/>
)
} else {
return (
<Image
style={{
width: width * 0.28 - 4,
height: width * 0.28 - 4,
}}
resizeMethod='resize'
resizeMode='stretch'
source={this.state.headImg && this.state.headImg.uri ? this.state.headImg : require('../../../imgs/noimg.png')}
/>
)
}
}
Do1 = () => {
this.setState({
rmb: this.state.rmbRandom[Math.ceil(Math.random() * 45) + 1],
isRandom: true,
})
}
render() {
return (
<TouchableWithoutFeedback
onPress={() => {
this.setState({
isEdit: false,
})
}}
>
<ImageBackground
resizeMode="stretch"
style={{
width: '100%',
height: '100%',
}}
source={require('./hb.png')}
>
<View style={{
marginTop: width * 0.03,
alignItems: 'center',
flexDirection: "column",
}}>
<View style={{
width: width * 0.28,
height: width * 0.28,
borderRadius: width * 0.14,
overflow: 'hidden',
borderColor: '#fea43c',
borderWidth: 2,
}}>
{this.render11()}
</View>
{this.render8()}
<Text style={{
fontSize: 30,
color: "#f8ec90",
}}>{this.state.rmb ? this.state.rmb : '0.00'}</Text>
<View style={{
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<ImageBackground
style={{
width: width * 0.55,
height: width * 0.12,
alignItems: 'center',
flexDirection: 'row',
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./ip.png')}
>
<TextInput
placeholder='手动输入金额'
placeholderTextColor='#fff'
style={{
color: '#fff',
fontSize: 20,
width: width * 0.55,
height: width * 0.12,
borderRadius: width * 0.05,
padding: 0,
fontSize: 15,
paddingLeft: 20,
}}
onChangeText={(text) => {
this.setState({
rmb: text,
isRandom: false,
})
}}
>{this.state.isRandom ? '' : this.state.rmb}</TextInput>
<Text style={{
position: 'absolute',
right: 20,
color: '#fff',
fontSize: 20,
}}>元</Text>
</ImageBackground>
</View>
<View style={{
marginTop: width * 0.03,
flexDirection: 'row',
alignItems: "center",
width: '100%',
justifyContent: 'space-between',
paddingLeft: 10,
paddingLeft: 10,
paddingRight: 10,
}}>
{this.render9()}
<TouchableOpacity
onPress={() => {
this.props.close1()
this.props.navigation.navigate('FuWuXieYi')
}}
style={{
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>《查看服务协议》</Text>
</TouchableOpacity>
</View>
<View style={{
marginTop: width * 0.03,
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
width: '100%',
}}>
<TouchableOpacity
onPress={() => {
this.Do1()
}}
style={{
width: width * 0.3,
height: width * 0.1,
borderRadius: 5,
borderWidth: 1,
borderColor: '#f6ea7e',
backgroundColor: '#e65340',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
fontSize: 20,
color: '#f6ea7e',
}}>换个金额</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.fun4('微信支付')
}}
style={{
borderWidth: 1,
borderColor: '#4caf50',
width: width * 0.3,
height: width * 0.1,
borderRadius: 5,
backgroundColor: '#009c46',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
alignItems: "center",
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>微信支付</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.fun4('支付宝')
}}
style={{
borderWidth: 1,
borderColor: '#2196f3',
width: width * 0.3,
height: width * 0.1,
borderRadius: 5,
backgroundColor: '#0055a2',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
alignItems: "center",
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>支付宝</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
</TouchableWithoutFeedback>
)
}
}
const BaseScript =
`
(function () {
var height = null;
function changeHeight() {
if (document.body.scrollHeight&&parseInt(document.body.scrollHeight)) {
height = document.body.scrollHeight;
if (window.ReactNativeWebView.postMessage) {
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'setHeight',
height: height,
}))
}
}
}
setTimeout(changeHeight, 600);
} ())
`
export default class SiYuanDetail extends Component {
static navigationOptions = {
header: null,
}
state = {
height: 55,//富文本实际高度值
heightNow: 65,//富文本当前使用的高度值
dataZheng: '',//寺院认证数据
showZheng: false,//是否显示【已认证】
isMore: false,//是否查看更多
AnimatedValue: new Animated.Value(0),
direction: 'up',
data2: '',//寺院资讯列表
textList: '',//实时捐款跑马灯
sc: false,//是否收藏
// 轮播图项目1数据1
_CarouseItem1Data_1: '',
// 轮播图项目1数据2
_CarouseItem1Data_2: '',// 轮播图项目1数据2
// 轮播图项目1数据3
_CarouseItem1Data_3: '',
data1: '',//寺院所有详情
sgHeight: 700,//
HeightArr: [300, 100, 700],
activeIndex: 0,
}
UNSAFE_componentWillMount() {
const didBlurSubscription2 = this.props.navigation.addListener('didFocus', (payload) => {
this.refresh1()
});
ModalIndicator.show('加载中。。。')
this.getValue1()
this.fun2()
}
componentWillUnmount() {
this.didBlurSubscription2 && this.didBlurSubscription2.remove();
}
// 刷新功德榜
refresh1 = () => {
this.fun3()
this.fun8()
this.fun9()
this.fun10()
}
/**
* web端发送过来的交互消息
*/
onMessage(event) {
console.log('enent', event.nativeEvent.data)
try {
const action = JSON.parse(event.nativeEvent.data)
if (action.type === 'setHeight' && action.height > 0) {
this.setState({
height: action.height + 50
}, () => {
console.log('成功设置高度', action.height)
})
}
} catch (error) {
// pass
console.log('error', error)
// Alert.alert('34343')
}
}
fun10 = () => {
// 获取寺院实时功德走马灯列表
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/merit/getLastAnyMeritRecord`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
body: JSON.stringify({//请求参数
"templeId": this.props.navigation.getParam('templeId'),
"limit": 100
}),
// body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
let newArr = responseJson.data.reduce((res, cur, index) => {
res.push({
label: `${index + 1}`, //用作点击事件的回调
value: `${cur.userNickName}:${cur.donateName}${cur.money}元` //文本显示
})
console.log('当前多多', cur)
return res
}, [])
console.log('_CarouseItem1Data_1', responseJson.data)
this.setState({
textList: newArr
})
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
fun9 = () => {
// 获取寺院年功德排行列表
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/merit/getMeritRank`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
body: JSON.stringify({//请求参数
"templeId": this.props.navigation.getParam('templeId'),
"queryType": 3,//3年,2月
"page": 0,
"size": 10
}),
// body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
// console.log('responseJson.data.list', responseJson.data.list);
// this.setState({
// data1: responseJson.data
// })
// 先进行排序,按照金额从高到低,
console.log('_CarouseItem1Data_3', responseJson.data.list)
let newArr = responseJson.data.list.sort((a, b) => a.sort - b.sort)
// let newArr = responseJson.data.list.sort((a, b) => b.moneyCount - a.moneyCount)
let HeightArr = this.state.HeightArr
HeightArr[2] = newArr.length ? newArr.length : 0
this.setState({
_CarouseItem1Data_3: newArr,
HeightArr: HeightArr
})
//
this.fun12()
})
.catch((error) => {
console.log('error', error);
})
}
fun8 = () => {
// 获取寺院月功德排行列表
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/merit/getMeritRank`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
body: JSON.stringify({//请求参数
"templeId": this.props.navigation.getParam('templeId'),
"queryType": 2,//3年,2月
"page": 0,
"size": 10
}),
// body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
let newArr = responseJson.data.list.sort((a, b) => a.sort - b.sort)//moneyCount
// let newArr = responseJson.data.list.sort((a, b) => b.moneyCount - a.moneyCount)
let HeightArr = this.state.HeightArr
HeightArr[1] = newArr ? newArr.length : 0
this.setState({
_CarouseItem1Data_2: newArr,
HeightArr: HeightArr
})
console.log('xmxmxxcxcxc', newArr)
//
this.fun12()
})
.catch((error) => {
console.log('error', error);
})
}
fun3 = () => {
// 获取寺院实时功德列表
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/merit/getMeritList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
body: JSON.stringify({//请求参数
"templeId": this.props.navigation.getParam('templeId'),
"page": 0,
"size": 10
}),
// body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('_CarouseItem1Data_1', responseJson.data)
let HeightArr = this.state.HeightArr
HeightArr[0] = responseJson.data.list.length ? responseJson.data.list.length : 0
this.setState({
_CarouseItem1Data_1: responseJson.data.list,
HeightArr: HeightArr,
})
//
this.fun12()
})
.catch((error) => {
console.log('error', error);
})
}
fun2 = () => {
// 获取寺院资讯列表
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getAllNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
body: JSON.stringify({//请求参数
"templeId": this.props.navigation.getParam('templeId'),
"page": 0,
"size": 100
}),
// body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('data2', responseJson.data)
this.setState({
data2: responseJson.data.list
})
})
.catch((error) => {
console.log('error', error);
})
}
fun11 = () => {
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/temple/authTempleInfo`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
// body: JSON.stringify({//请求参数
// // templeId: this.props.navigation.getParam('templeId')
// templeId: '1'
// }),
body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('data1111111', responseJson.data)
if (responseJson.data) {
this.setState({
showZheng: true,
dataZheng: responseJson.data
})
}
})
.catch((error) => {
console.log('error', error);
})
}
getValue1 = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 已登录情况下获取寺院详情
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
// 获取寺庙详情数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/temple/templeAllDetail`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
// body: JSON.stringify({//请求参数
// // templeId: this.props.navigation.getParam('templeId')
// templeId: '1'
// }),
body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('data1111111', responseJson.data)
if (responseJson.data) {
this.setState({
data1: responseJson.data
})
this.fun1(this.props.navigation.getParam('templeId'))
// 获取寺院授权信息
this.fun11(this.props.navigation.getParam('templeId'))
}
})
.catch((error) => {
console.log('error', error);
Alert.alert('网络连接失败')
})
} else {
// 未登录情况下获取寺院详情
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/temple/templeAllDetail`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}),
// body: JSON.stringify({//请求参数
body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('data1111111', responseJson.data)
if (responseJson.data) {
this.setState({
data1: responseJson.data
})
// 获取寺院授权信息
this.fun11(this.props.navigation.getParam('templeId'))
}
})
.catch((error) => {
Alert.alert('网络连接失败')
console.log('error', error);
})
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
console.log('Done.')
}
render1 = () => {
let dian = ''
if (this.state.isMore) {
dian = (
<TouchableOpacity
onPress={() => {
this.myScrollView.scrollTo({ x: 0, y: -10000, animated: true })
this.timer = setTimeout(() => {
this.setState({
isMore: false,
heightNow: 65,
})
this.timer && clearTimeout(this.timer);
}, 10)
console.log('触发了点击收起', this.myScrollView)
}}
>
<Text style={{
color: '#919191',
}}>点击收起</Text>
</TouchableOpacity>
)
} else {
dian = (
<TouchableOpacity
onPress={() => {
this.setState({
isMore: true,
heightNow: this.state.height,
})
}}
>
<Text style={{
color: '#919191',
}}>查看更多</Text>
</TouchableOpacity>
)
}
return (
<View style={{
width: width,
backgroundColor: '#fff',
}}>
{/* <View style={{
padding: 20,
paddingBottom: 10,
}}>
{txt}
</View> */}
<View style={{
width: width,
height: 20,
alignItems: "center",
}}>
{dian}
</View>
</View>
)
}
render2 = (tagList) => {
let tagName = ['素斋', '禅房', '法会', '祈福', '义工']
let tagGoto = ['SuZhai', 'ChanFang', 'FaHui', 'QiFu', 'YiGongJieShao']
let tagImg = [require('./ss.png'), require('./cf.png'), require('./fh.png'), require('./qf.png'), require('./yg.png')]
if (tagList && tagList.length > 0) {
// 想要的排序[祈福4,禅房2,素斋1,法会3,义工5,]
// 先进行排序
let arr00 = [4, 2, 1, 3, 5]
let arr0 = arr00.reduce((res, cur, index) => {
let obj = tagList.find((item) => {
return item.tagId == cur
})
if (obj) {
res.push(obj)
}
return res
}, [])
let arr = arr0.reduce((res, cur, index) => {
let tag = cur.tagId - 1
res.push(
<TouchableOpacity
key={index}
onPress={() => {
this.props.navigation.navigate(tagGoto[tag], {
name: this.state.data1.templeDetail.name,
templeId: this.state.data1.templeDetail.templeId,
tagId: cur.tagId
})
}}
style={{
flexDirection: "column",
alignItems: "center",
}}
>
<Image
resizeMethod='resize'
resizeMode='stretch'
style={{
width: 45,
height: 40,
}}
source={tagImg[tag]}
/>
<Text style={{
fontSize: 18,
}}>{tagName[tag]}</Text>
</TouchableOpacity>
)
return res
}, [])
return arr
} else {
return (
<>
</>
)
}
}
render3 = (data) => {
let title = ''
if (this.props.navigation.getParam('isCiShan', false)) {
title = '慈善协会'
}
return (
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('SiYuanZiXunDetail', {
cid: data.cid,
title: title
})
}}
style={{
flexDirection: "column",
}}
>
<View style={{
height: 130,
width: (width - 40) / 2,
overflow: 'hidden',
borderRadius: 10,
}}>
<Image
resizeMethod='resize'
resizeMode='stretch'
style={{
width: '100%',
height: '100%',
}}
source={data && data.mainImageUrl ? { uri: data.mainImageUrl } : require('../../../imgs/noimg.png')}
/>
</View>
<Text
numberOfLines={1}
style={{
width: (width - 40) / 2,
color: '#919191',
}}
>{data && data.title ? data.title : ''}</Text>
</TouchableOpacity>
)
}
render4 = (txt) => {
return (
<Text
style={{
width: 70,
height: 30,
borderRightColor: '#3f3f3f',
borderRightWidth: 1,
textAlign: "center",
lineHeight: 30,
fontSize: 18,
color: '#dd1010',
}}
>{txt}</Text>
)
}
// 排行榜单行View
View1 = (data, width) => {
return (
<View style={{
width: width / 4 * 3,
height: 35,
borderBottomColor: '#e2e2e2',
borderBottomWidth: 1,
flexDirection: "row",
flexDirection: 'row',
alignItems: 'center',
}}>
<View style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#ddae44',
}}>
<Text></Text>
</View>
</View>
)
}
// 轮播图项目1
CarouselItem1 = (data, where, name) => {
let arr = data.reduce((res, cur, index) => {
res.push(
<View
key={index}
style={{
width: width * 0.9,
height: 60,
borderBottomColor: '#e2e2e2',
borderBottomWidth: 1,
flexDirection: "row",
flexDirection: 'row',
alignItems: 'center',
}}
>
<View style={{
width: 50,
height: 50,
borderRadius: 25,
overflow: 'hidden',
}}>
<Image
style={{
width: '100%',
height: '100%',
}}
resizeMethod='resize'
resizeMode='stretch'
source={cur.usersign ? { uri: cur.usersign } : require('./ntx.png')}
/>
</View>
<View style={{
flex: 1,
}}>
<View style={{
flexDirection: 'row',
}}>
<Text style={{
marginLeft: 10,
color: '#2e2e2e',
fontSize: 15,
}}>{cur.userNickName ? cur.userNickName : '匿名'}</Text>
<Text style={{
position: 'absolute',
right: 10,
color: '#2e2e2e',
fontSize: 18,
}}>{cur.money}元</Text>
</View>
<View style={{
flexDirection: 'row',
}}>
<Text style={{
// marginLeft: 10,
color: '#db5145',
marginLeft: 10,
}}>{this.props.navigation.getParam('isCiShan', '') ? '' : cur.donateName}</Text>
<Text style={{
position: 'absolute',
right: 10,
color: '#6d6d6d',
}}>{moment(cur.donateTime).format('MM-DD HH:mm')}</Text>
</View>
</View>
</View>
)
return res
}, [])
return (
<SegmentedView.Sheet
title={this.SVtitle(name, width)}
>
<View style={{
width: width * 0.9,
height: 60 * 12,
// backgroundColor:'#596574',
flexDirection: 'column',
}}>
{arr}
<View style={{
height: 60,
width: '100%',
// backgroundColor:'#828229',
}}>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('PaiHang2', {
'type': where,
'name': name,
'templeDetail': this.state.data1.templeDetail
})
}}
style={{
position: 'absolute',
right: 20,
height: 35,
marginTop: 20,
// backgroundColor:'#543933',
}}
>
<Text style={{
lineHeight: 35,
color: '#424242',
fontSize: 13,
}}>点击查看更多</Text>
</TouchableOpacity>
</View>
</View>
</SegmentedView.Sheet>
)
}
// 轮播图项目2、3
CarouselItem_2_3 = (data, where, name) => {
let arr = data.reduce((res, cur, index) => {
res.push(
<View
key={index}
style={{
width: width * 0.9,
height: 60,
borderBottomColor: '#e2e2e2',
borderBottomWidth: 1,
flexDirection: "row",
flexDirection: 'row',
alignItems: 'center',
// paddingLeft: 10,
}}
>
{this.render7(index)}
<View style={{
width: 50,
height: 50,
borderRadius: 25,
overflow: 'hidden',
}}>
<Image
style={{
width: '100%',
height: '100%',
}}
resizeMethod='resize'
resizeMode='stretch'
source={cur.usersign ? { uri: cur.usersign } : require('./ntx.png')}
/>
</View>
<Text style={{
marginLeft: 10,
color: '#2e2e2e',
fontSize: 15,
}}>{cur.nickName ? cur.nickName : '素客'}</Text>
<Text style={{
position: 'absolute',
right: 10,
color: '#2e2e2e',
fontSize: 18,
}}>{cur.moneyCount}元</Text>
</View>
)
return res
}, [])
return (
<SegmentedView.Sheet
title={this.SVtitle(name, width)}
>
<View style={{
width: width * 0.9,
height: 60 * 12,
// backgroundColor:'#596574',
flexDirection: 'column',
}}>
{arr}
<View style={{
height: 60,
width: '100%',
// backgroundColor:'#828229',
}}>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('PaiHang', {
'type': where,
'name': name,
'templeDetail': this.state.data1.templeDetail
})
}}
style={{
position: 'absolute',
right: 20,
height: 35,
marginTop: 20,
// backgroundColor:'#543933',
}}
>
<Text style={{
lineHeight: 35,
color: '#424242',
fontSize: 13,
}}>点击查看更多</Text>
</TouchableOpacity>
</View>
</View>
</SegmentedView.Sheet>
)
}
SVtitle = (txt, width) => {
return (
<View style={{
width: width / 4,
justifyContent: "center",
alignItems: "center",
// backgroundColor:'#548509',
height: 35,
}}>
<Text
style={{
fontSize: 17,
color: '#373737',
}}
>{txt}</Text>
</View>
)
}
// tab导航条1被改变
onChange1 = (index) => {
// Alert.alert(index.toString())
Toast.message(index.toString())
}
renderTitle = (txt) => {
let arr = txt.split('').reduce((res, cur, index) => {
res.push(
<Text
key={index}
style={{
// width: 50,
fontSize: 20,
fontWeight: 'bold',
color: '#b28627',
textAlign: "center",
}}
>{cur}</Text>
)
return res
}, [])
return (
<View style={{
width: width,
height: 40,
backgroundColor: '#ffcc81',
justifyContent: "center",
alignItems: "center",
flexDirection: 'row',
}}>
<View style={{
width: width - 80,
// marginLeft: 40,
justifyContent: 'space-evenly',
flexDirection: 'row',
// backgroundColor:'#393433',
}}>
{arr}
</View>
{/* {this.render12()} */}
</View>
)
}
// 添加关注寺院的函数
fun1 = async (templeId) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 添加关注寺院
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/addFollow`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
// body: JSON.stringify({//请求参数
// "templeId": this.state.data1.templeDetail.templeId
// }),
body: `templeId=${templeId}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
// 重新获取寺院信息
console.log('成功', responseJson);
} else {
console.log('失败', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
// 提醒用户先登录
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
}
render5 = (data) => {
let arr = data.reduce((res, cur, index) => {
res.push(
<Image
key={index}
style={{
width: '100%',
height: 250,
// borderRadius: 5,
}}
resizeMethod='resize'
resizeMode='cover'
source={cur ? { uri: cur } : require('../../../imgs/noimg.png')}
/>
)
return res
}, [])
return (
<Carousel style={{
height: 250,
width: width,
// paddingLeft: 10,
// paddingRight: 10,
// marginBottom: 10,
}}>
{arr}
</Carousel>
)
}
scrollViewStartOffsetY = 0; //用于记录手指开始滑动时ScrollView组件的Y轴偏移量,通过这个变量可以判断滚动方向
scrollViewScrollDirection = 0; //ScrollView组件滚动的方向:0往上;1往下
_onScrollBeginDrag = (event) => {
//记录ScrollView开始滚动的Y轴偏移量
this.scrollViewStartOffsetY = event.nativeEvent.contentOffset.y;
};
_onScroll = (event) => {
const offsetY = event.nativeEvent.contentOffset.y;
if (this.scrollViewStartOffsetY > offsetY) {
//手势往下滑动,
console.log('手势往下滑动');
this.AnimafunUp()
} else if (this.scrollViewStartOffsetY < offsetY) {
//手势往上滑动,
console.log('手势往上滑动');
this.AnimafunDown()
}
};
// 动画函数升起功德箱
AnimafunUp = () => {
if (this.state.direction == 'down') {
this.setState({
direction: 'up',
})
Animated.timing(
this.state.AnimatedValue,
{
toValue: 0,
duration: 1000,
easing: Easing.linear
}
).start()
}
}
// 动画函数降下功德箱
AnimafunDown = () => {
if (this.state.direction == 'up') {
this.setState({
direction: 'down',
})
Animated.timing(
this.state.AnimatedValue,
{
toValue: -30,
duration: 1000,
// easing: Easing.linear
easing: Easing.linear
}
).start()
}
}
render6 = (txt) => {
let txtArr = txt.split("")
let arr = txtArr.reduce((res, cur, index) => {
res.push(
<Text
key={index}
style={{
fontWeight: 'bold',
fontSize: 25,
marginLeft: 20,
marginRight: 20,
color: '#db5044',
}}
>{cur}</Text>
)
return res
}, [])
return (
<View style={{
height: 30,
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
}}>
{arr}
</View>
)
}
render7 = (index) => {
if (index <= 2) {
return (
<View style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#ddae44',
justifyContent: 'center',
alignItems: 'center',
marginRight: 5,
}}>
<Text style={{
color: '#fff',
}}>{index + 1}</Text>
</View>
)
} else {
return (
<View style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#fff',
justifyContent: 'center',
alignItems: 'center',
marginRight: 5,
}}>
<Text style={{
color: '#9a9a9a',
}}>{index + 1}</Text>
</View>
)
}
}
// 捐款弹框
close1 = () => {
this.overlayView && this.overlayView.close()
}
// 提示用户先登录弹框
close3 = () => {
this.overlayView3 && this.overlayView3.close()
}
// 感谢用户的爱心捐赠弹框
close4 = () => {
this.overlayView4 && this.overlayView4.close()
}
// 询问支付是否已完成弹框
close2 = () => {
this.overlayView2 && this.overlayView2.close()
}
// 关闭所有弹框弹框
closeAll = () => {
this.close1()
this.close2()
this.close3()
this.close4()
}
render13 = () => {
if (this.state.showZheng) {
return (
<View style={{
// height:30,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 5,
paddingBottom: 5,
width: width,
}}>
<View
style={{
height: 35,
backgroundColor: '#96afd7',
borderRadius: 5,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
}}
>
<TouchableOpacity
onPress={() => {
this.setState({
showZheng: false,
})
}}
style={{
width: 30,
height: 30,
position: 'absolute',
left: 5,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Image
style={{
width: 20,
height: 20,
}}
resizeMode='contain'
resizeMethod='resize'
source={require('./gb.png')}
/>
</TouchableOpacity>
<Image
style={{
width: 20,
height: 20,
marginRight: 10,
}}
resizeMode='contain'
resizeMethod='resize'
source={require('./zheng.png')}
/>
<Text style={{
fontSize: 14,
color: '#fff',
}}>已认证,可放心访问</Text>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('RenZheng', {
data: this.state.dataZheng,
})
}}
style={{
width: 60,
height: 20,
borderRadius: 10,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
right: 5,
}}
>
<Text style={{
fontSize: 14,
color: '#6d8db6',
}}>查看</Text>
</TouchableOpacity>
</View>
</View>
)
} else {
return <></>
}
}
fun12 = () => {
this.timer2 = setTimeout(() => {
this.setState({
sgHeight: this.state.HeightArr[this.state.activeIndex] * 60 + 60 + 60,
})
console.log('当前高度', this.state.HeightArr[this.state.activeIndex] * 60 + 60 + 60)
this.timer2 && clearTimeout(this.timer2)
}, 100);
}
render14 = () => {
if (this.props.navigation.getParam('isCiShan', false)) {
return (
<View
style={{
width: width,
height: 10,
paddingBottom: 0,
}}
></View>
)
} else {
return (
<View
style={{
width: width,
height: 130,
paddingBottom: 0,
}}
>
<View
style={{
flex: 1,
margin: 5,
backgroundColor: '#fff',
borderRadius: 20,
flexDirection: "row",
alignItems: "center",
justifyContent: 'space-evenly',
borderWidth: 1,
borderColor: '#aaa',
}}
>
{this.render2(this.state.data1.templeDetail && this.state.data1.templeDetail.tagList ? this.state.data1.templeDetail.tagList : [])}
<></>
</View>
</View>
)
}
}
render16 = (item) => {
if (item) {
return (
<View>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('SiYuanZiXunDetail', {
cid: item.cid
})
console.log('资讯id', item.cid)
}}
style={{
width: width - 10,
// backgroundColor: '#234902',
paddingRight: 10,
paddingLeft: 10,
// paddingTop: 10,
flexDirection: 'row',
}}
>
<View style={{
alignItems: 'center',
flex: 1,
marginRight: 10,
}}>
<Text
numberOfLines={3}
style={{
fontSize: 14,
fontWeight: 'bold',
color: '#333',
}}
>【{item.title}】 {item.slug}</Text>
</View>
<View style={{
borderRadius: 3,
overflow: 'hidden',
}}>
<Image
style={{
width: width * 0.32,
height: width * 0.21,
borderRadius: 3,
}}
resizeMethod='resize'
resizeMode='cover'
source={item.mainImageUrl ? { uri: item.mainImageUrl } : require('../../../imgs/noimg.png')}
/>
</View>
</TouchableOpacity>
<View style={{
width: width - 10,
marginLeft: 10,
flexDirection: 'row',
height: 15,
alignItems: 'center',
// backgroundColor:'#439233',
}}>
<Text style={{
fontSize: 11,
color: '#a7a7a7',
marginRight: 20,
}}>{item.origin}</Text>
<Text style={{
fontSize: 11,
color: '#a7a7a7',
marginRight: 20,
}}>{item.gtmCreate ? moment(item.gtmCreate).format('YYYY-MM-DD') : ''}</Text>
</View>
</View>
)
}
}
render15 = () => {
if (this.props.navigation.getParam('isCiShan', '')) {
return (
<View style={{
// backgroundColor: '#249834',
width: width - 10,
// height: 200,
// alignItems: 'center',
// marginLeft: 5,
}}>
{this.render16(this.state.data2[0])}
{this.render16(this.state.data2[1])}
</View>
)
} else {
return (
<View style={{
flexDirection: "row",
justifyContent: 'space-evenly',
borderStartColor: '#545494',
width: width - 10,
}}>
{this.render3(this.state.data2[0])}
{this.render3(this.state.data2[1])}
</View>
)
}
}
fun14 = (rechText) => {
return rechText.replace(/<(.*?)>(.*?)<\/(.*?)>/g, '$2').replace(/<br>/g, '')
}
render() {
if (this.state.data1 && this.state._CarouseItem1Data_1 && this.state._CarouseItem1Data_2 && this.state._CarouseItem1Data_3 && this.state.textList && this.state.data2) {
return (
<View style={{
flex: 1,
position: 'relative',
backgroundColor: this.props.navigation.getParam('isCiShan', '') ? '#ffcc81' : '#eee',
}}>
<ScrollView
onScroll={this._onScroll}
onScrollBeginDrag={this._onScrollBeginDrag}
scrollEventThrottle={16}
style={{
flex: 1,
}}
ref={(view) => { this.myScrollView = view; }}
>
<Back
navigation={this.props.navigation}
/>
{this.renderTitle(this.state.data1.templeDetail && this.state.data1.templeDetail.name ? this.state.data1.templeDetail.name : '某某寺')}
{this.render13()}
{this.render5(this.state.data1.carouselList)}
<View style={{
width: width,
height: this.state.heightNow
// height: 100
}}>
<View style={{
width: width,
height: this.state.heightNow,
backgroundColor: 'transparent',
position: 'absolute',
left: 0,
top: 0,
zIndex: 10,
}}></View>
<WebView
style={{ flex: 1 }}
bounces={false}
scrollEnabled={false}
automaticallyAdjustContentInsets={true}
contentInset={{ top: 0, left: 0 }}
scalesPageToFit={false}//布尔值,控制网页内容是否自动适配视图的大小,同时启用用户缩放功能。默认为true。
originWhitelist={['*']}//允许被导航到的源字符串列表。字符串允许使用通配符,并且只根据原始地址(而不是完整的URL)进行匹配。如果用户点击导航到一个新页面,但是新页面不在这个白名单中,这个URL将由操作系统处理。默认的白名单起点是"http://"和"https://".
source={{ html: `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0;maximum-scale=1;user-scalable=no"><meta name="description" content=""/></head><body>${this.state.data1.templeDetail && this.state.data1.templeDetail.profile ? this.state.data1.templeDetail.profile : ''}</body></html>` }}
// onNavigationStateChange={(navState) => {
// if (navState.title && parseInt(navState.title)) {
// this.setState({
// height: parseInt(navState.title) + 20
// })
// console.log('获取到的高度', navState.title)
// }
// }}
injectedJavaScript={BaseScript}
onMessage={this.onMessage.bind(this)}
/>
</View>
{this.render1()}
{this.render14()}
<View style={{
width: width - 20,
flexDirection: "row",
alignItems: "center",
backgroundColor: '#fef4e0',
borderRadius: 20,
paddingRight: 10,
paddingLeft: 10,
marginLeft: 10,
}}>
<View style={{
width: 120,
height: 120,
borderRadius: 60,
overflow: 'hidden',
backgroundColor: '#fff',
}}>
<Image
source={this.state.data1.templeDetail && this.state.data1.templeDetail.hostImage ? { uri: this.state.data1.templeDetail.hostImage } : require('../../../imgs/noimg.png')}
resizeMethod='resize'
resizeMode='contain'
style={{
width: 120,
height: 120,
}}
/>
</View>
<View style={{
flexDirection: "column",
padding: 10,
flex: 1,
marginTop: 20,
}}>
<View style={{
paddingBottom: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
}}>
<Text style={{
fontSize: 15,
marginRight: 5,
}}>{this.state.data1.templeDetail && this.state.data1.templeDetail.hostName ? this.state.data1.templeDetail.hostName : ''}</Text>
<Text style={{
color: '#0c7d90',
borderWidth: 1,
borderRadius: 5,
borderColor: '#0c7d90',
fontSize: 13,
padding: 3,
}}>{this.props.navigation.getParam('isCiShan', '') ? '会长' : '方丈'}</Text>
</View>
{/* <View style={{
width: '100%',
height: 60,
// backgroundColor: '#493948',
}}>
<View style={{
width: '100%',
height: 60,
backgroundColor: 'transparent',
position: 'absolute',
left: 0,
top: 0,
zIndex: 10,
}}></View>
<WebView
style={{ flex: 1 }}
bounces={false}
scrollEnabled={false}
automaticallyAdjustContentInsets={true}
contentInset={{ top: 0, left: 0 }}
scalesPageToFit={false}//布尔值,控制网页内容是否自动适配视图的大小,同时启用用户缩放功能。默认为true。
originWhitelist={['*']}//允许被导航到的源字符串列表。字符串允许使用通配符,并且只根据原始地址(而不是完整的URL)进行匹配。如果用户点击导航到一个新页面,但是新页面不在这个白名单中,这个URL将由操作系统处理。默认的白名单起点是"http://"和"https://".
source={{ html: `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0;maximum-scale=1;user-scalable=no"><meta name="description" content=""/></head><body>${this.state.data1.templeDetail && this.state.data1.templeDetail.hostProfile ? this.state.data1.templeDetail.hostProfile : ''}</body></html>` }}
/>
</View> */}
<Text
numberOfLines={2}
style={{
color: '#919191',
}}
>{this.fun14(this.state.data1.templeDetail && this.state.data1.templeDetail.hostProfile ? this.state.data1.templeDetail.hostProfile : '')}</Text>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('ZhuChiDetail', {
templeDetail: this.state.data1.templeDetail,
isCiShan: this.props.navigation.getParam('isCiShan', '')
})
}}
style={{
alignSelf: "flex-end",
position: 'relative',
top: 10,
}}
>
<Text style={{
color: '#919191',
}}>更多</Text>
</TouchableOpacity>
</View>
</View>
<View style={{
// backgroundColor: '#ddd',
// height: 230,
width: width,
paddingBottom: 5,
}}>
<View style={{
flex: 1,
margin: 5,
borderRadius: 20,
backgroundColor: '#fff',
alignItems: "center",
justifyContent: 'center',
}}>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 18,
color: '#ac5601',
marginLeft: 10,
}}>{this.props.navigation.getParam('isCiShan', '') ? '慈善协会资讯' : '寺院资讯'}</Text>
</View>
{this.render15()}
<View style={{
width: '100%',
alignItems: 'flex-end',
// marginTop: 10,
}}>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('SiYuanZiXun', {
'templeDetail': this.state.data1.templeDetail,
'isCiShan': this.props.navigation.getParam('isCiShan', '')
})
}}
style={{
marginRight: 10,
}}
>
<Text
style={{
color: '#919191',
}}
>查看更多</Text>
</TouchableOpacity>
</View>
</View>
</View>
<View style={{
height: 30,
width: width,
backgroundColor: '#db5145',
flexDirection: 'row',
borderBottomColor: '#e4c58f',
}}>
<Image
resizeMethod='resize'
resizeMode='stretch'
style={{
width: 30,
height: 30,
marginLeft: 5,
marginRight: 10,
}}
source={require('./i.png')}
/>
<MarqueeHorizontal
textList={this.state.textList} //滚动的文字数组,具体数据格式请参照textList.item
speed={60} //平均的滚动速度,跑马灯使用这个属性(建议传入60)
width={width - 45} //宽度,不能使用flex
height={30} //高度,不能使用flex
direction={'left'} //动画方向(向上向下滚动)up or down
reverse={false} //是否将整个文本数据倒叙显示
bgContainerStyle={{
// marginLeft:45,
backgroundColor: '#db5145',
}} //背景样式
textStyle={{
color: '#fff',
lineHeight: 30,
fontSize: 22,
}} //文本样式
onTextClick={(item) => {
// alert('' + JSON.stringify(item));
}} //点击事件回调:(item) => void
/>
</View>
{/* 功德榜 */}
<View style={{
width: width - 26,
marginLeft: 13,
alignItems: "center",
backgroundColor: '#fff',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 0,
elevation: 2,
borderRadius: 5,
marginBottom: 5,
marginTop: 5,
padding: 20,
flexDirection: 'column',
minHeight: 60 * 3,
flex: 1,
}}>
{this.render6('功德栏')}
<SegmentedView
style={{
// height: 60 * 13,
height: this.state.sgHeight,
flex: 1,
width: width * 0.9,
// backgroundColor: '#495438',
}}
// indicatorLineColor='#000'
barStyle={{
backgroundColor: '#fff',
}}
type='carousel'
indicatorType='boxWidth'
indicatorLineColor='#e0e0e0'
onChange={(index) => {
console.log('当前序号', index)
this.setState({
sgHeight: this.state.HeightArr[index] * 60 + 60 + 60,
activeIndex: index,
})
console.log('当前高度', this.state.HeightArr[index] * 60 + 60 + 60)
}}
>
{this.CarouselItem1(this.state._CarouseItem1Data_1, 'RiPaiHang', '实时')}
{this.CarouselItem_2_3(this.state._CarouseItem1Data_2, 'YuePaiHang', '月榜')}
{this.CarouselItem_2_3(this.state._CarouseItem1Data_3, 'NianPaiHang', '年榜')}
</SegmentedView>
</View>
</ScrollView>
<Animated.View style={{
position: 'absolute',
bottom: this.state.AnimatedValue,
width: width,
alignItems: "center",
}}>
<TouchableOpacity
onPress={() => {
let overlayView = (
<Overlay.PullView
modal={false}
side='bottom'
animated={true}
ref={v => this.overlayView = v}
>
<View style={{
width: width,
backgroundColor: '#fff',
height: width * 1,
}}>
<JuanKuan
navigation={this.props.navigation}
close1={this.close1}
closeAll={this.closeAll}
refresh1={this.refresh1}
meritProductInfo={this.state.data1.meritProductInfo}
templeId={this.props.navigation.getParam('templeId')}
/>
</View>
</Overlay.PullView >
);
Overlay.show(overlayView);
}}
style={{
width: 100,
height: 100,
}}
>
<Image
style={{
width: '100%',
height: '100%',
}}
source={this.props.navigation.getParam('isCiShan','')?require('./hx2.png'):require('./hx.png')}
/>
</TouchableOpacity>
</Animated.View>
</View>
);
} else {
return (
<View style={{
flex: 1,
position: 'relative',
backgroundColor: '#eee',
}}>
<Image
style={{
width: '100%',
height: '100%',
}}
// resizeMethod='resize'
resizeMode='cover'
source={require('../../../imgs/abcd.png')}
/>
</View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, TextInput, Button, Image, TouchableOpacity, ScrollView, Dimensions, Alert } from 'react-native';
import { Overlay,Toast } from 'teaset'
import AsyncStorage from '@react-native-community/async-storage';
import appConfig from '../../../jsonData/appConfig.js'
import moment from 'moment';
export default class DengLu extends Component {
// static navigationOptions = ({ navigation }) => {
// return {
// title: navigation.getParam('otherParam', '登录'),
// }
// }
static navigationOptions = {
header: null,
}
state = {
passWord: '',//密码
phone: '',//手机号码
}
UNSAFE_componentWillMount() {
if (this.props.navigation.getParam('nickName', '')) {
this.setState({
nickName: this.props.navigation.getParam('nickName', ''),
})
}
if (this.props.navigation.getParam('passWord', '')) {
this.setState({
nickName: this.props.navigation.getParam('passWord', ''),
})
}
}
fun1 = () => {
if (this.state.passWord == '') {
// Alert.alert('密码未填写')
Toast.message('密码未填写')
return
}
if (!/^1\d{10}$/.test(this.state.phone)) {
// Alert.alert('请先填写正确的手机号码')
Toast.message('请先填写正确的手机号码')
return
}
// 登录
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/authentication/form`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic c3VrZWxhaTozYWI2N2ExMmJkNWE='
}),
body: `username=${this.state.phone}&password=${this.<PASSWORD>}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == '200') {
//存储已登录用户授权信息
this.setValue1(JSON.stringify({
...responseJson.data,
outTime: moment().add(1, 'days').unix()
}))
console.log('responseJson', responseJson)
Toast.success('登录成功')
this.props.navigation.navigate('ShouYe')
} else {
console.log('responseJson', responseJson)
// Alert.alert(responseJson.message)
Toast.message(responseJson.message)
}
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
setValue1 = async (data) => {
try {
await AsyncStorage.setItem('userData', data)
console.log('用户信息已存储', data)
// Alert.alert('用户信息已存储')
// Alert.alert('')
} catch (error) {
// save error
console.log('error', error)
// Alert.alert('出错了')
Toast.message('出错了')
}
console.log('Done.')
}
render() {
const { width } = Dimensions.get('window');
return (
<ScrollView
keyboardShouldPersistTaps='handled'
style={{
flex: 1,
paddingRight: 30,
paddingLeft: 30,
paddingBottom: 131,
}}
>
<View style={{
height: 220,
justifyContent: "center",
alignItems: "center",
// backgroundColor:'#847487'
}}>
<Text style={{
fontSize: 60,
color: '#6183b1',
// fontFamily:''
}}>素客莱</Text>
</View>
<Text style={{
color: '#6183b1',
fontSize:20,
}}>手机号码</Text>
<TextInput
placeholder='请填写手机号'
onChangeText={(text) => {
this.setState({
phone: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
fontSize:20,
}}
>{this.state.phone}</TextInput>
<Text style={{
color: '#6183b1',
fontSize:20,
}}>密码</Text>
<TextInput
secureTextEntry={true}
placeholder='请填写密码'
onChangeText={(text) => {
this.setState({
passWord: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
fontSize:20,
// marginBottom: 41,
}}
>{this.state.passWord}</TextInput>
<View style={{
flexDirection: 'row',
alignItems: 'center',
height: 36,
justifyContent: 'space-between',
marginTop:15,
marginBottom:15,
}}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('ZhuCe', {
itemId: 86,
name: '觱沸所',
})}
>
<Text style={{
color: '#6183b1',
fontSize:20,
}}>注册帐号</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('WangJiMiMa', {
itemId: 86,
name: '觱沸所',
})}
>
<Text style={{
color: '#6183b1',
fontSize:20,
}}>忘记密码</Text>
</TouchableOpacity>
</View>
<TouchableOpacity
onPress={() => this.fun1()}
style={{
backgroundColor: '#6183b1',
borderRadius: 5,
alignItems: "center",
justifyContent: "center",
height: 45,
}}
>
<Text style={{
color: '#FFFFFF',
fontSize:20,
}}>登录</Text>
</TouchableOpacity>
</ScrollView>
);
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, Alert, ScrollView, Dimensions, FlatList } from 'react-native';
import appConfig from '../../../jsonData/appConfig.js'
import { Carousel, SegmentedView, ModalIndicator, Overlay } from 'teaset';
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
const { width } = Dimensions.get('window');
export default class SiYuanZiXun extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: `${navigation.getParam('templeDetail') ? navigation.getParam('templeDetail').name : '某某寺'}资讯`,
headerRight: <Image />
}
}
state = {
data1: '',
nextPage: 1,// 下一页的页码
pageSize: 9,//每页条数
isLoading: false,//列表是否正在加载中
isOver: false,// 是否已经到底,没有更多内容了
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
this.refresh()
}
renderLine = () => {
return (
<View style={{
width: width,
height: 1,
backgroundColor: '#999999',
}}></View>
)
}
renderItem = ({ item }) => {
console.log('item.....', item)
return (
// <View>
// <TouchableOpacity
// onPress={() => {
// this.props.navigation.navigate('SiYuanZiXunDetail', {
// cid: item.cid
// })
// }}
// style={{
// width: width,
// paddingTop: 10,
// paddingLeft: 10,
// paddingRight: 10,
// flexDirection: 'row',
// }}
// >
// <Image
// style={{
// width: width * 0.45,
// height: width * 0.3,
// }}
// resizeMethod='resize'
// resizeMode='stretch'
// source={item.mainImageUrl ? { uri: item.mainImageUrl } : require('../../../imgs/noimg.png')}
// />
// <View style={{
// alignItems: 'center',
// flex: 1,
// padding: 10,
// }}>
// <Text
// numberOfLines={1}
// style={{
// fontSize: 25,
// fontWeight: 'bold',
// color: '#333',
// }}
// >{item.title}</Text>
// <Text
// numberOfLines={3}
// style={{
// fontSize: 15,
// color: '#666666',
// }}
// >{item.slug}</Text>
// </View>
// </TouchableOpacity>
// {this.renderLine()}
// </View>
<View>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('SiYuanZiXunDetail', {
cid: item.cid
})
console.log('资讯id', item.cid)
}}
style={{
width: width,
paddingRight: 10,
paddingLeft: 10,
paddingTop: 10,
flexDirection: 'row',
}}
>
<View style={{
alignItems: 'center',
flex: 1,
marginRight: 10,
}}>
<Text
numberOfLines={3}
style={{
fontSize: 14,
fontWeight: 'bold',
color: '#333',
}}
>【{item.title}】 {item.slug}</Text>
</View>
<View style={{
borderRadius: 3,
overflow: 'hidden',
}}>
<Image
style={{
width: width * 0.32,
height: width * 0.21,
borderRadius: 3,
}}
resizeMethod='resize'
resizeMode='cover'
source={item.mainImageUrl ? { uri: item.mainImageUrl } : require('../../../imgs/noimg.png')}
/>
</View>
</TouchableOpacity>
<View style={{
// backgroundColor: '#292434',
width: width - 20,
marginLeft: 10,
flexDirection: 'row',
// alignItems: 'center',
height: 30,
}}>
<Text style={{
fontSize: 11,
color: '#a7a7a7',
marginRight: 20,
}}>{item.origin}</Text>
<Text style={{
fontSize: 11,
color: '#a7a7a7',
marginRight: 20,
}}>{item.gtmCreate ? moment(item.gtmCreate).format('YYYY-MM-DD') : ''}</Text>
</View>
</View>
)
}
_renderFooter = () => {
if (this.state.data1 && (this.state.data1.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderEmptyComponent = () => {
return (
<View style={{
width: '100%',
alignItems: 'center',
height: 100,
justifyContent: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>暂无数据</Text>
</View>
)
}
// 加载下一页的数据
nextData = async () => {
if (this.state.isOver) {
// Alert('已经到最底部,没有更多内容了')
return
}
let nowPage = this.state.nextPage
this.setState({
isLoading: true,
nextPage: nowPage + 1,
})
console.log(`正在加载第${nowPage}页`)
// 获取寺院资讯列表
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getAllNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
}),
body: JSON.stringify({
"templeId": this.props.navigation.getParam('templeDetail').templeId,
"page": nowPage,
"size": this.state.pageSize
})
// body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('data1', responseJson.data)
if (responseJson.data) {
if (responseJson.data.list.length == this.pageSize) {
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
isOver: true,
})
} else {
this.setState({
isLoading: false,
isOver: true,
})
}
}
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
// 刷新列表
refresh = async () => {
this.setState({
isLoading: true,
nextPage: 2,
isOver: false,
})
// 获取寺院资讯列表
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getAllNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
}),
body: JSON.stringify({
"templeId": this.props.navigation.getParam('templeDetail').templeId,
"page": 1,
"size": this.state.pageSize
})
// body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('data1', responseJson.data)
if (responseJson.data) {
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
isOver: true,
})
} else {
this.setState({
data1: [],
isLoading: false,
isOver: true,
})
}
ModalIndicator.hide()
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
render1 = () => {
if (this.props.navigation.getParam('isCiShan', '')) {
return <></>
} else {
return (
<Image
style={{
width: width,
height: width * 0.21656,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./b.png')}
/>
)
}
}
render() {
if (this.state.data1) {
return (
<View style={{
flex: 1,
backgroundColor: '#fff',
}}>
{this.render1()}
{this.renderLine()}
{/* {this.render1(this.state.data1)} */}
<FlatList
data={this.state.data1}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
// ListHeaderComponent ={this._renderHeader }//头部组件
ListFooterComponent={this._renderFooter}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</View>
);
} else {
return (
<View style={{
backgroundColor: '#fff',
flex: 1,
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, TouchableOpacity, Image, Alert, Dimensions, ScrollView, ImageBackground, TextInput } from 'react-native';
import { Carousel, Overlay, Checkbox, ModalIndicator, Toast } from 'teaset';
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
// import Back from '../../../component/Back'
const { width, height } = Dimensions.get('window');
class DateList extends Component {
state = {
RuRi: '',
LiRi: '',
}
UNSAFE_componentWillMount() {
this.setState({
RuRi: this.props.RuRi,
LiRi: this.props.LiRi,
})
console.log('接收到的时间戳', this.props.RuRi, this.props.LiRi)
}
// 当前是多少年
Nian1 = moment().year()
Nian2 = moment().add(1, 'months').year()
Nian3 = moment().add(2, 'months').year()
Nian4 = moment().add(3, 'months').year()
Nian5 = moment().add(4, 'months').year()
Nian6 = moment().add(5, 'months').year()
// 当前是几月份
Yue1 = moment().month() + 1
Yue2 = moment().add(1, 'months').month() + 1
Yue3 = moment().add(2, 'months').month() + 1
Yue4 = moment().add(3, 'months').month() + 1
Yue5 = moment().add(4, 'months').month() + 1
Yue6 = moment().add(5, 'months').month() + 1
// 今天是几号
TodayRi = moment().date()
// 今天0点的时间戳
TodayChuo = moment(`${this.Nian1}-${this.Yue1}-${this.TodayRi}`, 'YYYY-MM-DD').unix()
// 当前月共有多少天
TianShu1 = moment().daysInMonth()
TianShu2 = moment().add(1, 'months').daysInMonth()
TianShu3 = moment().add(2, 'months').daysInMonth()
TianShu4 = moment().add(3, 'months').daysInMonth()
TianShu5 = moment().add(4, 'months').daysInMonth()
TianShu6 = moment().add(5, 'months').daysInMonth()
// 当前月1号之前有多少个空格
Kong1 = moment(`${this.Nian1}-${this.Yue1}-01`, 'YYYY-MM-DD').day()
Kong2 = moment(`${this.Nian2}-${this.Yue2}-01`, 'YYYY-MM-DD').day()
Kong3 = moment(`${this.Nian3}-${this.Yue3}-01`, 'YYYY-MM-DD').day()
Kong4 = moment(`${this.Nian4}-${this.Yue4}-01`, 'YYYY-MM-DD').day()
Kong5 = moment(`${this.Nian5}-${this.Yue5}-01`, 'YYYY-MM-DD').day()
Kong6 = moment(`${this.Nian6}-${this.Yue6}-01`, 'YYYY-MM-DD').day()
changeRuLi = (NewCur) => {
console.log('入住日期', this.state.RuRi)
console.log('离开日期', this.state.LiRi)
if (this.state.LiRi != '') {
this.setState({
RuRi: NewCur,
LiRi: ''
})
} else if (this.state.RuRi != '') {
if (NewCur > this.state.RuRi) {
this.setState({
LiRi: NewCur
})
} else if (NewCur == this.state.RuRi) {
this.setState({
RuRi: ''
})
} else {
this.setState({
RuRi: NewCur
})
}
} else {
this.setState({
RuRi: NewCur
})
}
console.log('选择出来的时间戳', this.state.RuRi, this.state.LiRi)
}
render6 = (N) => {
let TianShu = this[`TianShu${N}`]//当月天数
let aabb = Array.from(new Array(TianShu + 1).keys()).slice(1)
let arr = aabb.reduce((res, cur, index) => {
let NewCur = moment(`${this[`Nian${N}`]}-${this[`Yue${N}`]}-${cur}`, 'YYYY-MM-DD').unix()//当前日期0点时间戳
let TodayChuo30 = this.TodayChuo + 2592000//今日0点30天后时间戳
if ((NewCur < this.TodayChuo) || (TodayChuo30 < NewCur)) {
res.push(
<View
key={index}
style={{
width: 40,
height: 40,
marginTop: 5,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
color: '#bdbdbd',
}}>{cur}</Text>
</View>
)
} else if (NewCur == this.state.RuRi) {
let color = ''
if (this.state.LiRi > this.state.RuRi) {
color = '#ffbfca'
} else {
color = '#f0f0f0'
}
res.push(
<TouchableOpacity
style={{
marginTop: 5,
}}
key={index}
onPress={() => {
this.changeRuLi(NewCur)
}}
>
<View style={{
width: 40,
height: 40,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff5f7a',
zIndex: 1,
}}>
<Text style={{
color: '#fff',
}}>入住</Text>
</View>
<View style={{
width: 20,
height: 40,
position: 'absolute',
right: 0,
backgroundColor: color,
}}></View>
</TouchableOpacity>
)
} else if (NewCur == this.state.LiRi) {
res.push(
<TouchableOpacity
style={{
marginTop: 5,
}}
key={index}
onPress={() => {
this.changeRuLi(NewCur)
}}
>
<View style={{
width: 40,
height: 40,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff5f7a',
zIndex: 1,
}}>
<Text style={{
color: '#fff',
}}>离开</Text>
</View>
<View style={{
width: 20,
height: 40,
position: 'absolute',
left: 0,
backgroundColor: '#ffbfca',
}}></View>
</TouchableOpacity>
)
} else if (NewCur > this.state.RuRi && NewCur < this.state.LiRi) {
res.push(
<TouchableOpacity
key={index}
onPress={() => {
this.changeRuLi(NewCur)
}}
style={{
width: 40,
height: 40,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ffbfca',
marginTop: 5,
}}
>
<Text style={{
color: '#fff',
}}>{cur}</Text>
</TouchableOpacity>
)
} else if (NewCur == this.TodayChuo) {
res.push(
<TouchableOpacity
key={index}
onPress={() => {
this.changeRuLi(NewCur)
}}
style={{
width: 40,
height: 40,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
borderWidth: 1,
borderColor: '#bdbdbd',
marginTop: 5,
}}>
<Text style={{
color: '#212121',
}}>今</Text>
</TouchableOpacity>
)
} else {
res.push(
<TouchableOpacity
key={index}
onPress={() => {
this.changeRuLi(NewCur)
}}
style={{
width: 40,
height: 40,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
marginTop: 5,
}}>
<Text style={{
color: '#212121',
}}>{cur}</Text>
</TouchableOpacity>
)
}
return res
}, [])
return arr
}
render7 = () => {
let arr = ['日', '一', '二', '三', '四', '五', '六']
let arrView = arr.reduce((res, cur, index) => {
res.push(
<View
key={index}
style={{
width: 40,
height: 40,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text style={{
fontSize: 20,
color: '#000',
}}>{cur}</Text>
</View>
)
return res
}, [])
return (
<View style={{
width: '100%',
flexDirection: 'row',
}}>
{arrView}
</View>
)
}
render8 = (Kong) => {
let arr = []
for (let i = 0; i < Kong; i++) {
arr.push(
<View
key={i}
style={{
width: 40,
height: 40,
}}
></View>
)
}
return (
<>
{arr}
</>
)
}
render12 = (N) => {
return (
<View style={{
width: 280,
marginLeft: (width - 280) / 2,
marginTop: 20,
marginBottom: 20,
}}>
<View style={{
width: '100%',
alignItems: "center",
marginBottom: 10,
}}>
<Text style={{
fontSize: 20,
color: '#000',
}}>{this[`Nian${N}`]}.{this[`Yue${N}`]}</Text>
</View>
{this.render7()}
<View
style={{
width: '100%',
flexDirection: 'row',
flexWrap: 'wrap',
}}
>
{this.render8(this[`Kong${N}`])}
{this.render6(N)}
</View>
</View>
)
}
// 时间戳格式化
Do1 = (val) => {
if (val == '') {
return ''
} else {
return moment.unix(val).format('YYYY.MM.DD')
}
}
// 计算从入住到离开的时长
Do2 = () => {
if (this.state.LiRi != '') {
return (this.state.LiRi - this.state.RuRi) / 24 / 60 / 60
} else {
return 0
}
}
render13 = () => {
if (this.state.RuRi || this.state.LiRi) {
return (
<View style={{
width: width,
height: 80,
backgroundColor: '#fdfdfd',
justifyContent: 'center',
alignItems: 'stretch',
paddingLeft: 20,
paddingRight: 20,
}}>
<View style={{
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<Text>入住时间</Text>
<Text>离开时间</Text>
</View>
<View style={{
flexDirection: "row",
justifyContent: 'space-between',
alignItems: 'center',
}}>
<View style={{
width: width * 0.35,
}}>
<Text style={{
fontSize: 20,
color: '#000',
fontWeight: 'bold',
}}>{this.Do1(this.state.RuRi)}</Text>
</View>
<Text style={{
borderRadius: 3,
borderWidth: 1,
borderColor: '#bdbdbd',
padding: 5,
fontSize: 15,
color: '#bdbdbd',
}}>{this.Do2()}晚</Text>
<View style={{
width: width * 0.35,
alignItems: 'flex-end',
}}>
<Text style={{
fontSize: 20,
color: '#000',
fontWeight: 'bold',
}}>{this.Do1(this.state.LiRi)}</Text>
</View>
</View>
</View>
)
} else {
return (
<View style={{
width: width,
height: 80,
backgroundColor: '#fdfdfd',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 35,
color: '#212121',
}}>请选择入住离开时间</Text>
</View>
)
}
}
render14 = () => {
if (this.state.LiRi != '') {
return (
<TouchableOpacity
onPress={() => {
this.props.Fdo1(this.state.RuRi, this.state.LiRi)
}}
style={{
width: 100,
height: 30,
backgroundColor: '#ff5f7a',
borderRadius: 15,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
color: '#fff',
fontWeight: 'bold',
fontSize: 20,
}}>确定</Text>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
onPress={() => {
// Alert.alert('请先选择入住日期')
Toast.message('请先选择入住日期')
}}
style={{
width: 100,
height: 30,
backgroundColor: '#e0e0e0',
borderRadius: 15,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
color: '#fff',
fontWeight: 'bold',
fontSize: 20,
}}>确定</Text>
</TouchableOpacity>
)
}
}
render15 = () => {
if (this.state.LiRi != '') {
return (
<TouchableOpacity
onPress={() => {
this.setState({
RuRi: '',
LiRi: '',
})
}}
>
<Text style={{
fontSize: 20,
color: '#212121',
fontWeight: 'bold',
}}>清空</Text>
</TouchableOpacity>
)
} else {
return (
<Text style={{
fontSize: 20,
color: '#bdbdbd',
fontWeight: 'bold',
}}>清空</Text>
)
}
}
render() {
return (
<>
{this.render13()}
<ScrollView style={{
width: width,
backgroundColor: '#f0f0f0',
height: height - 20 - 80 - 80 - 50,
}}>
{this.render12(1)}
{this.render12(2)}
{/* {this.render12(3)} */}
{/* {this.render12(4)} */}
{/* {this.render12(5)} */}
{/* {this.render12(6)} */}
</ScrollView>
<View style={{
height: 50,
width: width,
backgroundColor: '#fff',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingLeft: 20,
paddingRight: 20,
}}>
{this.render15()}
{this.render14()}
</View>
</>
)
}
}
export default class ChanFangDetail extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
// title: `${navigation.getParam('data').haddr}${navigation.getParam('name', '详情')}`,
title: `${navigation.getParam('name', '详情')}`,
headerRight: <Image />
}
}
state = {
isRead: false,//是否已阅读协议内容
showTxt: false,
data11: [
// {
// name: '',
// shenfen: '',
// sex: true,//性别,true男,false女
// }
],//全部入住人信息
self: {
name: '',
shenfen: '',
phone: '',
sex: true,//性别,true男,false女
},//预订人自己的信息
RuRi: '',
LiRi: '',
RuDay: {
'day': '',
'week': ''
},
LiDay: {
'day': '',
'week': ''
},
During: {
RuRi: '',//时间戳
LiRi: '',//时间戳
},//从入住到离开时间段
Authorization: '',//当前登录权限码
userinfo: '',//当前用户信息
data2: '',//当前禅房详细信息
// showMore:true,//是否显示更多入住
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
let RuRi = moment().unix()
RuRi = RuRi - RuRi % 86400 - 28800//东八区用这个
// RuRi = RuRi - RuRi % 86400
let LiRi = RuRi + 86400
this.setState({
RuRi: RuRi,
LiRi: LiRi,
})
this.Fdo1(RuRi, LiRi)
this.JianCeDengLu()
}
fun1 = (Authorization) => {
ModalIndicator.show('加载中。。。')
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/hostel/roomInfo`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': Authorization
}),
body: `roomId=${this.props.navigation.getParam('data').productId}`,
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
this.setState({
data2: responseJson.data
})
ModalIndicator.hide()
console.log('返回的数据xxoooo', responseJson.data[0]);
} else {
console.log('responseJson', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
ModalIndicator.hide()
})
}
// 检测是否登录
JianCeDengLu = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户信息
let valueObj = JSON.parse(value)
if (valueObj.outTime > moment().unix()) {
console.log('valueObj', valueObj)
ModalIndicator.show('加载中。。。')
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/me`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: '',
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
this.setState({
Authorization: `${valueObj.token_type} ${valueObj.access_token}`,
userinfo: responseJson.data
})
//查询当前禅房详细信息
this.fun1(`${valueObj.token_type} ${valueObj.access_token}`)
console.log('返回的数据', responseJson.data.nickName);
ModalIndicator.hide()
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
this.TiShiDengLu()
}
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
ModalIndicator.hide()
})
} else {
ModalIndicator.hide()
this.TiShiDengLu()
}
} else {
ModalIndicator.hide()
this.TiShiDengLu()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
console.log('Done.')
}
// 提示用户登录
TiShiDengLu = () => {
// 提示用户先登录
let TiShiDengLuOverlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.TiShiDengLuOverlayView = v}
>
<ImageBackground
style={{
backgroundColor: '#fff',
padding: 3,
// borderRadius: 10,
height: 165,
width: 285,
}}
resizeMethod='resize'
resizeMode='cover'
source={require('../../../imgs/dl.png')}
>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 22,
}}>[请先登录]</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.overlayView1 && this.overlayView1.close()
this.overlayView2 && this.overlayView2.close()
this.props.navigation.goBack()
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>返回</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.overlayView1 && this.overlayView1.close()
this.overlayView2 && this.overlayView2.close()
this.props.navigation.replace('DengLu')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>确定</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Overlay.View>
);
Overlay.show(TiShiDengLuOverlayView);
}
render1 = (img, txt) => {
return (
<View style={{
alignItems: "center",
}}>
<Image
style={{
width: 30,
height: 30,
}}
resizeMethod='resize'
resizeMode='stretch'
source={img}
/>
<Text style={{
// width:60,
fontSize: 20,
color: '#6b6b6b',
}}>{txt}</Text>
</View>
)
}
render2 = (txt) => {
return (
<Text style={{
width: width - 40,
marginLeft: 20,
marginRight: 20,
color: '#6a6a6a',
fontSize: 15,
}}>{txt}</Text>
)
}
render3 = (txt1, txt2, txt3) => {
return (
<View style={{
alignItems: "center",
}}>
<View style={{
flexDirection: "row",
alignItems: 'center',
}}>
<Text style={{
fontSize: 20,
color: '#000',
marginRight: 20,
}}>{txt1}</Text>
<Text style={{
fontSize: 13,
color: '#000',
}}>{txt2}</Text>
</View>
<View style={{
justifyContent: "center",
alignItems: "center",
width: 110,
backgroundColor: '#e2e2e2',
paddingTop: 5,
paddingBottom: 5,
}}>
<Text style={{
fontSize: 18,
color: '#000',
}}>{txt3}</Text>
</View>
</View>
)
}
render4 = (txt) => {
return (
<View style={{
alignItems: 'center',
justifyContent: 'center',
}}>
<Text style={{
color: '#dd1010',
fontSize: 13,
}}>{txt}</Text>
<Image
resizeMode="stretch"
style={{
width: 80,
height: 5,
}}
source={require('./f.png')}
/>
</View>
)
}
render5 = () => {
if (this.state.showTxt) {
return (
<View style={{
marginTop: 10,
width: width - 20,
marginLeft: 10,
borderRadius: 10,
backgroundColor: '#fff',
overflow: 'hidden',
shadowColor: '#000',
shadowOffset: { width: 4, height: 4 },
shadowOpacity: 0.8,
shadowRadius: 6,
elevation: 1
}}>
<Image
style={{
width: width - 20,
height: width * 0.165,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./x.png')}
></Image>
<View style={{
width: width - 20,
backgroundColor: '#fff',
}}>
{this.render2('1. 为了便于各地前来朝圣的香客更好的安排住处, 但因禅房有限,为防止恶意占用而不到者,入住需缴(诚意金)无论签到与否(诚意金)不予退还,(诚意金)将以香客本人名义捐赠寺院建设用。(用餐全凭个人发心发愿,没有其它硬性收费)。 ')}
{this.render2('2. 安全出行的重要性,通过该平台入住寺院的香客每人赠送一份意外伤害险医疗险(保险仅对您在寺院房屋内发生的保险事故承担责任险,在此声明本公司只提供平台服务)。 ')}
{this.render2('3. 当天到寺报到,寺院客堂接待时间为早8:00---晚20 :00,需提供身份证领房间钥匙(如超客堂接待时间过时不候) ')}
{this.render2('4. 男女不限年龄65周岁内,身心健康,无传染性疾病,无精神病史,无吸毒等不良嗜好,不吸烟、喝酒。 ')}
{this.render2('5. 尊敬佛法僧,遵守寺院规章制度,随众、服从寺院管理。')}
</View>
{/* <View style={{
width: width,
alignItems: "flex-end",
paddingRight: 10,
}}>
<TouchableOpacity
onPress={() => {
this.setState({
showTxt: false,
})
}}
>
<Text>点击收起</Text>
</TouchableOpacity>
</View> */}
<View style={{
width: width,
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'center',
marginBottom: 10,
}}>
<Checkbox
style={{
marginLeft: 20,
}}
title=''
size='lg'
checked={this.state.isRead}
onChange={checked => {
this.setState({
isRead: checked,
})
}}
/>
<TouchableOpacity
style={{
width: 200,
height: 25,
borderRadius: 5,
backgroundColor: '#afd9fa',
justifyContent: 'center',
alignItems: 'center',
}}
onPress={() => {
this.setState({
// showTxt: false,
isRead: true,
})
}}
>
<Text style={{
color: '#474746'
}}>我已详细阅读本协议内容</Text>
</TouchableOpacity>
</View>
<View style={{
width: width - 20,
alignItems: "flex-end",
paddingRight: 10,
}}>
<TouchableOpacity
onPress={() => {
this.setState({
showTxt: false,
})
}}
>
<Text>点击收起</Text>
</TouchableOpacity>
</View>
</View>
)
} else {
return (
<View style={{
marginTop: 10,
width: width - 20,
marginLeft: 10,
borderRadius: 10,
backgroundColor: '#fff',
overflow: 'hidden',
shadowColor: '#000',
shadowOffset: { width: 4, height: 4 },
shadowOpacity: 0.8,
shadowRadius: 6,
elevation: 1
}}>
<Image
style={{
width: width - 20,
height: width * 0.165,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./x.png')}
></Image>
<View style={{
width: width - 20,
// height: 150,
overflow: 'hidden',
}}>
{this.render2('1. 为了便于各地前来朝圣的香客更好的安排住处, 但因禅房有限,为防止恶意占用而不到者,入住需缴(诚意金)无论签到与否(诚意金)不予退还,(诚意金)将以香客本人名义捐赠寺院建设用。(用餐全凭个人发心发愿,没有其它硬性收费)。 ')}
</View>
<View style={{
width: width - 20,
alignItems: "flex-end",
paddingRight: 10,
}}>
{/* <TouchableOpacity
onPress={() => {
this.setState({
showTxt: true,
})
}}
>
<Text>更多</Text>
</TouchableOpacity> */}
<TouchableOpacity
style={{
backgroundColor: '#ececec',
borderRadius: 5,
padding: 5,
marginBottom: 5,
width: 50,
justifyContent: 'center',
alignItems: 'center',
}}
onPress={() => {
this.setState({
showTxt: true,
})
}}
>
<Text style={{
fontSize: 13,
fontWeight: 'bold',
color: '#666666',
}}>更多</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
// 选择入住日期
pickTime = () => {
let overlayView = (
<Overlay.PullView
modal={true}
side='bottom'
animated={true}
overlayOpacity={1}
ref={v => this.overlayView = v}
>
<View style={{
width: width,
height: height - 20,
}}>
<View style={{
width: width,
height: 80,
backgroundColor: '#fff',
}}>
<TouchableOpacity
onPress={() => this.overlayView && this.overlayView.close()}
style={{
backgroundColor: '#000',
alignItems: 'center',
justifyContent: 'center',
height: 30,
width: 30,
position: 'relative',
left: 20,
top: 20,
borderRadius: 5,
overflow: 'hidden',
}}
>
<Image
source={require('./w.png')}
resizeMode='center'
/>
</TouchableOpacity>
</View>
<DateList
Fdo1={this.Fdo1}
RuRi={this.state.RuRi}
LiRi={this.state.LiRi}
/>
</View>
</Overlay.PullView >
);
Overlay.show(overlayView);
}
render21 = (txt) => {
let arr = txt.split("").reduce((res, cur, index) => {
res.push(
<Text
key={index}
style={{
fontSize: 17,
// fontWeight: 'bold',
color: '#333',
}}
>{cur}</Text>
)
return res
}, [])
return arr
}
render9 = (title, key) => {
return (
<View style={{
paddingLeft: 20,
paddingRight: 20,
width: '100%',
height: 35,
flexDirection: 'row',
// backgroundColor:'#493339',
alignItems: 'center',
marginBottom: 10,
justifyContent: 'space-between',
}}>
<View style={{
width: 70,
flexDirection: "row",
justifyContent: 'space-between',
alignItems: 'center',
paddingRight: 5,
}}>
{this.render21(title)}
</View>
<TextInput
style={{
// backgroundColor: '#cccccc',
flex: 1,
height: 35,
borderRadius: 5,
fontSize: 18,
padding: 0,
paddingLeft: 5,
// borderWidth: 1,
// borderColor: '#ccc',
backgroundColor: '#ececec',
}}
onChangeText={(text) => {
let self = this.state.self
self[key] = text
this.setState({
self: self
})
console.log('self', self)
}}
>{this.state.self[key]}</TextInput>
</View>
)
}
render10 = (title, index, key) => {
return (
<View style={{
height: 35,
width: '100%',
flexDirection: 'row',
// backgroundColor:'#493339',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 10,
}}>
<View style={{
width: 70,
flexDirection: "row",
justifyContent: 'space-between',
alignItems: 'center',
paddingRight: 5,
}}>
{this.render21(title)}
</View>
<TextInput
style={{
fontSize: 15,
padding: 0,
flex: 1,
paddingLeft: 5,
// borderWidth: 1,
// borderColor: '#ccc',
borderRadius: 5,
height: 35,
backgroundColor: '#ececec',
}}
onChangeText={(text) => this.change(text, index, key)}
>{this.state.data11[index][key]}</TextInput>
</View>
)
}
change = (text, index, key) => {
let newData11 = this.state.data11
newData11[index][key] = text
this.setState({
data11: newData11
})
console.log('text', text, 'index', index, 'key', key)
console.log(this.state.data11[index][key])
console.log(newData11)
}
addMan = () => {
if ((this.state.data11.length + 1) < parseInt(this.state.data2[0].hhumannum)) {
this.setState({
data11: [
...this.state.data11,
{
name: '',
shenfen: '',
sex: true
}
]
})
} else {
// Alert.alert('不能超过房间人数限制!')
Toast.message('不能超过房间人数限制!')
}
}
killMan = () => {
this.setState({
data11: []
})
}
render11 = (num) => {
let aabb = Array.from(new Array(num + 1).keys()).slice(1)
let arr = aabb.reduce((res, cur, index) => {
res.push(
<View
key={index}
style={{
// backgroundColor: '#c0c',
// borderRadius: 10,
// marginLeft: 20,
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 20,
paddingRight: 20,
width: '100%',
// marginTop: 10,
// marginBottom: 10,
}}
>
{this.render17('性别', index, 'sex')}
{this.render10('姓名', index, 'name')}
{this.render10('身份证', index, 'shenfen')}
</View>
)
return res
}, [])
return arr
}
Fdo1 = (RuRi, LiRi) => {
let weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
this.setState({
RuDay: {
'day': moment.unix(RuRi).format('MM月DD日'),
'week': weekArr[moment.unix(RuRi).day()]
},
LiDay: {
'day': moment.unix(LiRi).format('MM月DD日'),
'week': weekArr[moment.unix(LiRi).day()]
},
During: {
RuRi: RuRi,
LiRi: LiRi,
},
RuRi: RuRi,
LiRi: LiRi,
})
this.overlayView && this.overlayView.close()
}
// 性别选择框
render16 = (title, key) => {
return (
<View style={{
width: '100%',
paddingLeft: 20,
paddingRight: 20,
height: 35,
flexDirection: 'row',
// backgroundColor:'#493339',
alignItems: 'center',
marginBottom: 10,
justifyContent: "flex-start",
}}>
<View style={{
width: 70,
flexDirection: "row",
justifyContent: 'space-between',
alignItems: 'center',
paddingRight: 5,
}}>
{this.render21(title)}
</View>
<View style={{
flex: 1,
flexDirection: 'row',
}}>
<Checkbox
style={{
marginLeft: 20,
}}
title='男'
size='lg'
checked={this.state.self[key]}
onChange={checked => {
let self = this.state.self
self[key] = checked
this.setState({
self: self
})
}}
/>
<Checkbox
style={{
marginLeft: 20,
}}
title='女'
size='lg'
checked={!this.state.self[key]}
onChange={checked => {
let self = this.state.self
self[key] = !checked
this.setState({
self: self
})
}}
/>
</View>
</View>
)
}
render17 = (title, index, key) => {
return (
<View style={{
height: 35,
flexDirection: 'row',
// backgroundColor:'#493339',
alignItems: 'center',
justifyContent: 'flex-start',
marginBottom: 10,
}}>
<View style={{
width: 70,
flexDirection: "row",
justifyContent: 'space-between',
alignItems: 'center',
paddingRight: 5,
}}>
{this.render21(title)}
</View>
<View style={{
flex: 1,
flexDirection: 'row',
}}>
<Checkbox
style={{
marginLeft: 20,
}}
title='男'
size='lg'
checked={this.state.data11[index][key]}
onChange={checked => {
let newData11 = this.state.data11
newData11[index][key] = checked
this.setState({
data11: newData11
})
}}
/>
<Checkbox
style={{
marginLeft: 20,
}}
title='女'
size='lg'
checked={!this.state.data11[index][key]}
onChange={checked => {
let newData11 = this.state.data11
newData11[index][key] = !checked
this.setState({
data11: newData11
})
}}
/>
</View>
{/* <TextInput
style={{
width: width * 0.67,
fontSize: 15,
padding: 0,
paddingLeft: 5,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 5,
height: 45,
}}
onChangeText={(text) => this.change(text, index, key)}
>{this.state.data11[index][key]}</TextInput> */}
</View>
)
}
render18 = (data) => {
let arr = data.reduce((res, cur, index) => {
res.push(
<Image
key={index}
style={{
width: '100%',
height: '100%'
}}
resizeMethod='resize'
resizeMode='cover'
source={cur ? { uri: cur } : require('../../../imgs/noimg.png')}
/>
)
return res
}, [])
return arr
}
render19 = () => {
let arr = ['无人间', '单人间', '双人间', '三人间', '四人间', '五人间', '六人间', '七人间', '八人间', '九人间', '十人间']
if (this.state.data2[0] && this.state.data2[0].hhumannum) {
let num = parseInt(this.state.data2[0].hhumannum)
return (
<>
{this.render1(require('./d1.png'), arr[num] ? arr[num] : '超多人间')}
</>
)
} else {
return <></>
}
}
fun2 = () => {
// 表单验证
if (this.state.During.RuRi == '') {
// Alert.alert('入住时段未选择')
Toast.message('入住时段未选择')
return
}
if (this.state.During.LiRi == '') {
// Alert.alert('入住时段未选择完整')
Toast.message('入住时段未选择完整')
return
}
if (this.state.self.name == '') {
// Alert.alert('预订人姓名未填写')
Toast.message('预订人姓名未填写')
return
}
if (!/^[\u4e00-\u9fa5]{2,5}$/.test(this.state.self.name)) {
// Alert.alert('预订人姓名必须是2到5个汉字')
Toast.message('预订人姓名必须是2到5个汉字')
return
}
if (this.state.self.shenfen == '') {
// Alert.alert('预订人身份证未填写')
Toast.message('预订人身份证未填写')
return
}
if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.state.self.shenfen)) {
// Alert.alert('预订人身份证格式不正确')
Toast.message('预订人身份证格式不正确')
return
}
if (this.state.self.phone == '') {
// Alert.alert('预订人手机号未填写')
Toast.message('预订人手机号未填写')
return
}
if (!/^1\d{10}$/.test(this.state.self.phone)) {
// Alert.alert('预订人手机号格式不正确')
Toast.message('预订人手机号格式不正确')
return
}
let isReturn = false
let subTenantList = this.state.data11.reduce((res, cur, index) => {
if (cur.name || cur.shenfen) {
if (cur.name == '') {
// Alert.alert('2、若不需要添加此人,请先清空此人的身份证输入框。')
// Alert.alert('1、检测到有一个入住人的姓名未填写。')
Toast.message('检测到有一个入住人的姓名未填写。若不需要添加此人,请先清空此人的身份证输入框。')
isReturn = true
return
}
if (!/^[\u4e00-\u9fa5]{2,5}$/.test(cur.name)) {
// Alert.alert('姓名格式必须是2到5个汉字')
Toast.message('姓名格式必须是2到5个汉字')
isReturn = true
return
}
if (cur.shenfen == '') {
// Alert.alert('2、若不需要添加此人,请先清空此人的姓名输入框。')
// Alert.alert('1、检测到有一个入住人的身份证未填写。')
Toast.message('检测到有一个入住人的身份证未填写。若不需要添加此人,请先清空此人的姓名输入框。')
isReturn = true
return
}
if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(cur.shenfen)) {
// Alert.alert('其他入住人的身份证格式不正确')
Toast.message('其他入住人的身份证格式不正确')
isReturn = true
return
}
res.push({
identityNo: cur.shenfen,//"421126199601082515",
realName: cur.name,//"王五",
gender: cur.sex ? 1 : 0//1男,0女
})
}
return res
}, [])
if (isReturn) {
return
}
console.log('入日', this.state.During.RuRi)
console.log('入日', moment.unix(this.state.During.RuRi).format('YYYY-MM-DD'))
console.log('离日', this.state.During.LiRi)
console.log('离日', moment.unix(this.state.During.LiRi).format('YYYY-MM-DD'))
console.log('房间id', this.props.navigation.getParam('data').productId)
// return
ModalIndicator.show('数据提交中。。。')
// 下单
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/hostel/reserveRoom`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': this.state.Authorization
}),
body: JSON.stringify({//请求参数
roomId: this.props.navigation.getParam('data').productId,
enterDate: moment.unix(this.state.During.RuRi).format('YYYY-MM-DD'),//"2019-12-24"
leaveDate: moment.unix(this.state.During.LiRi).format('YYYY-MM-DD'),//"2019-12-25"
tenant: {
identityNo: this.state.self.shenfen,//"350102198412142457",
realName: this.state.self.name,//"张三",
telephone: this.state.self.phone,//"15959150551",
gender: this.state.self.sex ? 1 : 0,//1男,0女
},
subTenantList: subTenantList
}),
// body: `templeId=${templeId}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
// this.setState({
// data1: responseJson.data.list
// })
// Alert.alert('下单成功')
console.log('下单成功,返回的数据', responseJson);
ModalIndicator.hide()
this.props.navigation.navigate('QvZhiFu', {
other: this.state.data11,
self: this.state.self,
RuDay: this.state.RuDay,
LiDay: this.state.LiDay,
During: this.state.During,
data: responseJson.data,
data2: this.state.data2
})
console.log('other', this.state.data11)
console.log('self', this.state.self)
console.log('RuDay', this.state.RuDay)
console.log('LiDay', this.state.LiDay)
console.log('During', this.state.During)
console.log('data', responseJson.data)
console.log('data2', this.state.data2)
console.log('寺院', this.state.data2)
// 未完待续。。。。
} else {
ModalIndicator.hide()
if (responseJson.message == '您选择日期的禅房有已经预订过的,不能重复预订') {
// Alert.alert(`超过十分钟未支付的订单将被系统自动取消。`)
// Alert.alert(`请先到【我的 > 我的行程 > 待支付】中取消或继续支付订单。`)
// Alert.alert(`下单失败,${responseJson.message}。`)
Toast.message(`下单失败,${responseJson.message}。`)
// Alert.alert('下单失败,您还有未支付的订单。')
this.props.navigation.navigate('WoDeXingCheng')
} else {
// Alert.alert(responseJson.message)
Toast.message(responseJson.message)
console.log('responseJson', responseJson);
}
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
render20 = () => {
if (this.state.data2[0].hhumannum && (parseInt(this.state.data2[0].hhumannum) > 1)) {
return (
<View style={{
width: width - 20,
}}>
{this.render11(this.state.data11.length)}
</View>
)
} else {
return <></>
}
}
render22 = () => {
if ((this.state.data11.length + 1) < parseInt(this.state.data2[0].hhumannum)) {
return (
<View style={{
width: width,
alignItems: 'flex-end',
paddingRight: 20,
}}>
<TouchableOpacity
style={{
backgroundColor: '#ececec',
borderRadius: 5,
padding: 5,
marginRight: 20,
}}
onPress={() => this.addMan()}
>
<Text style={{
fontSize: 13,
fontWeight: 'bold',
color: '#666666',
}}>更多入住</Text>
</TouchableOpacity>
</View>
)
} else if ((this.state.data11.length > 0) && ((this.state.data11.length + 1) == parseInt(this.state.data2[0].hhumannum))) {
return (
<View style={{
width: width,
alignItems: 'flex-end',
paddingRight: 20,
}}>
<TouchableOpacity
style={{
backgroundColor: '#ececec',
borderRadius: 5,
padding: 5,
marginRight: 20,
}}
onPress={() => this.killMan()}
>
<Text style={{
fontSize: 13,
fontWeight: 'bold',
color: '#666666',
}}>清空收起</Text>
</TouchableOpacity>
</View>
)
} else {
return (
<></>
)
}
}
render23 = () => {
if (this.state.data11.length > 0) {
return (
<View style={{
width: width - 20,
// backgroundColor:'#ff3'
}}>
<Text style={{
width: width - 40,
color: '#1b93f3',
marginLeft: 20,
fontSize: 18,
fontWeight: 'bold',
}}>其他入住人信息,单人可不填</Text>
</View>
)
} else {
return <></>
}
}
render() {
if (this.state.data2) {
return (
<ScrollView
keyboardShouldPersistTaps='handled'
style={{
flex: 1,
backgroundColor: '#f0f0f0',
}}
ref={(view) => { this.myScrollView = view; }}
>
<Carousel style={{
// height: 238,
height: 170,
width: width,
}}>
{this.render18(this.state.data2[0].hcarousel ? this.state.data2[0].hcarousel : [''])}
</Carousel>
<View style={{
width: width - 20,
marginLeft: 10,
borderRadius: 10,
height: 80,
backgroundColor: '#fff',
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
marginTop: 10,
shadowColor: '#000',
shadowOffset: { width: 4, height: 4 },
shadowOpacity: 0.8,
shadowRadius: 6,
elevation: 1
}}>
<Text style={{
color: '#1b93f3',
fontSize: 20,
width: 95,
// textDecorationLine: 'underline',
}}>诚意金{this.state.data2[0].price}/晚</Text>
{this.render19()}
{this.state.data2[0] && this.state.data2[0].hequipment.wifi ? this.render1(require('./d2.png'), 'WiFi') : <></>}
{this.state.data2[0] && this.state.data2[0].hequipment.tv ? this.render1(require('./d3.png'), '电视') : <></>}
{this.state.data2[0] && this.state.data2[0].hequipment.bathroom ? this.render1(require('./d4.png'), '浴室') : <></>}
</View>
{this.render5()}
<TouchableOpacity
onPress={() => this.pickTime()}
style={{
width: width - 20,
backgroundColor: '#fff',
marginTop: 10,
marginBottom: 10,
marginLeft: 10,
borderRadius: 10,
overflow: 'hidden',
shadowColor: '#000',
shadowOffset: { width: 4, height: 4 },
shadowOpacity: 0.8,
shadowRadius: 6,
elevation: 1
}}
>
<ImageBackground
style={{
width: width - 20,
height: width * 0.222,
}}
source={require('./rr.png')}
resizeMethod='resize'
resizeMode='stretch'
>
<TouchableOpacity
onPress={() => this.pickTime()}
style={{
position: 'absolute',
top: width * 0.065,
left: width * 0.035,
width: width * 0.28,
height: width * 0.11,
// backgroundColor: '#cccccc',
borderWidth: 1,
borderColor: '#cccccc',
borderRadius: 5,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
color: '#f44336',
fontSize: 18,
}}>入住时段</Text>
</TouchableOpacity>
<Text style={{
position: 'absolute',
left: width * 0.43,
top: width * 0.035,
fontSize: 11,
}}>{this.state.RuDay.week}</Text>
<Text style={{
position: 'absolute',
left: width * 0.78,
top: width * 0.035,
fontSize: 11,
}}>{this.state.LiDay.week}</Text>
<Text style={{
position: 'absolute',
left: width * 0.34,
top: width * 0.09,
fontSize: 15,
}}>{this.state.RuDay.day}</Text>
<Text style={{
position: 'absolute',
left: width * 0.69,
top: width * 0.09,
fontSize: 15,
}}>{this.state.LiDay.day}</Text>
</ImageBackground>
</TouchableOpacity>
<View style={{
width: width - 20,
borderRadius: 10,
overflow: 'hidden',
backgroundColor: '#fff',
marginLeft: 10,
// paddingRight:10,
paddingBottom: 10,
shadowColor: '#000',
shadowOffset: { width: 4, height: 4 },
shadowOpacity: 0.8,
shadowRadius: 6,
elevation: 1
}}>
<View style={{
marginTop: 10,
width: width - 20,
marginBottom: 10,
}}>
<Text style={{
color: '#1b93f3',
marginLeft: 20,
fontSize: 18,
fontWeight: 'bold',
}}>预订人</Text>
</View>
{this.render16('性别', 'sex')}
{this.render9('姓名', 'name')}
{this.render9('身份证', 'shenfen')}
{this.render9('手机号', 'phone')}
<View style={{
width: width,
height: 10,
}}></View>
{this.render23()}
{this.render20()}
{this.render22()}
</View>
<View style={{
width: width,
height: width * 0.35,
alignItems: 'center',
}}>
<TouchableOpacity
onPress={() => {
if (this.state.isRead) {
this.fun2()
} else {
// Alert.alert('请先阅读入住须知')
Toast.message('请先阅读入住须知')
this.setState({
showTxt: true,
})
this.myScrollView.scrollTo({ x: 0, y: 300, animated: true });
}
}}
style={{
width: width - 40,
height: 50,
backgroundColor: '#708fb5',
borderRadius: 25,
alignItems: 'center',
justifyContent: 'center',
marginTop: 40,
}}
>
<Text style={{
color: '#fff',
fontSize: 25,
}}>去支付</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
} else {
return (
<View style={{
flex: 1,
backgroundColor: '#fff',
}}></View>
)
}
}
}
<file_sep>
import React, { Component, useState, useEffect } from 'react';
import { View, Text, Button, Image, TouchableOpacity, ScrollView, Dimensions, TextInput, ImageBackground, Animated, Easing, FlatList } from 'react-native';
import { Carousel, ModalIndicator } from 'teaset';
import appConfig from '../../../jsonData/appConfig.js'
const { width } = Dimensions.get('window');
const AnimatedView = (props) => {
const [AnimatedValue] = useState(new Animated.Value(-2000)) // 初始值设为0
React.useEffect(() => {
Animated.loop(
Animated.timing(
AnimatedValue,
{
toValue: 0,
duration: 50000,
easing: Easing.linear
}
)
).start()
}, [])
return (
<Animated.View // 使用专门的可动画化的View组件
style={{
...props.style,
right: AnimatedValue
}}
>
{props.children}
</Animated.View>
);
}
export default class SuZhaiList extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6083b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('name', '素斋'),
headerRight: <Image />
}
}
state = {
data6: '',
data4: '',
nextPage: 1,// 下一页的页码
pageSize: 4,//每页条数
isLoading: false,//列表是否正在加载中
isOver: false,// 是否已经到底,没有更多内容了
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
this.fun2()
this.refresh()
}
fun2 = () => {
// 获取素食轮播图数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/tag/carouselList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}),
// body: JSON.stringify({//请求参数
// tagId: 1,
// page: 0,
// size: 100
// }),
body: `tagId=1`,//1素斋,2禅房,3法会,4祈福,5义工
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('图片', responseJson.data.carouselList);
this.setState({
data4: responseJson.data.carouselList
})
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
render3 = (img, index) => {
return (
<View
key={index}
style={{
width: width / 2.5,
height: '100%',
marginRight: 5,
borderRadius: 15,
overflow: 'hidden',
}}
>
<Image
style={{
width: '100%',
height: '100%',
}}
resizeMethod='resize'
resizeMode='cover'
source={img ? { uri: img } : require('../../../imgs/noimg.png')}
/>
</View>
)
}
render4 = (data) => {
let mo = parseInt(24 / data.length)
let arr = []
for (let i = 0; i < mo; i++) {
data.reduce((res, cur, index) => {
res.push(this.render3(cur, '' + i + index))
return res
}, arr)
}
return (
arr
)
}
render5 = (img) => {
return (
<Image
style={{ width: width, height: 160 }}
resizeMethod='resize'
resizeMode='stretch'
source={img}
/>
)
}
renderItem = ({ item }) => {
return (
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('SuZhai', {
name: item.name,
templeId: item.templeId
})
}}
style={{
width: width - 20,
marginLeft: 10,
borderRadius: 5,
overflow: 'hidden',
height: 190,
backgroundColor: '#fff',
marginBottom: 10,
}}
>
<Image
style={{
width: width - 20,
height: 150,
}}
resizeMethod='resize'
resizeMode='cover'
source={item.imageUrl ? { uri: item.imageUrl } : require('../../../imgs/noimg.png')}
/>
<View style={{
flexDirection: 'row',
alignItems: 'center',
height: 40,
}}>
<Text style={{
flexDirection: 'row',
alignItems: 'center',
fontSize: 20,
color: '#333',
marginLeft: 10,
}}>{item.name}</Text>
</View>
</TouchableOpacity>
)
}
_renderFooter = () => {
if (this.state.data6 && (this.state.data6.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderEmptyComponent = () => {
return (
<View style={{
width: '100%',
alignItems: 'center',
height: 100,
justifyContent: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>暂无数据</Text>
</View>
)
}
// 加载下一页的数据
nextData = async () => {
if (this.state.isOver) {
// Alert('已经到最底部,没有更多内容了')
return
}
let nowPage = this.state.nextPage
this.setState({
isLoading: true,
nextPage: nowPage + 1,
})
console.log(`正在加载第${nowPage}页`)
// 获取素食寺院列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/tag/templeList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
tagId: 1,//1素斋,2禅房,3法会,4祈福,5义工
"page": nowPage,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('responseJson.data.list', responseJson.data.list);
if (responseJson.data.list.length == this.pageSize) {
this.setState({
data6: [
...this.state.data6,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data6: [
...this.state.data6,
...responseJson.data.list
],
isLoading: false,
isOver: true,
})
} else {
this.setState({
isLoading: false,
isOver: true,
})
}
})
.catch((error) => {
console.log('error', error);
})
}
// 刷新列表
refresh = async () => {
this.setState({
isLoading: true,
nextPage: 2,
isOver: false,
})
// 获取素食寺院列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/tag/templeList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
tagId: 1,//1素斋,2禅房,3法会,4祈福,5义工
"page": 1,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('responseJson.data.list', responseJson.data.list);
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data6: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data6: responseJson.data.list,
isLoading: false,
isOver: true,
})
} else {
this.setState({
data6: [],
isLoading: false,
isOver: true,
})
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
})
}
render() {
if (this.state.data6 && this.state.data4) {
return (
<ScrollView style={{
flex: 1
}}>
<Image
style={{
width: width,
height: 160,
borderTopLeftRadius: 15,
borderTopRightRadius: 15,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./llb.png')}
/>
<View style={{
height: 1,
backgroundColor: '#6183b1',
}}>
</View>
<AnimatedView style={{
backgroundColor: '#eee',
width: 2500,
position: 'absolute',
height: 140,
top: 161,
zIndex: 1,
flexDirection: 'row',
paddingBottom: 10,
justifyContent: "flex-start",
paddingTop: 10,
}}>
{this.render4(this.state.data4)}
</AnimatedView>
<View style={{
height: 141,
backgroundColor: '#6183b1',
}}></View>
{/* {this.render6(this.state.data6)} */}
<FlatList
style={{
width: width,
flex: 1,
marginTop: 10,
backgroundColor: '#f8f8f8',
}}
data={this.state.data6}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
// ListHeaderComponent ={this._renderHeader }//头部组件
ListFooterComponent={this._renderFooter}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</ScrollView>
)
} else {
return (
<View style={{
backgroundColor: '#fff',
flex: 1,
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, Alert, ScrollView, Dimensions, FlatList } from 'react-native';
import appConfig from '../../jsonData/appConfig.js'
import { Overlay, ModalIndicator, Toast, SegmentedView } from 'teaset'
import moment from 'moment';
const { width } = Dimensions.get('window');
export default class ZiXun extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6183b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('otherParam', '资讯'),
headerRight: <Image />
}
}
state = {
data0: '',
data1: '',
data2: '',
data3: '',
nextPage0: 1,// 下一页的页码
nextPage1: 1,// 下一页的页码
nextPage2: 1,// 下一页的页码
nextPage3: 1,// 下一页的页码
isOver0: false,// 是否已经到底,没有更多内容了
isOver1: false,// 是否已经到底,没有更多内容了
isOver2: false,// 是否已经到底,没有更多内容了
isOver3: false,// 是否已经到底,没有更多内容了
pageSize: 8,//每页条数
isLoading: false,//列表是否正在加载中
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
this.refresh0()
this.refresh1()
this.refresh2()
this.refresh3()
}
renderLine = () => {
return (
<View style={{
width: width,
height: 1,
backgroundColor: '#999999',
}}></View>
)
}
// render1 = (data) => {
// let arr = data.reduce((res, cur, index) => {
// res.push(
// )
// return res
// }, [])
// return arr
// }
// 加载下一页的数据
nextData0 = async () => {
if (this.state.isOver0) {
// Alert('已经到最底部,没有更多内容了')
return
}
let nowPage = this.state.nextPage0
this.setState({
isLoading: true,
nextPage0: nowPage + 1,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 0,
"page": nowPage,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// console.log('responseJson.data.list', responseJson.data.list);
if (responseJson.data.list.length == this.pageSize) {
this.setState({
data0: [
...this.state.data0,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data0: [
...this.state.data0,
...responseJson.data.list
],
isLoading: false,
isOver0: true,
})
} else {
this.setState({
isLoading: false,
isOver0: true,
})
}
})
.catch((error) => {
console.log('error', error);
})
}
// 加载下一页的数据
nextData1 = async () => {
if (this.state.isOver1) {
// Alert('已经到最底部,没有更多内容了')
return
}
let nowPage = this.state.nextPage1
this.setState({
isLoading: true,
nextPage1: nowPage + 1,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 1,
"page": nowPage,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// console.log('responseJson.data.list', responseJson.data.list);
if (responseJson.data.list.length == this.pageSize) {
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data1: [
...this.state.data1,
...responseJson.data.list
],
isLoading: false,
isOver1: true,
})
} else {
this.setState({
isLoading: false,
isOver1: true,
})
}
})
.catch((error) => {
console.log('error', error);
})
}
// 加载下一页的数据
nextData2 = async () => {
if (this.state.isOver2) {
// Alert('已经到最底部,没有更多内容了')
return
}
let nowPage = this.state.nextPage2
this.setState({
isLoading: true,
nextPage2: nowPage + 1,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 2,
"page": nowPage,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// console.log('responseJson.data.list', responseJson.data.list);
if (responseJson.data.list.length == this.pageSize) {
this.setState({
data2: [
...this.state.data2,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data2: [
...this.state.data2,
...responseJson.data.list
],
isLoading: false,
isOver2: true,
})
} else {
this.setState({
isLoading: false,
isOver2: true,
})
}
})
.catch((error) => {
console.log('error', error);
})
}
// 加载下一页的数据
nextData3 = async () => {
if (this.state.isOver3) {
// Alert('已经到最底部,没有更多内容了')
return
}
let nowPage = this.state.nextPage3
this.setState({
isLoading: true,
nextPage3: nowPage + 1,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 3,
"page": nowPage,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// console.log('responseJson.data.list', responseJson.data.list);
if (responseJson.data.list.length == this.pageSize) {
this.setState({
data3: [
...this.state.data3,
...responseJson.data.list
],
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data3: [
...this.state.data3,
...responseJson.data.list
],
isLoading: false,
isOver3: true,
})
} else {
this.setState({
isLoading: false,
isOver3: true,
})
}
})
.catch((error) => {
console.log('error', error);
})
}
// 刷新列表
refresh0 = async () => {
this.setState({
isLoading: true,
nextPage0: 2,
isOver0: false,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 0,
"page": 1,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('responseJson.data.listxxx', responseJson.data.list);
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data0: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data0: responseJson.data.list,
isLoading: false,
isOver0: true,
})
ModalIndicator.hide()
} else {
this.setState({
data0: [],
isLoading: false,
isOver0: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
// 刷新列表
refresh1 = async () => {
this.setState({
isLoading: true,
nextPage1: 2,
isOver1: false,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 1,
"page": 1,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('responseJson.data.listxxx', responseJson.data.list);
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data1: responseJson.data.list,
isLoading: false,
isOver1: true,
})
ModalIndicator.hide()
} else {
this.setState({
data1: [],
isLoading: false,
isOver1: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
// 刷新列表
refresh2 = async () => {
this.setState({
isLoading: true,
nextPage2: 2,
isOver2: false,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 2,
"page": 1,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('responseJson.data.listxxx', responseJson.data.list);
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data2: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data2: responseJson.data.list,
isLoading: false,
isOver2: true,
})
ModalIndicator.hide()
} else {
this.setState({
data2: [],
isLoading: false,
isOver2: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
// 刷新列表
refresh3 = async () => {
this.setState({
isLoading: true,
nextPage3: 2,
isOver3: false,
})
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getPlatNews`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify({//请求参数
"type": 3,
"page": 1,
"size": this.state.pageSize
}),
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('responseJson.data.listxxx', responseJson.data.list);
if (responseJson.data.list.length == this.state.pageSize) {
this.setState({
data3: responseJson.data.list,
isLoading: false,
})
} else if (responseJson.data.list.length > 0) {
this.setState({
data3: responseJson.data.list,
isLoading: false,
isOver3: true,
})
ModalIndicator.hide()
} else {
this.setState({
data3: [],
isLoading: false,
isOver3: true,
})
ModalIndicator.hide()
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
})
}
renderItem = (data) => {
return (
// <View>
// <TouchableOpacity
// onPress={() => {
// this.props.navigation.navigate('ShowWebView', {
// cid: data.item.cid
// })
// }}
// style={{
// width: width,
// paddingRight: 10,
// paddingLeft: 10,
// paddingTop: 10,
// flexDirection: 'row',
// }}
// >
// <Image
// style={{
// width: width * 0.45,
// height: width * 0.35,
// }}
// resizeMethod='resize'
// resizeMode='stretch'
// source={data.item.mainImageUrl ? { uri: data.item.mainImageUrl } : require('../../imgs/noimg.png')}
// />
// <View style={{
// alignItems: 'center',
// flex: 1,
// padding: 10,
// }}>
// <Text
// numberOfLines={1}
// style={{
// fontSize: 25,
// fontWeight: 'bold',
// color: '#333',
// }}
// >{data.item.title}</Text>
// <Text
// numberOfLines={3}
// style={{
// fontSize: 15,
// color: '#666666',
// }}
// >{data.item.slug}</Text>
// </View>
// </TouchableOpacity>
// {this.renderLine()}
// </View>
<View>
<TouchableOpacity
onPress={() => {
// this.props.navigation.navigate('ShowWebView', {
// cid: data.item.cid
// })
this.props.navigation.navigate('SiYuanZiXunDetail', {
cid: data.item.cid,
from: 'zixun'
})
}}
style={{
width: width,
paddingRight: 10,
paddingLeft: 10,
paddingTop: 10,
flexDirection: 'row',
}}
>
<View style={{
alignItems: 'center',
flex: 1,
marginRight: 10,
}}>
<Text
numberOfLines={3}
style={{
fontSize: 14,
fontWeight: 'bold',
color: '#333',
}}
>【{data.item.title}】 {data.item.slug}</Text>
</View>
<View style={{
borderRadius: 3,
overflow: 'hidden',
}}>
<Image
style={{
width: width * 0.32,
height: width * 0.21,
borderRadius: 3,
}}
resizeMethod='resize'
resizeMode='cover'
source={data.item.mainImageUrl ? { uri: data.item.mainImageUrl } : require('../../imgs/noimg.png')}
/>
</View>
</TouchableOpacity>
<View style={{
// backgroundColor: '#292434',
width: width - 20,
marginLeft: 10,
flexDirection: 'row',
// alignItems: 'center',
height: 30,
}}>
<Text style={{
fontSize: 11,
color: '#a7a7a7',
marginRight: 20,
}}>{data.item.origin}</Text>
<Text style={{
fontSize: 11,
color: '#a7a7a7',
marginRight: 20,
}}>{data.item.gtmCreate ? moment(data.item.gtmCreate).format('YYYY-MM-DD') : ''}</Text>
</View>
</View>
)
}
_renderFooter0 = () => {
if (this.state.data0 && (this.state.data0.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver0) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderFooter1 = () => {
if (this.state.data1 && (this.state.data1.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver1) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderFooter2 = () => {
if (this.state.data2 && (this.state.data2.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver2) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderFooter3 = () => {
if (this.state.data3 && (this.state.data3.length > 0)) {
if (this.state.isLoading) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>加载中。。。</Text>
</View>
)
} else if (this.state.isOver3) {
return (
<View style={{
width: '100%',
height: 50,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>已全部加载完成</Text>
</View>
)
} else {
return <></>
}
} else {
return <></>
}
}
_renderEmptyComponent = () => {
return (
<View style={{
width: '100%',
alignItems: 'center',
height: 100,
justifyContent: 'center',
}}>
<Text style={{
fontSize: 15,
color: '#666',
}}>暂无数据</Text>
</View>
)
}
render() {
if (this.state.data0 || this.state.data1 || this.state.data2 || this.state.data3) {
return (
<View style={{
flex: 1,
backgroundColor: '#fff',
// backgroundColor: '#eee',
}}>
{/* <FlatList
data={this.state.data1}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
ListHeaderComponent={this.renderLine}//头部组件
ListFooterComponent={this._renderFooter}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/> */}
<SegmentedView
style={{
flex: 1
}}
type='carousel'
justifyItem='fixed'
activeIndex={this.state.activeIndex}
onChange={(index) => {
this.setState({
activeIndex: index
})
// console.log('当前', `${index}`)
}}
>
<SegmentedView.Sheet
title='头条'
activeTitleStyle={{
color: '#333',
fontSize: 20,
}}
titleStyle={{
color: '#333',
fontSize: 20,
}}
>
<FlatList
data={this.state.data0}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData0()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh0()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
ListHeaderComponent={this.renderLine}//头部组件
ListFooterComponent={this._renderFooter0}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
<SegmentedView.Sheet
title='佛协'
activeTitleStyle={{
color: '#333',
fontSize: 20,
}}
titleStyle={{
color: '#333',
fontSize: 20,
}}
>
<FlatList
data={this.state.data2}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData2()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh2()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
ListHeaderComponent={this.renderLine}//头部组件
ListFooterComponent={this._renderFooter2}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
<SegmentedView.Sheet
title='社会'
activeTitleStyle={{
color: '#333',
fontSize: 20,
}}
titleStyle={{
color: '#333',
fontSize: 20,
}}
>
<FlatList
data={this.state.data3}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData3()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh3()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
ListHeaderComponent={this.renderLine}//头部组件
ListFooterComponent={this._renderFooter3}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
<SegmentedView.Sheet
title='法讯'
activeTitleStyle={{
color: '#333',
fontSize: 20,
}}
titleStyle={{
color: '#333',
fontSize: 20,
}}
>
<FlatList
data={this.state.data1}//数据源
renderItem={(data) => this.renderItem(data)}//列表呈现方式
onEndReached={() => this.nextData1()}//下拉加载触发的函数
onEndReachedThreshold={0.5}//决定当距离内容最底部还有多远时触发onEndReached回调
onRefresh={() => this.refresh1()}//上拉刷新触发的函数
refreshing={this.state.isLoading}//在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号
// ItemSeparatorComponent ={this._renderItemSeparatorComponent }//行与行之间的分隔线
ListHeaderComponent={this.renderLine}//头部组件
ListFooterComponent={this._renderFooter1}//尾部组件
ListEmptyComponent={this._renderEmptyComponent}//列表为空时呈现的内容
keyExtractor={(item, index) => index.toString()}//用于为给定的item生成一个不重复的key。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标index。
/>
</SegmentedView.Sheet>
</SegmentedView>
</View>
);
} else {
return (
<View style={{
backgroundColor: '#fff',
flex: 1,
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, Platform, ScrollView, Dimensions, Alert, ImageBackground, Linking } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import appConfig from '../../../jsonData/appConfig.js'
import { Overlay, ModalIndicator } from 'teaset'
import moment from 'moment';
const { width, height } = Dimensions.get('window');
export default class SheZhi extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6183b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('otherParam', '设置'),
}
}
state = {
userInfo: {
usersign: '',
nickName: '未登录',
username: ''
},
showBtn: false,//与否显示【退出登录】按钮
}
UNSAFE_componentWillMount() {
this.JianCeDengLu(() => {
this.setState({
showBtn: true
})
}, true)
}
// 检测是否登录
JianCeDengLu = async (callBack, noTiShi) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户信息
let valueObj = JSON.parse(value)
if (valueObj.outTime > moment().unix()) {
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/me`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: '',
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
this.setState({
userInfo: responseJson.data,
Authorization: `${valueObj.token_type} ${valueObj.access_token}`
})
ModalIndicator.hide()
if (callBack) {
callBack()
}
console.log('返回的数据', responseJson.data.nickName);
} else {
console.log('responseJson', responseJson);
ModalIndicator.hide()
if (!noTiShi) {
this.TiShiDengLu()
}
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
if (!noTiShi) {
this.TiShiDengLu()
}
}
} else {
ModalIndicator.hide()
if (!noTiShi) {
this.TiShiDengLu()
}
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 提示用户登录
TiShiDengLu = () => {
// 提示用户先登录
let TiShiDengLuOverlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.TiShiDengLuOverlayView = v}
>
<ImageBackground
style={{
backgroundColor: '#fff',
padding: 3,
// borderRadius: 10,
height: 165,
width: 285,
}}
resizeMethod='resize'
resizeMode='cover'
source={require('../../../imgs/dl.png')}
>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 22,
}}>[请先登录]</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
// this.props.navigation.navigate('ShouYe')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>返回</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.props.navigation.navigate('DengLu')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>确定</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Overlay.View>
);
Overlay.show(TiShiDengLuOverlayView);
}
fun1 = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 退出登录
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
ModalIndicator.show('加载中。。。')
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/logout`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: ``,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.message == '登录信息已失效,请重新登录') {
console.log('退出成功', responseJson);
} else {
console.log('没有获取到用户数据', responseJson);
}
ModalIndicator.hide()
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
console.log('error', error)
}
}
render2 = () => {
if (this.state.showBtn) {
return (
<View style={{
width: width,
justifyContent: 'center',
alignItems: 'center',
}}>
<TouchableOpacity
onPress={() => {
this.fun1()
// 清除本地用户数据
this.props.navigation.getParam('clearAll')()
this.props.navigation.replace('DengLu', {
})
}}
style={{
backgroundColor: '#B71C1C',
width: 140,
marginTop: 34,
height: 40,
borderRadius: 5,
justifyContent: "center",
alignItems: "center",
}}
>
<Text style={{
color: '#FFFFFF',
fontWeight: 'bold',
fontSize: 20,
}}>退出登录</Text>
</TouchableOpacity>
</View>
)
} else {
return <></>
}
}
render() {
return (
<View style={{
flex: 1,
backgroundColor: '#FAFAFA',
}}>
<TouchableOpacity
onPress={() => {
this.JianCeDengLu(() => {
this.props.navigation.navigate('MiMaChongZhi', {
itemId: 86,
name: '觱沸所',
})
})
}}
style={{
height: 64,
borderBottomWidth: 1,
borderBottomColor: '#6183b1',
alignItems: 'center',
flexDirection: 'row',
}}
>
<Image
resizeMode='cover'
style={{
width: 20,
height: 20,
marginLeft: 17,
marginRight: 10,
}} source={require('./mm.png')}
/>
<Text style={{
fontSize: 17,
color: '#6183b1',
}}>密码重置</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.JianCeDengLu(() => {
this.props.navigation.navigate('SheZhiFangMing', {
itemId: 86,
name: '觱沸所',
})
})
}}
style={{
height: 64,
borderBottomWidth: 1,
borderBottomColor: '#6183b1',
alignItems: 'center',
flexDirection: 'row',
}}
>
<Image
resizeMode='cover'
style={{
width: 20,
height: 20,
marginLeft: 17,
marginRight: 10,
}} source={require('./bi.png')}
/>
<Text style={{
fontSize: 17,
color: '#6183b1',
}}>设置芳名</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('SiYuanRuZhuBaoMing', {
itemId: 86,
name: '觱沸所',
})}
style={{
height: 64,
borderBottomWidth: 1,
borderBottomColor: '#6183b1',
alignItems: 'center',
flexDirection: 'row',
}}
>
<Image
resizeMode='cover'
style={{
width: 20,
height: 20,
marginLeft: 17,
marginRight: 10,
}} source={require('./rz.png')}
/>
<Text style={{
fontSize: 17,
color: '#6183b1',
}}>寺院免费入驻</Text>
</TouchableOpacity>
{this.render2()}
</View>
);
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, ScrollView, Dimensions, Linking, Alert } from 'react-native';
import { Toast } from 'teaset'
export default class KeFu extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6183b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('otherParam', '客服'),
}
}
state = {
phoneNumber: '19890539653'
}
// 调用拨号键盘
_callPhone(phoneNumber) {
if (phoneNumber != '') {
return Linking.openURL(`tel:${phoneNumber}`)
} else {
// Alert.alert('没有电话号')
Toast.fail('没有电话号')
}
}
render() {
return (
<View style={{
flex: 1,
backgroundColor: '#FAFAFA',
}}>
<TouchableOpacity
onPress={() => this._callPhone(this.state.phoneNumber)}
style={{
flexDirection: "row",
alignItems: 'center',
borderBottomColor: '#6183b1',
borderBottomWidth: 1,
height: 64,
}}
>
<Image
resizeMode='center'
style={{
width: 27,
height: 27,
marginLeft: 18,
marginRight: 10,
}}
source={require('./ph.png')}
></Image>
<Text style={{
color: '#6183b1',
fontSize: 20,
}}>联系电话:{this.state.phoneNumber}</Text>
</TouchableOpacity>
</View>
);
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, ScrollView, Dimensions, Linking, TextInput, TouchableWithoutFeedback, ImageBackground, Alert } from 'react-native';
import { Overlay, ModalIndicator, Toast } from 'teaset';
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
const { width, height } = Dimensions.get('window');
export default class YiGong extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: `${navigation.getParam('name', '')}`,
}
}
state = {
name: '',
phone: '',
iden: '',
sex: '',
Authorization: '',//用户登录权限暂存
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
this.JianCeDengLu()
}
// 检测是否登录
JianCeDengLu = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户信息
let valueObj = JSON.parse(value)
if (valueObj.outTime > moment().unix()) {
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/me`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
// body: JSON.stringify({//请求参数
// "templeId": templeId,
// "tagId": tagId,
// "page": 0,
// "size": 10
// }),
body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
this.setState({
Authorization: `${valueObj.token_type} ${valueObj.access_token}`
})
ModalIndicator.hide()
console.log('返回的数据', responseJson.data.nickName);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
this.TiShiDengLu()
}
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
this.TiShiDengLu()
}
} else {
ModalIndicator.hide()
this.TiShiDengLu()
}
console.log('value', value)
} catch (error) {
// read error
ModalIndicator.hide()
console.log('error', error)
}
console.log('Done.')
}
// 提示用户登录
TiShiDengLu = () => {
// 提示用户先登录
let overlayView3 = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.overlayView3 = v}
>
<ImageBackground
style={{
backgroundColor: '#fff',
padding: 3,
// borderRadius: 10,
height: 165,
width: 285,
}}
resizeMethod='resize'
resizeMode='cover'
source={require('../../../imgs/dl.png')}
>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 22,
}}>[请先登录]</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.overlayView3 && this.overlayView3.close()
this.overlayView1 && this.overlayView1.close()
this.overlayView2 && this.overlayView2.close()
this.props.navigation.goBack()
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding:5,
}}>返回</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.overlayView3 && this.overlayView3.close()
this.overlayView1 && this.overlayView1.close()
this.overlayView2 && this.overlayView2.close()
this.props.navigation.replace('DengLu')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding:5,
}}>确定</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Overlay.View>
);
Overlay.show(overlayView3);
}
render1 = (title, key) => {
return (
<View style={{
flexDirection: 'row',
alignItems: "center",
paddingTop: 5,
}}>
<Text style={{
fontSize: 14,
textAlign: 'right',
color: '#656565',
paddingRight: 5,
}}>{title}</Text>
<TextInput
onChangeText={(text) => {
this.setState({
[`${key}`]: text
})
}}
style={{
width: width * 0.45,
height: width * 0.10,
backgroundColor: '#cccccc',
borderRadius: 5,
padding: 0,
paddingLeft: 5,
color: '#fff',
}}
>{this.state[`${key}`]}</TextInput>
</View>
)
}
handle = (txt) => {
if (txt == '男') {
this.setState({
sex: true
})
} else if (txt == '女') {
this.setState({
sex: false
})
}
}
render2 = (txt, color) => {
return (
<TouchableOpacity
onPress={() => {
this.handle(txt)
}}
style={{
width: 35,
height: 35,
borderRadius: 3,
backgroundColor: '#ccc',
justifyContent: "center",
alignItems: 'center',
marginLeft: 5,
marginRight: 10
}}
>
<Text style={{
fontSize: 16,
color: color,
}}>{txt}</Text>
</TouchableOpacity>
)
}
render3 = () => {
if (this.state.sex === '') {
return (
<View style={{
flexDirection: 'row',
width: width * 0.45,
justifyContent: 'space-evenly',
}}>
{this.render2('男', '#666666')}
{this.render2('女', '#666666')}
</View>
)
} else if (this.state.sex) {
return (
<View style={{
flexDirection: 'row',
width: width * 0.45,
justifyContent: 'space-evenly',
}}>
{this.render2('男', '#f44336')}
{this.render2('女', '#666666')}
</View>
)
} else {
return (
<View style={{
flexDirection: 'row',
width: width * 0.45,
justifyContent: 'space-evenly',
}}>
{this.render2('男', '#666666')}
{this.render2('女', '#f44336')}
</View>
)
}
}
fun1 = async () => {
//字段验证
if (this.state.name == '') {
// Alert.alert('请填写姓名')
Toast.fail('请填写姓名')
return
}
if (this.state.phone == '') {
// Alert.alert('请填写手机号')
Toast.fail('请填写手机号')
return
}
if (!/^0?(13|14|15|17|18|19)[0-9]{9}$/.test(this.state.phone)) {
// Alert.alert('手机号格式错误')
Toast.fail('手机号格式错误')
return
}
if (this.state.iden == '') {
// Alert.alert('请填写身份证号')
Toast.fail('请填写身份证号')
return
}
if (!/^\d{17}[\d|x]|\d{15}$/.test(this.state.iden)) {
// Alert.alert('身份证号格式错误')
Toast.fail('身份证号格式错误')
return
}
if (this.state.sex == '') {
// Alert.alert('请选择性别')
Toast.fail('请选择性别')
return
}
const value = await AsyncStorage.getItem('userData')
// 获取用户信息
ModalIndicator.show('加载中。。。')
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/reserve/reserveVolunteer`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': this.state.Authorization
}),
body: JSON.stringify({//请求参数
"name": this.state.name,
"gender": this.state.sex == '男' ? 1 : 0,
"identityNo": this.state.iden,
"telPhone": this.state.phone,
"templeId": this.props.navigation.getParam('templeId')
}),
// body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
ModalIndicator.hide()
// Alert.alert('申请已提交,正在审核中')
Toast.message('申请已提交,正在审核中')
console.log('申请已提交,正在审核中', responseJson);
} else {
ModalIndicator.hide()
// Alert.alert(responseJson.message)
Toast.message(responseJson.message)
console.log('提交失败,请检查网络', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
render() {
return (
<ScrollView
keyboardShouldPersistTaps='handled'
style={{
flex: 1,
backgroundColor: '#FAFAFA',
}}
>
<ImageBackground
style={{
width: width,
// height: width * 1.2,
flexDirection: 'column',
alignItems: 'center',
paddingTop: width * 0.25,
// flex:1,
paddingBottom: 60,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./bbbb.png')}
>
{this.render1('姓 名', 'name')}
{this.render1('电 话', 'phone')}
{this.render1('身份证', 'iden')}
<View style={{
flexDirection: 'row',
alignItems: "center",
paddingTop: 5,
justifyContent: 'space-between',
}}>
<Text style={{
fontSize: 14,
textAlign: 'right',
color: '#656565',
paddingRight: 5,
}}>性 别</Text>
{this.render3()}
</View>
<View style={{
height: 35,
flexDirection: 'row',
alignItems: "center",
}}>
</View>
<TouchableOpacity
onPress={() => {
this.fun1()
}}
style={{
width: width * 0.40,
height: width * 0.1,
backgroundColor: '#b61d1c',
borderRadius: 3,
justifyContent: 'center',
alignItems: 'center',
marginBottom: 5,
marginTop: 5,
}}
>
<Text style={{
color: '#fff',
fontSize: 23,
}}>提交申请</Text>
</TouchableOpacity>
</ImageBackground>
<View style={{
width: width,
height: 60,
backgroundColor: '#fdfdfd',
}}></View>
<ImageBackground
style={{
width: width,
height: width * 0.6882,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./xx.png')}
></ImageBackground>
</ScrollView>
);
}
}
<file_sep>import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, ScrollView, Dimensions, Linking, TextInput, TouchableWithoutFeedback, Alert, StyleSheet } from 'react-native';
import { Wheel } from 'teaset';
import areaData from '../../jsonData/area.js'
const { width } = Dimensions.get('window');
export default class AreaSelect extends Component {
state = {
Sheng: [],
Shi: [],
Qu: [],
ShengIndex: 0,
ShiIndex: 0,
QuIndex: 0,
}
componentWillMount() {
this.setState({
Sheng: this.Sheng(),
Shi: this.Shi(0),
Qu: this.Qu(0, 0),
})
}
Sheng = () => {
let arr = []
areaData.reduce((res, cur, index) => {
res.push(cur.name)
return res
}, arr)
return arr
}
Shi = (key) => {
let arr = []
areaData[key].children.reduce((res, cur, index) => {
res.push(cur.name)
return res
}, arr)
return arr
}
Qu = (key1, key2) => {
let arr = []
if (areaData[key1].children[key2].children) {
areaData[key1].children[key2].children.reduce((res, cur, index) => {
res.push(cur.name)
return res
}, arr)
}
return arr
}
onShengChange = (index) => {
this.setState({
Shi: this.Shi(index),
Qu: this.Qu(index, 0),
ShengIndex: index,
})
}
onShiChange = (index) => {
this.setState({
Qu: this.Qu(this.state.ShengIndex, index),
ShiIndex: index,
})
}
onQuChange = (index) => {
this.setState({
QuIndex: index,
})
}
render() {
return (
<View
side='bottom'
modal={false}
containerStyle={{
backgroundColor: '#fff',
height: 197,
}}
>
<View style={{
height: 35,
// backgroundColor: '#548579',
flexDirection: 'row',
justifyContent: "space-between",
alignItems: "center",
}}>
<TouchableOpacity
onPress={() => {
this.props.closeOverlayAreaSelect()
}}
style={{
// backgroundColor: '#454992',
height: 30,
}}
>
<Text style={{
color: '#B71C1C',
marginLeft: 30,
marginRight: 30,
lineHeight: 30,
}}>取消</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.props.closeOverlayAreaSelect()
this.props.changeArea(this.state.Sheng[this.state.ShengIndex],this.state.Shi[this.state.ShiIndex],this.state.Qu[this.state.QuIndex])
// this.props.changeArea('省佛','dsdfsd','sdfsdf')
}}
style={{
// backgroundColor: '#454992',
height: 30,
}}
>
<Text style={{
color: '#B71C1C',
marginLeft: 30,
marginRight: 30,
lineHeight: 30,
}}>确定</Text>
</TouchableOpacity>
</View>
<View style={{
height: 162,
width: '100%',
// backgroundColor: '#840407',
flexDirection: "row",
}}>
<Wheel
style={styles.WheelStyle}
itemStyle={styles.WheelItemStyle}
onChange={(index) => this.onShengChange(index)}
index={this.state.ShengIndex}
items={this.state.Sheng}
/>
<Wheel
style={styles.WheelStyle}
itemStyle={styles.WheelItemStyle}
onChange={(index) => this.onShiChange(index)}
index={this.state.ShiIndex}
items={this.state.Shi}
/>
<Wheel
style={styles.WheelStyle}
itemStyle={styles.WheelItemStyle}
onChange={(index) => this.onQuChange(index)}
index={this.state.QuIndex}
items={this.state.Qu}
/>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
WheelItemStyle: {
textAlign: 'center',
color: '#000000',
fontWeight: 'bold',
},
WheelStyle: {
height: 162,
width: width / 3 - 12,
marginLeft: 6,
marginRight: 6,
},
});<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, TextInput, ScrollView, Dimensions, ImageBackground, Alert, Modal, TouchableHighlight } from 'react-native';
import { Overlay, ModalIndicator, Toast } from 'teaset'
import AsyncStorage from '@react-native-community/async-storage';
import appConfig from '../../jsonData/appConfig.js';
import moment from 'moment';
import RNBugly from 'rn-bugly';
import {
isFirstTime,
isRolledBack,
packageVersion,
currentVersion,
checkUpdate,
downloadUpdate,
switchVersion,
switchVersionLater,
markSuccess,
} from 'react-native-update';
import _updateConfig from '../../../update.json';
const { appKey } = _updateConfig[Platform.OS];
const { width } = Dimensions.get('window');
export default class WoDe extends Component {
static navigationOptions = {
header: null,
}
state = {
userInfo: {
usersign: '',
nickName: '未登录',
username: '',
integration: '',
},
avatarSource: '',//选择的图片的本地路径
newName: '',//要改成的新昵称
}
UNSAFE_componentWillMount() {
// ModalIndicator.show('加载中。。。')
const didBlurSubscription = this.props.navigation.addListener('didFocus', (payload) => {
this.JianCeDengLu(() => { }, true)
});
}
componentWillUnmount() {
this.didBlurSubscription && this.didBlurSubscription.remove();
}
doUpdate = async (info) => {
try {
const hash = await downloadUpdate(info);
ModalIndicator.hide()
Alert.alert('提示', '下载完毕,是否重启应用?', [
{ text: '是', onPress: () => { switchVersion(hash); } },
{ text: '否', },
{ text: '下次启动时', onPress: () => { switchVersionLater(hash); } },
]);
} catch (err) {
ModalIndicator.hide()
// Alert.alert('提示', '更新失败.');
Toast.fail('更新失败')
}
};
// bugly全量包方式更新
checkUpdate2 = async () => {
RNBugly.checkUpgrade({ isManual: true, isSilence: false });
}
// rn中文网的热更新功能,暂时用不到,先留着
checkUpdate = async () => {
if (__DEV__) {
// 开发模式不支持热更新,跳过检查
ModalIndicator.hide()
return;
}
// let info;
// try {
// info = await checkUpdate(appKey);
// ModalIndicator.hide()
// } catch (err) {
// ModalIndicator.hide()
// console.warn(err);
// Alert.alert('出错了啦')
// return;
// }
// if (info.expired) {
// Alert.alert('提示', '您的应用版本已更新,请前往应用商店下载新的版本', [
// { text: '确定', onPress: () => { info.downloadUrl && Linking.openURL(info.downloadUrl) } },
// ]);
// } else if (info.upToDate) {
// Alert.alert('提示', '您的应用版本已是最新.');
// } else {
// Alert.alert('提示', '检查到新的版本' + info.name + ',是否下载?\n' + info.description, [
// {
// text: '是', onPress: () => {
// ModalIndicator.show('下载更新数据...')
// this.doUpdate(info)
// }
// },
// { text: '否', },
// ]);
// }
};
// 检测是否登录
JianCeDengLu = async (callBack, noTiShi) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户信息
let valueObj = JSON.parse(value)
if (valueObj.outTime > moment().unix()) {
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/me`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: '',
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
this.setState({
userInfo: responseJson.data,
Authorization: `${valueObj.token_type} ${valueObj.access_token}`
})
ModalIndicator.hide()
if (callBack) {
callBack()
}
console.log('返回的数据xxddd', responseJson.data);
} else {
console.log('responseJson', responseJson);
ModalIndicator.hide()
if (!noTiShi) {
this.TiShiDengLu()
}
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
if (!noTiShi) {
this.TiShiDengLu()
}
}
} else {
ModalIndicator.hide()
if (!noTiShi) {
this.TiShiDengLu()
}
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
// read error
console.log('error', error)
}
console.log('Done.')
}
// 提示用户登录
TiShiDengLu = () => {
// 提示用户先登录
let TiShiDengLuOverlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.TiShiDengLuOverlayView = v}
>
<ImageBackground
style={{
backgroundColor: '#fff',
padding: 3,
// borderRadius: 10,
height: 165,
width: 285,
}}
resizeMethod='resize'
resizeMode='cover'
source={require('../../imgs/dl.png')}
>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 22,
}}>[请先登录]</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
// this.props.navigation.navigate('ShouYe')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>返回</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.props.navigation.navigate('DengLu')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>确定</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Overlay.View>
);
Overlay.show(TiShiDengLuOverlayView);
}
clearAll = async () => {
try {
await AsyncStorage.clear()
// this.getValue1()
this.setState({
userInfo: {
usersign: '',
nickName: '未登录',
username: ''
},
})
} catch (e) {
// clear error
}
console.log('Done.')
}
render1 = (name, img, goto) => {
return (
<TouchableOpacity
onPress={() => {
this.JianCeDengLu(() => {
this.props.navigation.navigate(goto, {
key1: ''
})
})
}}
style={{
flexDirection: "column",
alignItems: "center",
}}
>
<Image
resizeMethod='resize'
resizeMode='stretch'
style={{
height: 30,
width: 30,
}}
source={img}
/>
<Text style={{
// color: '#549405',
}}>{name}</Text>
</TouchableOpacity>
)
}
render2 = () => {
if (this.state.userInfo.integration) {
return (
<Text style={{
fontSize: 10,
color: '#fff',
textShadowOffset: { width: 1, height: 1 },
textShadowRadius: 1,
textShadowColor: '#9a4171',
}}>积分:{this.state.userInfo.integration}</Text>
)
} else {
return <></>
}
}
render() {
// if (this.state.userInfo) {
return (
<ScrollView style={{
flex: 1,
backgroundColor: '#FAFAFA',
}}>
<ImageBackground
resizeMethod='resize'
resizeMode='stretch'
style={{
width: width,
height: 240,
}}
source={require('./bg2.jpg')}
>
<Text style={{
fontSize: 20,
position: 'absolute',
color: '#fff',
right: 0,
fontWeight: 'bold',
marginRight: 10,
marginTop: 15,
}}>个人中心</Text>
<View style={{
position: 'absolute',
top: 50,
flexDirection: "row",
marginLeft: 20,
}}>
<TouchableOpacity
onPress={() => {
this.JianCeDengLu(() => {
this.props.navigation.navigate('GeRenZiLiao', {
userInfo: this.state.userInfo
})
})
}}
style={{
height: 110,
width: 110,
borderRadius: 55,
borderWidth: 5,
borderColor: '#fffbf8',
overflow: 'hidden',
}}
>
<Image
source={this.state.userInfo.usersign ? { uri: this.state.userInfo.usersign } : require('../../imgs/ntx.png')}
style={{
height: 100,
width: 100,
borderRadius: 50,
}}
resizeMethod='resize'
resizeMode='cover'
/>
</TouchableOpacity>
<View style={{
flexDirection: "column",
alignItems: "center",
marginLeft: 10,
}}>
<TouchableOpacity
onPress={() => {
this.JianCeDengLu(() => {
this.props.navigation.navigate('GeRenZiLiao', {
userInfo: this.state.userInfo
})
})
}}
>
<Text style={{
fontSize: 20,
color: '#fff',
marginTop: 35,
textShadowOffset: { width: 1, height: 1 },
textShadowRadius: 1,
textShadowColor: '#9a4171',
}}>{this.state.userInfo.nickName}</Text>
</TouchableOpacity>
<Text style={{
fontSize: 15,
color: '#fff',
textShadowOffset: { width: 1, height: 1 },
textShadowRadius: 1,
textShadowColor: '#9a4171',
}}>{this.state.userInfo.username}</Text>
{this.render2()}
</View>
</View>
</ImageBackground>
<View style={{
backgroundColor: '#fff',
width: width - 50,
marginLeft: 25,
height: 100,
borderWidth: 2,
justifyContent: 'space-around',
flexDirection: "row",
position: 'absolute',
top: 200,
zIndex: 1,
alignItems: "center",
borderRadius: 30,
}}>
{this.render1('我的善缘', require('./sy.png'), 'WoDeGongDe')}
{this.render1('我的行程', require('./xc.png'), 'WoDeXingCheng')}
{this.render1('我的收藏', require('./sc.png'), 'WoDeShouCang')}
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('KeFu', {
itemId: 86,
name: '觱沸所',
})}
style={{
height: 60,
backgroundColor: '#fff',
borderTopWidth: 1,
flexDirection: "row",
alignItems: "center",
marginTop: 80,
paddingLeft: 10,
borderBottomColor: '#6183b1',
borderBottomWidth: 1,
}}
>
<Text style={{
fontSize: 15,
color: '#6183b1',
}}>客服</Text>
<Image
style={{
height: 20,
width: 20,
position: 'absolute',
right: 10,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./kf2.png')}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('SheZhi', {
key1: '',
clearAll: this.clearAll
})
}}
style={{
height: 60,
flexDirection: "row",
alignItems: "center",
paddingLeft: 10,
backgroundColor: '#fff',
borderBottomColor: '#6183b1',
borderBottomWidth: 1,
}}
>
<Text style={{
fontSize: 15,
color: '#6183b1',
}}>设置</Text>
<Image
style={{
height: 15,
width: 15,
position: 'absolute',
right: 10,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./jt.png')}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('FuWuXieYi')
}}
style={{
height: 60,
flexDirection: "row",
alignItems: "center",
paddingLeft: 10,
backgroundColor: '#fff',
borderBottomColor: '#6183b1',
borderBottomWidth: 1,
}}
>
<Text style={{
fontSize: 15,
color: '#6183b1',
}}>服务协议</Text>
<Image
style={{
height: 15,
width: 15,
position: 'absolute',
right: 10,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./jt.png')}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
// ModalIndicator.show('加载中。。。')
// this.checkUpdate()
this.checkUpdate2()
}}
style={{
height: 60,
flexDirection: "row",
alignItems: "center",
paddingLeft: 10,
backgroundColor: '#fff',
borderBottomColor: '#6183b1',
borderBottomWidth: 1,
}}
>
<Text style={{
fontSize: 15,
color: '#6183b1',
}}>版本更新</Text>
<Image
style={{
height: 15,
width: 15,
position: 'absolute',
right: 10,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./jt.png')}
/>
{/* <Text style={{
position: 'absolute',
right: 10,
fontSize: 17,
color: '#666',
}}>{packageVersion}.1</Text> */}
</TouchableOpacity>
</ScrollView>
)
// } else {
// return (
// <View style={{
// alignItems: 'center',
// justifyContent: 'center',
// }}>
// <Text></Text>
// </View>
// )
// }
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, TextInput, Image, TouchableOpacity, ScrollView, Dimensions, Alert } from 'react-native';
import { Overlay, ModalIndicator,Toast } from 'teaset'
import AsyncStorage from '@react-native-community/async-storage';
import appConfig from '../../../jsonData/appConfig.js'
export default class MiMaChongZhi extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6183b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('otherParam', '密码重置'),
}
}
state = {
oldPwd: "",//旧密码
newPwd: ""//新密码
}
fun1 = async () => {
if (this.state.oldPwd == '') {
// Alert.alert('旧密码未填写')
Toast.fail('旧密码未填写')
return
}
if (this.state.newPwd == '') {
// Alert.alert('新密码未填写')
Toast.fail('新密码未填写')
return
}
// 修改密码
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 重置密码
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
ModalIndicator.show('请稍等。。。')
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/modifyPwd`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
oldPwd: this.state.oldPwd,
newPwd: this.state.newPwd
}),
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
ModalIndicator.hide()
this.clearAll()
// 提示用户密码修改成功
let overlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.overlayView = v}
>
<View style={{
backgroundColor: '#fff',
padding: 20,
borderRadius: 10,
height: 200,
width: 250,
}}>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 20,
}}>密码修改成功,请重新登录</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
onPress={() => {
this.overlayView && this.overlayView.close()
this.props.navigation.navigate('DengLu')
}}
style={{
padding: 10,
backgroundColor: '#485784',
borderRadius: 10,
}}
>
<Text style={{
fontSize: 20,
color: '#fff',
}}>确定</Text>
</TouchableOpacity>
</View>
</View>
</Overlay.View>
);
Overlay.show(overlayView);
console.log('修改成功,请妥善保管', responseJson);
} else {
ModalIndicator.hide()
console.log('失败', responseJson);
// 提示用户密码修改成功
let overlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.overlayView = v}
>
<View style={{
backgroundColor: '#fff',
padding: 20,
borderRadius: 10,
height: 200,
width: 250,
}}>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 20,
}}>密码修改失败,请检查输入</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
onPress={() => {
this.overlayView && this.overlayView.close()
}}
style={{
padding: 10,
backgroundColor: '#485784',
borderRadius: 10,
}}
>
<Text style={{
fontSize: 20,
color: '#fff',
}}>确定</Text>
</TouchableOpacity>
</View>
</View>
</Overlay.View>
);
Overlay.show(overlayView);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
ModalIndicator.hide()
console.log('error', error)
}
}
clearAll = async () => {
try {
await AsyncStorage.clear()
console.log('全部清除成功')
} catch (e) {
// clear error
}
console.log('Done.')
}
render() {
const { width } = Dimensions.get('window');
return (
<ScrollView style={{
flex: 1,
paddingRight: 30,
paddingLeft: 30,
paddingTop: 93,
paddingBottom: 131,
}}>
<Text style={{
color: '#6183b1',
}}>旧密码</Text>
<TextInput
secureTextEntry={true}
placeholder="请填写旧密码"
onChangeText={(text) => {
this.setState({
oldPwd: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
>{this.state.oldPwd}</TextInput>
<Text style={{
color: '#6183b1',
}}>新密码</Text>
<TextInput
secureTextEntry={true}
placeholder='请填写新密码'
onChangeText={(text) => {
this.setState({
newPwd: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
>{this.state.newPwd}</TextInput>
<TouchableOpacity
onPress={() => {
this.fun1()
}}
style={{
backgroundColor: '#6183b1',
borderRadius: 5,
alignItems: "center",
justifyContent: "center",
height: 36,
}}
>
<Text style={{
color: '#FFFFFF',
}}>提交</Text>
</TouchableOpacity>
</ScrollView>
);
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TouchableOpacity, Dimensions, ScrollView } from 'react-native';
import { WebView } from 'react-native-webview';
import appConfig from '../../../jsonData/appConfig.js'
import { Overlay, ModalIndicator, Toast } from 'teaset'
import moment from 'moment';
const { width, height } = Dimensions.get('window');
export default class ShowWebView extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6183b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('otherParam', '资讯详情'),
headerRight: <Image />
}
}
state = {
data1: '',
title: '',
origin: "",
gtmModified: '',
INJECTEDJAVASCRIPT: ` const meta = document.createElement('meta'); meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'); meta.setAttribute('name', 'viewport'); document.getElementsByTagName('head')[0].appendChild(meta); `
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
// 获取平台资讯列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getNewsDetail`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}),
// body: JSON.stringify({//请求参数
// "templeId": 0,
// "page": this.state.nextPage,
// "size": this.state.pageSize
// }),
body: `newsId=${this.props.navigation.getParam('cid')}`
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// console.log('responseJson.data.list', responseJson.data.list);
// 先正则替换
// let re = /<img(.*?)style="(.*?)"(.*?)>/g
// let arr1 = re.exec(responseJson.data.content)
// console.log('匹配结果', arr1, re.lastIndex)
let newContent = responseJson.data.content.replace(/<img(.*?)style="(.*?)"(.*?)>/g, '<img $1 style="border-width: 0px; border-style: initial; display: block; height: auto; width: 608px; max-width: 100%; margin: 0px auto;" $3 >')
if (responseJson.code == 200) {
this.setState({
// data1: responseJson.data.content,
data1: newContent,
title: responseJson.data.title,
gtmModified: responseJson.data.gtmModified,
origin: responseJson.data.origin,
})
console.log('富文本数据xxxxx', responseJson.data)
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
})
}
render() {
if (this.state.data1) {
return (
<WebView
javaScriptEnabled={true}
scalesPageToFit={true}//布尔值,控制网页内容是否自动适配视图的大小,同时启用用户缩放功能。默认为true。
originWhitelist={['*']}//允许被导航到的源字符串列表。字符串允许使用通配符,并且只根据原始地址(而不是完整的URL)进行匹配。如果用户点击导航到一个新页面,但是新页面不在这个白名单中,这个URL将由操作系统处理。默认的白名单起点是"http://"和"https://".
source={{ html: `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>广场 · 看云</title><meta name="viewport" content="width=device-width, initial-scale=1.0;maximum-scale=1;user-scalable=no"><meta name="description" content=""/></head><body><div style="color:#3d3d3d;"><h2>${this.state.title ? this.state.title : ''}</h2></div><div style="font-size:15px;color:#cdcdcd;"><span>${this.state.origin ? `来自${this.state.origin}` : ''} </span><span>${this.state.gtmModified ? moment(this.state.gtmModified).format('YYYY-MM-DD HH:mm') : ''}</span></div>${this.state.data1}</body></html>` }}
injectedJavaScript={this.state.INJECTEDJAVASCRIPT}
/>
);
} else {
return (
<View style={{
flex: 1,
width: width,
backgroundColor: '#fff',
}}></View>
);
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, ScrollView, Image, TouchableOpacity, Dimensions, ImageBackground, Alert } from 'react-native';
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
import { Overlay, ModalIndicator } from 'teaset'
import moment from 'moment';
import QRCode from 'react-native-qrcode-svg';
const { width, height } = Dimensions.get('window');
export default class DingDanDetail extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 18,
color: '#bb2a09',
fontWeight: 'bold',
},
title: navigation.getParam('otherParam', '订单详情'),
}
}
state = {
data1: ''
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
this.fun1(this.props.navigation.getParam('orderNo'))
}
fun1 = async (orderNo) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户订单详情
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/roomOrderDetail`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
// body: JSON.stringify({//请求参数
// "status": 1,//1未支付,2已支付
// "page": 0,
// "size": 100
// }),
body: `orderNo=${orderNo}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
this.setState({
data1: responseJson.data
})
ModalIndicator.hide()
console.log('支付状态', responseJson.data.sattus);
console.log('返回的数据', responseJson);
} else {
console.log('responseJson', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('error', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
ModalIndicator.hide()
console.log('error', error)
}
console.log('Done.')
}
render1 = (txt1, txt2) => {
return (
<View style={{
flexDirection: 'row',
justifyContent: 'space-between',
padding: 10,
}}>
<Text style={{
fontSize: 12,
color: '#666',
}}>{txt1}</Text>
<Text style={{
fontSize: 12,
color: '#666',
}}>{txt2}</Text>
</View>
)
}
render3 = (txt1, txt2, txt3) => {
return (
<View style={{
flexDirection: 'row',
justifyContent: 'space-between',
padding: 10,
}}>
<Text style={{
fontSize: 12,
color: '#666',
}}>{txt1}</Text>
<Text style={{
fontSize: 12,
color: '#666',
}}>{txt2}</Text>
<Text style={{
fontSize: 12,
color: '#666',
}}>{txt3}</Text>
</View>
)
}
render2 = (txt) => {
return (
<View style={{
width: width,
paddingLeft: 10,
}}>
<Text style={{
fontSize: 15,
color: '#517096',
}}>{txt}</Text>
</View>
)
}
render4 = (data) => {
if (data.length > 0) {
let arr = data.reduce((res, cur, index) => {
res.push(
<View
key={index}
style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
}}
>
{this.render1('姓名', cur.realName)}
{this.render1('性别', cur.gender ? '男' : '女')}
{this.render1('身份证', cur.identityNo)}
</View>
)
return res
}, [])
return (
<>
{this.render2('同行人员信息')}
{arr}
</>
)
} else {
return <></>
}
}
fun3 = async (orderNo) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/cancelOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
// body: JSON.stringify({//请求参数
// "status": 1,//1未支付,2已支付
// "page": 0,
// "size": 100
// }),
body: `orderNo=${orderNo}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
console.log('主动取消订单成功', responseJson);
// Alert.alert('订单取消成功!')
Toast.success('订单取消成功!')
this.props.navigation.goBack()
} else {
console.log('主动取消订单失败', responseJson.message);
}
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
}
render5 = (val) => {
if (val == 10) {
return (
<View style={{
width: width,
height: 80,
// backgroundColor:'#549434',
alignItems: 'center',
justifyContent: 'center'
}}>
<TouchableOpacity
onPress={() => {
this.fun3(this.state.data1.orderNo)
}}
style={{
height: 30,
width: 100,
backgroundColor: '#666',
borderRadius: 5,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
fontSize: 12,
color: '#fff',
}}>取消订单</Text>
</TouchableOpacity>
</View>
)
} else {
return <></>
}
}
fun2 = (status) => {
if (status == 10) {
return '未支付'
} else if (status == 20) {
return '已付款'
} else if (status == 40) {
return '交易完成'
} else {
return '已取消'
}
}
render6 = (val) => {
if (val == 20) {
return (
<>
{this.render2('订单二维码')}
< View style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#ececec',
borderRadius: 10,
alignItems: 'center',
}
}>
<QRCode
size={150}
value={this.state.data1.orderNo ? this.state.data1.orderNo : ''}
/>
</View >
</>
)
} else {
return (
<>
</>
)
}
}
render() {
if (this.state.data1) {
return (
<ScrollView style={{
flex: 1,
backgroundColor: '#ececec',
}}>
{this.render2('订单信息')}
<View style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
borderRadius: 10,
}}>
{this.render1('订单编号', this.state.data1.orderNo ? this.state.data1.orderNo : '')}
{this.render1('下单时间', moment(this.state.data1.createDate).format('YYYY.MM.DD HH:mm'))}
</View>
{this.render2('交易信息')}
<View style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
borderRadius: 10,
}}>
{this.render3('客房类型', this.state.data1.productName, `${this.state.data1.hhumannum}人间`)}
{this.render3('入住时间', `${moment(this.state.data1.enterDate).format('MM.DD')}-${moment(this.state.data1.leaveDate).format('MM.DD')}`, `${this.state.data1.stayDays}晚`)}
{this.render1('入住人数', `${this.state.data1.tenantNum}人`)}
{this.render3('交易状态', this.fun2(this.state.data1.status), `${this.state.data1.payment}元`)}
</View>
{this.render2('预订人信息')}
<View style={{
width: width - 20,
marginLeft: 10,
backgroundColor: '#fff',
borderRadius: 10,
}}>
{this.render1('姓名', this.state.data1.tenantName)}
{this.render1('性别', this.state.data1.gender ? '男' : '女')}
{this.render1('身份证', `${this.state.data1.tenantIdentityNo.substring(0,12)}******`)}
{this.render1('预留电话', this.state.data1.tenantTelephone)}
</View>
{this.render4(this.state.data1.tenantList)}
{this.render6(this.state.data1.status)}
{this.render5(this.state.data1.status)}
{/* {this.render5(10)} */}
{/* <View style={{
width: width,
height: 60,
}}></View> */}
</ScrollView>
);
} else {
return (
<View style={{
backgroundColor: '#fff',
flex: 1,
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, Image, TextInput, Alert, TouchableWithoutFeedback, TouchableOpacity, ScrollView, Dimensions } from 'react-native';
import appConfig from '../../../jsonData/appConfig.js'
import { Overlay, ModalIndicator, Toast } from 'teaset'
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
export default class ZhuCe extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#6183b1',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: navigation.getParam('otherParam', '注册'),
}
}
state = {
// nickName: '',//昵称
phone: '',//手机号码
passWord: '',//密码
}
//获取验证码
fun1 = () => {
if (!/^1\d{10}$/.test(this.state.phone)) {
// Alert.alert('请先填写正确的手机号码')
Toast.fail('请先填写正确的手机号码')
return
}
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/code`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}),
// body: JSON.stringify({//请求参数
// // templeId: this.props.navigation.getParam('templeId')
// templeId: '1'
// }),
body: `phone=${this.state.phone}`,
})
.then((response) => {
// console.log('response', response);
// return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
// console.log('data1', responseJson.data)
Toast.message('验证码发送成功,请注意查收')
})
.catch((error) => {
console.log('error', error);
Toast.fail('验证码发送失败,请重试。')
})
}
fun3 = (phone, passWord) => {
// 登录
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/authentication/form`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic c3VrZWxhaTozYWI2N2ExMmJkNWE='
}),
body: `username=${phone}&password=${<PASSWORD>}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == '200') {
//存储已登录用户授权信息
this.setValue1(JSON.stringify({
...responseJson.data,
outTime: moment().add(1, 'days').unix()
}))
console.log('responseJson', responseJson)
this.props.navigation.navigate('ShouYe')
} else {
console.log('responseJson', responseJson)
// Alert.alert(responseJson.message)
Toast.message(responseJson.message)
}
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
setValue1 = async (data) => {
try {
await AsyncStorage.setItem('userData', data)
console.log('用户信息已存储', data)
// Alert.alert('用户信息已存储')
// Alert.alert('')
} catch (error) {
// save error
console.log('error', error)
// Alert.alert('出错了')
Toast.fail('出错了')
}
console.log('Done.')
}
fun2 = () => {
// if (this.state.nickName == '') {
// Alert.alert('昵称未填写')
// return
// }
if (!/^1\d{10}$/.test(this.state.phone)) {
// Alert.alert('请先填写正确的手机号码')
Toast.fail('请先填写正确的手机号码')
return
}
if (this.state.passWord == '') {
// Alert.alert('密码未填写')
Toast.fail('密码未填写')
return
}
if (!/^\d{6}$/.test(this.state.verify)) {
// Alert.alert('验证码格式不正确')
Toast.fail('验证码格式不正确')
return
}
ModalIndicator.show('请稍等。。。')
// 注册
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/register`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
}),
body: JSON.stringify({//请求参数
// templeId: this.props.navigation.getParam('templeId')
// "nickName": this.state.nickName,
"phone": this.state.phone,
"pwd": <PASSWORD>,
"code": this.state.verify
}),
// body: `phone=${this.state.phone}`,
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.message == 'success') {
ModalIndicator.hide()
Toast.success('注册成功')
this.fun3(this.state.phone, this.state.passWord)
} else {
ModalIndicator.hide()
// Alert.alert(responseJson.message)
Toast.message(responseJson.message)
}
})
.catch((error) => {
console.log('error', error);
})
}
render() {
const { width } = Dimensions.get('window');
return (
<ScrollView
keyboardShouldPersistTaps='handled'
style={{
flex: 1,
paddingRight: 30,
paddingLeft: 30,
paddingTop: 93,
paddingBottom: 131,
}}
>
{/* <Text style={{
color: '#6183b1',
}}>昵称</Text>
<TextInput
placeholder='请填写昵称'
onChangeText={(text) => {
this.setState({
nickName: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
>{this.state.nickName}</TextInput> */}
<Text style={{
color: '#6183b1',
}}>手机号码</Text>
<TextInput
placeholder='请填写手机号码'
onChangeText={(text) => {
this.setState({
phone: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
>{this.state.phone}</TextInput>
<Text style={{
color: '#6183b1',
}}>密码</Text>
<TextInput
secureTextEntry={true}
placeholder='请填写密码'
onChangeText={(text) => {
this.setState({
passWord: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
>{this.state.passWord}</TextInput>
<View style={{
flexDirection: "row",
alignItems: "center",
}}>
<View style={{
width: width - 60 - 116 - 21,
}}>
<Text style={{
color: '#6183b1',
}}>验证码</Text>
<TextInput
placeholder='请填写验证码'
onChangeText={(text) => {
this.setState({
verify: text
})
}}
style={{
borderBottomWidth: 2,
borderBottomColor: '#6183b1',
marginBottom: 41,
}}
>{this.state.verify}</TextInput>
</View>
<TouchableOpacity
onPress={() => this.fun1()}
style={{
height: 46,
alignItems: "center",
justifyContent: 'center',
borderRadius: 5,
borderWidth: 1,
borderColor: '#6183b1',
position: 'relative',
top: -21,
width: 116,
marginLeft: 21,
}}
>
<Text style={{
color: '#6183b1',
}}>获取验证码</Text>
</TouchableOpacity>
</View>
<TouchableOpacity
onPress={() => {
this.fun2()
}}
style={{
backgroundColor: '#6183b1',
borderRadius: 5,
alignItems: "center",
justifyContent: "center",
height: 36,
}}
>
<Text style={{
color: '#FFFFFF',
}}>注册</Text>
</TouchableOpacity>
</ScrollView>
);
}
}
<file_sep>// 实现一个登录检测函数,在需要登录才能操作的页面调用,若未登录则自动跳转到登录页面,
// 尝试在公共函数里面调用原生alert,
//尝试在公共函数里面调用Teaset组件弹框,
// 尝试在公共函数里实现页面跳转,
// 尝试在公共函数里,操作当前页面的state。
// 尝试同时导出多个函数,
// export function DengLuJianCe(){
// // 服务器ip
// // serversIp:'172.16.58.3',
// // wxAppId:'wx604ebb6e95cc63ed',//微信appid
// this.console.log('成功调用模块内的函数')
// this.Toast.fail('成功调用模块内的函数');
// }
<file_sep>
import React, { Component } from 'react';
import { View, Text, Button, TouchableOpacity, Image, Alert, Dimensions, ScrollView } from 'react-native';
import { Carousel, ModalIndicator } from 'teaset';
import appConfig from '../../../jsonData/appConfig.js'
import AsyncStorage from '@react-native-community/async-storage';
const { width } = Dimensions.get('window');
export default class QiFu extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: '#ffcc80',
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: `${navigation.getParam('name', '')}祈福`,
headerRight: <Image />
}
}
state = {
data1: '',
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
this.getValue1(this.props.navigation.getParam('templeId', ''), this.props.navigation.getParam('tagId', ''))
}
getValue1 = async (templeId, tagId) => {
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/temple/productInfoList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
"templeId": templeId,
"tagId": tagId,
"page": 0,
"size": 10
}),
// body: `templeId=${templeId}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
this.setState({
data1: responseJson.data.list
})
ModalIndicator.hide()
console.log('返回的数据', responseJson.data.list);
} else {
ModalIndicator.hide()
console.log('responseJson', responseJson);
}
})
.catch((error) => {
ModalIndicator.hide()
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
render1 = (praytype) => {
let praytypeImg = [
'',
require('./gffx.png'),
require('./jslj.png'),
require('./gs.png'),
require('./zyjs.png'),
require('./fs.png'),
require('./ghg.png'),
''
]
let praytypeName = [
'日行一善',
'供佛',
'建寺乐捐',
'供僧',
'助印经书',
'放生',
'供花果',
'供灯',
'住宿',
]
return (
<View
style={{
alignItems: 'center',
backgroundColor: '#eee',
}}
>
<View style={{
borderWidth: 1,
borderColor: '#8a8a8a',
}}>
<Image
style={{
width: width * 0.48,
height: width * 0.48 * 0.643,
}}
resizeMethod='resize'
resizeMode='stretch'
source={praytypeImg[praytype]}
/>
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('JuanZeng', {
title: praytypeName[praytype],
praytype: praytype,
productId: this.state.data1.find(item => item.praytype == praytype).productId,
})}
style={{
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#007499',
width: width * 0.4,
height: width * 0.12,
borderRadius: 3,
marginTop: 10,
marginBottom: 10,
borderWidth: 1,
borderColor: '#cccccc'
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>{praytypeName[praytype]}</Text>
</TouchableOpacity>
</View>
)
}
render() {
if (this.state.data1) {
return (
<ScrollView style={{
flex: 1,
backgroundColor: '#eee',
}}>
<Image
style={{
width: width,
height: width * 0.5478,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./top.png')}
/>
<View style={{
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
paddingTop: 5,
}}>
{this.render1(1)}
{this.render1(6)}
{this.render1(3)}
{this.render1(4)}
{this.render1(5)}
{this.render1(2)}
</View>
<View style={{
width: width,
height: 20,
borderTopColor: '#d7d7d7',
borderTopWidth: 1,
backgroundColor: '#fff',
}}></View>
<View
style={{
alignItems: 'center',
}}
>
<Image
style={{
width: width,
height: width * 0.5478,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./gd.png')}
/>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('GongDeng', {
title: '供灯',
praytype: 7,
productId: this.state.data1.find(item => item.praytype == 7).productId,
})}
style={{
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#007499',
width: width * 0.4,
height: width * 0.12,
borderRadius: 3,
position: 'absolute',
borderWidth: 1,
borderColor: '#cccccc',
top: -10,
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>供灯</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
} else {
return (
<View style={{
flex: 1,
backgroundColor: '#fff',
}}></View>
)
}
}
}
<file_sep>
import React, { Component } from 'react';
import { View, Text, TextInput, Button, Image, TouchableOpacity, Dimensions, ScrollView, Alert, TouchableWithoutFeedback, ImageBackground } from 'react-native';
import { WebView } from 'react-native-webview';
import appConfig from '../../../jsonData/appConfig.js'
import { Overlay, ModalIndicator, Toast } from 'teaset'
import moment from 'moment';
import AsyncStorage from '@react-native-community/async-storage';
import * as WeChat from 'react-native-wechat-lib'
import Alipay from '@0x5e/react-native-alipay';
const { width } = Dimensions.get('window');
class JuanKuan extends Component {
state = {
isEdit: false,//是否编辑捐款名字
SiYuanFangName: '',//用户寺院芳名
JuanName: '用户xx',//捐款用的昵称
headImg: {
uri: ''
},//头像图片
rmb: '',//捐赠金额
isNiMing: false,//是否匿名
isRandom: false,//是否随机金额
rmbRandom: [
6,
6.6,
18,
26,
28,
0.88,
1.88,
188,
18.88,
28.88,
36.66,
55,
5.5,
123,
13,
1.33,
6.66,
8.88,
88.8,
4.6,
7.88,
13,
1.33,
23,
23.33,
3,
0.88,
7.77,
9.99,
98,
65,
2.33,
10,
20,
30,
50,
60,
70,
80,
90,
188.88,
88.88,
66.66,
6.88,
8.66
],//随机金额
Authorization: '',//用户唯一标识
}
UNSAFE_componentWillMount() {
this.Do1()
this.JianCeDengLu()
}
// 获取功德芳名
fun13 = (templeId, Authorization) => {
if (templeId && Authorization) {
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/getUserMeritName`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
// 'Content-Type': 'application/json',
'Authorization': Authorization
}),
body: `templeId=${templeId}`,
// body: JSON.stringify({//请求参数
// templeId: parseInt(templeId),
// }),
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
this.setState({
SiYuanFangName: responseJson.data,
JuanName: responseJson.data,
})
} else {
this.setState({
SiYuanFangName: '',
})
}
console.log('野兽到的芳名', responseJson)
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
})
}
}
// 检测是否登录
JianCeDengLu = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户信息
let valueObj = JSON.parse(value)
if (valueObj.outTime > moment().unix()) {
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/user/me`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: '',
})
.then((response) => {
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
if (responseJson.code == 200) {
this.setState({
JuanName: responseJson.data.nickName,
headImg: {
uri: responseJson.data.usersign
},
Authorization: `${valueObj.token_type} ${valueObj.access_token}`
}, () => {
// 获取功德芳名
this.fun13(this.props.templeId, this.state.Authorization)
console.log('寺庙id', this.props.templeId)
})
console.log('返回的数据', responseJson.data.nickName);
} else {
console.log('responseJson', responseJson);
this.TiShiDengLu()
}
})
.catch((error) => {
console.log('error', error);
// Alert.alert('失败,请重试。')
})
} else {
this.TiShiDengLu()
}
} else {
this.TiShiDengLu()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
console.log('Done.')
}
// 提示用户登录
TiShiDengLu = () => {
// 提示用户先登录
let TiShiDengLuOverlayView = (
<Overlay.View
style={{ alignItems: 'center', justifyContent: 'center' }}
modal={true}
overlayOpacity={0.5}
ref={v => this.TiShiDengLuOverlayView = v}
>
<ImageBackground
style={{
backgroundColor: '#fff',
padding: 3,
// borderRadius: 10,
height: 165,
width: 285,
}}
resizeMethod='resize'
resizeMode='cover'
source={require('../../../imgs/dl.png')}
>
<View style={{
width: '100%',
height: 50,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text style={{
fontSize: 22,
}}>[请先登录]</Text>
</View>
<View style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.props.close1()
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>返回</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.TiShiDengLuOverlayView && this.TiShiDengLuOverlayView.close()
this.props.close1()
this.props.navigation.replace('DengLu')
}}
style={{
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
borderRadius: 2,
}}
>
<Text style={{
fontSize: 18,
color: '#fff',
padding: 5,
}}>确定</Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Overlay.View>
);
Overlay.show(TiShiDengLuOverlayView);
}
// 通过用户唯一识别码和订单号查询支付是否成功的函数
isPaySucceed = (orderNum, Authorization) => {
this.timerIsPaySucceed = setTimeout(() => {
console.log('订单号', orderNum)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/checkOrderPayInfo`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': Authorization
}),
// body: JSON.stringify({//请求参数
// productId: parseInt(this.props.navigation.getParam('productId', '')),
// userNickName: this.state.JuanName,
// }),
body: `orderNo=${orderNum}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
this.timerIsPaySucceed && clearTimeout(this.timerIsPaySucceed);
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
if (responseJson.data.platformStatus == 1) {
ModalIndicator.hide()
// 收起红包
this.props.close1()
// 刷新功德榜
this.props.refresh1()
// this.props.navigation.goBack()
// Alert.alert('订单支付成功')
Toast.success('订单支付成功')
}
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
// Alert.alert('订单支付失败')
Toast.fail('后台认为订单支付失败')
// 取消订单
this.fun6(orderNum)
}
})
.catch((error) => {
this.timerIsPaySucceed && clearTimeout(this.timerIsPaySucceed);
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
}, 1000);
}
//取消订单
fun6 = async (orderNo) => {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
// 获取用户的行程订单列表
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/busy/cancelOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: `orderNo=${orderNo}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
if (responseJson.code == 200) {
// Toast.message('订单已取消!')
} else {
Toast.message('服务器取消订单失败')
}
})
.catch((error) => {
console.log('error', error);
})
} else {
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
}
}
fun4 = async (txt) => {
if (this.state.rmb == '') {
// Alert.alert('请先填写或随机生成捐赠金额')
Toast.message('请先填写或随机生成捐赠金额')
return
}
if (this.state.rmb <= 0) {
// Alert.alert('捐赠金额必须大于0')
Toast.message('捐赠金额必须大于0')
return
}
if (!/^[0-9]+(.[0-9]{1,2})?$/.test(this.state.rmb)) {
// Alert.alert('输入的金额格式不正确')
Toast.message('输入的金额格式不正确')
return
}
ModalIndicator.show()
// 支付类型判断
// this.timer = setTimeout(() => {
// this.fun5()
// this.timer && clearTimeout(this.timer)
// }, 3000)
if (txt == '微信支付') {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/wxpay/createMeritOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
productId: parseInt(this.props.meritProductInfo.productId),
userNickName: this.state.isNiMing ? '' : this.state.JuanName,
money: parseFloat(this.state.rmb).toFixed(2),
// days: parseInt(this.state.Tian),
// lamps: parseInt(1),
// blessing: this.state.hxw,
prayType: this.props.meritProductInfo.praytype,
}),
// body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
WeChat.isWXAppInstalled()
.then((isInstalled) => {
if (isInstalled) {
this.payFun(responseJson)
} else {
ModalIndicator.hide()
// Alert.alert('请安装微信');
Toast.message('请安装微信')
}
});
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
ModalIndicator.hide()
}
} else if (txt == '支付宝') {
try {
const value = await AsyncStorage.getItem('userData')
if (value) {
let valueObj = JSON.parse(value)
console.log('valueObj', valueObj)
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/alipay/createMeritOrder`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `${valueObj.token_type} ${valueObj.access_token}`
}),
body: JSON.stringify({//请求参数
productId: parseInt(this.props.meritProductInfo.productId),
userNickName: this.state.isNiMing ? '' : this.state.JuanName,
money: parseFloat(this.state.rmb).toFixed(2),
// days: parseInt(this.state.Tian),
// lamps: parseInt(1),
// blessing: this.state.hxw,
prayType: this.props.meritProductInfo.praytype,
}),
// body: '',
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// Alert.alert(JSON.stringify(responseJson));
console.log('接受参数', responseJson);
if (responseJson.code == 200) {
this.toPay(responseJson)
} else {
console.log('错误', responseJson);
ModalIndicator.hide()
}
})
.catch((error) => {
console.log('链接错误', error);
ModalIndicator.hide()
// Alert.alert('失败,请重试。')
})
} else {
ModalIndicator.hide()
}
console.log('value', value)
} catch (error) {
// read error
console.log('error', error)
ModalIndicator.hide()
}
}
}
toPay = async (val) => {
if (val.data) {
// APP支付
try {
let response = await Alipay.pay(val.data.orderParams)
let { resultStatus, result, memo } = response;
// let { code, msg, app_id, out_trade_no, trade_no, total_amount, seller_id, charset, timestamp } = JSON.parse(result);
console.log('支付宝支付返回的结果', response)
if (resultStatus == '9000') {
ModalIndicator.show('查询支付结果。。。')
this.isPaySucceed(val.data.orderNo, this.state.Authorization)
} else {
ModalIndicator.hide()
Toast.message(memo)
// 取消未支付的订单
this.fun6(val.data.orderNo)
return
}
} catch (error) {
ModalIndicator.hide()
console.error('错误', error);
console.info('支付失败');
Toast.fail('支付失败,请联系开发人员')
}
} else {
ModalIndicator.hide()
// Alert.alert('支付参数不正确')
Toast.fail('支付参数不正确')
}
}
// 微信支付函数
payFun = async function (responseJson) {
try {
console.log('支付参数', responseJson.data)
console.log('支付参数partnerid', responseJson.data.orderParams.partnerid)
console.log('支付参数prepayid', responseJson.data.orderParams.prepayid)
console.log('支付参数noncestr', responseJson.data.orderParams.noncestr)
console.log('支付参数timestamp', responseJson.data.orderParams.timestamp)
console.log('支付参数package', responseJson.data.orderParams.package)
console.log('支付参数sign', responseJson.data.orderParams.sign)
console.log('支付参数appid', responseJson.data.orderParams.appid)
let result = await WeChat.pay({
partnerId: responseJson.data.orderParams.partnerid, // 商家向财付通申请的商家id
prepayId: responseJson.data.orderParams.prepayid, // 预支付订单
nonceStr: responseJson.data.orderParams.noncestr, // 随机串,防重发
timeStamp: responseJson.data.orderParams.timestamp, // 时间戳,防重发
package: responseJson.data.orderParams.package, // 商家根据财付通文档填写的数据和签名
sign: responseJson.data.orderParams.sign, // 商家根据微信开放平台文档对数据做的签名
appId: responseJson.data.orderParams.appid
});
let { errCode, errStr } = result
if (errCode == 0) {
ModalIndicator.show('查询支付结果。。。')
this.isPaySucceed(responseJson.data.orderNo, this.state.Authorization)
} else {
ModalIndicator.hide()
Toast.message(errStr)
// 取消未支付的订单
this.fun6(responseJson.data.orderNo)
return
}
} catch (e) {
ModalIndicator.hide()
console.log('支付失败了', e)
// Toast.fail('支付失败,请联系开发者')
Toast.fail('操作已取消')
}
}
render8 = () => {
if (this.state.isNiMing) {
return (
<View style={{
marginTop: 10,
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<Text style={{
color: '#fff',
fontSize: 20,
marginRight: 10,
}}>素客</Text>
</View>
)
} else if (this.state.isEdit) {
return (
<View style={{
marginTop: 10,
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<ImageBackground
style={{
width: width * 0.55,
height: width * 0.12,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./ip.png')}
>
<TextInput
style={{
color: '#fff',
fontSize: 20,
width: width * 0.55,
height: width * 0.12,
borderRadius: width * 0.05,
padding: 0,
fontSize: 15,
paddingLeft: 20,
}}
onChangeText={(text) => {
this.setState({
JuanName: text
})
}}
>{this.state.JuanName}</TextInput>
</ImageBackground>
</View>
)
} else {
return (
<View style={{
marginTop: 10,
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<TouchableOpacity
style={{
flexDirection: 'row',
alignItems: "center",
}}
onPress={() => {
this.setState({
isEdit: true
})
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
marginRight: 10,
}}>{this.state.JuanName}</Text>
<Image
style={{
width: width * 0.04,
height: width * 0.04,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./bi.png')}
/>
</TouchableOpacity>
</View>
)
}
}
render9 = () => {
if (this.state.isNiMing) {
return (
<TouchableOpacity
onPress={() => {
this.setState({
isNiMing: false,
JuanName: ''
})
}}
style={{
flexDirection: "row",
alignItems: 'center',
}}
>
<View style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#fff',
justifyContent: 'center',
alignItems: 'center',
}}>
<View style={{
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: '#d9392a',
}}></View>
</View>
<Text style={{
color: '#fff',
fontSize: 20,
}}>匿名参与</Text>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
onPress={() => {
this.setState({
isNiMing: true,
JuanName: '素客',
})
}}
style={{
flexDirection: "row",
alignItems: 'center',
}}>
<View style={{
width: 20,
height: 20,
borderRadius: 10,
backgroundColor: '#fff',
}}
></View>
<Text style={{
color: '#fff',
fontSize: 20,
}}>匿名参与</Text>
</TouchableOpacity>
)
}
}
render11 = () => {
if (this.state.isNiMing) {
return (
<Image
style={{
width: width * 0.28 - 4,
height: width * 0.28 - 4,
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./ntx.png')}
/>
)
} else {
return (
<Image
style={{
width: width * 0.28 - 4,
height: width * 0.28 - 4,
}}
resizeMethod='resize'
resizeMode='stretch'
source={this.state.headImg && this.state.headImg.uri ? this.state.headImg : require('../../../imgs/noimg.png')}
/>
)
}
}
Do1 = () => {
this.setState({
rmb: this.state.rmbRandom[Math.ceil(Math.random() * 45) + 1],
isRandom: true,
})
}
render() {
return (
<TouchableWithoutFeedback
onPress={() => {
this.setState({
isEdit: false,
})
}}
>
<ImageBackground
resizeMode="stretch"
style={{
width: '100%',
height: '100%',
}}
source={require('./hb.png')}
>
<View style={{
marginTop: width * 0.03,
alignItems: 'center',
flexDirection: "column",
}}>
<View style={{
width: width * 0.28,
height: width * 0.28,
borderRadius: width * 0.14,
overflow: 'hidden',
borderColor: '#fea43c',
borderWidth: 2,
}}>
{this.render11()}
</View>
{this.render8()}
<Text style={{
fontSize: 30,
color: "#f8ec90",
}}>{this.state.rmb ? this.state.rmb : '0.00'}</Text>
<View style={{
height: width * 0.12,
flexDirection: 'row',
alignItems: 'center',
}}>
<ImageBackground
style={{
width: width * 0.55,
height: width * 0.12,
alignItems: 'center',
flexDirection: 'row',
}}
resizeMethod='resize'
resizeMode='stretch'
source={require('./ip.png')}
>
<TextInput
placeholder='手动输入金额'
placeholderTextColor='#fff'
style={{
color: '#fff',
fontSize: 20,
width: width * 0.55,
height: width * 0.12,
borderRadius: width * 0.05,
padding: 0,
fontSize: 15,
paddingLeft: 20,
}}
onChangeText={(text) => {
this.setState({
rmb: text,
isRandom: false,
})
}}
>{this.state.isRandom ? '' : this.state.rmb}</TextInput>
<Text style={{
position: 'absolute',
right: 20,
color: '#fff',
fontSize: 20,
}}>元</Text>
</ImageBackground>
</View>
<View style={{
marginTop: width * 0.03,
flexDirection: 'row',
alignItems: "center",
width: '100%',
justifyContent: 'space-between',
paddingLeft: 10,
paddingLeft: 10,
paddingRight: 10,
}}>
{this.render9()}
<TouchableOpacity
onPress={() => {
this.props.close1()
this.props.navigation.navigate('FuWuXieYi')
}}
style={{
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>《查看服务协议》</Text>
</TouchableOpacity>
</View>
<View style={{
marginTop: width * 0.03,
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
width: '100%',
}}>
<TouchableOpacity
onPress={() => {
this.Do1()
}}
style={{
width: width * 0.3,
height: width * 0.1,
borderRadius: 5,
borderWidth: 1,
borderColor: '#f6ea7e',
backgroundColor: '#e65340',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text style={{
fontSize: 20,
color: '#f6ea7e',
}}>换个金额</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.fun4('微信支付')
}}
style={{
borderWidth: 1,
borderColor: '#4caf50',
width: width * 0.3,
height: width * 0.1,
borderRadius: 5,
backgroundColor: '#009c46',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
alignItems: "center",
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>微信支付</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.fun4('支付宝')
}}
style={{
borderWidth: 1,
borderColor: '#2196f3',
width: width * 0.3,
height: width * 0.1,
borderRadius: 5,
backgroundColor: '#0055a2',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
alignItems: "center",
}}
>
<Text style={{
color: '#fff',
fontSize: 20,
}}>支付宝</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
</TouchableWithoutFeedback>
)
}
}
const BaseScript =
`
(function () {
var height = null;
function changeHeight() {
if (document.body.scrollHeight&&parseInt(document.body.scrollHeight)) {
height = document.body.scrollHeight;
if (window.ReactNativeWebView.postMessage) {
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'setHeight',
height: height,
}))
}
}
}
setTimeout(changeHeight, 600);
} ())
`
export default class SiYuanZiXunDetail extends Component {
static navigationOptions = ({ navigation }) => {
let color = ''
if (navigation.getParam('from', '') == 'zixun') {
color = '#6183b1'
} else {
color = '#ffcc80'
}
let title = navigation.getParam('title', '')
if (title) {
} else {
title = '资讯'
}
return {
headerStyle: {
backgroundColor: color,
height: 30,
},
headerTitleStyle: {
fontSize: 20,
},
title: title,
headerRight: <Image />
}
}
state = {
data1: '',//资讯详情富文本内容
data2: '',//捐款流水列表
title: '',
origin: "",
gtmModified: '',
showZheng: false,//是否显示认证信息
height: 1000,
type: '',//资讯类型:0头条,1法讯,2佛协,3社会
cid: '',//文章id
dataZheng: '',//寺院认证数据
}
UNSAFE_componentWillMount() {
ModalIndicator.show('加载中。。。')
// 获取资讯详情数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/news/getNewsDetail`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}),
// body: JSON.stringify({//请求参数
// "templeId": 0,
// "page": this.state.nextPage,
// "size": this.state.pageSize
// }),
body: `newsId=${this.props.navigation.getParam('cid')}`
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
// console.log('responseJson.data.list', responseJson.data.list);
// 先正则替换
// let re = /<img(.*?)style="(.*?)"(.*?)>/g
// let arr1 = re.exec(responseJson.data.content)
// console.log('匹配结果',arr1,re.lastIndex)
// <img src="https://sk-temple-file.oss-cn-hangzhou.aliyuncs.com/temple/blog/9e0d3aae-84e8-4c25-8661-7e25badd9cc2.jpg" style="width: 50%;"></img>
// <img alt="1.png" src="http://e0.ifengimg.com/12/2019/0718/2F81A0E22BF26B5D38B03B10CEEE9A3E3C4BC7C6_size1124_w895_h617.png" style="border-width: 0px; border-style: initial; display: block; height: auto; width: 608px; max-width: 100%; margin: 0px auto;"></img>
// let newContent = responseJson.data.content.replace(/><img(.*?)style="(.*?)"(.*?)></g, '><img alt="1.png" src="https://e0.ifengimg.com/12/2019/0718/2F81A0E22BF26B5D38B03B10CEEE9A3E3C4BC7C6_size1124_w895_h617.png" style="border-width: 0px; border-style: initial; display: block; height: auto; width: 608px; max-width: 100%; margin: 0px auto;"><')
let newContent2 = responseJson.data.content.replace(/<img(.*?)style="(.*?)"(.*?)>/g, '<img $1 style="border-width: 0px; border-style: initial; display: block; height: auto; width: 608px; max-width: 100%; margin: 0px auto;" $3 >')
// let newContent = responseJson.data.content.replace(/<img(.*?)style="(.*?)"(.*?)>/g, '<img $1 style="border-width: 0px; border-style: initial; display: block; height: auto; width: 608px; max-width: 100%; margin: 0px auto;" $3 >')
// let newContent2 = newContent1.replace(/<img(.*?)src="http(s?):(.*?)>/g, '<img $1 src="https:$3>')
if (responseJson.code == 200) {
this.setState({
// data1: responseJson.data.content,
data1: newContent2,
title: responseJson.data.title,
gtmModified: responseJson.data.gtmModified,
origin: responseJson.data.origin,
type: responseJson.data.type,
cid: this.props.navigation.getParam('cid')
}, () => {
this.fun8(this.props.navigation.getParam('cid'))
})
console.log('富文本数据', responseJson.data.content)
}
ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
})
//获取寺院认证授权信息。
this.fun11()
}
// 刷新功德榜
refresh1 = () => {
this.fun8(this.props.navigation.getParam('cid'))
}
fun8 = (cid) => {
// 获取捐款列表数据
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/merit/getNewsMeritRecordList`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
}),
body: JSON.stringify({//请求参数
"newsId": cid,
"page": 1,
"size": 1000
}),
// body: `newsId=${this.props.navigation.getParam('cid')}`
})
.then((response) => {
console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
this.setState({
data2: responseJson.data.list
})
// ModalIndicator.hide()
})
.catch((error) => {
console.log('error', error);
})
}
// 获取认证授权信息
fun11 = () => {
if (this.props.navigation.getParam('templeId', false)) {
fetch(`${appConfig.SorNot}://${appConfig.serversIp}/temple/authTempleInfo`, {
method: 'POST',//如果为GET方式,则不要添加body,否则会出错 GET/POST
headers: new Headers({
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': `${valueObj.token_type} ${valueObj.access_token}`,
}),
// body: JSON.stringify({//请求参数
// // templeId: this.props.navigation.getParam('templeId')
// templeId: '1'
// }),
body: `templeId=${this.props.navigation.getParam('templeId')}`,
})
.then((response) => {
// console.log('response', response);
return response.json()
})//将数据转成json,也可以转成 response.text、response.html
.then((responseJson) => {//获取转化后的数据responseJson、responseText、responseHtml
console.log('data1111111', responseJson.data)
if (responseJson.data) {
this.setState({
showZheng: true,
dataZheng: responseJson.data
})
}
})
.catch((error) => {
console.log('error', error);
})
}
}
render13 = () => {
if ((this.state.type == 1) && this.state.showZheng) {
return (
<View style={{
// height:30,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 5,
paddingBottom: 5,
width: width,
}}>
<View
style={{
height: 35,
backgroundColor: '#96afd7',
borderRadius: 5,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
}}
>
<TouchableOpacity
onPress={() => {
this.setState({
showZheng: false,
})
}}
style={{
width: 30,
height: 30,
position: 'absolute',
left: 5,
justifyContent: 'center',
alignItems: 'center',
}}
>
<Image
style={{
width: 20,
height: 20,
}}
resizeMode='contain'
resizeMethod='resize'
source={require('./gb.png')}
/>
</TouchableOpacity>
<Image
style={{
width: 20,
height: 20,
marginRight: 10,
}}
resizeMode='contain'
resizeMethod='resize'
source={require('./zheng.png')}
/>
<Text style={{
fontSize: 14,
color: '#fff',
}}>已认证,可放心访问</Text>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('RenZheng', {
data: this.state.dataZheng,
})
}}
style={{
width: 60,
height: 20,
borderRadius: 10,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
right: 5,
}}
>
<Text style={{
fontSize: 14,
color: '#6d8db6',
}}>查看</Text>
</TouchableOpacity>
</View>
</View>
)
} else {
return <></>
}
}
/**
* web端发送过来的交互消息
*/
onMessage(event) {
console.log('enent', event.nativeEvent.data)
try {
const action = JSON.parse(event.nativeEvent.data)
if (action.type === 'setHeight' && action.height > 0) {
this.setState({
height: action.height + 30
}, () => {
console.log('成功设置高度', action.height)
})
}
} catch (error) {
// pass
console.log('error', error)
// Alert.alert('34343')
}
}
// 捐款弹框
close1 = () => {
this.overlayView && this.overlayView.close()
}
render20 = (data) => {
return data.map((cur, index) => {
console.log('捐款时间', cur.donateTime)
return (
<View
key={index}
style={{
width: width - 60,
borderBottomColor: '#f6f6f6',
borderBottomWidth: 1,
flexDirection: 'column',
// paddingTop: 20,
// paddingBottom: 20,
}}
>
<View style={{
flexDirection: 'row',
alignItems: 'center',
}}>
<Image
style={{
width: 40,
height: 40,
borderRadius: 20,
}}
resizeMethod='resize'
resizeMode='cover'
source={cur.usersign ? { uri: cur.usersign } : require('../../../imgs/ntx.png')}
/>
<Text style={{
marginLeft: 15,
color: '#3a3a3a',
fontSize: 13,
}}>{cur.userNickName}</Text>
<Text style={{
color: '#7190c8',
fontSize: 13,
position: 'absolute',
right: 0,
}}>{cur.money}元</Text>
</View>
<View style={{
alignItems: 'flex-end',
}}>
<Text style={{ color: '#8d8d8f' }}>{moment(cur.donateTime).format('MM-DD HH:mm')}</Text>
</View>
</View>
)
})
}
render21 = (data) => {
if (this.state.type == 1 && data) {
return (
<View style={{
width: width,
backgroundColor: '#f7f7f7',
}}>
<View style={{
width: width - 20,
backgroundColor: '#fff',
marginBottom: 50,
marginLeft: 10,
marginTop: 10,
alignItems: "center",
}}>
<View style={{
width: width - 60,
height: 30,
flexDirection: 'row',
alignItems: 'center',
borderBottomColor: '#f6f6f6',
borderBottomWidth: 1,
}}>
<Text style={{
color: '#3a3a3a',
fontSize: 20,
}}>参与者</Text>
</View>
{this.render20(data)}
</View>
</View>
)
} else {
return <></>
}
}
render22 = () => {
if (this.state.type == 1) {
return (
<TouchableOpacity
onPress={() => {
let overlayView = (
<Overlay.PullView
modal={false}
side='bottom'
animated={true}
ref={v => this.overlayView = v}
>
<View style={{
width: width,
backgroundColor: '#fff',
height: width * 1,
}}>
<JuanKuan
navigation={this.props.navigation}
close1={this.close1}
refresh1={this.refresh1}
meritProductInfo={{
productId: this.state.cid,
praytype: 9,
}}
templeId={this.props.navigation.getParam('templeId', '')}
/>
</View>
</Overlay.PullView >
);
Overlay.show(overlayView);
}}
style={{
width: width,
height: 50,
backgroundColor: '#7a9ac1',
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
bottom: 0,
}}
>
<Text style={{
color: '#fff',
}}>参与乐捐</Text>
</TouchableOpacity>
)
} else {
return <></>
}
}
render() {
if (this.state.data1) {
return (
<View style={{
flex: 1,
}}>
<ScrollView style={{
flex: 1,
}}>
{this.render13()}
<View style={{
width: width,
height: this.state.height,
}}>
<View style={{
width: width,
height: this.state.height,
// backgroundColor: '#294209',
zIndex: 10,
position: 'absolute',
top: 0,
left: 0,
backgroundColor: 'transparent',
}}></View>
<WebView
style={{ flex: 1 }}
bounces={false}
scrollEnabled={false}
automaticallyAdjustContentInsets={true}
contentInset={{ top: 0, left: 0 }}
scalesPageToFit={false}//布尔值,控制网页内容是否自动适配视图的大小,同时启用用户缩放功能。默认为true。
originWhitelist={['*']}//允许被导航到的源字符串列表。字符串允许使用通配符,并且只根据原始地址(而不是完整的URL)进行匹配。如果用户点击导航到一个新页面,但是新页面不在这个白名单中,这个URL将由操作系统处理。默认的白名单起点是"http://"和"https://".
source={{ html: `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0;maximum-scale=1;user-scalable=no"><meta name="description" content=""/></head><body><div style="color:#3d3d3d;"><h2>${this.state.title ? this.state.title : ''}</h2></div><div style="font-size:15px;color:#cdcdcd;"><span>${this.state.origin ? `来自${this.state.origin}` : ''} </span><span>${this.state.gtmModified ? moment(this.state.gtmModified).format('YYYY-MM-DD HH:mm') : ''}</span></div>${this.state.data1}</body></html>` }}
// onNavigationStateChange={(navState) => {
// if (navState.title && parseInt(navState.title)) {
// this.setState({
// height: parseInt(navState.title) + 20
// })
// console.log('获取到的高度', navState.title)
// }
// }}
injectedJavaScript={BaseScript}
onMessage={this.onMessage.bind(this)}
/>
</View>
{this.render21(this.state.data2)}
</ScrollView>
{this.render22()}
</View>
);
} else {
return (
<View style={{
flex: 1,
width: width,
backgroundColor: '#fff',
}}></View>
);
}
}
}
| 08ced0113fae173ec4bb4fec0e4e11e369fa8d0e | [
"JavaScript"
] | 24 | JavaScript | oMhuAaN/sukelai | 89b73088d52dd83c9c01a3f2c13563a37e9c695f | ccd7b31c7c1aa8dc98787ae926cb14e5d6d96882 |
refs/heads/main | <repo_name>estefanysuarez/suarez_neuromorphicnetworks2<file_sep>/03_analysis/tmp/figS10.py
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 13:36:29 2021
@author: <NAME>
"""
import os
import numpy as np
import pandas as pd
from reservoir.tasks import tasks
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
from plotting import plotting
#%% --------------------------------------------------------------------------------------------------------------------
# GLOBAL VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
CONNECTOME = 'human_500'
CLASS = 'functional' #'functional' 'cytoarch'
INPUTS = 'subctx'
ANALYSIS = 'reliability' # 'reliability' 'significance' 'spintest'
#%% --------------------------------------------------------------------------------------------------------------------
# DIRECTORIES
# ----------------------------------------------------------------------------------------------------------------------
PROJ_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DATA_DIR = os.path.join(PROJ_DIR, 'data')
RAW_RES_DIR = os.path.join(PROJ_DIR, 'raw_results')
PROC_RES_DIR = os.path.join(PROJ_DIR, 'proc_results')
RES_TSK_DIR = os.path.join(PROC_RES_DIR, 'tsk_results')
brain = pd.read_csv(os.path.join(RES_TSK_DIR, 'reliability', 'subctx_scale500', 'functional_avg_encoding.csv'))
leakyIF = pd.read_csv(os.path.join(RES_TSK_DIR, 'leakyIF', 'subctx_scale500', 'functional_avg_encoding.csv'))
lsm = np.unique(np.loadtxt(os.path.join(RES_TSK_DIR, 'lsm', 'lsm.txt')))
lsm = np.hstack((np.arange(len(lsm))[:,np.newaxis], np.repeat(['lsm'], len(lsm), axis=0)[:,np.newaxis], lsm[:,np.newaxis], np.repeat(['lsm'], len(lsm), axis=0)[:,np.newaxis]))
#%% --------------------------------------------------------------------------------------------------------------------
# IMPORT RESULTS
# ----------------------------------------------------------------------------------------------------------------------
df_br = brain[['sample_id', 'alpha', 'performance', 'analysis']]
df_br['analysis'] = 'brain'
df_lk = leakyIF[['sample_id', 'alpha', 'performance', 'analysis']]
df_lsm = pd.DataFrame(data=lsm, columns=['sample_id', 'alpha', 'performance', 'analysis'])
new_df = pd.concat([df_br, df_lk, df_lsm], axis=0).reset_index()[['sample_id', 'alpha', 'performance', 'analysis']]
new_df['performance'] = new_df['performance'].astype(float)
# scale values between 0 and 1
min_score = np.min(new_df['performance'])
max_score = np.max(new_df['performance'])
new_df['performance'] = (new_df['performance']-min_score)/(max_score-min_score)
# select alpha = 1.0
new_df['alpha'] = new_df['alpha'].astype(str)
include_alpha = ['1.0', 'lsm']
new_df = pd.concat([new_df.loc[new_df['alpha'] == alpha, :] for alpha in include_alpha])\
.reset_index(drop=True)
#%% --------------------------------------------------------------------------------------------------------------------
# BRAIN vs LEAKY INTEGRATE-FIRE vs LIQUID STATE MACHINE
# ----------------------------------------------------------------------------------------------------------------------
plotting.boxplot(x='analysis', y='performance', df=new_df.copy(),
hue='analysis',
order=None,
xlim=None,
ylim=(-0.1,1.1),
width=0.7,
figsize=(8,8),
showfliers=True,
)
<file_sep>/01_rc_workflow/reservoir/tests.py
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 19:04:05 2021
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
from reservoir.tasks import io
#%%
io_kwargs = {'task':'sgnl_recon',
'task_ref':'T1',
'time_len':2050 # total number of training+test samples
}
inputs, outputs = io.get_io_data(**io_kwargs)
plt.plot(inputs[0], label='input')
plt.plot(outputs[0], label='target')
plt.legend()
plt.show()
plt.close()
#%%
# io_kwargs = {'task':'sgnl_recon',
# 'task_ref':'T2',
# 'step_len':50,
# 'bias':5,
# 'n_repeats':3
# }
# inputs, outputs = io.get_io_data(**io_kwargs)
# plt.plot(inputs[0], label='input')
# plt.plot(outputs[0], label='target')
# plt.legend()
# plt.show()
# plt.close()
#%%
# io_kwargs = {'task':'pttn_recog',
# 'task_ref':'T1',
# 'n_input_nodes':5,
# 'gain':3, # number of input nodes
# 'n_patterns':3, # number of patterns to classify
# 'n_repeats':50, # total number of training+test samples
# 'time_len':20 # length of each pattern
# }
# inputs, outputs = io.get_io_data(**io_kwargs)
# plt.plot(inputs[0][:20,0], label='pattern 1- node 1', c='yellow', marker='o')
# plt.plot(inputs[0][:20,1], label='pattern 1- node 2', c='blue', marker='o')
# plt.plot(inputs[0][:20,2], label='pattern 1- node 3', c='red', marker='o')
# plt.legend()
# plt.show()
# plt.close()
#%%
io_kwargs = {'task':'pttn_recog',
'task_ref':'T2',
'n_patterns':3, # number of patterns to classify
'n_repeats':50, # total number of training+test samples
'time_len':20 # length of each pattern
}
inputs, outputs = io.get_io_data(**io_kwargs)
plt.plot(inputs[0][:20], label='pattern 1', c='yellow', marker='o')
plt.plot(inputs[0][20:40], label='pattern 2', c='blue', marker='o')
plt.plot(inputs[0][40:60], label='pattern 3', c='red', marker='o')
plt.legend()
plt.show()
plt.close()
#%%\
def child_fcn(word='HOLA', **kwargs):
print(word)
def parent_fcn(a, b, c, **kwargs):
child_fcn(**kwargs)
return a+b+c
params = {}
d = parent_fcn(1,2,3, **params)
params = {'word':'HELLO'}
d = parent_fcn(1,2,3, **params)
d = parent_fcn(1,2,3, word='HELLO')
<file_sep>/03_analysis/fig3.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 11:06:24 2020
@author: <NAME>
"""
import os
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import numpy as np
import pandas as pd
from scipy import stats
from scipy.spatial import distance
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator)
from plotting import plotting
#%% --------------------------------------------------------------------------------------------------------------------
# GLOBAL VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
VERSION = 'V3'
TASK = 'pttn_recog' #'mem_cap' 'pttn_recog'
CONNECTOME = 'human_500'
CLASS = 'functional'
INPUTS = 'subctx'
#%% --------------------------------------------------------------------------------------------------------------------
# DIRECTORIES
# ----------------------------------------------------------------------------------------------------------------------
PROJ_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DATA_DIR = os.path.join(PROJ_DIR, 'data')
RAW_RES_DIR = os.path.join(PROJ_DIR, 'raw_results')
PROC_RES_DIR = os.path.join(PROJ_DIR, 'proc_results', VERSION, TASK)
coords = np.load(os.path.join(DATA_DIR, 'coords', f'coords_{CONNECTOME}.npy'))
dist = distance.cdist(coords, coords, 'euclidean')
#%% --------------------------------------------------------------------------------------------------------------------
# IMPORT DATA FUNCTIONS
# ----------------------------------------------------------------------------------------------------------------------
def load_avg_scores_per_alpha(analysis, coding):
RES_TSK_DIR = os.path.join(PROC_RES_DIR, 'tsk_results', analysis, f'{INPUTS}_scale{CONNECTOME[-3:]}')
avg_scores = pd.read_csv(os.path.join(RES_TSK_DIR, f'{CLASS}_avg_{coding}.csv'))
return avg_scores
#%% --------------------------------------------------------------------------------------------------------------------
# PI - ESTIMATING WIRING COST
# ----------------------------------------------------------------------------------------------------------------------
# load data
score = 'performance'
ANALYSES = ['reliability', 'significance']
df_brain_scores = []
for analysis in ANALYSES:
if analysis == 'reliability': conn_fname = 'consensus'
elif analysis == 'significance': conn_fname = 'rand_mio'
avg_scores = load_avg_scores_per_alpha(analysis, 'encoding')
avg_scores['cost'] = 0
# estimate wiring cost for every sample
for sample_id in np.unique(avg_scores.sample_id):
conn_wei = np.load(os.path.join(RAW_RES_DIR, 'conn_results', analysis, f'scale{CONNECTOME[-3:]}', f'{conn_fname}_{sample_id}.npy'))
conn_bin = conn_wei.copy().astype(bool).astype(int)
dist_ = (dist.copy()*conn_bin)[np.tril_indices_from(conn_bin, -1)]
dist_ = dist_[np.nonzero(dist_)]
wiring_density = (conn_wei*conn_bin)[np.tril_indices_from(conn_wei, -1)]
wiring_density = wiring_density[np.nonzero(wiring_density)]
cost = np.dot(dist_, wiring_density)
avg_scores.loc[avg_scores.sample_id == sample_id, 'cost'] = cost
df_brain_scores.append(avg_scores)
df_brain_scores = pd.concat(df_brain_scores)
# estimate and scale score to wiring cost ratio
df_brain_scores['score-to-wiring_cost ratio'] = df_brain_scores[score]/df_brain_scores['cost']
min_score = np.min(df_brain_scores['score-to-wiring_cost ratio'].values)
max_score = np.max(df_brain_scores['score-to-wiring_cost ratio'].values)
df_brain_scores['score-to-wiring_cost ratio'] = (df_brain_scores['score-to-wiring_cost ratio']-min_score)/(max_score-min_score)
#%% --------------------------------------------------------------------------------------------------------------------
# PII - SCORE TO WIRING COST RATIO
# ----------------------------------------------------------------------------------------------------------------------
score = 'score-to-wiring_cost ratio'
include_alpha = [0.3, 0.5, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 2.0, 2.5, 3.0, 3.5]
df_brain_scores = pd.concat([df_brain_scores.loc[np.isclose(df_brain_scores['alpha'], alpha), :] for alpha in include_alpha])\
.reset_index(drop=True)
plotting.boxplot(x='alpha', y=score, df=df_brain_scores.copy(),
palette=sns.color_palette('husl', 5),
hue='analysis',
order=None,
xlim=None,
ylim=(0,1),
legend=True,
width=0.8,
figsize=(22,8),
showfliers=True,
)
#%% --------------------------------------------------------------------------------------------------------------------
# PIII - STATISTICAL TESTS
# ----------------------------------------------------------------------------------------------------------------------
def cohen_d_2samp(x,y):
nx = len(x)
ny = len(y)
dof = nx + ny - 2
# 2 independent sample t test
return (np.mean(x) - np.mean(y)) / np.sqrt(((nx-1)*np.std(x, ddof=1) ** 2 + (ny-1)*np.std(y, ddof=1) ** 2) / dof)
#statistical tests
score = 'score-to-wiring_cost ratio'
include_alpha = [1.0] # [0.3, 0.5, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 2.0, 2.5, 3.0, 3.5]
for alpha in include_alpha:
print(f'\n---------------------------------------alpha: ... {alpha} ---------------------------------------')
brain = df_brain_scores.loc[(df_brain_scores.analysis == 'reliability') & (np.isclose(df_brain_scores['alpha'], alpha))]
rewir = df_brain_scores.loc[(df_brain_scores.analysis == 'significance') & (np.isclose(df_brain_scores['alpha'], alpha))]
print('Two-sample Wilcoxon-Mann-Whitney rank-sum test:')
print(f' Brain median: {np.nanmedian(brain[score].values)}')
print(f' Rewired median: {np.nanmedian(rewir[score].values)}')
# ----------------------------------------------------------------------------
# nonparametric Mann-Whitney U test
# empirical vs rewired null model
Urewir, mannu_p_rewir = stats.mannwhitneyu(brain[score].values[~np.isnan(brain[score].values)],
rewir[score].values[~np.isnan(rewir[score].values)],
alternative='two-sided'
)
Urewir = Urewir/(1000*1000)
print(f'\tmannU. pval - rewired: {mannu_p_rewir} Effect size: {Urewir}')
# ----------------------------------------------------------------------------
# parametric t-test
# empirical vs rewired null model
print('\n')
print('Two-sample student t-test:')
print(f' Brain mean: {np.nanmean(brain.performance.values)}')
print(f' Rewired mean: {np.nanmean(rewir.performance.values)}')
_, ttest_p_rewir = stats.ttest_ind(np.array(brain[score].values[~np.isnan(brain[score].values)]),
np.array(rewir[score].values[~np.isnan(rewir[score].values)]),
equal_var=False
)
eff_size_rewir = cohen_d_2samp(brain[score].values[~np.isnan(brain[score].values)], rewir[score].values[~np.isnan(rewir[score].values)])
print(f'\tttest. pval - rewired: {ttest_p_rewir} Effect size:{eff_size_rewir}')
# ----------------------------------------------------------------------------
# visual inspection
tmp_df_alpha = df_brain_scores.loc[np.isclose(df_brain_scores['alpha'], alpha), :]
sns.set(style="ticks", font_scale=2.0)
fig = plt.figure(figsize=(13,7))
ax = plt.subplot(111)
for analysis in ANALYSES:
sns.distplot(tmp_df_alpha.loc[tmp_df_alpha.analysis == analysis, score].values,
bins=50,
hist=False,
kde=True,
kde_kws={'shade':True},
label=analysis
)
ax.xaxis.set_major_locator(MultipleLocator(0.1))
ax.get_yaxis().set_visible(False)
ax.legend(fontsize=15, frameon=False, ncol=1, loc='upper right')
plt.title('memory capacity - to - wiring cost ratio')
sns.despine(offset=10, left=True, trim=True)
plt.show()
plt.close()
#%% --------------------------------------------------------------------------------------------------------------------
# PII - VISUAL INSPECTION CONNECTION LENGTH DISTRIBUTION
# ----------------------------------------------------------------------------------------------------------------------
# connection-length distribution for a single sample
sample_ids = np.unique(avg_scores.sample_id)
sample_id = np.random.choice(sample_ids, 1)[0]
sns.set(style="ticks", font_scale=2.0)
fig = plt.figure(figsize=(8,8))
ax = plt.subplot(111)
for analysis in ANALYSES:
if analysis == 'reliability': conn_fname = 'consensus'
elif analysis == 'significance': conn_fname = 'rand_mio'
conn_wei = np.load(os.path.join(RAW_RES_DIR, 'conn_results', analysis, f'scale{CONNECTOME[-3:]}', f'{conn_fname}_{sample_id}.npy'))
conn_bin = conn_wei.copy().astype(bool).astype(int)
dist_ = (dist.copy()*conn_bin)[np.tril_indices_from(conn_bin, -1)]
dist_ = dist_[np.nonzero(dist_)]
sns.distplot(dist_,
bins=50,
hist=False,
kde=True,
kde_kws={'shade':True},
label=analysis
)
ax.xaxis.set_major_locator(MultipleLocator(50))
ax.set_xlim(0, 200)
ax.get_yaxis().set_visible(False)
ax.legend(fontsize=15, frameon=False, ncol=1, loc='upper right')
plt.title('connection length distribution')
sns.despine(offset=10, left=True, trim=True)
plt.show()
plt.close()
<file_sep>/01_rc_workflow/reservoir_workflow.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 10:44:16 2021
@author: <NAME>
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = "1"
os.environ['MKL_NUM_THREADS'] = "1"
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import time
import sys, getopt
import configparser
import multiprocessing as mp
# from tqdm import tqdm
import numpy as np
from scipy.linalg import eigh
from scipy.spatial.distance import cdist
from netneurotools import networks
from rnns import (io_data, rnns, sim, nulls, coding, lyapunov)
#%% --------------------------------------------------------------------------------------------------------------------
# LOAD CONFIGURATION FILE
# ----------------------------------------------------------------------------------------------------------------------
try:
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, 'c:', ['config_file='])
except getopt.GetoptError:
print ('reservoir_workflow.py -c <config_file>')
sys.exit(2)
for opt, arg in opts:
if opt in ("-c", "--config_file"):
config_file = arg
# print ('CONFIGURATION FILE: ', config_file)
config = configparser.ConfigParser()
config.read(config_file)
#%% --------------------------------------------------------------------------------------------------------------------
# DYNAMIC VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
ANALYSIS = config['GENERAL']['analysis']
CONNECTOME = config['GENERAL']['connectome']
TASK = config['GENERAL']['task']
MODULES = config['GENERAL']['modules']
N_RUNS = int(config['GENERAL']['num_iters'])
N_PROCESS = int(config['GENERAL']['num_process'])
# --------------------------------------------------------------------------------------------------------------------
# CREATE DIRECTORIES
# ----------------------------------------------------------------------------------------------------------------------
PROJ_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.join(PROJ_DIR, 'data')
RAW_RES_DIR = os.path.join(PROJ_DIR, 'raw_results')
IO_TASK_DIR = os.path.join(RAW_RES_DIR, TASK, 'io_task')
RES_CONN_DIR = os.path.join(RAW_RES_DIR, 'conn_res', ANALYSIS, CONNECTOME)
RES_SIM_DIR = os.path.join(RAW_RES_DIR, TASK, 'sim_res', ANALYSIS, CONNECTOME)
RES_TSK_DIR = os.path.join(RAW_RES_DIR, TASK, 'tsk_res', ANALYSIS, CONNECTOME)
if not os.path.exists(IO_TASK_DIR): os.makedirs(IO_TASK_DIR)
if not os.path.exists(RES_CONN_DIR): os.makedirs(RES_CONN_DIR)
if not os.path.exists(RES_SIM_DIR): os.makedirs(RES_SIM_DIR)
if not os.path.exists(RES_TSK_DIR): os.makedirs(RES_TSK_DIR)
#%% --------------------------------------------------------------------------------------------------------------------
# FUNCTIONS
# ----------------------------------------------------------------------------------------------------------------------
def consensus_network(coords, hemiid, iter_id):
conn_file = f'consensus_{iter_id}.npy'
resampling_file = f'resampling_{iter_id}.npy'
if not os.path.exists(os.path.join(RES_CONN_DIR, conn_file)):
def bootstrapp(n, exclude=None):
# create a list of samples
samples = np.arange(n)
# discard samples indicated in exclude
if exclude is not None: samples = np.delete(samples, exclude)
# bootstrapp resampling
samples = np.random.choice(samples, size=len(samples), replace=True)
return samples
# load connectivity data
CONN_DIR = os.path.join(DATA_DIR, 'connectivity', 'individual')
stru_conn = np.load(os.path.join(CONN_DIR, f'{CONNECTOME}.npy'))
# remove bad subjects
bad_subj = [7, 12, 43] #SC:7,12,43 #FC:32
bad_subj.extend(np.unique(np.where(np.isnan(stru_conn))[-1]))
# bootstrapp resampling
resampling = bootstrapp(n=stru_conn.shape[2], exclude=bad_subj)
stru_conn_avg = networks.struct_consensus(data=stru_conn.copy()[:,:,resampling],
distance=cdist(coords, coords, metric='euclidean'),
hemiid=hemiid[:, np.newaxis]
)
stru_conn_avg = stru_conn_avg*np.mean(stru_conn, axis=2)
np.save(os.path.join(RES_CONN_DIR, conn_file), stru_conn_avg)
np.save(os.path.join(RES_CONN_DIR, resampling_file), resampling)
def rewired_network(model_name, iter_id, **kwargs):
conn_file = f'{model_name}_{iter_id}.npy'
if not os.path.exists(os.path.join(RES_CONN_DIR, conn_file)):
new_conn = nulls.construct_null_model(model_name, **kwargs)
np.save(os.path.join(RES_CONN_DIR, conn_file), new_conn)
def workflow(conn_file, input_nodes, output_nodes, gain, readout_modules, id_number=None, \
alphas=[1.0], io_kwargs={}, sim_kwargs={}, task_kwargs={}, \
bin=False, iter_conn=True, iter_io=False, iter_sim=False, \
encode=True, decode=True, **kwargs):
# --------------------------------------------------------------------------------------------------------------------
# DEFINE FILE NAMES
# ----------------------------------------------------------------------------------------------------------------------
# define file connectivity data
if np.logical_and(id_number is not None, iter_conn):
conn_file = f'{conn_file}_{id_number}.npy'
else: conn_file = f'{conn_file}.npy'
# define file I/O data
if np.logical_and(id_number is not None, iter_io):
input_file = f'inputs_{id_number}.npy'
output_file = f'outputs_{id_number}.npy'
else:
input_file = 'inputs.npy'
output_file = 'outputs.npy'
# define file simulation data (reservoir states)
if np.logical_and(id_number is not None, iter_sim):
res_states_file = f'reservoir_states_{id_number}.npy'
else:
res_states_file = 'reservoir_states.npy'
# define file encoding/decoding scores data
if id_number is not None:
encoding_file = f'encoding_score_{id_number}.csv'
decoding_file = f'decoding_score_{id_number}.csv'
else:
encoding_file = 'encoding_score.csv'
decoding_file = 'decoding_score.csv'
if os.path.exists(os.path.join(RES_TSK_DIR, encoding_file)):
return
#%% --------------------------------------------------------------------------------------------------------------------
# IMPORT CONNECTIVITY DATA
# ----------------------------------------------------------------------------------------------------------------------
print("\tLoading connectivity data ...")
# load connectivity data
conn = np.load(os.path.join(RES_CONN_DIR, conn_file))
# scale weights [0,1]
if bin: conn = conn.astype(bool).astype(int)
else: conn = (conn-conn.min())/(conn.max()-conn.min())
# normalize by the spectral radius
ew, _ = eigh(conn)
conn = conn/np.max(ew)
# --------------------------------------------------------------------------------------------------------------------
# CREATE I/O DATA FOR TASK
# ----------------------------------------------------------------------------------------------------------------------
if not os.path.exists(os.path.join(IO_TASK_DIR, input_file)):
print("\tGenerating IO data ...")
x, y = io_data.generate_IOData(TASK, **io_kwargs)
np.save(os.path.join(IO_TASK_DIR, input_file), x)
np.save(os.path.join(IO_TASK_DIR, output_file), y)
# --------------------------------------------------------------------------------------------------------------------
# NETWORK SIMULATION
# ----------------------------------------------------------------------------------------------------------------------
reservoir_states = None
if not os.path.exists(os.path.join(RES_SIM_DIR, res_states_file)):
print("\tSimulating network ...")
X = np.load(os.path.join(IO_TASK_DIR, input_file))
# fully connected input layer
w_in = np.zeros((len(conn), X.shape[-1]))
w_in[input_nodes] = gain
# simulate network
states_train, states_test = sim.run_multiple_sim(w_ih=w_in,
w_hh=conn,
inputs=X,
alphas=alphas,
**sim_kwargs
)
reservoir_states = [(rs_train, rs_test) for rs_train, rs_test in zip(states_train, states_test)]
np.save(os.path.join(RES_SIM_DIR, res_states_file), reservoir_states, allow_pickle=False)
# --------------------------------------------------------------------------------------------------------------------
# IMPORT I/O DATA FOR TASK
# ----------------------------------------------------------------------------------------------------------------------
if reservoir_states is None:
print("\tUploading networks states ...")
reservoir_states = np.load(os.path.join(RES_SIM_DIR, res_states_file), allow_pickle=True)
else:
reservoir_states = np.array(reservoir_states)
reservoir_states = reservoir_states[:, :, :, output_nodes]
reservoir_states = reservoir_states.squeeze()
reservoir_states = np.split(reservoir_states, len(reservoir_states), axis=0)
reservoir_states = [rs.squeeze() for rs in reservoir_states]
y = np.load(os.path.join(IO_TASK_DIR, output_file))
# --------------------------------------------------------------------------------------------------------------------
# PERFORM TASK - ENCODERS
# ---------------------------------------------------------------------------------------------------------------------- #
# try:
if np.logical_and(encode, not os.path.exists(os.path.join(RES_TSK_DIR, encoding_file))):
print(" Performing task ...")
df_encoding = coding.encoder(task=TASK,
reservoir_states=reservoir_states,
target=y,
readout_modules=readout_modules,
alphas=alphas,
**task_kwargs
)
df_encoding.to_csv(os.path.join(RES_TSK_DIR, encoding_file))
# except:
# pass
#
# delete reservoir states to release memory storage
if iter_sim:
# os.remove(os.path.join(path_res_sim, res_states_file))
pass
def run_workflow(iter_id, **kwargs):
# --------------------------------------------------------------------------------------------------------------------
# CREATE CONSENSUS MATRICES
# ----------------------------------------------------------------------------------------------------------------------
print("Creating consensus network ...")
ctx = np.load(os.path.join(DATA_DIR, 'cortical', f'cortical_{CONNECTOME}.npy'))
coords = np.load(os.path.join(DATA_DIR, 'coords', f'coords_{CONNECTOME}.npy'))
hemiid = np.load(os.path.join(DATA_DIR, 'hemispheres', f'hemiid_{CONNECTOME}.npy'))
consensus_network(coords, hemiid, iter_id)
# --------------------------------------------------------------------------------------------------------------------
# DEFINE MODULES
# ----------------------------------------------------------------------------------------------------------------------
print("Defining modules ...")
if MODULES == 'functional':
modules = np.load(os.path.join(DATA_DIR, 'rsn_mapping', f'rsn_{CONNECTOME}.npy'))
elif MODULES == 'cytoarch':
modules = np.load(os.path.join(DATA_DIR, 'cyto_mapping', f'cyto_{CONNECTOME}.npy'))
# --------------------------------------------------------------------------------------------------------------------
# DEFINE OTHER VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
print("Defining other variables ...")
if ANALYSIS == 'reliability':
conn_name = 'consensus'
modules = modules[ctx == 1]
elif ANALYSIS == 'significance':
conn_name = 'rand_mio'
modules = modules[ctx == 1]
# create rewired network
conn = np.load(os.path.join(RES_CONN_DIR, f'consensus_{iter_id}.npy'))
try:
rewired_network(iter_id,
model_name=conn_name,
conn=conn,
swaps=10
)
except:
pass
elif ANALYSIS == 'spintest':
conn_name = 'consensus'
spins = np.genfromtxt(os.path.join(DATA_DIR, 'spin_test', f'spin_{CONNECTOME}.csv'), delimiter=',').astype(int)
modules = modules[ctx == 1][spins[:, iter_id]]
# --------------------------------------------------------------------------------------------------------------------
# RUN WORKFLOW
# ----------------------------------------------------------------------------------------------------------------------
print("\nRunning workflow ...")
if 'IO_PARAMS' in config: io_kwargs = {k:int(v) for k,v in config['IO_PARAMS'].items()}
else: io_kwargs = {}
if 'ALT_SIM_PARAMS' in config: sim_kwargs = {k:v for k,v in config['ALT_SIM_PARAMS'].items()}
else: sim_kwargs = {}
if TASK == 'pttn_recog':
time_lens = io_kwargs['time_len']*np.ones(int(0.5*io_kwargs['n_patterns']*io_kwargs['n_repeats']), dtype=int)
task_kwargs = {'pttn_lens':time_lens}
else:
task_kwargs = {}
try:
workflow(conn_file=conn_name,
input_nodes=np.where(ctx==0)[0], # internal input nodes
output_nodes=np.where(ctx==1)[0], # internal output nodes
gain=float(config['SIM_PARAMS']['gain']),
readout_modules=modules, # only output nodes i.e., only for ctx
id_number=iter_id,
alphas=eval(config['SIM_PARAMS']['alphas']),
io_kwargs=io_kwargs,
sim_kwargs=sim_kwargs,
task_kwargs=task_kwargs,
iter_conn=config.getboolean('WORKFLOW','iter_conn'),
iter_io=config.getboolean('WORKFLOW','iter_io'),
iter_sim=config.getboolean('WORKFLOW','iter_sim'),
encode=config.getboolean('WORKFLOW','encode'),
decode=config.getboolean('WORKFLOW','decode')
)
except:
pass
def main():
print (f'\nINITIATING PROCESSING TIME - {ANALYSIS.upper()} for {CONNECTOME.upper()}')
t0 = time.perf_counter()
# # run iteration No. 0
# run_workflow(iter_id=0)
# run iterations No. 1-1000 in parallel
start = 89
params = [{'iter_id': i} for i in range(start, N_RUNS)]
pool = mp.Pool(processes=N_PROCESS)
res = [pool.apply_async(run_workflow, (), p) for p in params]
for r in res: r.get()
pool.close()
print (f'\nTOTAL PROCESSING TIME - {ANALYSIS.upper()}')
print (time.perf_counter()-t0, "seconds process time")
print ('END')
if __name__ == '__main__':
main()
<file_sep>/01_rc_workflow/mem_cap.ini
[GENERAL]
analysis = reliability
connectome = human_500
task = mem_cap
modules = functional
num_iters = 100
num_process = 20
[WORKFLOW]
iter_conn = True
iter_io = False
iter_sim = True
encode = True
decode = False
[IO_PARAMS]
time_len = 2000
[SIM_PARAMS]
gain = 0.0001
alphas = np.linspace(0.5, 1.5, 21)
<file_sep>/02_fetch_results/fetch_task_results.py
"""
Created on Mon Jul 6 11:06:24 2020
@author: <NAME>
"""
import os
import numpy as np
import pandas as pd
#%% --------------------------------------------------------------------------------------------------------------------
# GLOBAL DYNAMIC VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
#%% --------------------------------------------------------------------------------------------------------------------
# GLOBAL STATIC VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
PROJ_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DATA_DIR = os.path.join(PROJ_DIR, 'data')
RAW_RES_DIR = os.path.join(PROJ_DIR, 'raw_results')
PROC_RES_DIR = os.path.join(PROJ_DIR, 'proc_results')
# --------------------------------------------------------------------------------------------------------------------
# GENERAL
# ----------------------------------------------------------------------------------------------------------------------
def sort_class_labels(class_labels):
if 'subctx' in class_labels:
rsn_labels = ['VIS', 'SM', 'DA', 'VA', 'LIM', 'FP', 'DMN', 'subctx']
else:
rsn_labels = ['VIS', 'SM', 'DA', 'VA', 'LIM', 'FP', 'DMN']
if class_labels.all() in rsn_labels:
return np.array([clase for clase in rsn_labels if clase in class_labels])
else:
return class_labels
def concatenate_tsk_results(path, coding, scores2return, include_alpha, n_samples=1000):
df_scores = []
df_avg_scores_per_class = []
df_avg_scores_per_alpha = []
for sample_id in range(n_samples):
succes_sample = True
try:
# print(f'sample_id: {sample_id}')
scores = pd.read_csv(os.path.join(path, f'{coding}_score_{sample_id}.csv')).reset_index(drop=True)
except:
succes_sample = False
print('\n Could not find sample No. ' + str(sample_id))
pass
if succes_sample:
# all scores (per alpha and per class)
if 'scores' in scores2return:
scores['coding'] = coding
scores['sample_id'] = sample_id
df_scores.append(scores[['sample_id', 'coding', 'module', 'alpha', 'performance', 'capacity', 'n_nodes']])
# avg scores across alphas per class
if 'avg_scores_per_class' in scores2return:
avg_scores_per_class = get_avg_scores_per_class(scores.copy(),
include_alpha=include_alpha,
coding=coding
)
avg_scores_per_class['coding'] = coding
avg_scores_per_class['sample_id'] = sample_id
df_avg_scores_per_class.append(avg_scores_per_class[['sample_id', 'coding', 'module', 'performance', 'capacity', 'n_nodes']])
# avg scores across classes per alpha
if 'avg_scores_per_alpha' in scores2return:
avg_scores_per_alpha = get_avg_scores_per_alpha(scores.copy(),
include_alpha=None,
coding=coding
)
avg_scores_per_alpha['coding'] = coding
avg_scores_per_alpha['sample_id'] = sample_id
df_avg_scores_per_alpha.append(avg_scores_per_alpha[['sample_id', 'coding', 'alpha', 'performance', 'capacity', 'n_nodes']])
res_dict = {}
if 'scores' in scores2return:
df_scores = pd.concat(df_scores).reset_index(drop=True)
res_dict['scores'] = df_scores
if 'avg_scores_per_class' in scores2return:
df_avg_scores_per_class = pd.concat(df_avg_scores_per_class).reset_index(drop=True)
res_dict['avg_scores_per_class'] = df_avg_scores_per_class
if 'avg_scores_per_alpha' in scores2return:
df_avg_scores_per_alpha = pd.concat(df_avg_scores_per_alpha).reset_index(drop=True)
res_dict['avg_scores_per_alpha'] = df_avg_scores_per_alpha
return res_dict
def get_avg_scores_per_class(df_scores, include_alpha, coding='encoding'):
if include_alpha is None: include_alpha = np.unique(df_scores['alpha'])
# get class labels
class_labels = sort_class_labels(np.unique(df_scores['module']))
# filter scores by values of alpha
df_scores = pd.concat([df_scores.loc[np.isclose(df_scores['alpha'], alpha), :] for alpha in include_alpha])
# average scores across alphas per class
avg_scores = []
for clase in class_labels:
tmp = df_scores.loc[df_scores['module'] == clase, ['performance', 'capacity', 'n_nodes']]\
.reset_index(drop=True)
avg_scores.append(tmp.mean())
avg_scores = pd.concat(avg_scores, axis=1).T
# dataFrame with avg coding scores per class
df_avg_scores = pd.DataFrame(data = np.column_stack((class_labels, avg_scores)),
columns = ['module', 'performance', 'capacity', 'n_nodes'],
).reset_index(drop=True)
df_avg_scores['performance'] = df_avg_scores['performance'].astype('float')
df_avg_scores['capacity'] = df_avg_scores['capacity'].astype('float')
df_avg_scores['n_nodes'] = df_avg_scores['n_nodes'].astype('float').astype('int')
return df_avg_scores
def get_avg_scores_per_alpha(df_scores, include_alpha, coding='encoding'):
if include_alpha is None: include_alpha = np.unique(df_scores['alpha'])
# average scores across alphas per class
avg_scores = []
for alpha in include_alpha:
tmp = df_scores.loc[np.isclose(df_scores['alpha'], alpha), ['performance', 'capacity', 'n_nodes']]\
.reset_index(drop=True)
avg_scores.append(tmp.mean())
avg_scores = pd.concat(avg_scores, axis=1).T
# dataFrame with avg coding scores per class
df_avg_scores = pd.DataFrame(data = np.column_stack((include_alpha, avg_scores)),
columns = ['alpha', 'performance', 'capacity', 'n_nodes'],
).reset_index(drop=True)
df_avg_scores['performance'] = df_avg_scores['performance'].astype('float')
df_avg_scores['capacity'] = df_avg_scores['capacity'].astype('float')
df_avg_scores['n_nodes'] = df_avg_scores['n_nodes'].astype('float').astype('int')
return df_avg_scores
#%% --------------------------------------------------------------------------------------------------------------------
def concat_tsk_results(connectome, task, analysis, dynamics, coding='encoding', n_samples=1000):
"""
connectome (str): 'human_250', 'human_500'
analysis (str): 'reliability', 'significance', 'spintest'
dynamics (str): 'stable', 'critical', 'chaotic'
"""
output_dir = os.path.join(PROC_RES_DIR, task, analysis, connectome)
if not os.path.exists(output_dir): os.makedirs(output_dir)
outputs = {
'scores':os.path.join(output_dir, f'{coding}.csv'),
'avg_scores_per_alpha':os.path.join(output_dir, f'avg_{coding}.csv'),
'avg_scores_per_class':os.path.join(output_dir, f'avg_{coding}_{dynamics}.csv')
}
include_alpha = {
'stable':np.linspace(0.5, 0.95, 10),
'critical':[1.0],
'chaotic':np.linspace(1.05, 1.5, 10)
}
scores2return = []
for output, path in outputs.items():
if not os.path.exists(path):
scores2return.append(output)
input_dir = os.path.join(RAW_RES_DIR, task, 'tsk_res', analysis, connectome)
res = concatenate_tsk_results(path=input_dir,
coding=coding,
scores2return=scores2return,
include_alpha=include_alpha[dynamics],
n_samples=n_samples,
)
for coding_score, df in res.items():
df['analysis'] = analysis
df.to_csv(outputs[coding_score], index=False)
#%% --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
CONNECTOMES = [
# 'human_250',
'human_500',
]
TASKS = [
'mem_cap',
'pttn_recog'
]
ANALYSES = {
'reliability':100,
# 'significance':1000,
# 'spintest':1000,
}
DYNAMICS = [
'stable',
'critical',
'chaotic',
]
for connectome in CONNECTOMES[::-1]:
for analysis, n_samples in ANALYSES.items():
for dyn_regime in DYNAMICS:
for task in TASKS:
concat_tsk_results(connectome,
task,
analysis,
dyn_regime,
coding='encoding',
n_samples=n_samples
)
# concat_tsk_results(connectome,
# analysis,
# dyn_regime,
# coding='decoding',
# n_samples=n_samples
# )
<file_sep>/01_rc_workflow/reservoir/reservoir_workflow.py
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 3 15:27:07 2020
@author: <NAME>
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = "1"
os.environ['MKL_NUM_THREADS'] = "1"
import configparser
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import time
import numpy as np
import pandas as pd
import multiprocessing as mp
import scipy.io as sio
from scipy.linalg import (eig, eigh)
from scipy.spatial.distance import cdist
from reservoir.network import nulls
from reservoir.tasks import (io, coding, tasks)
from reservoir.simulator import sim_lnm
from netneurotools import networks
#%% --------------------------------------------------------------------------------------------------------------------
# DYNAMIC GLOBAL VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
params_config = configparser.ConfigParser()
params_config.read('pttn_recog.ini')
# params_config.read('mem_cap.ini')
INPUTS = params_config['network']['network_inputs']
CLASS = params_config['network']['network_partition']
TASK = params_config['task_params']['task']
SPEC_TASK = params_config['task_params']['specific_task']
TASK_REF = params_config['task_params']['task_reference']
FACTOR = float(params_config['task_params']['input_gain'])
N_PROCESS = int(params_config['parall_params']['num_process'])
N_RUNS = int(params_config['parall_params']['num_iters'])
#%% --------------------------------------------------------------------------------------------------------------------
# STATIC GLOBAL VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
PROJ_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DATA_DIR = os.path.join(PROJ_DIR, 'data')
RAW_RES_DIR = os.path.join(PROJ_DIR, 'raw_results')
#%% --------------------------------------------------------------------------------------------------------------------
# FUNCTIONS
# ----------------------------------------------------------------------------------------------------------------------
def load_metada(connectome):
if CLASS == 'functional':
class_mapping = np.load(os.path.join(DATA_DIR, 'rsn_mapping', f'rsn_{connectome}.npy'))
elif CLASS == 'cytoarch':
class_mapping = np.load(os.path.join(DATA_DIR, 'cyto_mapping', f'cyto_{connectome}.npy'))
return class_mapping
def consensus_network(connectome, coords, hemiid, path_res_conn, iter_id):
conn_file = f'consensus_{iter_id}.npy'
resampling_file = f'resampling_{iter_id}.npy'
if not os.path.exists(os.path.join(path_res_conn, conn_file)):
def bootstrapp(n, exclude=None):
# create a list of samples
samples = np.arange(n)
# discard samples indicated in exclude
if exclude is not None: samples = np.delete(samples, exclude)
# bootstrapp resampling
samples = np.random.choice(samples, size=len(samples), replace=True)
return samples
# load connectivity data
CONN_DIR = os.path.join(DATA_DIR, 'connectivity', 'individual')
stru_conn = np.load(os.path.join(CONN_DIR, connectome + '.npy'))
# remove bad subjects
bad_subj = [7, 12, 43] #SC:7,12,43 #FC:32
bad_subj.extend(np.unique(np.where(np.isnan(stru_conn))[-1]))
# bootstrapp resampling
resampling = bootstrapp(n=stru_conn.shape[2], exclude=bad_subj)
stru_conn_avg = networks.struct_consensus(data=stru_conn.copy()[:,:,resampling],
distance=cdist(coords, coords, metric='euclidean'),
hemiid=hemiid[:, np.newaxis]
)
stru_conn_avg = stru_conn_avg*np.mean(stru_conn, axis=2)
np.save(os.path.join(path_res_conn, conn_file), stru_conn_avg)
np.save(os.path.join(path_res_conn, resampling_file), resampling)
def rewire_network(path_res_conn, iter_id, model_name, **kwargs):
conn_file = f'{model_name}_{iter_id}.npy'
if not os.path.exists(os.path.join(path_res_conn, conn_file)):
new_conn = nulls.construct_null_model(model_name, **kwargs)
np.save(os.path.join(path_res_conn, conn_file), new_conn)
def workflow(conn_name, io_nodes, readout_modules, \
path_res_conn, path_io, path_res_sim, path_res_tsk, \
iter_id=None, bin=False, alphas=None, partition_name=None, \
iter_conn=True, iter_io=False, iter_sim=False, \
encode=True, decode=True, **kwargs):
"""
Runs the full pipeline: loads and scales connectivity matrix, generates
input/output data for the task, simulates reservoir states, and trains
the readout module.
Parameters
----------
conn_name: str, {'consensus', 'rewired'}
Specifies the name of the connectivity matrix file
io_nodes: (N,) numpy.darray
Binary array that indicates input and output nodes in the recurrent
network. 1 for input, 0 for output.
N: number of nodes in the network
readout_modules: (N, ) numpy.darray
Array that indicates the module at which each output node belongs
to. Modules can be int or str
N: number of output nodes
path_res_conn : str
Path to conenctivity matrix
path_io : str
Path to simulation results
path_res_sim : str
Path to simulation results
path_res_tsk : str
Path to task scores
bin : bool
If True, the binary matrix will be used
partition_name : str, {'functional', 'cytoarch'}
Name of the partition used
iter_id : int
Number/name of the iteration
iter_{conn,io,sim} : bool
If True, specific instances (i.e., connectivity, input/output data,
network states) related to the iteration indicated by iter_id will
be used.
encode,decode : bool
If True, encoding,decoding will run
"""
# --------------------------------------------------------------------------------------------------------------------
# DEFINE FILE NAMES
# ----------------------------------------------------------------------------------------------------------------------
# define file connectivity data
if np.logical_and(iter_id is not None, iter_conn):
conn_file = f'{conn_name}_{iter_id}.npy'
else: conn_file = f'{conn_name}.npy'
# define file I/O data
if np.logical_and(iter_id is not None, iter_io):
input_file = f'inputs_{iter_id}.npy'
output_file = f'outputs_{iter_id}.npy'
else:
input_file = 'inputs.npy'
output_file = 'outputs.npy'
# define file simulation data (reservoir states)
if np.logical_and(iter_id is not None, iter_sim):
res_states_file = f'reservoir_states_{iter_id}.npy'
else:
res_states_file = 'reservoir_states.npy'
# define file encoding/decoding scores data
if np.logical_and(iter_id is not None, partition_name is not None):
encoding_file = f'{partition_name}_encoding_score_{iter_id}.csv'
decoding_file = f'{partition_name}_decoding_score_{iter_id}.csv'
elif np.logical_and(iter_id is not None, partition_name is None):
encoding_file = f'encoding_score_{iter_id}.csv'
decoding_file = f'decoding_score_{iter_id}.csv'
elif np.logical_and(iter_id is None, partition_name is not None):
encoding_file = f'{partition_name}_encoding_score.csv'
decoding_file = f'{partition_name}_decoding_score.csv'
else:
encoding_file = 'encoding_score.csv'
decoding_file = 'decoding_score.csv'
#%% --------------------------------------------------------------------------------------------------------------------
# IMPORT CONNECTIVITY DATA
# ----------------------------------------------------------------------------------------------------------------------
# load connectivity data
conn = np.load(os.path.join(path_res_conn, conn_file))
# scale weights [0,1]
if bin: conn = conn.astype(bool).astype(int)
else: conn = (conn-conn.min())/(conn.max()-conn.min())
# normalize by the spectral radius
if nulls.check_symmetric(conn):
ew, _ = eigh(conn)
else:
ew, _ = eig(conn)
conn = conn/np.max(ew)
# --------------------------------------------------------------------------------------------------------------------
# CREATE I/O DATA FOR TASK
# ----------------------------------------------------------------------------------------------------------------------
# memory capacity task kwargs
if TASK == 'sgnl_recon':
io_kwargs = {'task':TASK,
'task_ref':TASK_REF,
'time_len':2000 # number of training/test samples
}
pttn_recog_kwargs = {}
# pattern recognition task kwargs
elif TASK == 'pttn_recog':
n_patterns = 10
n_repeats = 500
time_len = 20 #20
io_kwargs = {'task':TASK,
'task_ref':TASK_REF,
'n_patterns':n_patterns, # number of patterns to classify
'n_repeats':n_repeats, # total number of training+test samples per pattern
'time_len':time_len, # length of each pattern
'gain':3.0,
}
# 0.5 is the training/text proportion
pttn_recog_kwargs = {'time_lens':time_len*np.ones(int(0.5*n_patterns*n_repeats), dtype=int)}
if not os.path.exists(os.path.join(path_io, input_file)):
inputs, outputs = io.get_io_data(**io_kwargs)
np.save(os.path.join(path_io, input_file), inputs)
np.save(os.path.join(path_io, output_file), outputs)
# --------------------------------------------------------------------------------------------------------------------
# NETWORK SIMULATION - LINEAR MODEL
# ----------------------------------------------------------------------------------------------------------------------
if alphas is None: alphas = tasks.get_default_alpha_values(SPEC_TASK)
if not os.path.exists(os.path.join(path_res_sim, res_states_file)):
input_train, input_test = np.load(os.path.join(path_io, input_file))
# create input connectivity matrix
w_in = np.zeros((input_train.shape[1],len(conn)))
w_in[:,io_nodes == 1] = FACTOR # fully connected input layer
# w_in = FACTOR * np.ones((input_train.shape[1],len(conn)))
reservoir_states_train = sim_lnm.run_sim(w_in=w_in,
w=conn,
inputs=input_train,
alphas=alphas,
)
reservoir_states_test = sim_lnm.run_sim(w_in=w_in,
w=conn,
inputs=input_test,
alphas=alphas,
)
reservoir_states = [(rs_train, rs_test) for rs_train, rs_test in zip(reservoir_states_train, reservoir_states_test)]
np.save(os.path.join(path_res_sim, res_states_file), reservoir_states, allow_pickle=False)
# --------------------------------------------------------------------------------------------------------------------
# IMPORT I/O DATA FOR TASK
# ----------------------------------------------------------------------------------------------------------------------
reservoir_states = np.load(os.path.join(path_res_sim, res_states_file), allow_pickle=True)
reservoir_states = reservoir_states[:, :, :, io_nodes==0]
reservoir_states = reservoir_states.squeeze()
reservoir_states = np.split(reservoir_states, len(reservoir_states), axis=0)
reservoir_states = [rs.squeeze() for rs in reservoir_states]
outputs = np.load(os.path.join(path_io, output_file))
# --------------------------------------------------------------------------------------------------------------------
# PERFORM TASK - ENCODERS
# ----------------------------------------------------------------------------------------------------------------------
try:
if np.logical_and(encode, not os.path.exists(os.path.join(path_res_tsk, encoding_file))):
print('\nEncoding: ')
df_encoding = coding.encoder(task=SPEC_TASK,
target=outputs,
reservoir_states=reservoir_states,
readout_modules=readout_modules,
alphas=alphas,
**pttn_recog_kwargs
)
df_encoding.to_csv(os.path.join(path_res_tsk, encoding_file))
except:
pass
# --------------------------------------------------------------------------------------------------------------------
# PERFORM TASK - DECODERS
# ----------------------------------------------------------------------------------------------------------------------
try:
if np.logical_and(decode, not os.path.exists(os.path.join(path_res_tsk, decoding_file))):
# binarize cortical adjacency matrix
conn_bin = conn.copy()[np.ix_(np.where(io_nodes==0)[0], np.where(io_nodes==0)[0])].astype(bool).astype(int)
print('\nDecoding: ')
df_decoding = coding.decoder(task=SPEC_TASK,
target=outputs,
reservoir_states=reservoir_states,
readout_modules=readout_modules,
bin_conn=conn_bin,
alphas=alphas,
**pttn_recog_kwargs
)
df_decoding.to_csv(os.path.join(path_res_tsk, decoding_file))
except:
pass
# delete reservoir states to release memory storage
if iter_sim:
os.remove(os.path.join(path_res_sim, res_states_file))
pass
#%% --------------------------------------------------------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------------------------------------------------------
def run_workflow(analysis, connectome, iter_id, **kwargs):
# --------------------------------------------------------------------------------------------------------------------
# CREATE DIRECTORIES
# ----------------------------------------------------------------------------------------------------------------------
IO_TASK_DIR = os.path.join(RAW_RES_DIR, SPEC_TASK, 'io_tasks')
RES_CONN_DIR = os.path.join(RAW_RES_DIR, 'conn_results', analysis, f'scale{connectome[-3:]}')
RES_SIM_DIR = os.path.join(RAW_RES_DIR, SPEC_TASK, 'sim_results', analysis, f'{INPUTS}_scale{connectome[-3:]}')
RES_TSK_DIR = os.path.join(RAW_RES_DIR, SPEC_TASK, 'tsk_results', analysis, f'{INPUTS}_scale{connectome[-3:]}')
if not os.path.exists(IO_TASK_DIR): os.makedirs(IO_TASK_DIR)
if not os.path.exists(RES_CONN_DIR): os.makedirs(RES_CONN_DIR)
if not os.path.exists(RES_SIM_DIR): os.makedirs(RES_SIM_DIR)
if not os.path.exists(RES_TSK_DIR): os.makedirs(RES_TSK_DIR)
# --------------------------------------------------------------------------------------------------------------------
# LOAD METADATA
# ----------------------------------------------------------------------------------------------------------------------
class_mapping = load_metada(connectome)
ctx = np.load(os.path.join(DATA_DIR, 'cortical', f'cortical_{connectome}.npy'))
coords = np.load(os.path.join(DATA_DIR, 'coords', f'coords_{connectome}.npy'))
hemiid = np.load(os.path.join(DATA_DIR, 'hemispheres', f'hemiid_{connectome}.npy'))
# --------------------------------------------------------------------------------------------------------------------
# CREATE CONSENSUS MATRICES
# ----------------------------------------------------------------------------------------------------------------------
consensus_network(connectome,
coords,
hemiid,
RES_CONN_DIR,
iter_id,
)
# --------------------------------------------------------------------------------------------------------------------
# DEFINE PARAMS
# ----------------------------------------------------------------------------------------------------------------------
if analysis == 'reliability':
conn_name = 'consensus'
class_mapping = class_mapping[ctx == 1]
elif analysis == 'significance':
conn_name = 'rand_mio'
class_mapping = class_mapping[ctx == 1]
# create rewired network
conn = np.load(os.path.join(RES_CONN_DIR, f'consensus_{iter_id}.npy'))
try:
rewire_network(RES_CONN_DIR,
iter_id,
model_name=conn_name,
conn=conn,
swaps=10
)
except:
pass
elif analysis == 'spintest':
conn_name = 'consensus'
spins = np.genfromtxt(os.path.join(DATA_DIR, 'spin_test', f'spin_{connectome}.csv'), delimiter=',').astype(int)
class_mapping = class_mapping[ctx == 1][spins[:, iter_id]]
# --------------------------------------------------------------------------------------------------------------------
# RUN WORKFLOW
# ----------------------------------------------------------------------------------------------------------------------
try:
workflow(conn_name=conn_name,
io_nodes=np.logical_not(ctx).astype(int), # input and output nodes i.e., ctx + subctx
readout_modules=class_mapping, # only output nodes i.e., only for ctx
iter_id=iter_id,
iter_conn=True,
iter_io=False,
iter_sim=True,
encode=True,
decode=False,
path_res_conn=RES_CONN_DIR,
path_io=IO_TASK_DIR,
path_res_sim=RES_SIM_DIR,
path_res_tsk=RES_TSK_DIR,
partition_name=CLASS,
)
except:
pass
def main():
ANALYSIS = [
'reliability',
# 'significance',
# 'spintest'
]
for analysis in ANALYSIS:
connectome = 'human_500'
print (f'INITIATING PROCESSING TIME - {analysis.upper()}')
t0_1 = time.perf_counter()
# run iteration No. 0
run_workflow(analysis,
connectome,
iter_id=0, #np.random.randint(1,1000,1)[0],
)
# # run iterations No. 1-1000 in parallel
# start = 1
# params = []
# for i in range(start, N_RUNS):
# params.append({
# 'analysis':analysis,
# 'connectome':connectome,
# 'iter_id': i,
# })
# pool = mp.Pool(processes=N_PROCESS)
# res = [pool.apply_async(run_workflow, (), p) for p in params]
# for r in res: r.get()
# pool.close()
print (f'PROCESSING TIME - {analysis.upper()}')
print (time.perf_counter()-t0_1, "seconds process time")
# print (time.time()-t0_2, "seconds wall time")
print('END')
if __name__ == '__main__':
main()
<file_sep>/01_rc_workflow/reservoir/mem_cap.ini
[task_params]
task = sgnl_recon
specific_task = mem_cap
task_reference = T1
input_gain = 0.0001
[network]
connectome = human_500
network_inputs = subctx
network_partition = functional
[parall_params]
num_process = 1
num_iters = 100
<file_sep>/01_rc_workflow/pttn_recog.ini
[GENERAL]
analysis = reliability
connectome = human_500
task = pttn_recog
modules = functional
num_iters = 100
num_process = 8
[WORKFLOW]
iter_conn = True
iter_io = False
iter_sim = True
encode = True
decode = False
[IO_PARAMS]
time_len = 25
n_input_nodes = 1
n_patterns = 10
n_repeats = 250
input_gain = 3
[SIM_PARAMS]
gain = 0.1
alphas = np.linspace(0.5, 1.5, 21)
<file_sep>/03_analysis/fig2.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 11:06:24 2020
@author: <NAME>
"""
import os
import warnings
warnings.simplefilter(action='ignore', category=(FutureWarning, RuntimeWarning))#,RuntimeWarning])
import numpy as np
import pandas as pd
from scipy import stats
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator)
from plotting import plotting
#%% --------------------------------------------------------------------------------------------------------------------
# GLOBAL VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
VERSION = 'V3'
TASK = 'mem_cap' #'mem_cap' 'pttn_recog'
CONNECTOME = 'human_500'
CLASS = 'functional'
INPUTS = 'subctx'
#%% --------------------------------------------------------------------------------------------------------------------
# DIRECTORIES
# ----------------------------------------------------------------------------------------------------------------------
PROJ_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PROC_RES_DIR = os.path.join(PROJ_DIR, 'proc_results', TASK)
#%% --------------------------------------------------------------------------------------------------------------------
# IMPORT DATA FUNCTIONS
# ----------------------------------------------------------------------------------------------------------------------
def load_avg_scores_per_alpha(analysis, coding):
RES_TSK_DIR = os.path.join(PROC_RES_DIR, 'tsk_results', analysis, f'{INPUTS}_scale{CONNECTOME[-3:]}')
avg_scores = pd.read_csv(os.path.join(RES_TSK_DIR, f'{CLASS}_avg_{coding}.csv'))
return avg_scores
#%% --------------------------------------------------------------------------------------------------------------------
# PI - AVG SCORE ACROSS CLASSES PER ALPHA VALUE - ALL REGIMES AT ONCE
# ----------------------------------------------------------------------------------------------------------------------
# load data
ANALYSES = [
'reliability',
'significance',
'spintest'
]
df_brain_scores = []
for analysis in ANALYSES:
avg_scores = load_avg_scores_per_alpha(analysis, 'encoding')
df_brain_scores.append(avg_scores)
df_brain_scores = pd.concat(df_brain_scores)
# scale data
score = 'performance'
min_score = np.min(df_brain_scores[score].values)
max_score = np.max(df_brain_scores[score].values)
df_brain_scores[score] = (df_brain_scores[score]-min_score)/(max_score-min_score)
#%%
# boxplot
score = 'performance'
include_alpha = [0.3, 0.5, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 2.0, 2.5, 3.0, 3.5]
df_brain_scores = pd.concat([df_brain_scores.loc[np.isclose(df_brain_scores['alpha'], alpha), :] for alpha in include_alpha])\
.reset_index(drop=True)
plotting.boxplot(x='alpha', y=score, df=df_brain_scores.copy(),
palette=sns.color_palette('husl', 5),
hue='analysis',
order=None,
xlim=None,
ylim=(0,1),
legend=True,
width=0.8,
figsize=(22,8),
showfliers=True,
)
#%% --------------------------------------------------------------------------------------------------------------------
# PII - VISUAL INSPECTION SCORES DISTRIBUTION
# ----------------------------------------------------------------------------------------------------------------------
include_alpha = [1.0]#, 1.2, 1.3, 1.4, 1.5]
for alpha in include_alpha:
print(f'\n---------------------------------------alpha: ... {alpha} ---------------------------------------')
tmp_df_alpha = df_brain_scores.loc[np.isclose(df_brain_scores['alpha'], alpha), :]
sns.set(style="ticks", font_scale=2.0)
fig = plt.figure(figsize=(10,7))
ax = plt.subplot(111)
for analysis in ANALYSES:
sns.distplot(tmp_df_alpha.loc[tmp_df_alpha.analysis == analysis, score].values,
bins=50,
hist=False,
kde=True,
kde_kws={'shade':True},
label=analysis
)
ax.xaxis.set_major_locator(MultipleLocator(0.05))
ax.get_yaxis().set_visible(False)
ax.legend(fontsize=15, frameon=False, ncol=1, loc='upper right')
# ax.set_xlim(0.7, 0.95)
sns.despine(offset=10, left=True, trim=True)
# fig.savefig(fname='C:/Users/User/Dropbox/figs/distplots.eps',
# orientation='portrait',
# transparent=True,
# bbox_inches='tight',
# dpi=300)
plt.show()
plt.close()
#%% --------------------------------------------------------------------------------------------------------------------
# PIII - STATISTICAL TESTS
# ----------------------------------------------------------------------------------------------------------------------
def cohen_d_2samp(x,y):
nx = len(x)
ny = len(y)
dof = nx + ny - 2
# 2 independent sample t test
return (np.mean(x) - np.mean(y)) / np.sqrt(((nx-1)*np.std(x, ddof=1) ** 2 + (ny-1)*np.std(y, ddof=1) ** 2) / dof)
include_alpha = [1.0]#, 1.2, 1.3, 1.4, 1.5]
for alpha in include_alpha:
print(f'\n---------------------------------------alpha: ... {alpha} ---------------------------------------')
brain = df_brain_scores.loc[(df_brain_scores.analysis == 'reliability') & (np.isclose(df_brain_scores['alpha'], alpha))]
rewir = df_brain_scores.loc[(df_brain_scores.analysis == 'significance') & (np.isclose(df_brain_scores['alpha'], alpha))] #significance
spint = df_brain_scores.loc[(df_brain_scores.analysis == 'spintest') & (np.isclose(df_brain_scores['alpha'], alpha))] #spintest
print('Two-sample Wilcoxon-Mann-Whitney rank-sum test:')
print(f' Brain median: {np.nanmedian(brain.performance.values)}')
print(f' Rewired median: {np.nanmedian(rewir.performance.values)}')
print(f' Spintest median: {np.nanmedian(spint.performance.values)}')
# ----------------------------------------------------------------------------
# nonparametric Mann-Whitney U test
# rewired null model
Urewir, mannu_p_rewir = stats.mannwhitneyu(brain.performance.values[~np.isnan(brain.performance.values)],
rewir.performance.values[~np.isnan(rewir.performance.values)],
alternative='two-sided'
)
Urewir = Urewir/(1000*1000)
print(f'\tmannU. pval - rewired: {mannu_p_rewir} Effect size: {Urewir}')
# spintest null model
Uspint, mannu_p_spint = stats.mannwhitneyu(brain.performance.values[~np.isnan(brain.performance.values)],
spint.performance.values[~np.isnan(spint.performance.values)],
alternative='two-sided'
)
Uspint = Uspint/(1000*1000)
print(f'\tmannU. pval - spintest: {mannu_p_spint} Effect size: {Uspint}')
# ----------------------------------------------------------------------------
# parametric t-test
# rewired null model
print('\n')
print('Two-sample student t-test:')
print(f' Brain mean: {np.nanmean(brain.performance.values)}')
print(f' Rewired mean: {np.nanmean(rewir.performance.values)}')
print(f' Spintest mean: {np.nanmean(spint.performance.values)}')
_, ttest_p_rewir = stats.ttest_ind(brain.performance.values[~np.isnan(brain.performance.values)],
rewir.performance.values[~np.isnan(rewir.performance.values)],
equal_var=False
)
eff_size_rewir = cohen_d_2samp(brain.performance.values[~np.isnan(brain.performance.values)], rewir.performance.values[~np.isnan(rewir.performance.values)])
print(f'\tttest. pval - rewired: {ttest_p_rewir} Effect size:{eff_size_rewir}')
# spintest null model
_, ttest_p_spint = stats.ttest_ind(brain.performance.values[~np.isnan(brain.performance.values)],
spint.performance.values[~np.isnan(spint.performance.values)],
equal_var=False
)
eff_size_spint = cohen_d_2samp(brain.performance.values[~np.isnan(brain.performance.values)], spint.performance.values[~np.isnan(spint.performance.values)])
print(f'\tttest. pval - spintest: {ttest_p_spint} Effect size:{eff_size_spint}')
<file_sep>/03_analysis/fig1.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 13:56:13 2020
@author: <NAME>
"""
import os
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import numpy as np
import pandas as pd
from plotting import plot_tasks
#%% --------------------------------------------------------------------------------------------------------------------
# GLOBAL VARIABLES
# ----------------------------------------------------------------------------------------------------------------------
TASK = 'pttn_recog' #'mem_cap' 'pttn_recog'
CONNECTOME = 'human_500'
ANALYSIS = 'reliability' # 'reliability' 'significance' 'spintest'
#%% --------------------------------------------------------------------------------------------------------------------
# DIRECTORIES
# ----------------------------------------------------------------------------------------------------------------------
PROJ_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PROC_RES_DIR = os.path.join(PROJ_DIR, 'proc_results')
# PROC_RES_DIR = os.path.join(PROJ_DIR, 'proc_results')#, '100_reservoir', 'V2')
# PROC_RES_DIR = os.path.join(PROJ_DIR, 'proc_results', '100_rnns')
RES_TSK_DIR = os.path.join(PROC_RES_DIR, TASK, ANALYSIS, CONNECTOME)
#%% --------------------------------------------------------------------------------------------------------------------
# IMPORT DATA FUNCTIONS
# ----------------------------------------------------------------------------------------------------------------------
def load_scores(coding):
coding_scores = pd.read_csv(os.path.join(RES_TSK_DIR, f'{coding}.csv'))
return coding_scores
# %%--------------------------------------------------------------------------------------------------------------------
# PI - BETWEEN NETWORK COMPARISON - CLASS SCORES DISTRIBUTION AS A FCN OF ALPHA
# --------------------------------------------------------------------------------------------------------------------
df_encoding = load_scores('encoding')
score = 'performance'
# include_alpha = np.linspace(0, 1.5, 31)[1:]
include_alpha = [0.3, 0.5, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5]#, 2.0, 2.5, 3.0, 3.5]
plot_tasks.lnplt_scores_vs_alpha(df_encoding.copy(),
score,
include_alpha=include_alpha,
scale=True,
minmax=None,
ci='sd',
err_style='band',
markers=True,
marker='o',
markersize=12,
linewidth=2,
dashes=False,
x_major_loc=0.2,
ylim=(0,1.1),
xlim=(0.5,1.5),
legend=True,
figsize=(20,8),
)
<file_sep>/01_rc_workflow/reservoir/pttn_recog.ini
[task_params]
task = pttn_recog
specific_task = pttn_recog
task_reference = T2
input_gain = 0.1
[network]
connectome = human_500
network_inputs = subctx
network_partition = functional
[parall_params]
num_process = 1
num_iters = 100
<file_sep>/03_analysis/plotting/plot_tasks.py
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 10:10:14 2019
@author: <NAME>
"""
import os
import numpy as np
import pandas as pd
import scipy.io as sio
from scipy import stats
#from statsmodels.stats.multitest import multipletests
from sklearn.linear_model import LinearRegression
from sklearn.metrics import auc
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['pdf.fonttype'] = 42
# matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['ps.usedistiller'] = 'xpdf'
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator)
import seaborn as sns
from . import plotting
COLORS = sns.color_palette("husl", 8)
ENCODE_COL = '#E55FA3'
DECODE_COL = '#6CC8BA'
norm_score_by = None #'n_nodes'
# --------------------------------------------------------------------------------------------------------------------
# GENERAL
# ----------------------------------------------------------------------------------------------------------------------
def sort_class_labels(class_labels):
if 'subctx' in class_labels:
rsn_labels = ['VIS', 'SM', 'DA', 'VA', 'LIM', 'FP', 'DMN', 'subctx']
else:
rsn_labels = ['VIS', 'SM', 'DA', 'VA', 'LIM', 'FP', 'DMN']
if class_labels.all() in rsn_labels:
return np.array([clase for clase in rsn_labels if clase in class_labels])
else:
return class_labels
def merge_scores(df_scores):
df_encoding_scores = df_scores.loc[df_scores['coding'] == 'encoding', :] \
.rename(columns={'performance':'encoding performance', 'capacity':'encoding capacity'}) \
.reset_index(drop=True)
df_encoding_scores.fillna({'encoding_performance':np.nanmean(df_encoding_scores['encoding performance']), \
'encoding capacity':np.nanmean(df_encoding_scores['encoding capacity'])}, \
inplace=True)
df_decoding_scores = df_scores.loc[df_scores['coding'] == 'decoding', :] \
.rename(columns={'performance':'decoding performance', 'capacity':'decoding capacity'})\
.reset_index(drop=True)
df_decoding_scores.fillna({'decoding performance':np.nanmean(df_decoding_scores['decoding performance']), \
'decoding capacity':np.nanmean(df_decoding_scores['decoding capacity'])}, \
inplace=True)
merge_columns = list(np.intersect1d(df_encoding_scores.columns, df_decoding_scores.columns))
df_merge_scores = pd.merge(df_encoding_scores, df_decoding_scores, on=merge_columns, left_index=True, right_index=True).reset_index(drop=True)
df_merge_scores = df_merge_scores.drop(columns={'coding'})
# df_merge_scores['coding performance'] = (df_merge_scores['encoding performance'] - df_merge_scores['decoding performance']).astype(float)
# df_merge_scores['coding capacity'] = (df_merge_scores['encoding capacity'] - df_merge_scores['decoding capacity']).astype(float)
# df_merge_scores = df_merge_scores[['sample_id', 'module',
# 'encoding performance', 'decoding performance', 'coding performance', \
# 'encoding capacity', 'decoding capacity', 'coding capacity', \
# 'n_nodes', 'analysis']]
df_merge_scores = df_merge_scores[['sample_id', 'module',
'encoding performance', 'decoding performance', \
'encoding capacity', 'decoding capacity', \
'n_nodes', 'analysis']]
return df_merge_scores
# --------------------------------------------------------------------------------------------------------------------
# P I - BETWEEN NETWORK COMPARISON AS A FCN OF ALPHA
# ----------------------------------------------------------------------------------------------------------------------
def lnplt_scores_vs_alpha(df, score, include_alpha=None, scale=True, minmax=None, norm_score_by=None, **kwargs):
if norm_score_by is not None:
# regress out a variable from coding scores
x = np.array(df[norm_score_by].values)[:, np.newaxis]
reg = LinearRegression().fit(x, y=df[score])
df[score] = df[score] - reg.predict(x)
if include_alpha is not None:
df = pd.concat([df.loc[np.isclose(df['alpha'], alpha), :] for alpha in include_alpha])\
.reset_index(drop=True)
if scale:
if minmax is None:
min_score = np.min(df[score])
max_score = np.max(df[score])
else:
min_score = minmax[0]
max_score = minmax[1]
df[score] = (df[score]-min_score)/(max_score-min_score)
# ----------------------------------------------------
df = df.rename(columns={'alpha':r'$\alpha$'})
plotting.lineplot(x=r'$\alpha$', y=score,
df=df,
palette=COLORS[:-1],
hue='module',
hue_order=sort_class_labels(np.unique(df['module'])),
# fig_name='ln_encod_vs_alpha',
**kwargs
)
# --------------------------------------------------------------------------------------------------------------------
# P II - BETWEEN NETWORK COMPARISON - AVG ACROSS ALPHA
# ----------------------------------------------------------------------------------------------------------------------
def bxplt_scores(df_scores, score, order=None, scale=True, minmax=None, norm_score_by=None, title=None, legend=True, **kwargs):
if norm_score_by is not None:
# regress out a variable from coding scores
X = np.array(df_scores[norm_score_by])[:, np.newaxis]
reg_enc = LinearRegression().fit(X, y=df_scores[score])
df_scores[score] = df_scores[score] - reg_enc.predict(X)
if scale:
if minmax is None:
min_score = np.min(df_scores[score])
max_score = np.max(df_scores[score])
else:
min_score = minmax[0]
max_score = minmax[1]
df_scores[score] = ((df_scores[score]-min_score)/(max_score-min_score))
if order is not None:
class_labels = sort_class_labels(np.unique(df_scores['module']))
palette = np.array([np.array(COLORS)[np.where(class_labels == clase)[0][0]] for clase in order])
else:
palette = COLORS[:-1]
# ----------------------------------------------------
plotting.boxplot(x='module', y=score,
df=df_scores,
order=order,
palette=palette,
legend=legend,
# title=f'regime: {title}',
# fig_name=f'bx_enc_{title}',
**kwargs
)
# --------------------------------------------------------------------------------------------------------------------
# P IV - ENCODING VS DECODING
# ----------------------------------------------------------------------------------------------------------------------
def jointplot_enc_vs_dec(df_scores, score, scale=True, minmax=None, hue_order=None, kind='scatter', draw_line=True, title=None, **kwargs):
df_scores = merge_scores(df_scores)
if scale:
if minmax is None:
max_score = max(np.max(df_scores[f'decoding {score}']), np.max(df_scores[f'encoding {score}']))
min_score = min(np.min(df_scores[f'decoding {score}']), np.min(df_scores[f'encoding {score}']))
else:
min_score = minmax[0]
max_score = minmax[1]
df_scores[f'encoding {score}'] = ((df_scores[f'encoding {score}']-min_score)/(max_score-min_score))
df_scores[f'decoding {score}'] = ((df_scores[f'decoding {score}']-min_score)/(max_score-min_score))
# ----------------------------------------------------------------------
sns.set(style="ticks", font_scale=2.0)
class_labels = sort_class_labels(np.unique(df_scores['module']))
if hue_order is None: hue_order = class_labels.copy()
palette = [COLORS[np.where(class_labels == clase)[0][0]] for clase in hue_order]
tmp = df_scores.loc[df_scores['module'] == hue_order[0], :]
g = sns.JointGrid(x=tmp[f'decoding {score}'].values,
y=tmp[f'encoding {score}'].values,
dropna=True,
height=8,
ratio=7,
**kwargs
)
if kind == 'kde':
g.plot_joint(sns.kdeplot, color=palette[0], shade=True, shade_lowest=False) # label=class_labels[0], legend=False) #
elif kind == 'scatter':
g.plot_joint(sns.scatterplot, color=palette[0], s=50, linewidths=0.5, alpha=0.3, edgecolor='face') # label=class_labels[0], legend=False) #
g.plot_marginals(sns.distplot, hist=False, kde=True, kde_kws={"shade": True}, color=palette[0])
for i, clase in enumerate(hue_order[1:]):
tmp = df_scores.loc[df_scores['module'] == clase, :]
g.x = tmp[f'decoding {score}'].values
g.y = tmp[f'encoding {score}'].values
if kind == 'kde':
g.plot_joint(sns.kdeplot, color=palette[i+1], shade=True, shade_lowest=False) # label=clase, legend=False) #
elif kind == 'scatter':
g.plot_joint(sns.scatterplot, color=palette[i+1], s=50, linewidths=0.5, alpha=0.3, edgecolor='face') # label=clase, legend=False) #
g.plot_marginals(sns.distplot, hist=False, kde=True, kde_kws={"shade": True}, color=palette[i+1])
g.ax_joint.set_xlabel(f'decoding {score}')
g.ax_joint.set_ylabel(f'encoding {score}')
#g.ax_joint.get_legend().remove()
#g.ax_joint.legend(fontsize=10, frameon=False, ncol=1, loc='lower right', title='rsn')
#plt.legend(fontsize=10, frameon=False, ncol=1)#, loc='lower right')
if draw_line:
g.x = [0.05,0.95]
g.y = [0.05,0.95]
g.plot_joint(sns.lineplot, color='dimgrey', linestyle='--', linewidth=0.8)
# plt.suptitle(f'regime : {title}', fontsize=25)
plt.show()
plt.close()
def ttest(df_scores, score, fdr_correction=True):
# get class labels
class_labels = sort_class_labels(np.unique(df_scores['module']))
pval = []
tstat = []
for clase in class_labels:
encod_scores = df_scores.loc[(df_scores['module'] == clase) & (df_scores['coding'] == 'encoding'), :][score].values
decod_scores = df_scores.loc[(df_scores['module'] == clase) & (df_scores['coding'] == 'decoding'), :][score].values
t, p = stats.ttest_1samp(encod_scores-decod_scores, popmean=0.0)
pval.append(p)
tstat.append(t)
# if fdr_correction: pval = multipletests(pval, 0.05, 'bonferroni')[1]
return tstat, pval
def effect_size(df_scores, score, minmax=None):
# ---------------------------------------------------
def cohen_d_1samp(x, mu=0.0):
return (np.mean(x) - mu) / np.std(x)
# get class labels
class_labels = sort_class_labels(np.unique(df_scores['module']))
effect_size = []
for clase in class_labels:
encod_scores = df_scores.loc[(df_scores['module'] == clase) & (df_scores['coding'] == 'encoding'), :][score].values
decod_scores = df_scores.loc[(df_scores['module'] == clase) & (df_scores['coding'] == 'decoding'), :][score].values
effect_size.append(cohen_d_1samp(encod_scores-decod_scores))
return np.array(effect_size)
def barplot_eff_size(eff_size, class_labels, title=None):
df_eff_size = pd.DataFrame(data = np.column_stack((class_labels, eff_size)),
columns = ['module', 'effect size'],
index = np.arange(len(class_labels))
)
df_eff_size['effect size'] = df_eff_size['effect size'].astype('float')
# bar plot
sns.set(style="ticks", font_scale=2.0)
fig = plt.figure(num=1, figsize=(8,8))
ax = plt.subplot(111)
hue_order = np.array(class_labels)[np.argsort(eff_size)]
palette = np.array([np.array(COLORS)[np.where(class_labels == clase)[0][0]] for clase in hue_order])
sns.barplot(x='module',
y='effect size',
data=df_eff_size,
order=hue_order,
palette=palette,
orient='v',
# width=0.5
)
ax.set_ylim(-6,6)
ax.yaxis.set_major_locator(MultipleLocator(2.0))
# plt.suptitle(f'regime: {title}', fontsize=25)
sns.despine(offset=10, trim=True)
plt.show()
plt.close()
| 8c1c2969ced5bef3593960e7f6cd17d339f79a18 | [
"Python",
"INI"
] | 13 | Python | estefanysuarez/suarez_neuromorphicnetworks2 | 06d993282f4991318dd190a53e20178eb4a69e49 | 7007c18ca4ac916b44314a14d2b4256e8b350359 |
refs/heads/master | <file_sep>apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName rootProject.version
}
}
dependencies {
compile project(":fire-core-jvm")
compile deps.kotlin_stdlib
compile 'com.jakewharton.timber:timber:4.5.1'
}<file_sep>package fire.log
import fire.log.Intensity.ASSERT
import fire.log.Intensity.DEBUG
import fire.log.Intensity.ERROR
import fire.log.Intensity.INFO
import fire.log.Intensity.VERBOSE
import fire.log.Intensity.WARN
enum class Intensity(val value: Int) {
VERBOSE(2),
DEBUG(3),
INFO(4),
WARN(5),
ERROR(6),
ASSERT(7)
}
typealias Log = (intensity: Intensity, tag:String, t: Throwable?, message: String) -> Unit
private val logLevelSuffix: Map<Intensity, String> = mapOf(
VERBOSE to "V",
DEBUG to "D",
INFO to "I",
WARN to "W",
ERROR to "E",
ASSERT to "WFT"
)
val printLnLog : Log get() {
return { intensity, tag, t, message ->
//todo do something with the throwable
println("${logLevelSuffix[intensity]}/$tag: $message")
}
}
object Fire {
var logs: List<Log> = emptyList()
private set
fun add(log: Log) {
logs += log
}
fun removeAllLogs() {
logs = emptyList()
}
inline fun v(tag: String? = null, t: Throwable? = null, message: ()->String) {
log(intensity = VERBOSE, tag = tag, t = t, message = message)
}
inline fun d(tag: String? = null, t: Throwable? = null, message: ()->String) {
log(intensity = DEBUG, tag = tag, t = t, message = message)
}
inline fun i(tag: String? = null, t: Throwable? = null, message: ()->String) {
log(intensity = INFO, tag = tag, t = t, message = message)
}
inline fun w(tag: String? = null, t: Throwable? = null, message: ()->String) {
log(intensity = WARN, tag = tag, t = t, message = message)
}
inline fun e(tag: String? = null, t: Throwable? = null, message: ()->String) {
log(intensity = ERROR, tag = tag, t = t, message = message)
}
inline fun wtf(tag: String? = null, t: Throwable? = null, message: ()->String) {
log(intensity = ASSERT, tag = tag, t = t, message = message)
}
inline fun log(intensity: Intensity, tag:String? = null, t: Throwable? = null, message: ()->String) {
if (logs.isNotEmpty()) {
val msg = message()
logs.forEach { it(intensity, tag ?: "", t, msg) }
}
}
}<file_sep>package fire.log
import timber.log.Timber
val timberLog : Log get() {
return { intensity: Intensity, tag: String, t: Throwable?, message: String ->
if (tag.isNotBlank()) {
Timber.tag(tag).log(intensity.value, t, message)
} else {
Timber.log(intensity.value, t, message)
}
}
}<file_sep>//apply plugin: 'kotlin-platform-common'
//
//dependencies {
// compile deps.kotlin_stdlib_common
// testCompile deps.junit
// testCompile deps.kotlin_test_common
//}
//compileKotlin {
// kotlinOptions.jvmTarget = "1.8"
//}
//compileTestKotlin {
// kotlinOptions.jvmTarget = "1.8"
//}<file_sep>package fire.log
import fire.log.Intensity.ASSERT
import fire.log.Intensity.DEBUG
import fire.log.Intensity.ERROR
import fire.log.Intensity.INFO
import fire.log.Intensity.VERBOSE
import fire.log.Intensity.WARN
import org.junit.Before
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
fun Fire.assertCorrectIntensity(correctIntensity: Intensity) {
add { intensity, _, _, _ ->
println("correctIntensity = ${correctIntensity}, intensity = ${intensity}")
assertTrue { intensity == correctIntensity }
}
}
class FireTests {
@Before fun removeLogs() {
Fire.removeAllLogs()
}
@Test fun `should add log and remove logs`() {
assertTrue("logs size should be 0") { Fire.logs.isEmpty() }
for (i in 1..100) {
Fire.add(printLnLog)
assertTrue("logs size doesn't match index") { Fire.logs.size == i }
}
Fire.removeAllLogs()
assertTrue("logs size should be 0") { Fire.logs.isEmpty() }
}
//region: valid intensity
@Test fun `v should call log with correct intensity`() {
Fire.assertCorrectIntensity(VERBOSE)
Fire.v { "ignored" }
}
@Test fun `d should call log with correct intensity`() {
Fire.assertCorrectIntensity(DEBUG)
Fire.d { "ignored" }
}
@Test fun `i should call log with correct intensity`() {
Fire.assertCorrectIntensity(INFO)
Fire.i { "ignored" }
}
@Test fun `w should call log with correct intensity`() {
Fire.assertCorrectIntensity(WARN)
Fire.w { "ignored" }
}
@Test fun `e should call log with correct intensity`() {
Fire.assertCorrectIntensity(ERROR)
Fire.e { "ignored" }
}
@Test fun `wtf should call log with correct intensity`() {
Fire.assertCorrectIntensity(ASSERT)
Fire.wtf { "ignored" }
}
//endregion
@Test fun `message() block should not be called if no logs in fire`() {
var messageBlockCalled = false
Fire.v {
messageBlockCalled = true
""
}
Fire.d {
messageBlockCalled = true
""
}
Fire.i {
messageBlockCalled = true
""
}
Fire.w {
messageBlockCalled = true
""
}
Fire.e {
messageBlockCalled = true
""
}
Fire.wtf {
messageBlockCalled = true
""
}
Fire.log(ASSERT) {
messageBlockCalled = true
""
}
assertFalse(messageBlockCalled)
}
@Test fun `message() block should be called if logs in fire`() {
var messageBlockCalled = false
val testMessage = "testMessage"
Fire.add { _, _, _, message -> assertTrue { message == testMessage } }
Fire.v {
messageBlockCalled = true
testMessage
}
Fire.d {
messageBlockCalled = true
testMessage
}
Fire.i {
messageBlockCalled = true
testMessage
}
Fire.w {
messageBlockCalled = true
testMessage
}
Fire.e {
messageBlockCalled = true
testMessage
}
Fire.wtf {
messageBlockCalled = true
testMessage
}
Fire.log(ASSERT) {
messageBlockCalled = true
testMessage
}
assertTrue(messageBlockCalled)
}
}<file_sep>Fire
===
A pure kotlin logging library inspired by [Timber](https://github.com/JakeWharton/timber)
## Should you use Fire
No
Fire is in very early stages of development and is being used as a test bed for mutli-platform
library development in kotlin.<file_sep>buildscript {
ext.kotlin_version = '1.1.4-3'
repositories {
mavenCentral()
jcenter()
maven { url = 'https://maven.google.com' }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
allprojects {
repositories {
mavenCentral()
jcenter()
maven { url = 'https://maven.google.com' }
}
group = 'com.bulwinkel.fire'
version = '0.1.1'
}
ext {
minSdkVersion = 9
targetSdkVersion = 26
compileSdkVersion = 26
buildToolsVersion = '26.0.1'
deps = [
junit: "junit:junit:4.12",
kotlin_stdlib: "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version",
kotlin_stdlib_js: "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version",
kotlin_stdlib_jre8: "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version",
kotlin_stdlib_common: "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version",
kotlin_test: "org.jetbrains.kotlin:kotlin-test:$kotlin_version",
kotlin_test_js: "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version",
kotlin_test_common: "org.jetbrains.kotlin:kotlin-test-common:$kotlin_version",
]
}<file_sep>apply plugin: 'kotlin2js'
dependencies {
compile deps.kotlin_stdlib_js
testCompile deps.kotlin_test_js
}
<file_sep>rootProject.name = 'fire'
include 'fire-core'
include 'fire-core-jvm'
include 'fire-core-js'
include 'fire-timber'
<file_sep>plugins {
id "com.jfrog.bintray" version "1.7.3"
}
apply plugin: 'kotlin'
apply plugin: 'java-library'
apply plugin: 'maven-publish'
sourceSets {
final def coreSourcesPath = file('../fire-core/src').path
main.kotlin.srcDirs += "$coreSourcesPath/main/kotlin"
test.java.srcDirs += "$coreSourcesPath/test/kotlin"
}
dependencies {
implementation deps.kotlin_stdlib
testCompile deps.kotlin_test
testCompile deps.junit
}
compileKotlin {
kotlinOptions.jvmTarget = "1.6"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.6"
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
artifacts {
archives sourcesJar
}
publishing {
publications {
fireCoreJvm(MavenPublication) {
from components.java
artifact sourcesJar
artifactId = 'fire-core-jvm'
}
}
}
// load bintray credentials
final Properties properties = new Properties()
final File propFile = "${System.properties['user.home']}${File.separator}.gradle${File.separator}bintray.properties" as File
properties.load(propFile.newDataInputStream())
println("properties.propertyNames() = ${properties.propertyNames().collect { "$it" }}")
bintray {
user = properties.getProperty("bintray.user")
key = properties.getProperty("bintray.apikey")
publications = ['fireCoreJvm']
pkg {
repo = 'fire'
name = 'fire-core-jvm'
licenses = ['MIT']
vcsUrl = 'https://github.com/bulwinkel/fire'
version {
name = project.version
// desc = 'Gradle Bintray Plugin 1.0 final'
// released = new Date()
// vcsTag = '1.3.0'
// attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin']
}
}
} | d9637189fe4655994a3574d648ca26f20c48b2d4 | [
"Markdown",
"Kotlin",
"Gradle"
] | 10 | Gradle | bulwinkel/fire | 4b211fcba9d38bd9adc88b863e09315295b5f6b9 | 633f5112704293f79d17e19035cb4431c9fb2988 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
conda env create -n weka-porter -c defaults python=2 -f environment.yml
source activate weka-porter<file_sep>
# weka-porter
[](https://travis-ci.org/nok/weka-porter)
[](https://pypi.python.org/pypi/weka-porter)
[](https://pypi.python.org/pypi/weka-porter)
[](https://raw.githubusercontent.com/nok/weka-porter/master/license.txt)
Port or transpile trained decision trees from [Weka](http://www.cs.waikato.ac.nz/ml/weka/) to a low-level programming language like [C](https://en.wikipedia.org/wiki/C_(programming_language)), [Java](https://en.wikipedia.org/wiki/Java_(programming_language)) or [JavaScript](https://en.wikipedia.org/wiki/JavaScript).<br>It's recommended for limited embedded systems and critical applications where performance matters most.
## Benefit
The benefit of the module is to transpile a decision tree from the compact representation by the [Weka](http://www.cs.waikato.ac.nz/ml/weka/) software to a target programming language.
### Input
```
outlook = sunny
| humidity <= 75: yes (2.0)
| humidity > 75: no (3.0)
outlook = overcast: yes (4.0)
outlook = rainy
| windy = TRUE: no (2.0)
| windy = FALSE: yes (3.0)
```
### Output
```java
public static String classify(String outlook, boolean windy, double humidity) {
if (outlook.equals("sunny")) {
if (humidity <= 75) {
return "yes";
}
else if (humidity > 75) {
return "no";
}
}
else if (outlook.equals("overcast")) {
return "yes";
}
else if (outlook.equals("rainy")) {
if (windy == true) {
return "no";
}
else if (windy == false) {
return "yes";
}
}
return null;
}
```
## Installation
```sh
pip install weka-porter
```
## Usage
Either you use the porter as [imported module](#module) in your application or you use the [command-line interface](#cli).
### Module
This example shows how you can port a decision tree to Java:
```python
from weka_porter import Porter
porter = Porter(language='java')
result = porter.port('weather_data.txt', method_name='classify')
print(result)
```
The ported [tree](examples/basics.py#L9-L31) matches the [original version](examples/weather_data.txt) of the model.
### Command-line interface
This examples shows how you can port a model from the command line. The model can be ported by using the following command:
```sh
python -m weka_porter --input <txt_file> [--output <destination_dir>] [--language {c,java,js}]
python -m weka_porter -i <txt_file> [-o <destination_dir>] [-l {c,java,js}]
```
For example:
```sh
python -m weka_porter --input model.txt --language java
python -m weka_porter -i model.txt -l java
```
By changing the language parameter you can set the target programming language:
```
python -m weka_porter -i model.txt -l java
python -m weka_porter -i model.txt -l js
python -m weka_porter -i model.txt -l c
```
Finally the following command will display all options:
```sh
python -m weka_porter --help
python -m weka_porter -h
```
## Development
### Environment
Install the required environment [modules](environment.yml) by executing the bash script [sh_environment.sh](sh_environment.sh) or type:
```sh
conda config --add channels conda-forge
conda env create -n weka-porter python=2 -f environment.yml
```
Furthermore you need to install [Node.js](https://nodejs.org) (`>=6`), [Java](https://java.com) (`>=1.6`) and [GCC](https://gcc.gnu.org) (`>=4.2`) for testing.
### Testing
Run all [tests](tests) by executing the bash script [sh_tests.sh](sh_tests.sh) or type:
```sh
source activate weka-porter
python -m unittest discover -vp '*Test.py'
source deactivate
```
The tests cover module functions as well as matching predictions of ported trees.
## Questions?
Don't be shy and feel free to contact me on [Twitter](https://twitter.com/darius_morawiec).
## License
The library is Open Source Software released under the [MIT](license.txt) license.
<file_sep>#!/usr/bin/env bash
# pip install wheel twine
source activate weka-porter
python setup.py sdist bdist_wheel
# TEST
twine register dist/sklearn-porter-0.1.0.tar.gz -r pypitest
twine register dist/sklearn_porter-0.1.0-py2-none-any.whl -r pypitest
twine upload dist/* -r pypitest
# https://testpypi.python.org/pypi?:action=display&name=weka-porter&version=0.1.0
# PROD
# twine register dist/sklearn-porter-0.1.0.tar.gz -r pypi
# twine register dist/sklearn_porter-0.1.0-py2-none-any.whl -r pypi
# twine upload dist/* -r pypi
# https://pypi.python.org/pypi?:action=display&name=weka-porter&version=0.1.0<file_sep>import os
import argparse
from . import Porter
def main():
parser = argparse.ArgumentParser(
description=('Transpile a decision tree from Weka '
'to a low-level programming language.'),
epilog='More details on: https://github.com/nok/weka-porter')
parser.add_argument(
'--input', '-i',
required=True,
help='Set the path of an exported tree in Weka format.')
parser.add_argument(
'--output', '-o',
required=False,
help='Set the destination directory.')
parser.add_argument(
'--language', '-l',
choices=['c', 'java', 'js'],
default='java',
required=False,
help='Set the target programming language.')
parser.add_argument(
'--print', '-p',
required=False,
default=False,
help='Set whether the result should be printed to the console.')
args = vars(parser.parse_args())
arg_input = str(args['input'])
arg_output = str(args['output'])
arg_print = args['print']
arg_language = args['language']
if arg_input.endswith('.txt') and os.path.isfile(arg_input):
porter = Porter(language=arg_language)
result = porter.port(arg_input)
if arg_print is True:
print(result)
else:
filename = 'result.txt'
path = arg_input.split(os.sep)
del path[-1]
path += [filename]
path = os.sep.join(path)
if arg_output != '' and os.path.isdir(arg_output):
path = os.path.join(arg_output, filename)
with open(path, 'w') as file:
file.write(result)
if __name__ == "__main__":
main()
| 3811eec89dd481874afc52e723812c23997024f3 | [
"Markdown",
"Python",
"Shell"
] | 4 | Shell | knowline/weka-porter | 99f11c76435658e444d9647d8103255f0ddc4618 | d442b1c81747b22b325e0c25f7ca6772b23fdab7 |
refs/heads/master | <file_sep>import cv2
import pytesseract
from PIL import Image
from picamera.array import PiRGBArray
from picamera import PiCamera
camera = PiCamera()
camera.resolution = (800, 600)
rawCapture = PiRGBArray(camera)
camera.start_preview(fullscreen=False, window=(100,20,800,600))
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
try:
frame = rawCapture.array
im = cv2.resize(frame, (800, 600))
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
# cv2.imwrite('temp.jpg', gray)
# gray = Image.open('temp.jpg')
text = pytesseract.image_to_string(gray)
print(text.encode('utf-8'))
rawCapture.truncate(0)
except:
camera.stop_preview()
break
def recognizetext(im=None, im_path=None):
if im_path != None:
image = Image.open(im_path)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# filename = "{}.png".format(os.getpid())
# cv2.imwrite(filename, image)
text = pytesseract.image_to_string(image)
print(text.encode('utf-8'))
else:
text = pytesseract.image_to_string(im)
print(text)
# if __name__=="__main__":
# recognizetext(im_path='textimage.png')<file_sep>#!/usr/bin/env bash
apt-get install tesseract-ocr libtesseract-dev
#pip install numpy pyzbar opencv-python
pip install pytesseract<file_sep>import pyzbar.pyzbar as pyzbar
from picamera.array import PiRGBArray
from picamera import PiCamera
# import numpy as np
import time
import os
audio_list = ['1.wav','2.wav','3.wav','4.wav','5.wav','6.wav','7.wav','8.wav','9.wav'
,'10.wav','11.wav','12.wav','13.wav','14.wav','15.wav','16.wav','17.wav','18.wav'
,'19.wav','20.wav','21.wav','22.wav','23.wav','24.wav','25.wav','26.wav','27.wav'
,'28.wav','29.wav','30.wav','31.wav','32.wav','33.wav','34.wav','35.wav','36.wav'
,'37.wav','38.wav','39.wav','40.wav','41.wav','42.wav','43.wav','44.wav','45.wav'
,'46.wav','47.wav','48.wav','49.wav','50.wav','51.wav','52.wav','53.wav','54.wav'
,'55.wav','56.wav','57.wav','58.wav','59.wav','60.wav','61.wav','62.wav']
camera = PiCamera()
# camera.resolution = (480, 320)
rawCapture = PiRGBArray(camera)
privious_data = []
privious_time = 0
camera.start_preview(fullscreen=False, window=(100,20,480,320))
for frame in camera.capture_continuous(rawCapture, format="bgr",
use_video_port=True):
try:
frame = rawCapture.array
decodedObjects = pyzbar.decode(frame)
if decodedObjects != []:
wait_time = time.time() - privious_time
for obj in decodedObjects:
if obj.data != privious_data or wait_time > 5:
print('Type : ', obj.type)
print('Data : ', obj.data,'\n')
os.system("aplay ./audio/{0}".format(audio_list[int(obj.data)-1]))
privious_data = obj.data
## privious_time = time.time()
rawCapture.truncate(0)
except:
camera.stop_preview()
break
<file_sep># import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (800, 600)
rawCapture = PiRGBArray(camera)
# allow the camera to warmup
time.sleep(0.1)
# grab an image from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr",
use_video_port=True):
image = frame.array
# display the image on screen and wait for a keypress
cv2.imshow("Image", image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
rawCapture.truncate(0)
<file_sep># Cai dat cac goi sau:
sudo apt-get install libzbar-dev libzbar0 zbar-tools python-zbar
pip install -r requirement.txt
# Chuong trinh se mo camera tren Rasp, neu phat hien qr code, se in ra console data trong qr code do.
python qrcode.py
# nhan Control+C de thoat | 88851b3e4d3b61d965e8e1f64865fc8fa92f593f | [
"Python",
"Text",
"Shell"
] | 5 | Python | dehuy69/flashcard_reader | 181aef8c653445f062d3bbb6909667a6396c7e43 | 9eeaea798c3119550e9bf4146987dcf48f5a3d8f |
refs/heads/master | <file_sep>#<NAME>
Página WEB criada como atividade avaliativa da disciplina de linguagem de programação IV da Faculdade de Tecnologia de Jundiaí - FATEC.
###Equipe:
- <NAME>
- <NAME>
##Disponível em:
https://github.com/eltonbgomes/ArtesMarciais
<file_sep><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos - BJJ - Jiu Jitsu</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
<style type="text/css">
/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
/* Carousel base class */
.carousel {
margin-bottom: 4rem;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
bottom: 3rem;
z-index: 10;
}
/* Declare heights because of positioning of img element */
.carousel-item {
height:450px;
background-color: #777;
}
.carousel-item > img {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
height: 450px;
}
</style>
</head>
<?php
session_start();
?>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-10 text-right menu-1">
<ul>
<li><a href="index.php">Inicio</a></li>
<li><a href="gerar_orcamento.php">Ver preços</a></li>
<li class="has-dropdown ">
<a id="#drop" style="color: red">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsu.php">Jiu Jitsu </a></li>
<li><a href="muaythai.php" style="color: red">Muay Thai </a></li>
<li><a href="boxe.php">Boxe </a></li>
</ul>
</li>
<li><a href="contato.php">Contato</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<aside id="colorlib-hero">
<div class="flexslider" style="background:gray">
<ul class="slides">
<li style="background-image: url(images/img_bg_3.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-sm-12 col-md-offset-3 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
<li style="background-image: url(images/fotos/muay/b1.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-sm-12 col-md-offset-2 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
<li style="background-image: url(images/fotos/muay/b3.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-sm-12 col-md-offset-2 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</aside>
<div class="colorlib-classes">
<div class="container">
<div class="row">
<div class="col-md-7 animate-box">
<div class="classes">
<div class="classes-img classes-img-single" style="background-image: url(images/fotos/muay/b.jpg);"></div>
</div>
</div>
<div class="col-lg-5">
<div class="desc">
<h3 class="text-center"><a href="#"><NAME></a></h3>
<p class="text-justify"> O muay thai é uma das artes marciais que mais têm se destacado nas academias. O esporte possui origem tailandesa e também pode ser conhecido como “Boxe Tailandês”.</p>
<p class="text-justify"> É comum se questionar sobre quais contribuições um determinado esporte pode oferecer à sua vida, essa é uma pergunta chave para se apaixonar pelos exercícios. Os chutes e socos são muito recomendados para aqueles que desejam queimar as gordurinhas extras, mas os benefícios do Muay Thai não se limitam a isso.</p>
</div>
</div>
<div class="col-lg-12" style="margin-top:25px">
<p class="text-justify"> Se você está pensando em se inscrever em uma turma, conheça os principais benefícios do Muay Thai, e quais contribuições são válidas para sua vida.</p>
</div>
<div class="col-md-8 animate-box">
<div class="classes">
<h3 class="text-center">1 - Disciplina</h3>
<div class="classes-img classes-img-single" style="background-image: url(images/fotos/muay/disciplina.jpg);"></div>
<div class="desc">
<p class="text-justify"> Ela é fundamental não só no Muay Thai, mas em todos os esportes. A disciplina pode ser aplicada desde o início da prática, mas o aprendizado contribui para que respeite os limites dos adversários, e admita que a oposição deve existir apenas no posicionamento das aulas. A disciplina adquirida com o esporte pode não só ser posta em prática durante a aula, mas sim construir uma melhor doutrina comportamental em diversos campos da vida.
</p>
</div>
</div>
<div class="classes">
<h3 class="text-center">2 - Coordenação motora</h3>
<div class="classes-img classes-img-single" style="background-image: url(images/fotos/muay/coragem.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<p class="text-justify"> Esquiva, chuta, jab… Pois é, conciliar golpes e movimentos utilizando diversos membros de seu corpo pode se tornar uma tarefa difícil, mas isso ocorre apenas inicialmente. Os treinos regulares possibilitam que você se sinta cada vez mais preparado para atingir o oponente, ou se proteger de algum ataque.
</p>
<p class="text-justify"> Alguns benefícios do Muay Thai neste campo são que o seu tempo de reação será reduzido, seu reflexo ficará mais aguçado, e você se manterá em evolução enquanto se dedicar ao esporte.</p>
</div>
</div>
<div class="classes">
<h3 class="text-center">3 - Emagrece</h3>
<div class="classes-img classes-img-single" style="background-image: url(images/fotos/muay/emagrece.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<p class="text-justify"> O Muay Thai tem sido escolhido por diversas pessoas, e essa procura pode ser justificada principalmente pela sua contribuição para perda de peso. Se você praticar em média 90 minutos dessa luta, é possível eliminar em torno de 750 a 800 calorias, o que pode ser muito positivo para pessoas que estão com uma dieta voltada para perda de peso. Os benefícios do Muay Thai visam também a função cardiorrespiratória, o que favorece o melhor controle de respiração, e também a função metabólica.</p>
</div>
</div>
<div class="classes">
<h3 class="text-center">4 - Força</h3>
<div class="classes-img classes-img-single" style="background-image: url(images/fotos/muay/força.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<p class="text-justify"> O treinamento regular de Muay Thai pode ajudar a construir maior aptidão de resistência. Durante as aulas, o seu corpo ficará exposto a rotinas de exercícios de alta intensidade, o que favorece na sua evolução corporal, tornando-se assim mais forte e resistente. Dentro das academias, é importante destacar que não deve ser aplicada força sobre os oponentes, mas o conhecimento sobre os movimentos contribui para seu corpo ficar mais forte e preparado para possíveis choques ou pancadas.</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="side animate-box">
<h3 class="text-center">Detalhes Muay Thai</h3>
<ul>
<li><span>Professor:</span> <span><NAME></span></li>
<li><span>Aulas:</span> <span>Segunda, terça, quarta, quinta, sexta e sabado</span></li>
<li><span>Publico alvo:</span> <span>Todos os gêneros e idades</span></li>
<li><span>Preço:</span> <span><?php echo "R$ ".number_format($_SESSION["muayThaiMensalidade"], 2, ',', '.') ?></span></li>
</ul>
</div>
<div class="side animate-box text-center">
<h3 class="text-center">Professor</h3>
<div class="trainers-entry">
<div class="trainer-img" style="background-image: url(images/anderson-silva.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<h3><NAME></h3>
<span><NAME></span>
</div>
</div>
</div>
<div class="side animate-box" style="background: white;">
<h4 class="text-center">Graduação <NAME>ai</h4>
<img src="images/fotos/muay/graduacao.jpg" style="width: 100%; border: 1px solid black;height:400px">
</div>
</div>
</div>
</div>
</div> <!-- Fim div colorlib classes -->
<?php include 'rodape.php'?>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos - BJJ - Jiu Jitsu</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
<style type="text/css">
/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
/* Carousel base class */
.carousel {
margin-bottom: 4rem;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
bottom: 3rem;
z-index: 10;
}
/* Declare heights because of positioning of img element */
.carousel-item {
height:450px;
background-color: #777;
}
.carousel-item > img {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
height: 450px;
}
</style>
</head>
<?php
session_start();
//usar dados XML
$xml = simplexml_load_file("lutas.xml") -> jiujitsu;
?>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-10 text-right menu-1">
<ul>
<li><a href="index.php">Inicio</a></li>
<li><a href="gerar_orcamento.php">Ver preços</a></li>
<li class="has-dropdown ">
<a id="#drop" style="color: red">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsu.php" style="color: red">Jiu Jitsu </a></li>
<li><a href="muaythai.php">Muay Thai </a></li>
<li><a href="boxe.php">Boxe </a></li>
</ul>
</li>
<li><a href="contato.php">Contato</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<aside id="colorlib-hero">
<div class="flexslider">
<ul class="slides">
<li style="background-image: url(images/fotos/Jiu/b2.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-sm-12 col-md-offset-3 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
<li style="background-image: url(images/fotos/Jiu/b1.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-sm-12 col-md-offset-2 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</aside>
<div class="colorlib-classes">
<div class="container">
<div class="row">
<div class="col-md-8 animate-box">
<div class="classes">
<div class="classes-img classes-img-single" style="background-image: url(images/classes-9.jpg);"></div>
<div class="desc">
<h3><a href="#">Jiu jitsu brasileiro (Bjj)</a></h3>
<p class="text-justify"> Você sabe o que é jiu jitsu? Se você pensou que jiu jitsu é uma luta praticada por pessoas que têm um pitbull de estimação e que adoram arrumar briga na rua, muito bem: você errou feio !</p>
<p class="text-justify"> A tradução do termo jiu jitsu é “caminho suave”. Isso se deve aos seus princípios básicos, uma vez que essa prática privilegia o equilíbrio e o sistema de alavancas do corpo humano em detrimento do uso da força e das armas. Ou seja, uma luta que prioriza a consciência corporal ao invés da força, não pode ser associada às arruaças de rua.</p>
<p class="text-justify"> Os níveis de desenvolvimento de um atleta são representados pela cor da faixa que amarra o seu quimono. Para atletas adultos, as cores são: branca, azul, roxa, marrom, preta, coral e vermelha, em ordem crescente de habilidade. Já no que se refere às crianças, como modo de incentivo, há a inclusão de outras três cores de faixa, localizadas entre a branca e a azul, são elas: cinza, amarela, laranja e verde.</p>
</div>
</div>
<div class="classes-desc">
<div class="row row-pb-lg">
<div class="col-md-12">
<h3>Benefícios da prática de Jiu Jitsu</h3>
</div>
<div class="col-md-6">
<ul>
<?php foreach ($xml -> beneficios1 as $beneficios) { ?>
<li><i class="icon-check"></i>
<?php echo utf8_decode($beneficios); ?>
</li>
<?php } ?>
</ul>
</div>
<div class="col-md-6">
<ul>
<?php foreach ($xml -> beneficios2 as $beneficios) { ?>
<li><i class="icon-check"></i>
<?php echo utf8_decode($beneficios); ?>
</li>
<?php } ?>
</ul>
</div>
<div class="col-md-12">
<p class="text-justify"> O esporte favorece a conduta disciplinar do praticante, de respeito as regras e ao mestre. A hierarquia rígida de graduação também contribui para que o respeito adquirido na arte marcial ultrapasse o tatame. Inclusive, o jiu-jitsu é indicado para crianças e adolescente, para controlar a hiperatividade, ansiedade e proporcionar disciplina.</p>
<div class="col-md-12">
<h4>Combate a timidez</h4>
</div>
<p class="text-justify"> A arte vai te tirar da zona de conforto. Nela, pessoas menores e mais fracas podem dominar outras maiores. Você vai aprender a manter a calma, controlar a ansiedade, pensar em situações sob pressão e cansaço. Este tipo de situação é algo que você vive diariamente, no trabalho, na vida acadêmica, no relacionamento. O Jiu possibilita você controlar a adrenalina e a ansiedade, sofrer menos com o frio na barriga e até a deixar a timidez de lado.</p>
<br>
<p class="text-left">Fontes :</p>
<br>
<p style="font-size: 12px" class="col-lg-12 text-justify">https://manualdohomemmoderno.com.br/fitness/10-motivos-para-voce-praticar-jiu-jitsu
Manual do Homem Moderno<br>
<br>
RONDINELLI, Paula. "Jiu Jitsu"; Brasil Escola. Disponível em https://brasilescola.uol.com.br/educacao-fisica/jiu-jitsu.htm. Acesso em 09 de janeiro de 2019.
</p>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="side animate-box">
<h3>Detalhes Jiu Jitsu</h3>
<ul>
<li><span>Professor:</span> <span><NAME></span></li>
<li><span>Aulas:</span> <span>Segunda, terça, quarta, quinta, sexta e sabado</span></li>
<li><span>Publico alvo:</span> <span>Todos os gêneros e idades</span></li>
<li><span>Preço:</span> <span><?php echo "R$ ".number_format($_SESSION["jiujitsuMensalidade"], 2, ',', '.') ?></span></li>
</ul>
</div>
<div class="side animate-box text-center">
<h3>Professor</h3>
<div class="trainers-entry">
<div class="trainer-img" style="background-image: url(images/mc-gregor.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<h3><NAME></h3>
<span>Jiu Jitsu</span>
</div>
</div>
</div>
<div class="side animate-box" style="background: white;">
<h4 class="text-center">Faixas Jiu jitsu</h4>
<img src="images/fotos/Jiu/faixas.png" style="width: 100%; border: 1px solid black;">
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12 col-lg-12 animate-box">
<h3 class="text-center"><strong>Razões para uma criança treinar Jiu Jitsu</strong></h3>
<div class="col-md-1"></div>
<div class="classes col-md-9">
<div class="classes-img classes-img-single" style="background-image: url(images/fotos/Jiu/bjjcriancas.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
</div>
<div class="desc text-justify" style="color:black">
<p>
<ul>
<strong><li>Socialização:</strong> o tatame é um ótimo lugar para sua criança conhecer novos amigos. É um lugar que se reúnem pessoas de diversos países e culturas, unidos por um objetivo em comum. As amizades feitas no treino costumas ser leais e duradouras.</li>
<br>
<strong><li>Coordenação motora e consciência corporal:</strong> Uma criança que treina Jiu Jitsu vai melhorar naturalmente sua coordenação motora e consciência corporal. Isto vai ajudar na sua postura, caligrafia e cuidado nas atividades do dia a dia.</li>
<br>
<strong><li>Defesa Pessoal:</strong> Hoje em dia a segurança é preocupação de todos os pais. Uma criança que treina Jiu Jitsu vai poder se defender de um ataque de outro colega, e até seus irmãos menores do bulling. A artes marcial também ensina a criança sempre se defender na medida certa, nuca usando da covardia contra outra criança que não treina.</li>
</ul>
</p>
</div>
<div class="classes-img classes-img-single" style="background-image: url(images/fotos/Jiu/bjjcriancas1.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
</div>
<div class="desc text-justify" style="color:black">
<p>
<ul>
<strong><li>Humildade: </strong> o Jiu Jitsu ensina as qualidades de você ser humilde inclusive na vitória. A ética de não comemorar finalizações no treino, nem comentar seus melhores golpes, ensina para a criança o valor de respeitar até os adversários mais fracos.</li>
<br>
<strong><li>Disciplina: </strong> o tatame nas aulas infantis é um ambiente extremamente lúdico. Mas existe hora para tudo. A criança acaba seguindo o exemplo dos alunos mais graduados e aprende a ouvir e prestar atenção em diversos momentos da aula.</li>
<br>
<strong><li>Diversão:</strong> Talvez a razão mais importante que toda criança, e até adultos, devem começar no Jiu Jitsu é porque é extremamente divertido.</li>
</ul>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include 'rodape.php'?>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep><?php
session_start();
$nome = $_POST["nome"];
$cpf = $_POST["cpf"];
$email = $_POST["email"];
$telefone = $_POST["telefone"];
if(isset($_POST["mua"])){
$mua = "true";
} else {
$mua = "false";
}
if(isset($_POST["box"])){
$box = "true";
} else {
$box = "false";
}
if(isset($_POST["jiu"])){
$jiu = "true";
} else {
$jiu = "false";
}
// SALVANDO EM JSON
$fp = fopen("cliente.json", "w");
fwrite($fp,json_encode($_POST));
fclose($fp);
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Owl Carousel -->
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation" style="background: black">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-4">
<div id="colorlib-logo"><a href="index.php" style="font-size:18px">Espartanos</a></div>
</div>
<div class="col-md-8 text-right menu-1">
<ul>
<li ><a href="index.php">Inicio</a></li>
<li ><a href="gerar_orcamento.php">Ver preços</a></li>
<li class="has-dropdown ">
<a id="#drop">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsu.php"><NAME> </a></li>
<li><a href="muaythai.php"><NAME> </a></li>
<li><a href="boxe.php">Boxe </a></li>
</ul>
</li>
<li><a href="consulta.php">Consulta</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<br><br><br><br>
<div id="colorlib-contact">
<div class="container">
<h1>Olá, <?php echo $nome ?>.</h1><br><br>
<?php
$dia = date('d');
$numMes = 0;
$mes = date('m');
$ano = date('Y');
switch ($mes) {
case 1:
$mes = "Janeiro";
$numMes = 1;
break;
case 2:
$mes = "Fevereiro";
$numMes = 2;
break;
case 3:
$mes = "Março";
$numMes = 3;
break;
case 4:
$mes = "Abril";
$numMes = 4;
break;
case 5:
$mes = "Maio";
$numMes = 5;
break;
case 6:
$mes = "Junho";
$numMes = 6;
break;
case 7:
$mes = "Julho";
$numMes = 7;
break;
case 8:
$mes = "Agosto";
$numMes = 8;
break;
case 9:
$mes = "Setembro";
$numMes = 9;
break;
case 10:
$mes = "Outubro";
$numMes = 10;
break;
case 11:
$mes = "Novembro";
$numMes = 11;
break;
case 12:
$mes = "Dezembro";
$numMes = 12;
break;
}
$texto_orcamento = "Seu orçamento foi gerado em: Jundiaí, <span style='color:green'>" . $dia . " de " . $mes . " de " . $ano . "</span> e ";
$mesSeguinte = $numMes+1;
switch ($mesSeguinte) {
case 1:
$mesSeguinte = "Janeiro";
break;
case 2:
$mesSeguinte = "Fevereiro";
break;
case 3:
$mesSeguinte = "Março";
break;
case 4:
$mesSeguinte = "Abril";
break;
case 5:
$mesSeguinte = "Maio";
break;
case 6:
$mesSeguinte = "Junho";
break;
case 7:
$mesSeguinte = "Julho";
break;
case 8:
$mesSeguinte = "Agosto";
break;
case 9:
$mesSeguinte = "Setembro";
break;
case 10:
$mesSeguinte = "Outubro";
break;
case 11:
$mesSeguinte = "Novembro";
break;
case 12:
$mesSeguinte = "Dezembro";
break;
}
$texto_orcamento .= "possui validade até: <span style='color:red'>" . $dia . " de " . $mesSeguinte . " de " . $ano . "</span>.";
?>
<h4><?php echo $texto_orcamento . "<br>";?></h4>
<h4><u>Artes Marciais escolhidas e seu preço final:</u></h4>
<hr>
<?php
$valor_total = 0;
$cursos_escolhidos = "";
if($jiu == "true"){
$cursos_escolhidos .= "Jiu Jitsu: ".$_POST["mesesJiu"]." mes(es).<br> Total de R$ ".
number_format($_SESSION["jiujitsuMensalidade"]*$_POST["mesesJiu"], 2, ',', '.')."<br><hr>";
$valor_total += $_SESSION["jiujitsuMensalidade"]*$_POST["mesesJiu"];
}
if($box == "true"){
$cursos_escolhidos .= "Boxe: ".$_POST["mesesBoxe"]." mes(es).<br> Total de R$ ".
number_format($_SESSION["boxeMensalidade"]*$_POST["mesesBoxe"], 2, ',', '.')."<br><hr>";
$valor_total += $_SESSION["boxeMensalidade"]*$_POST["mesesBoxe"];
}
if($mua == "true"){
$cursos_escolhidos .= "Muay Thai: ".$_POST["mesesMuay"]." mes(es). <br>Total de R$ ".
number_format($_SESSION["muayThaiMensalidade"]*$_POST["mesesMuay"], 2, ',', '.')."<br><hr>";
$valor_total += $_SESSION["muayThaiMensalidade"]*$_POST["mesesMuay"];
}
echo $cursos_escolhidos;
if($_POST["desconto"] != "" && $_POST["desconto"] != 0 && $_POST["desconto"] < 100 ){
$valor_desconto = $_POST["desconto"]/100 * $valor_total;
$valor_total = $valor_total * ( 1 - ($_POST["desconto"]/100) );
echo "Você inseriu um cupom de " . $_POST["desconto"] . "% de desconto.<br>";
echo "Valor do desconto: R$ " . number_format($valor_desconto, 2, ',', '.'). "<br>";
echo "<br><b>Valor total com desconto: R$ " . number_format($valor_total, 2, ',', '.') . "</b>";
} else {
echo "<b>Valor total: R$ " . number_format($valor_total, 2, ',', '.') . "</b>";
}
?>
</div>
</div>
<?php include 'rodape.php' ?>
</div>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Google Map -->
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false"></script>
<script src="js/google_map.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep><?php
session_start();
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Owl Carousel -->
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.input-margin input {
margin-left: 15px;
}
</style>
</head>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation" style="background: black">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-4">
<div id="colorlib-logo"><a href="index.php" style="font-size:18px">Espartanos</a></div>
</div>
<div class="col-md-8 text-right menu-1">
<ul>
<li ><a href="index.php">Inicio</a></li>
<li class="has-dropdown ">
<a id="#drop">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsuMensalidade.php">Jiu Jitsu </a></li>
<li><a href="muaythai.php">Muay Thai </a></li>
<li><a href="boxe.php">Boxe </a></li>
</ul>
</li>
<li class="active"><a href="contato.php">Contato</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<br><br><br><br>
<div id="colorlib-contact">
<div class="container">
<div class="row">
<div class="colorlib-classes">
<div class="container">
<div class="row">
<div class="col-md-4 animate-box">
<div class="classes">
<div class="classes-img" style="background-image: url(images/jiu.jpg);">
</div>
<div class="desc">
<h3 align="center">
<a href="#">Jiu-Jitsu </a>
</h3>
<p align="center" style="font-size: 3.5rem">
<?php echo "R$ ".number_format($_SESSION["jiujitsuMensalidade"], 2, ',', '.')." / Mês" ?>
</p>
</div>
</div>
</div>
<div class="col-md-4 animate-box">
<div class="classes">
<div class="classes-img" style="background-image: url(images/boxe.jpg);">
</div>
<div class="desc">
<h3 align="center">
<a href="#">Boxe</a>
</h3>
<p align="center" style="font-size: 3.5rem">
<?php echo "R$ ".number_format($_SESSION["boxeMensalidade"], 2, ',', '.')." / Mês" ?>
</p>
</div>
</div>
</div>
<div class="col-md-4 animate-box">
<div class="classes">
<div class="classes-img" style="background-image: url(images/muay.jpg);">
</div>
<div class="desc">
<h3 align="center">
<a href="#">Muay Thai </a>
</h3>
<p align="center" style="font-size: 3.5rem">
<?php echo "R$ ".number_format($_SESSION["muayThaiMensalidade"], 2, ',', '.')." / Mês" ?>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-10 col-md-offset-1 animate-box">
<h2>Vamos gerar um orçamento para você!</h2>
<form action="pegar_dados.php" method="post">
<div class="row form-group">
<div class="col-md-6">
<!-- <label for="fname">First Name</label> -->
<input type="text" name="nome" id="nome" class="form-control" placeholder="Insira seu nome" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-6">
<!-- <label for="fname">First Name</label> -->
<input type="number" name="cpf" id="cpf" class="form-control" placeholder="Insira seu CPF" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="email" name="email" id="email" class="form-control" placeholder="Insira o Email" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="number" name="telefone" id="telefone" class="form-control" placeholder="Telefone para contato" required>
</div>
</div>
<?php
$dia = date('d');
$numMes = 0;
$mes = date('m');
$ano = date('Y');
switch ($mes) {
case 1:
$mes = "Janeiro";
$numMes = 1;
break;
case 2:
$mes = "Fevereiro";
$numMes = 2;
break;
case 3:
$mes = "Março";
$numMes = 3;
break;
case 4:
$mes = "Abril";
$numMes = 4;
break;
case 5:
$mes = "Maio";
$numMes = 5;
break;
case 6:
$mes = "Junho";
$numMes = 6;
break;
case 7:
$mes = "Julho";
$numMes = 7;
break;
case 8:
$mes = "Agosto";
$numMes = 8;
break;
case 9:
$mes = "Setembro";
$numMes = 9;
break;
case 10:
$mes = "Outubro";
$numMes = 10;
break;
case 11:
$mes = "Novembro";
$numMes = 11;
break;
case 12:
$mes = "Dezembro";
$numMes = 12;
break;
}
$data_geramento = $dia . " de " . $mes . " de " . $ano;
$mesSeguinte = $numMes+1;
switch ($mesSeguinte) {
case 1:
$mesSeguinte = "Janeiro";
break;
case 2:
$mesSeguinte = "Fevereiro";
break;
case 3:
$mesSeguinte = "Março";
break;
case 4:
$mesSeguinte = "Abril";
break;
case 5:
$mesSeguinte = "Maio";
break;
case 6:
$mesSeguinte = "Junho";
break;
case 7:
$mesSeguinte = "Julho";
break;
case 8:
$mesSeguinte = "Agosto";
break;
case 9:
$mesSeguinte = "Setembro";
break;
case 10:
$mesSeguinte = "Outubro";
break;
case 11:
$mesSeguinte = "Novembro";
break;
case 12:
$mesSeguinte = "Dezembro";
break;
}
$data_validade = $dia . " de " . $mesSeguinte . " de " . $ano;
?>
<input type="hidden" name="validade" value="<?php echo $data_validade?>" >
<input type="hidden" name="gerado" value="<?php echo $data_geramento?>" >
<h3>Escolha as artes marciais que você deseja treinar</h3>
<br>
<!-- Jiu Jitsu -->
<input class="form-check-input" type="checkbox" value="true" id="jiu" name="jiu"> Jiu Jitsu
<br>
<div id="mesesJiu" style="display: none" class="input-margin">
<input type="radio" name="mesesJiu" value="1" checked> 1 Mês
<input type="radio" name="mesesJiu" value="3"> 3 Meses
<input type="radio" name="mesesJiu" value="12"> 12 Meses
</div>
<!-- end Jiu Jitsu -->
<br>
<!-- Boxe -->
<input class="form-check-input" type="checkbox" value="true" id="box" name="box"> Boxe
<br>
<div id="mesesBoxe" style="display: none" class="input-margin">
<input type="radio" name="mesesBoxe" value="1" checked> 1 Mês
<input type="radio" name="mesesBoxe" value="3"> 3 Meses
<input type="radio" name="mesesBoxe" value="12"> 12 Meses
</div>
<!-- end Boxe -->
<br>
<!-- Muay Thai -->
<input class="form-check-input" type="checkbox" value="true" id="mua" name="mua"> Muay Thai
<br>
<div id="mesesMuay" style="display: none" class="input-margin">
<input type="radio" name="mesesMuay" value="1" checked> 1 Mês
<input type="radio" name="mesesMuay" value="3"> 3 Meses
<input type="radio" name="mesesMuay" value="12"> 12 Meses
</div>
<!-- end Muay Thai -->
<br><br>
<div class="row form-group">
<div class="col-md-6">
<label for="desconto">Desconto</label>
<input type="number" name="desconto" id="desconto" class="form-control" placeholder="Insira o desconto em porcentagem (Ex 25% = 25)" min="0" max="100">
</div>
</div>
<br>
<br> <br>
<div class="form-group">
<input type="submit" value="Gerar" class="btn btn-success" name="enviar">
<input type="reset" value="Limpar" class="btn btn-primary" name="limpar">
</div>
</form>
</div>
</div>
</div>
</div>
<?php include 'rodape.php' ?>
</div>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<script type="text/javascript" src="gerar_orcamento.js"></script>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Google Map -->
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false"></script>
<script src="js/google_map.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep><?php
$cliente = json_decode(file_get_contents('cliente.json'));
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Owl Carousel -->
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.dados {
margin-left: 1.5rem;
}
</style>
</head>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation" style="background: black">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-4">
<div id="colorlib-logo"><a href="index.php" style="font-size:18px">Espartanos</a></div>
</div>
<div class="col-md-8 text-right menu-1">
<ul>
<li ><a href="index.php">Inicio</a></li>
<li ><a href="gerar_orcamento.php">Ver preços</a></li>
<li class="has-dropdown ">
<a id="#drop">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsu.php">Jiu Jitsu </a></li>
<li><a href="muaythai.php">Muay Thai </a></li>
<li><a href="boxe.php">Boxe </a></li>
</ul>
</li>
<li class="active"><a href="consulta.php">Consulta</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<br><br><br><br>
<div id="colorlib-contact">
<div class="container">
<h1>Orçamento do Último cliente</h1><br><br>
<h2 style="color: green">Cliente gerou orçamento em : <?php echo $cliente->gerado ?></h2>
<h2 style="color: red">Validade do orçamento : <?php echo $cliente->validade ?></h2>
<br><br>
<h2>Dados pessoais</h2>
<p class="dados">Nome: <?php echo $cliente->nome ?></p>
<p class="dados">CPF: <?php echo $cliente->cpf ?></p>
<p class="dados">Email: <?php echo $cliente->email ?></p>
<p class="dados">Telefone: <?php echo $cliente->telefone ?></p>
<h2><NAME></h2>
<?php
$valor_total = 0;
if(isset($cliente->jiu)){
if($cliente->mesesJiu == 1) {
echo "Jiu jitsu: ". $cliente->mesesJiu." mes<br>";
} else {
echo "Jiu jitsu: ". $cliente->mesesJiu." meses<br>";
}
echo "R$ ".number_format($cliente->mesesJiu*70, 2, ',', '.');
echo "<hr>";
$valor_total += $cliente->mesesJiu*70;
}
if(isset($cliente->mua)){
if($cliente->mesesMuay == 1) {
echo "Muay Thai: ". $cliente->mesesMuay." mes<br>";
} else {
echo "Muay Thai: ". $cliente->mesesMuay." meses<br>";
}
echo "R$ ".number_format($cliente->mesesMuay*90, 2, ',', '.');
echo "<hr>";
$valor_total += $cliente->mesesMuay*90;
}
if(isset($cliente->box)){
if($cliente->mesesBoxe == 1) {
echo "Boxe: ". $cliente->mesesBoxe." mes<br>";
} else {
echo "Boxe: ". $cliente->mesesBoxe." meses<br>";
}
echo "R$ ".number_format($cliente->mesesBoxe*75, 2, ',', '.');
echo "<hr>";
$valor_total += $cliente->mesesBoxe*75;
}
?>
<?php
if($cliente->desconto != "" && $cliente->desconto != 0 && $cliente->desconto < 100){
echo "O cliente possui cupom de " . $cliente->desconto . "% de desconto !<hr>";
echo "<h3>Preço total: R$ " . number_format( ($valor_total * (1 - ($cliente->desconto/100))), 2, ',', '.') ."</h3>";
} else {
echo "O cliente <span style='color:red'>NÃO</span> possui cupom de desconto !<hr>";
echo "<h3>Preço total: R$ " . number_format($valor_total, 2, ',', '.') . "</h3>";
}
?>
</div>
</div>
<?php include 'rodape.php' ?>
</div>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Google Map -->
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false"></script>
<script src="js/google_map.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Owl Carousel -->
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation" style="background: black">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-4">
<div id="colorlib-logo"><a href="index.php" style="font-size:18px">Espartanos</a></div>
</div>
<div class="col-md-8 text-right menu-1">
<ul>
<li ><a href="index.php">Inicio</a></li>
<li ><a href="gerar_orcamento.php">Ver preços</a></li>
<li class="has-dropdown ">
<a id="#drop">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsu.php">Jiu Jitsu </a></li>
<li><a href="muaythai.php">Mu<NAME> </a></li>
<li><a href="boxe.php">Boxe </a></li>
</ul>
</li>
<li class="active"><a href="contato.php">Contato</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<br><br><br><br>
<div id="colorlib-contact">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1 animate-box">
<h2>Informações de Contato</h2>
<div class="row">
<div class="col-md-12">
<div class="contact-info-wrap-flex">
<div class="con-info">
<p><span><i class="icon-location-2"></i> Endereço: </span> <br>R. Rua, 112 - Bairro, Cidade - SP, 00000-000</p>
</div>
<div class="con-info">
<p><span><i class="icon-phone3"></i></span> <a href="#">(11) 0000-3669</a></p>
</div>
<div class="con-info" style="width:auto">
<p><span><i class="icon-paperplane"></i></span> <a href="#"><EMAIL></a></p>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-10 col-md-offset-1 animate-box">
<br><br>
<br><br>
<h2>Entre em Contato</h2>
<form action="enviodeemail.php" method="post">
<div class="row form-group">
<div class="col-md-6">
<!-- <label for="fname">First Name</label> -->
<input type="text" name="nome" id="fname" class="form-control" placeholder="Insira seu nome" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="email" name="email" id="email" class="form-control" placeholder="Insira o Email" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="number" name="telefone" id="subject" class="form-control" placeholder="Telefone para contato" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="message">Message</label> -->
<textarea name="msg" id="message" cols="30" rows="10" class="form-control" placeholder="Mensagem . . ." required></textarea>
</div>
</div>
<div class="form-group">
<input type="submit" value="Enviar" class="btn btn-primary" name="enviar">
</div>
</form>
</div>
</div>
</div>
</div>
<?php include 'rodape.php' ?>
</div>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Google Map -->
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false"></script>
<script src="js/google_map.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos - BOXE</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
<style type="text/css">
/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
/* Carousel base class */
.carousel {
margin-bottom: 4rem;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
bottom: 3rem;
z-index: 10;
}
/* Declare heights because of positioning of img element */
.carousel-item {
height:450px;
background-color: #777;
}
.carousel-item > img {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
height: 450px;
}
</style>
</head>
<?php
session_start();
//usar dados XML
$xml = simplexml_load_file("lutas.xml") -> boxe;
?>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-10 text-right menu-1">
<ul>
<li><a href="index.php">Inicio</a></li>
<li><a href="gerar_orcamento.php">Ver preços</a></li>
<li class="has-dropdown ">
<a id="#drop" style="color: red">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsu.php">Jiu Jitsu </a></li>
<li><a href="muaythai.php">Muay Thai </a></li>
<li><a href="boxe.php" style="color: red">Boxe </a></li>
</ul>
</li>
<li><a href="contato.php">Contato</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<aside id="colorlib-hero">
<div class="flexslider">
<ul class="slides">
<li style="background-image: url(images/boxe1.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-sm-12 col-md-offset-3 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
<li style="background-image: url(images/boxe2.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-sm-12 col-md-offset-2 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</aside>
<div class="colorlib-classes">
<div class="container">
<div class="row">
<div class="col-md-8 animate-box">
<div class="classes">
<div class="classes-img classes-img-single" style="background-image: url(images/boxe3.jpg);"></div>
<div class="desc">
<h3><a href="#">Boxe</a></h3>
<p class="text-justify"> O boxe é tradicionalmente um tipo de luta que tem como principal característica o combate “homem a homem” utilizando-se apenas dos punhos. Por ser um meio de combate, o boxe apenas passou a integrar o calendário moderno dos Jogos Olímpicos em 1920, na Olimpíada de Antuérpia (Bélgica). O Comitê Olímpico Internacional acreditava que o boxe era uma prática que incitava a violência, fato que contrariava o ideal de fraternidade, mote estreitamente vinculado ao espírito olímpico.</p>
<p class="text-justify"> Deve-se ressaltar que o boxe é uma luta bastante tradicional no Ocidente. Há relatos de que ela era praticada entre jovens, na Creta Antiga. Outro elemento a ser considerado são os indicativos de que o boxe integrou os Jogos Olímpicos da Antiguidade. Porém, tratando de um período mais recente, foi na Inglaterra dos séculos XVIII e XIX que o boxe ficou bastante popular: era um combate de rua, lutado com as mãos desprotegidas, marcado pela violência dos golpes. A versão moderna do boxe foi oficializada em 1867, porém foram colocadas efetivamente em prática apenas em 1872, com as regras de Queensberry: o uso de luvas era obrigatório e o confronto era composto de rounds de três minutos cada. Atualmente, uma luta de boxe é constituída de dez rounds. Em alguns casos excepcionais, a partida pode ter até doze.</p>
<p class="text-justify"> Uma curiosidade é que, mesmo sob o domínio da Associação Mundial de Boxe, as regras não são as mesmas entre as competições amadoras e profissionais. Variam, inclusive, entre as diferentes comissões organizadoras profissionais. Um fato muito comum é o de antes de uma grande luta, as regras gerais e particulares são expostas em uma reunião entre as duas partes que entrarão em confronto. As organizadoras da luta também decidem sobre o tamanho do ringue, mas sua estrutura deve ser sempre a mesma em todas as lutas: trata-se de uma plataforma quadrada elevada com uma superfície de lona acolchoada. Em todo caso, a área máxima de um ringue deve ser de 6,10 metros quadrados.</p>
</div>
</div>
<div class="classes-desc">
<div class="row row-pb-lg">
<div class="col-md-12">
<h3>Benefícios da prática de Boxe</h3>
</div>
<div class="col-md-6">
<ul>
<?php foreach ($xml -> beneficios1 as $beneficios) { ?>
<li><i class="icon-check"></i>
<?php echo utf8_decode($beneficios); ?>
</li>
<?php } ?>
</ul>
</div>
<div class="col-md-6">
<ul>
<?php foreach ($xml -> beneficios2 as $beneficios) { ?>
<li><i class="icon-check"></i>
<?php echo utf8_decode($beneficios); ?>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="side animate-box">
<h3>Detalhes Boxe</h3>
<ul>
<li><span>Professor:</span> <span><NAME></span></li>
<li><span>Aulas:</span> <span>Segunda, terça, quarta, quinta, sexta e sabado</span></li>
<li><span>Publico alvo:</span> <span>Todos os gêneros e idades</span></li>
<li><span>Preço:</span> <span><?php echo "R$ ".number_format($_SESSION["boxeMensalidade"], 2, ',', '.') ?></span></li>
</ul>
</div>
<div class="side animate-box text-center">
<h3>Professor</h3>
<div class="trainers-entry">
<div class="trainer-img" style="background-image: url(images/mc-gregor.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<h3><NAME></h3>
<span>Boxe</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12 col-lg-12 animate-box">
<h3 class="text-center"><strong>Razões para praticar</strong></h3>
<div class="col-md-1"></div>
<div class="classes col-md-9">
<div class="classes-img classes-img-single" style="background-image: url(images/boxe4.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
</div>
<div class="desc text-justify" style="color:black">
<p>
<ul>
<strong><li>Queima de calorias:</strong> Se você está acima do peso ou se preocupa em manter a boa forma, saiba que o boxe pode ajudar você nesse quesito. Em uma hora, é possível queimar até 1200 calorias, especialmente por causa dos movimentos esquiva e pêndulo. Além do mais, bater nos sacos de areia e treinar com oponentes também são atividades intensas, que exigem muito do corpo.</li>
<br>
<strong><li>Definição muscular:</strong>
Os exercícios intensos praticados no boxe são excelentes para definir massa muscular, principalmente nas pernas, nos braços e na panturrilha. Além disso, é possível afinar a cintura e defini-la.</li>
<br>
<strong><li>Correção da postura:</strong> As mulheres, quando precisam corrigir a postura, normalmente fazem aulas de Pilates. Os homens podem praticar boxe para alinhar a coluna, porque há fortalecimento da região lombar e definição do abdômen.</li>
</ul>
</p>
</div>
<div class="classes-img classes-img-single" style="background-image: url(images/boxe5.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
</div>
<div class="desc text-justify" style="color:black">
<p>
<ul>
<strong><li> Ganho de resistência: </strong> É claro que a alta intensidade dos exercícios praticados no boxe proporciona ganho de resistência. Portanto, se você quer aumentar a capacidade do coração e da respiração, saiba que o boxe é excelente para gerar condicionamento físico.
Mesmo nas aulas mais tranquilas é possível queimar 600 calorias, porque o atleta levantará pesos, praticará corrida, fará abdominais e atividades em circuito.</li>
<br>
<strong><li>Defesa Pessoal: </strong> Se você já pensou em fazer aulas de judô ou caratê para conhecer técnicas de defesa pessoal, saiba que praticar boxe pode resolver o seu problema. Além de ser um esporte, é uma atividade que ensina defesa, inclusive para uso em grandes cidades.</li>
<br>
<strong><li>Diversão:</strong> Talvez a razão mais importante que toda criança, e até adultos, devem começar no Boxe é porque é extremamente divertido.</li>
</ul>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include 'rodape.php'?>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep><?php
session_start();
//valores das mensalidades
$_SESSION["jiujitsuMensalidade"] = 69.98;
$_SESSION["boxeMensalidade"] = 74.98;
$_SESSION["muayThaiMensalidade"] = 89.98;
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Espartanos</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Facebook and Twitter integration -->
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,700,900" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Flexslider -->
<link rel="stylesheet" href="css/flexslider.css">
<!-- Owl Carousel -->
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<!-- Flaticons -->
<link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="colorlib-loader"></div>
<div id="page">
<nav class="colorlib-nav" role="navigation">
<div class="top-menu">
<div class="container">
<div class="row">
<div class="col-md-2">
<div id="colorlib-logo"><a href="index.php"><img src="images/icon.png" height="100" width="100"></a></div>
</div>
<div class="col-md-10 text-right menu-1">
<ul>
<li class="active"><a href="index.php">Inicio</a></li>
<li><a href="gerar_orcamento.php">Ver preços</a></li>
<li class="has-dropdown ">
<a id="#drop">Artes Marciais</a>
<ul class="dropdown" id="drop">
<li><a href="jiujitsu.php">Jiu Jitsu </a></li>
<li><a href="muaythai.php">Muay Thai </a></li>
<li><a href="boxe.php">Boxe </a></li>
</ul>
</li>
<li><a href="contato.php">Contato</a></li>
<li><a href="consulta.php" style="color: darkblue">Consultar</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<aside id="colorlib-hero">
<div class="flexslider">
<ul class="slides">
<li style="background-image: url(images/apresentacao.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;">
<div class="overlay"></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-sm-12 col-md-offset-2 slider-text">
<div class="slider-text-inner text-center">
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</aside>
<div id="colorlib-services" style="background: lightgray;margin-top:710px">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center colorlib-heading animate-box">
<h2>Os Espartanos</h2>
<p>Academia de artes marciais</p>
</div>
</div>
</div>
</div>
<div class="colorlib-classes">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center colorlib-heading animate-box">
<h2>MODALIDADES</h2>
</div>
<div class="col-md-4 animate-box">
<div class="classes">
<div class="classes-img" style="background-image: url(images/jiu.jpg);">
</div>
<div class="desc">
<h3><a href="#">Jiu-Jitsu </a></h3>
<p>O jiu-jitsu é uma arte marcial de origem japonesa. Ela é voltada para o ataque e autodefesa. Jujutsu, mais conhecido na sua forma ocidentalizada Jiu-jitsu, ju-jitsu, é uma arte marcial japonesa que utiliza técnicas de golpes de alavancas.</p>
<p><a href="jiujitsu.php" class="btn-learn" style="color: darkblue">Leia Mais <i class="icon-arrow-right3"></i></a></p>
</div>
</div>
</div>
<div class="col-md-4 animate-box">
<div class="classes">
<div class="classes-img" style="background-image: url(images/boxe.jpg);">
</div>
<div class="desc">
<h3><a href="#">Boxe</a></h3>
<p>O boxe ou pugilismo é um esporte de combate, no qual os lutadores usam apenas os punhos, tanto para a defesa, quanto para o ataque. A palavra deriva do inglês box, ou pugilismo, expressão utilizada na Inglaterra entre 1000 e 1850.</p>
<p><a href="#" class="btn-learn" style="color: darkblue">Leia Mais <i class="icon-arrow-right3"></i></a></p>
</div>
</div>
</div>
<div class="col-md-4 animate-box">
<div class="classes">
<div class="classes-img" style="background-image: url(images/muay.jpg);">
</div>
<div class="desc">
<h3><a href="#">Muay Thai</a></h3>
<p>Muay thai é uma arte marcial originária da Tailândia, onde é considerado desporto nacional. Esta disciplina física e mental que inclui golpes de combate em pé, é conhecida como "a arte das oito armas"</p><br>
<p><a href="muaythai.php" class="btn-learn" style="color: darkblue"><NAME> <i class="icon-arrow-right3"></i></a></p>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="colorlib-schedule" class="colorlib-light-grey">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center colorlib-heading animate-box">
<h2>Cronograma de aulas </h2>
</div>
</div>
<div class="row">
<div class="schedule text-center animate-box">
<div class="col-md-12">
<ul class="week nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#seg" role="tab" aria-controls="seg" aria-selected="true">Segunda</a>
</li>
<li class="nav-item">
<a class="nav-link" id="profile-tab" data-toggle="tab" href="#ter" role="tab" aria-controls="ter" aria-selected="false">Terça</a>
</li>
<li class="nav-item"><a class="nav-link" id="contact-tab" data-toggle="tab" href="#qua" role="tab" aria-controls="qua" aria-selected="false">Quarta</a>
</li>
<li><a class="nav-link" id="contact-tab" data-toggle="tab" href="#qui" role="tab" aria-controls="qui" aria-selected="false">Quinta</a>
</li>
<li><a class="nav-link" id="contact-tab" data-toggle="tab" href="#sex" role="tab" aria-controls="sex" aria-selected="false">Sexta</a>
</li>
<li><a class="nav-link" id="contact-tab" data-toggle="tab" href="#sab" role="tab" aria-controls="sab" aria-selected="false">Sábado</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade" id="seg" role="tabpanel" aria-labelledby="home-tab">
<div class="schedule-flex">
<div class="entry-forth">
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/muay1.png" height="70" width="70"></span></p>
<p class="time"><span>19:00</span></p>
<h3><NAME></h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>20:30</span></p>
<h3><NAME></h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
</div>
</div>
<div class="tab-pane fade" id="ter" role="tabpanel" aria-labelledby="profile-tab">
<div class="schedule-flex">
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>09:00</span></p>
<h3>Jiu-Jitsu</h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>17:00</span></p>
<h3>Jiu-Jitsu</h3>
<p class="trainer"><span>Professor Conor McGregor</span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/funcional.png" height="70" width="60" ></span></p>
<p class="time"><span>18:00</span></p>
<h3>Treino - Funcional</h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>19:00</span></p>
<h3>Jiu-Jitsu para crianças </h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
</div>
<div class="schedule-flex">
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>20:00</span></p>
<h3>Jiu-Jitsu </h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/boxe1.jpg" height="90" width="90" class="img-circle"></span></p>
<p class="time"><span>21:00</span></p>
<h3>Boxe</h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
</div>
</div>
<div class="tab-pane fade" id="qua" role="tabpanel" aria-labelledby="contact-tab">
<div class="schedule-flex">
<div class="entry-forth">
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/muay1.png" height="70" width="70"></span></p>
<p class="time"><span>19:00</span></p>
<h3><NAME></h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>20:30</span></p>
<h3><NAME></h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
</div>
</div>
<div class="tab-pane fade" id="qui" role="tabpanel" aria-labelledby="profile-tab">
<div class="schedule-flex">
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>09:00</span></p>
<h3>Jiu-Jitsu</h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>17:00</span></p>
<h3>Jiu-Jitsu</h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/funcional.png" height="70" width="60" ></span></p>
<p class="time"><span>18:00</span></p>
<h3>Treino - Funcional</h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>19:00</span></p>
<h3>Jiu-Jitsu para crianças </h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
</div>
<div class="schedule-flex">
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>20:00</span></p>
<h3>Jiu-Jitsu </h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/boxe1.jpg" height="90" width="90" class="img-circle"></span></p>
<p class="time"><span>21:00</span></p>
<h3>Boxe</h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
</div>
</div>
<div class="tab-pane fade" id="sex" role="tabpanel" aria-labelledby="contact-tab">
<div class="schedule-flex">
<div class="entry-forth">
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/muay1.png" height="70" width="70"></span></p>
<p class="time"><span>19:00</span></p>
<h3><NAME></h3>
<p class="trainer"><span>Professor <NAME></span></p>
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>20:30</span></p>
<h3><NAME></h3>
<p class="trainer"><span>Professor Conor McGregor</span></p>
</div>
</div>
</div>
<div class="tab-pane fade" id="sab" role="tabpanel" aria-labelledby="contact-tab">
<div class="schedule-flex">
<div class="entry-forth">
</div>
<div class="entry-forth">
<p class="icon"><span><img src="images/bjj.png" height="70" width="70"></span></p>
<p class="time"><span>09:00</span></p>
<h3><NAME></h3>
<p class="trainer"><span>Professor Conor McGregor</span></p>
</div>
</div>
</div>
</div><!-- tab content -->
</div>
</div>
</div>
</div>
</div>
<div class="colorlib-trainers">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center colorlib-heading animate-box">
<h2>Professores</h2>
</div>
</div>
<div class="row">
<div class="col-md-3 col-sm-3 animate-box">
<div class="trainers-entry">
</div>
</div>
<div class="col-md-3 col-sm-3 animate-box">
<div class="trainers-entry">
<div class="trainer-img" style="background-image: url(images/anderson-silva.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<h3><NAME></h3>
<span>Boxe / <NAME></span>
</div>
</div>
</div>
<div class="col-md-3 col-sm-3 animate-box">
<div class="trainers-entry">
<div class="trainer-img" style="background-image: url(images/mc-gregor.jpg);background-size:100% 100%;-webkit-background-size: 100% 100%;-o-background-size: 100% 100%;-khtml-background-size: 100% 100%;-moz-background-size: 100% 100%;"></div>
<div class="desc">
<h3><NAME></h3>
<span> <NAME> </span>
</div>
</div>
</div>
<div class="col-md-3 col-sm-3 animate-box">
<div class="trainers-entry">
</div>
</div>
</div>
</div>
</div>
<?php include 'rodape.php'?>
</div>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up2"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Flexslider -->
<script src="js/jquery.flexslider-min.js"></script>
<!-- Owl carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Counters -->
<script src="js/jquery.countTo.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
| 7706110f53606bac54a88d347f18257f8bede0b8 | [
"Markdown",
"PHP"
] | 9 | Markdown | eltonbgomes/artesMarciais | f4c8c2cad5601e653b477b9fce4bfed5f36e7deb | b3412327aedb7737d7dfa67604592bd6dbae163e |
refs/heads/master | <repo_name>max92dev/luis-fit<file_sep>/app/controllers/pages_controller.rb
class PagesController < ApplicationController
def index
end
def nutrition
end
def training
end
def start
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :posts
get 'posts/index'
root "pages#index"
get 'nutrition' , to: 'pages#nutrition'
get 'training' , to: 'pages#training'
end
| e0090afcfa03cb895e3fbad679c0f4495f9c1b03 | [
"Ruby"
] | 2 | Ruby | max92dev/luis-fit | 5821d68bca5242bc43ba929d121d04e74a7a83e8 | 7c883f55f0842866d97aefcfc384830b972bc81e |
refs/heads/master | <repo_name>raghadzohair/Customer-Management-System<file_sep>/src/p51705628gcr/P51705628GCR.java
/*
* <NAME>, ID 1705628, section number GCR .
* EMAIL <EMAIL>
* Program 5: Customer Management System. Sunday December 17, 2017
*/
package p51705628gcr;
import java.util.Scanner;
/**
*
* @author Raghad
*/
public class P51705628GCR {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("-------------------------------------------------------------------");
System.out.println(" ------ Welcome to the Customer Management System ------ ");
System.out.println("-------------------------------------------------------------------");
System.out.print("> Please enter the registration year (ex: 2017): ");
int year = input.nextInt();
System.out.println();
System.out.print("> How many customers do you want to register in year "+year+" : ");
int customer = input.nextInt();
System.out.println();
//declear var
int[] id = new int[customer];
String[] fname = new String[customer];
String[] lname = new String[customer];
double[] totalPurchase = new double[customer];
int[] yearCustomer =new int[customer];
double[] ageCustomer = new double[customer];
String[] genderCustomer = new String[customer];
String[] cityCustomer = new String[customer];
// count number of customers in the system
int customerCount = 0 ;
while(true){
displayMainMenu();
String choice = input.next();
inputAndCheck(choice);
System.out.println();
// enter the data of customer if the user choice 'a'
if(choice.equalsIgnoreCase("a")){
// inc. 1 if user inter the data of customer
customerCount++;
int posion = customerCount - 1;
System.out.println();
System.out.print(" > Enter customer ID: ");
id[posion] = input.nextInt();
System.out.print(" > Enter customer first name: ");
fname[posion] = input.next();
System.out.print(" > Enter customer last name: ");
lname[posion] = input.next();
totalPurchase[posion] = readTotalPurchase(0);
yearCustomer[posion] = readRegisterYear (0);
ageCustomer[posion] =readCustomerAge(0);
genderCustomer[posion]= readCustomerGender("");
cityCustomer[posion] = readCustomerCity("");
System.out.println("*****************************");
System.out.println(" > "+fname[posion]+" "+lname[posion]+" (ID #"+id[posion]+") has been added to the system.");
System.out.println();
continue;
}
// the program search about the customer if user choice 'd'
if(choice.equalsIgnoreCase("d")){
while(true){
System.out.println(" > Enter 1 to search/display customer by ID number");
System.out.println(" > Enter 2 to search/display customer by name");
System.out.println(" > Enter 0 to return to the Main Menu");
System.out.println();
System.out.print(" > Enter choice: ");
int choice2 = input.nextInt();
input.nextLine();
System.out.println();
if ( !(choice2 == 1 || choice2 == 2 || choice2 == 0) ){
System.out.println("Invalid selection! Please try again");
System.out.println();
continue;
}
// if user choice 1 the program search about customer by ID
if(choice2 == 1){
while(true){
System.out.print(" > Enter customer id: ");
int customerId = input.nextInt();
System.out.println(" > Customer Details:");
System.out.println();
int posionId = search (id , customerId, customerCount);
if(posionId == -1){
System.out.println("Sorry! ID customer #"+customerId+" Not found in the system");
System.out.println();
continue;
}
displayCustomerInformation(id[posionId], fname[posionId], lname[posionId], totalPurchase[posionId],
yearCustomer[posionId], ageCustomer[posionId], genderCustomer[posionId], cityCustomer[posionId] );
System.out.println();
break;
}
}
// if user choice 2 the program search about the customer by first and last name
if(choice2 == 2){
while(true){
System.out.print(" > Enter customer first name: ");
String fnameCustomer = input.nextLine();
System.out.print(" > Enter customer last name: ");
String lnameCustomer = input.nextLine();
System.out.println(" > Customer Details:");
System.out.println();
int posionName = search(fname, lname, fnameCustomer, lnameCustomer, customerCount);
if(posionName == -1){
System.out.println("Sorry! Name customer: "+fnameCustomer+" "+lnameCustomer+". Not found in the system");
System.out.println();
continue;
}
displayCustomerInformation(id[posionName], fname[posionName], lname[posionName], totalPurchase[posionName],
yearCustomer[posionName], ageCustomer[posionName], genderCustomer[posionName], cityCustomer[posionName] );
System.out.println();
break;
}
}
// if user choice 0 the program back to main menu
if(choice2 == 0){
break;
}
}
}
// The program ends if user choice 'e'
if(choice.equalsIgnoreCase("e")){
System.out.println(" > Thank you for using the Customers Management System!");
System.out.println();
System.out.println(" > Good Bye.");
System.out.println();
System.exit(0);
}
}
}
// for displayMainMenu
public static void displayMainMenu(){
System.out.println("-------------------------------------------------------------------");
System.out.println("------- Customer Management System -------");
System.out.println("------- *MAIN MENU* -------");
System.out.println("-------------------------------------------------------------------");
System.out.println(" | A/a: Enter A or a for Adding a Customer | ");
System.out.println(" | D/d: Enter D or d for Printing Customer Details | ");
System.out.println(" | E/e: Enter E or e for Exiting the Program | ");
System.out.println("-------------------------------------------------------------------");
System.out.println();
System.out.print(" > Please enter your choice: ");
}
// check if choice correct from main menu
public static char inputAndCheck(String choice){
while(true){
if( !(choice.equalsIgnoreCase("a") || choice.equalsIgnoreCase("d") || choice.equalsIgnoreCase("e")) ){
System.out.println(">Invalid selection! Please try again.");
System.out.println();
}
char ch = choice.charAt(0);
return ch;
}
}
// for take the age of customer from user
public static double readCustomerAge(double age ){
Scanner input = new Scanner(System.in);
while(true){
System.out.print(" > Enter the age of customer: ");
age = input.nextDouble();
// check if the age includes the range
if(age<15 || age>90){
System.out.println();
System.out.println(" > Invalid input! (age must be between 15 and 90)");
System.out.println(" > Please try again.");
System.out.println();
continue;
}
return age;
}
}
// for take the Total Purchase of customer from user
public static double readTotalPurchase(double purchase){
Scanner input = new Scanner(System.in);
System.out.print(" > Enter the customer total number of purchases: ");
purchase = input.nextDouble();
return purchase;
}
// for take the Register Year of customer from user
public static int readRegisterYear (int yearCus){
Scanner input = new Scanner(System.in);
System.out.print(" > Enter the customer regisrtation year: ");
yearCus = input.nextInt();
return yearCus;
}
// for take the Gender of customer from user
public static String readCustomerGender (String gender){
Scanner input = new Scanner(System.in);
while(true){
System.out.print(" > Enter the gender of customer: ");
gender = input.nextLine();
// check if user enter male or femal
if(! (gender.equalsIgnoreCase("female") || gender.equalsIgnoreCase("male")) ){
System.out.println();
System.out.println(" > Invalid input! (gender must be male or female)");
System.out.println(" > Please try again");
System.out.println();
continue;
}
return gender;
}
}
// for take the City of customer from user
public static String readCustomerCity (String city){
Scanner input = new Scanner(System.in);
System.out.print(" > Enter the city of customer: ");
city = input.nextLine();
return city ;
}
// search about the customer by ID
public static int search (int[] id, int customerId, int customerCount){
// initialized posion Id
int posion = 0 ;
// check the id posion by length of id for customer
for(int check = 0; check<id.length; check++){
if(id[check] == customerId){
posion = check ;
break;
}
else
posion = -1;
}
return posion ;
}
// search about the customer by first and last name
public static int search (String[] fname, String[] lname, String fristName, String lastName, int customerCount){
// initialized posionId
int posion = 0;
// check the first and last name posion by length of name for customer
for(int i = 0; i<fname.length && i<lname.length; i++){
if(fname[i].equalsIgnoreCase(fristName)) {
if(lname[i].equalsIgnoreCase(lastName)){
posion = i;
break;
}
}
else
posion = -1;
}
return posion ;
}
// display Customer Information
public static void displayCustomerInformation(int id, String fname, String lname, double tpur, int ryear,
double age, String gender, String city){
System.out.println(" > ID Name "+
"Number of Purchases Registration Year Age"
+" Gender City");
System.out.println(" > -----------------------------------------"+
"-----------------------------------------------------------------------");
System.out.println(" "+id+" "+fname+" "+lname+" "+tpur+" "+ryear+" "+
age+" "+gender+" "+city);
}
}
| ca1c7d91971fd35d83d26f52b399b0d9faa6378b | [
"Java"
] | 1 | Java | raghadzohair/Customer-Management-System | a89612a713a4f6f5597076666179f5bcc227f095 | 23e99adfd52df2f9633f583c2949a8cbb5bda673 |
refs/heads/master | <file_sep><?php
session_start();
$_SESSION ['username'] = "Juana";
?><file_sep># chat-system-php-mysql | a78170563e6bd3d2cfea53c43c33efb328590e21 | [
"Markdown",
"PHP"
] | 2 | PHP | VictorLlado/chat-system-php-mysql | 37450bb203febb905b36f2e51f80e22f3150d160 | 8346b9fe078237c5355dd2f04b0cedcd9df414d2 |
refs/heads/master | <file_sep>#!/usr/bin/python
#--*--coding=utf-8--*--
from __future__ import print_function
import sys
import binascii
from bluepy import btle
import os
import struct
import cv2
ble_conn = None
class MyDelegate(btle.DefaultDelegate):
def __init__(self, conn):
btle.DefaultDelegate.__init__(self)
self.conn = conn
def handleNotification(self, cHandle, data):
data = binascii.b2a_hex(data)
print("Notification:", str(cHandle), " data ", data)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
pass
elif isNewData:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
def ble_connect(devAddr):
global ble_conn
if not devAddr is None and ble_conn is None:
# ble_conn = btle.Peripheral(devAddr, btle.ADDR_TYPE_PUBLIC)
ble_conn = btle.Peripheral(devAddr, btle.ADDR_TYPE_RANDOM)
ble_conn.setDelegate(MyDelegate(ble_conn))
print("connected")
def ble_disconnect():
global ble_conn
ble_conn = None
print("disconnected")
if __name__ == '__main__':
ble_mac = "cc:50:98:e9:2a:b9"
# scan
scanner = btle.Scanner().withDelegate(MyDelegate(None))
timeout = 10.0
devices = scanner.scan(timeout)
for dev in devices:
if dev.addr == ble_mac:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
for (adtype, desc, value) in dev.getScanData():
print (" %s(0x%x) = %s" % (desc, int(adtype), value))
break
# connect
ble_connect(ble_mac)
# write , set listen
ch = ""
for item in ble_conn.getServices():
# print("services:",item.uuid)
if item.uuid == "be940000-7333-be46-b7ae-689e71722bd5":
# print(item.uuid)
for iitem in item.getCharacteristics("be940001-7333-be46-b7ae-689e71722bd5"):
ch = iitem
print(ch)
break
# ch.write(val = b"0x05060700010007",withResponse=True)
# ch.peripheral.waitForNotifications(10.0)
i=0
ble_conn.writeCharacteristic(ch.getHandle(), b"0x05060700010007",withResponse=True)
while(True):
if(ble_conn.waitForNotifications(2.0)):
i=i+1
if(i>1000):
break
continue
print("Waiting...")
time.sleep(0.5)
# ble_conn.waitForNotifications(2.0)
# wait notification
# ble_conn.waitForNotifications(10.0)
# disconnect
ble_disconnect()
# p = btle.Peripheral("cc:50:98:e9:2a:b9", "random")
# p.setDelegate( MyDelegate(None) )
# services=p.getServices()
# for service in services:
# print(service)
# s = p.getServiceByUUID("be940000-7333-be46-b7ae-689e71722bd5")
# c = s.getCharacteristics()[0]
# print(c)
# c.write(b"0x05060700010007", "utf-8")
# print(c)
# i=0
# while(True):
# if(p.waitForNotifications(1)):
# i=i+1
# if(i>1000):
# break
# continue
# print("Waiting...")
# time.sleep(0.5)
# p.disconnect()
<file_sep>#!/usr/bin/python
#--*--coding=utf-8--*--
from __future__ import print_function
import sys
import binascii
from bluepy import btle
import os
import struct
import cv2
ble_conn = None
class MyDelegate(btle.DefaultDelegate):
def __init__(self, conn):
btle.DefaultDelegate.__init__(self)
self.conn = conn
def handleNotification(self, cHandle, data):
data = binascii.b2a_hex(data)
print("Notification:", str(cHandle), " data ", data)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
pass
elif isNewData:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
def ble_connect(devAddr):
global ble_conn
if not devAddr is None and ble_conn is None:
# ble_conn = btle.Peripheral(devAddr, btle.ADDR_TYPE_PUBLIC)
ble_conn = btle.Peripheral(devAddr, btle.ADDR_TYPE_RANDOM)
ble_conn.setDelegate(MyDelegate(ble_conn))
print("connected")
def ble_disconnect():
global ble_conn
ble_conn = None
print("disconnected")
class Crc16Util:
def getBytesByString(data):
byte[] bytes = null;
if (data != null):
data = data.toUpperCase();
int length = data.length() / 2;
char[] dataChars = data.toCharArray();
bytes = new byte[length];
for i in range(length):
int pos = i * 2;
bytes[i] = (byte) (charToByte(dataChars[pos]) << 4 | charToByte(dataChars[pos + 1]));
return bytes;
def crcTable(bytes):
int[] table = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
};
int crc = 0xffff;
for b in bytes:
crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
String crcStr = hex(crc);
String substring = crcStr[2:];
# System.out.println("substring:"+substring);
byte[] bytes1 = getBytesByString(substring);
String substring2 = crcStr[0:2];
# System.out.println("substring2:"+substring2);
byte[] bytes2 = getBytesByString(substring2);
byte[] bytes3 = new byte[2];
# System.arraycopy(bytes1,0,bytes3,0,bytes1.length);
# System.arraycopy(bytes2,0,bytes3,1,bytes2.length);
return bytes3;
def getCrc(data):
int high;
int flag;
# 16位寄存器,所有数位均为1
int wcrc = 0xffff;
for i in range(data.length):
# 16 位寄存器的高位字节
high = wcrc >> 8;
# 取被校验串的一个字节与 16 位寄存器的高位字节进行“异或”运算
wcrc = high ^ data[i];
for j in range(8):
flag = wcrc & 0x0001;
# 把这个 16 寄存器向右移一位
wcrc = wcrc >> 1;
# 若向右(标记位)移出的数位是 1,则生成多项式 1010 0000 0000 0001 和这个寄存器进行“异或”运算
if (flag == 1)
wcrc ^= 0xa001;
return hex(wcrc)
def makeSend(test):
testc = [0 for i in range(len(test) + 2)];
count = 0;
for i in range(len(test)):
testc[i+count] = test[i];
if (i == 1):
length = len(test) + 4;
testc[2] = str(length % 0x100).encode('utf-8')
testc[3] = str(length / 0x100).encode('utf-8')
count = 2;
return makeCRC16(testc);
def makeCRC(msg):
# print("MyApp","msg : "+ DataUtil.byteToHexString(msg));
print("msg : "+ binascii.b2a_hex(msg));
# xx = crc16JNI(msg);
xx = msg;
byte[] testaa = new byte[2];
testaa[0] = (byte) xx;
testaa[1] = (byte) (xx >> 8);
return testaa;
def makeCRC16(test):
crc = makeCRC(test);
# bytess = Crc16Util.crcTable(test);
# Log.e("Crc16Util",DataUtil.byteToHexString(bytes));
# Log.e("Crc16",Crc16Util.getCrc(test));
testc = [len(test) + 2];
for i in range(len(test)):
testc[i] = test[i];
# System.out.println(test.length);
testc[len(test)] = crc[0];
testc[len(test) + 1] = crc[1];
# Log.e("crc16",DataUtil.byteToHexString(testc));
print("crc16 "+ binascii.b2a_hex(testc))
return testc;
def onDoSynchronizedHistoryHeartRate(ble_conn):
byte[] smsg = {0x05, 0x06, 0x01};
smsg = makeSend(smsg);
ble_conn.writeCharacteristic(ch.getHandle(), snd_content_str)
if __name__ == '__main__':
#
ble_mac = "cc:50:98:e9:2a:b9"
# scan
scanner = btle.Scanner().withDelegate(MyDelegate(None))
timeout = 10.0
devices = scanner.scan(timeout)
for dev in devices:
if dev.addr == ble_mac:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
for (adtype, desc, value) in dev.getScanData():
print (" %s(0x%x) = %s" % (desc, int(adtype), value))
break
# connect
ble_connect(ble_mac)
# write , set listen
# for item in ble_conn.getServices():
# print("services:",item)
# for item in ble_conn.getDescriptors():
# print("descriptors:",item)
# for item in ble_conn.getCharacteristics():
# print("characteristics:",item)
# while(True):
for item in ble_conn.getCharacteristics(uuid='BE940001-7333-BE46-B7AE-689E71722BD5'):
print("characteristics:",item)
ch = item
# snd_content_str = "0x050601"
# tmp = ble_conn.writeCharacteristic(ch.getHandle(), snd_content_str)
# print("tmp: ",tmp)
# print("ch: ",ch)
# print(ch.read())
# print(ch.getHandle())
# print(binascii.b2a_hex(ch))
try:
val = binascii.b2a_hex(ch.read())
print ("step one:",str(val))
except:
pass
try:
val = binascii.unhexlify(val)
print ("step two:",str(val))
except:
pass
# wait notification
# ble_conn.waitForNotifications(10.0)
# disconnect
ble_disconnect()
<file_sep># from bluepy.btle import Scanner, DefaultDelegate
# class ScanDelegate(DefaultDelegate):
# def __init__(self):
# DefaultDelegate.__init__(self)
# def handleDiscovery(self, dev, isNewDev, isNewData):
# if isNewDev:
# print( "Discovered device", dev.addr )
# elif isNewData:
# print( "Received new data from", dev.addr)
# def handleNotification(self,cHandle,data):
# print("notify from "+str(cHandle)+str(data)+"\n")
# scanner = Scanner().withDelegate(ScanDelegate())
# devices = scanner.scan(10.0)
# for dev in devices:
# print ("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi) )
# for (adtype, desc, value) in dev.getScanData():
# print (" %s = %s" % (desc, value))
#!/usr/bin/python
#--*--coding=utf-8--*--
from __future__ import print_function
import sys
import binascii
from bluepy import btle
import os
import struct
ble_conn = None
class MyDelegate(btle.DefaultDelegate):
def __init__(self, conn):
btle.DefaultDelegate.__init__(self)
self.conn = conn
def handleNotification(self, cHandle, data):
data = binascii.b2a_hex(data)
print("Notification:", str(cHandle), " data ", data)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
pass
elif isNewData:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
def ble_connect(devAddr):
global ble_conn
if not devAddr is None and ble_conn is None:
# ble_conn = btle.Peripheral(devAddr, btle.ADDR_TYPE_PUBLIC)
ble_conn = btle.Peripheral(devAddr, btle.ADDR_TYPE_RANDOM)
ble_conn.setDelegate(MyDelegate(ble_conn))
print("connected")
def ble_disconnect():
global ble_conn
ble_conn = None
print("disconnected")
if __name__ == '__main__':
#
ble_mac = "cc:50:98:e9:2a:b9"
# scan
scanner = btle.Scanner().withDelegate(MyDelegate(None))
timeout = 10.0
devices = scanner.scan(timeout)
for dev in devices:
if dev.addr == ble_mac:
print("\\nDiscovery:", "MAC:", dev.addr, " Rssi ", str(dev.rssi))
for (adtype, desc, value) in dev.getScanData():
print (" %s(0x%x) = %s" % (desc, int(adtype), value))
break
# connect
ble_connect(ble_mac)
# write , set listen
snd_content_str = """\\x01\\x00"""
for item in ble_conn.getServices():
print("services:",item)
try:
ch = item
except:
pass
try:
val = binascii.b2a_hex(ch.read())
print ("step one:",str(val))
except:
pass
try:
val = binascii.unhexlify(val)
print ("step two:",str(val))
except:
pass
try:
val = struct.unpack('f', val)[0]
print ("step three:",str(val))
except:
pass
for item in ble_conn.getCharacteristics():
print("characteristics:",item)
# val = binascii.b2a_hex(ch.read())
# val = binascii.unhexlify(val)
# val = struct.unpack('f', val)[0]
# print (str(val) + "************")
try:
ch = item
except:
pass
try:
val = binascii.b2a_hex(ch.read())
print ("step one:",str(val))
except:
pass
try:
val = binascii.unhexlify(val)
print ("step two:",str(val))
except:
pass
try:
val = struct.unpack('f', val)[0]
print ("step three:",str(val))
except:
pass
for item in ble_conn.getDescriptors():
print("descriptors:",item)
try:
ch = item
except:
pass
try:
val = binascii.b2a_hex(ch.read())
print ("step one:",str(val))
except:
pass
try:
val = binascii.unhexlify(val)
print ("step two:",str(val))
except:
pass
try:
val = struct.unpack('f', val)[0]
print ("step three:",str(val))
except:
pass
# ble_conn.writeCharacteristic(handle, snd_content_str)
# wait notification
ble_conn.waitForNotifications(20.0)
# disconnect
ble_disconnect()
<file_sep>import blescan
import sys
import time
import bluetooth._bluetooth as bluez
dev_id = 0
sock = bluez.hci_open_dev(dev_id)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
measured_anterior = 0
try:
while True:
returnedList = blescan.parse_events(sock, 1)
# print("------------------")
# print(returnedList)
# print("------------------")
for returnedItem in returnedList:
(mac, uuid, major, minor, txpower, rssi) = returnedItem.split(',', 6)
if mac == 'cc:50:98:e9:2a:b9':
print("------------------")
print(returnedItem)
print("------------------")
if len(returnedList) > 0:
(mac, uuid, major, minor, txpower, rssi) = returnedList[0].split(',', 6)
# CAMBIAR LA DIRECCION MAC
if mac == 'cc:50:98:e9:2a:b9':
# print("get this device")
# print(uuid)
measunit = uuid[22:24]
measured = int((uuid[26:28] + uuid[24:26]), 16) * 0.01
unit = ''
if measunit.startswith(('03', 'b3')): unit = 'lbs'
if measunit.startswith(('12', 'b2')): unit = 'jin'
if measunit.startswith(('22', 'a2')): unit = 'Kg' ; measured = measured / 2
if unit:
if measured != measured_anterior:
print("measured : %s %s" % (measured, unit))
measured_anterior = measured
except KeyboardInterrupt:
sys.exit(1)
<file_sep># WristBand
- about this project i have three points to say ...
| 5a33d6178eb66e3af1daf65bb9fd666036bd280e | [
"Markdown",
"Python"
] | 5 | Python | iMediaLab-518/WristBand | 286bbb7fcbb897065aceb524e7859b392fe5a482 | 85fa1e9e5cf75afba8d37374fb797b43b8059f2f |
refs/heads/master | <repo_name>romantic011/leakcanary<file_sep>/library/leakcanary-android/src/main/java/com/squareup/leakcanary/LeakCanary.java
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.leakcanary;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.util.Log;
import com.squareup.leakcanary.internal.DisplayLeakActivity;
import com.squareup.leakcanary.internal.HeapAnalyzerService;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
import static android.content.pm.PackageManager.DONT_KILL_APP;
import static android.content.pm.PackageManager.GET_SERVICES;
public final class LeakCanary {
/**
* Creates a {@link RefWatcher} that works out of the box, and starts watching activity
* references (on ICS+).
*/
public static RefWatcher install(Application application) {
return install(application, DisplayLeakService.class);
}
/**
* Creates a {@link RefWatcher} that reports results to the provided service, and starts watching
* activity references (on ICS+).
*/
public static RefWatcher install(Application application,
Class<? extends AbstractAnalysisResultService> listenerServiceClass) {
if (isInAnalyzerProcess(application)) {
return RefWatcher.DISABLED;
}
enableDisplayLeakActivity(application);
HeapDump.Listener heapDumpListener =
new ServiceHeapDumpListener(application, listenerServiceClass);
RefWatcher refWatcher = androidWatcher(application, heapDumpListener);
ActivityRefWatcher.installOnIcsPlus(application, refWatcher);
return refWatcher;
}
/**
* Creates a {@link RefWatcher} with a default configuration suitable for Android.
*/
public static RefWatcher androidWatcher(Application app, HeapDump.Listener heapDumpListener) {
DebuggerControl debuggerControl = new AndroidDebuggerControl();
AndroidHeapDumper heapDumper = new AndroidHeapDumper(app);
heapDumper.cleanup();
return new RefWatcher(new AndroidWatchExecutor(), debuggerControl, GcTrigger.DEFAULT,
heapDumper, heapDumpListener);
}
public static void enableDisplayLeakActivity(Context context) {
setEnabled(context, DisplayLeakActivity.class, true);
}
/** Returns a string representation of the result of a heap analysis. */
public static String leakInfo(Context context, HeapDump heapDump, AnalysisResult result) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
PackageInfo packageInfo;
try {
packageInfo = packageManager.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
String versionName = packageInfo.versionName;
int versionCode = packageInfo.versionCode;
String info = "In " + packageName + ":" + versionName + ":" + versionCode + ".\n";
if (result.leakFound) {
if (result.excludedLeak) {
info += "* LEAK CAN BE IGNORED.\n";
}
info += "* " + result.className;
if (!heapDump.referenceName.equals("")) {
info += " (" + heapDump.referenceName + ")";
}
info += " has leaked:\n" + result.leakTrace.toString() + "\n";
} else if (result.failure != null) {
info += "* FAILURE:\n" + Log.getStackTraceString(result.failure) + "\n";
} else {
info += "* NO LEAK FOUND.\n\n";
}
info += "* Reference Key: "
+ heapDump.referenceKey
+ "\n"
+ "* Device: "
+ Build.MANUFACTURER
+ " "
+ Build.BRAND
+ " "
+ Build.MODEL
+ " "
+ Build.PRODUCT
+ "\n"
+ "* Android Version: "
+ Build.VERSION.RELEASE
+ " API: "
+ Build.VERSION.SDK_INT
+ "\n"
+ "* Durations: watch="
+ heapDump.watchDurationMs
+ "ms, gc="
+ heapDump.gcDurationMs
+ "ms, heap dump="
+ heapDump.heapDumpDurationMs
+ "ms, analysis="
+ result.analysisDurationMs
+ "ms"
+ "\n";
return info;
}
/**
* Whether the current process is the process running the {@link HeapAnalyzerService}, which is
* a different process than the normal app process.
*/
public static boolean isInAnalyzerProcess(Context context) {
return isInServiceProcess(context, HeapAnalyzerService.class);
}
private static boolean isInServiceProcess(Context context,
Class<? extends Service> serviceClass) {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo;
try {
packageInfo = packageManager.getPackageInfo(context.getPackageName(), GET_SERVICES);
} catch (Exception e) {
Log.e("AndroidUtils", "Could not get package info for " + context.getPackageName(), e);
return false;
}
String mainProcess = packageInfo.applicationInfo.processName;
ComponentName component = new ComponentName(context, serviceClass);
ServiceInfo serviceInfo;
try {
serviceInfo = packageManager.getServiceInfo(component, 0);
} catch (PackageManager.NameNotFoundException ignored) {
// Service is disabled.
return false;
}
if (serviceInfo.processName.equals(mainProcess)) {
Log.e("AndroidUtils",
"Did not expect service " + serviceClass + " to run in main process " + mainProcess);
// Technically we are in the service process, but we're not in the service dedicated process.
return false;
}
int myPid = android.os.Process.myPid();
ActivityManager activityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.RunningAppProcessInfo myProcess = null;
for (ActivityManager.RunningAppProcessInfo process : activityManager.getRunningAppProcesses()) {
if (process.pid == myPid) {
myProcess = process;
break;
}
}
if (myProcess == null) {
Log.e("AndroidUtils", "Could not find running process for " + myPid);
return false;
}
return myProcess.processName.equals(serviceInfo.processName);
}
static void setEnabled(Context context, Class<?> componentClass, boolean enabled) {
ComponentName component = new ComponentName(context, componentClass);
PackageManager packageManager = context.getPackageManager();
int newState = enabled ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DISABLED;
// Blocks on IPC.
packageManager.setComponentEnabledSetting(component, newState, DONT_KILL_APP);
}
/** Extracts the class simple name out of a string containing a fully qualified class name. */
static String classSimpleName(String className) {
int separator = className.lastIndexOf('.');
if (separator == -1) {
return className;
} else {
return className.substring(separator + 1);
}
}
private LeakCanary() {
throw new AssertionError();
}
}
<file_sep>/library/leakcanary-analyzer/src/main/java/com/squareup/leakcanary/ExcludedRefs.java
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.leakcanary;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import static com.squareup.leakcanary.Preconditions.checkNotNull;
/**
* Prevents specific references from being taken into account when computing the shortest strong
* reference path from a suspected leaking instance to the GC roots.
*
* This class lets you ignore known memory leaks that you known about. If the shortest path
* matches {@link ExcludedRefs}, than the {@link HeapAnalyzer} looks for a longer path with nothing
* matching in {@link ExcludedRefs}.
*/
public final class ExcludedRefs {
final Map<String, Set<String>> excludeFieldMap = new LinkedHashMap<>();
final Map<String, Set<String>> excludeStaticFieldMap = new LinkedHashMap<>();
final Set<String> excludedThreads = new LinkedHashSet<>();
public void instanceField(String className, String fieldName) {
checkNotNull(className, "className");
checkNotNull(fieldName, "fieldName");
Set<String> excludedFields = excludeFieldMap.get(className);
if (excludedFields == null) {
excludedFields = new LinkedHashSet<>();
excludeFieldMap.put(className, excludedFields);
}
excludedFields.add(fieldName);
}
public void staticField(String className, String fieldName) {
checkNotNull(className, "className");
checkNotNull(fieldName, "fieldName");
Set<String> excludedFields = excludeStaticFieldMap.get(className);
if (excludedFields == null) {
excludedFields = new LinkedHashSet<>();
excludeStaticFieldMap.put(className, excludedFields);
}
excludedFields.add(fieldName);
}
public void thread(String threadName) {
checkNotNull(threadName, "threadName");
excludedThreads.add(threadName);
}
}
| d4460e180b8f57db0ebcc0ca54fe5b2dfcb0c3d1 | [
"Java"
] | 2 | Java | romantic011/leakcanary | 48be9a1bdaa8b225f9f7e5647454d7bb82b4315e | cd9fe2e428a2bc6b8720e0e8e92433dde078c066 |
refs/heads/master | <repo_name>victortodoran/Laborator1MPP<file_sep>/flightticketsmanager/readMe.txt
Files contain a generic implementation for a generic CRUD model
using C# and a SqlDatabase.
The project uses XAMPP for a database server.
(This only affects the way the connection is made
not the generic CRUD model itself)
For this to work it assumes that all entities are
identified by a unique id(INT).
Validations are not made on the data introduced in th DB
so you can extend the source code however you want to
implement this functionality.
The example table is:
Student: id(INT PK AUTOINCREMENT), name(VARCHAR), age(INT)
Each field in the Student Class has the exact coresponding name
from the database table.
Any questions or suggestions drop a line at
<EMAIL>
<file_sep>/flightticketsmanager/DB/DBConnectionFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace FlightTicketsManager.DB
{
class DBConnectionFactory
{
private MySqlConnection dbconn = null;
private string innitData;
public DBConnectionFactory( string innitData) {
this.innitData = innitData;
}
private void createConnection()
{
dbconn = new MySqlConnection(innitData);
}
public MySqlConnection getConnectionHandler()
{
if(dbconn == null)
{
this.createConnection();
}
return dbconn;
}
}
}
<file_sep>/flightticketsmanager/Model/CRUDModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using FlightTicketsManager.Entities;
using System.Data;
using System.Windows.Forms;
using System.Reflection;
namespace FlightTicketsManager.Model
{
class CRUDModel
{
private MySqlConnection dbconnection = null;
private MySqlDataReader reader = null;
public CRUDModel(MySqlConnection conn)
{
this.dbconnection = conn;
}
public List<Object> readAll(string tableName)
{
List<Object> allEntities = new List<Object>();
string query = "Select * from " + tableName;
MySqlCommand sqlCommand = new MySqlCommand(query,dbconnection);
try
{
dbconnection.Open();
reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
List<string> attributes = new List<string>();
while (reader.Read())
{
for(int index = 0; index < reader.FieldCount; index++)
{
attributes.Add(reader.GetValue(index).ToString());
}
Type t = Type.GetType("FlightTicketsManager.Entities." + tableName);
Object currentEntity = Activator.CreateInstance(t, attributes);
allEntities.Add(currentEntity);
attributes.Clear();
}
}
dbconnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return allEntities;
}
public void insertEntity(Entity entity)
{
List<string> allColTypes = this.getAllColumnTypes(entity);
List<string> allColNames = this.getAllColumnNames(entity);
List<string> allValues = this.getAllValues(entity);
string query = this.buildInsertQuery(entity,allColNames, allValues);
MySqlCommand sqlCommand = new MySqlCommand(query, dbconnection);
try
{
dbconnection.Open();
sqlCommand.ExecuteNonQuery();
dbconnection.Close();
}catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
public void updateEntity(Entity entity)
{
List<string> allColNames = this.getAllColumnNames(entity);
List<string> allValues = this.getAllValues(entity);
string query = this.buildUpdateQuery(entity, allColNames, allValues);
MySqlCommand sqlCommand = new MySqlCommand(query, dbconnection);
try
{
dbconnection.Open();
sqlCommand.ExecuteNonQuery();
dbconnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public void deleteEntity(Entity entity)
{
string query = "DELETE FROM " + entity.getTableName() + " WHERE id=" + entity.getId().ToString() + " LIMIT 1";
MySqlCommand sqlCommand = new MySqlCommand(query, dbconnection);
try
{
dbconnection.Open();
sqlCommand.ExecuteNonQuery();
dbconnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private string buildUpdateQuery(Entity entity, List<string> allColNames, List<string> allValues)
{
string query = "UPDATE " + entity.getTableName() + " SET ";
for (int index = 1; index < allColNames.Count; index++)
{
query += allColNames[index] + "=" + allValues[index];
if (index < allColNames.Count - 1)
{
query += ", ";
}
}
query += " WHERE id=" + entity.getId();
Console.WriteLine(query);
return query;
}
private string buildInsertQuery(Entity entity,List<string> allColNames, List<string> allValues)
{
string query = "INSERT INTO " + entity.getTableName() + "(";
for (int index = 1; index < allColNames.Count; index++)
{
query += allColNames[index];
if (index < allColNames.Count - 1)
{
query += ", ";
}
}
query += ") VALUES(";
for (int index = 1; index < allValues.Count; index++)
{
query += allValues[index];
if (index < allColNames.Count - 1)
{
query += ", ";
}
}
query += ")";
Console.WriteLine(query);
return query;
}
private List<string> getAllColumnTypes(Entity e)
{
List<string> allColTypes = new List<string>();
PropertyInfo[] properties = e.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
string propertyType = prop.PropertyType.ToString();
if (propertyType.Contains("String"))
{
propertyType = "String";
}else
{
propertyType = "Int";
}
allColTypes.Add(propertyType);
}
return allColTypes;
}
private List<string> getAllColumnNames(Entity e)
{
List<string> allColNames = new List<string>();
PropertyInfo[] properties = e.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
string colName = prop.Name;
allColNames.Add(colName.ToLower());
}
return allColNames;
}
private List<string> getAllValues(Entity e)
{
List<string> allValues = new List<string>();
PropertyInfo[] properties = e.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
String p = prop.Name;
string value = (e.GetType().GetProperty(p).GetValue(e, null)).ToString();
string propertyType = prop.PropertyType.ToString();
if (propertyType.Contains("String"))
{
value = "'" + value + "'";
}
allValues.Add(value);
}
return allValues;
}
}
}
<file_sep>/flightticketsmanager/Entities/Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlightTicketsManager.Entities
{
class Student : Entity
{
private string name;
private int id, age;
public Student()
{
this.id = 0;
this.name = "vic";
this.age = 0;
}
public Student(List<String> attributes)
{
this.id = int.Parse( attributes[0]);
this.name = attributes[1];
this.age = int.Parse(attributes[2]);
}
public Student(int id, string name, int age)
{
this.id = id;
this.age = age;
this.name = name;
}
public int Id
{
get
{
return this.id;
}
}
public string Name{
get{
return this.name;
}
set{
this.name = value;
}
}
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
}
}
public string foo()
{
return "foo";
}
public string getTableName()
{
return "Student";
}
public int getId()
{
return this.id;
}
}
}
<file_sep>/flightticketsmanager/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using FlightTicketsManager.Book;
using System.Reflection;
using FlightTicketsManager.Entities;
using MySql.Data.MySqlClient;
namespace FlightTicketsManager
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Entity e = new Student(5, "Vasile",20);
/*
PropertyInfo[] properties = e.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
Console.WriteLine(prop.Name);
Console.WriteLine(prop.PropertyType);
String p = prop.Name;
Console.WriteLine(e.GetType().GetProperty(p).GetValue(e,null));
}
*/
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
/*
Entity s = new Student(1,"vic",20);
Student b = (Student)s;
Type t = Type.GetType("FlightTicketsManager.Entities.Student");
Object obj = Activator.CreateInstance(t,1, "Jhon", 20);
Student c = (Student)obj;
Console.WriteLine(c.Name);
*/
DB.DBConnectionFactory dbConFactory = new DB.DBConnectionFactory("datasource=127.0.0.1;port=3306;username=root;password=;database=mpp;");
MySqlConnection dbconn = dbConFactory.getConnectionHandler();
Model.CRUDModel model = new Model.CRUDModel(dbconn);
/*
List<Object> allStudents = model.readAll("Student");
foreach(Object obj in allStudents)
{
Console.WriteLine(((Student)obj).Name);
Console.WriteLine(((Student)obj).Age.ToString());
}
*/
model.updateEntity(e);
}
}
}
<file_sep>/flightticketsmanager/Entities/Entity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlightTicketsManager.Entities
{
interface Entity
{
int getId();
string getTableName();
}
}
| 8b1c375b845f04b7906cadc7fdb788685fd67fff | [
"C#",
"Text"
] | 6 | Text | victortodoran/Laborator1MPP | 495183fa5febc8895c73f530af344282bcd56047 | 64f1c0c4ef0ffddf62128937852cf471c84fc19a |
refs/heads/master | <repo_name>april7229/Data-Structures<file_sep>/queue/queue.py
import sys
sys.path.append('../linked_list')
from linked_list import LinkedList
#queue-first in out
class Queue:
def __init__(self):
self.size = 0
self.storage = LinkedList()
def enqueue(self, item):
#add
#this the start size and adds 1
self.size += 1
#this returns the last node to storage
return self.storage.add_to_tail(item)
def dequeue(self):
#to delete
#your removing what was you add in enque
remove_result = self.storage.remove_head()
if remove_result != None:
self.size -= 1
return remove_result
def len(self):
return self.size
| 9379d239a78f28e031ce0878db2a8dc238fbc667 | [
"Python"
] | 1 | Python | april7229/Data-Structures | c634a8615bb66d4dab5046d9ac1910df4b6df4ee | 5452b6fdbccfe615b1c330cc8dd7f4d0a0306651 |
refs/heads/master | <repo_name>tglovernuppy/mwitter-android<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/io/JSONHandler.java
package jp.ac.nitech.itolab.mwitter.io;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import jp.ac.nitech.itolab.mwitter.Config;
import jp.ac.nitech.itolab.mwitter.util.JacksonFactory;
import jp.ac.nitech.itolab.mwitter.util.PreferencesUtils;
import static jp.ac.nitech.itolab.mwitter.util.LogUtils.LOGD;
import static jp.ac.nitech.itolab.mwitter.util.LogUtils.LOGE;
import static jp.ac.nitech.itolab.mwitter.util.LogUtils.makeLogTag;
/**
* APIとのやり取りを行うハンドラ
* Created by masayuki on 12/02/2016.
*/
public class JSONHandler {
private static final String TAG = makeLogTag(JSONHandler.class);
protected final Context mContext;
protected boolean mSessionRenewed = false;
public JSONHandler(Context context) {
mContext = context;
}
/**
* GET メソッドでリクエストを送る
* @param url URL
* @return {@link HttpURLConnection#connect()} された後のインスタンス
* @throws IOException
*/
public HttpURLConnection httpGet(URL url) throws IOException {
LOGD(TAG, "HttpGet: "+url);
// 接続用HttpURLConnectionオブジェクト作成
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// リクエストメソッドの設定
conn.setRequestMethod("GET");
// リクエストヘッダの設定
conn.setRequestProperty("Authorization", "Bearer " + PreferencesUtils.User.getAuthToken(mContext, ""));
// リダイレクトを自動で許可しない設定
conn.setInstanceFollowRedirects(false);
// URL接続からデータを読み取る場合はtrue
conn.setDoInput(true);
// URL接続にデータを書き込む場合はtrue
conn.setDoOutput(false);
// 接続
conn.connect();
if (sessionExpired(conn) && !mSessionRenewed) {
conn.disconnect();
onSessionExpired();
mSessionRenewed = true;
return httpGet(url);
} else {
return conn;
}
}
/**
* POST メソッドでリクエストを送る
* @param url URL
* @param data 送信するデータ
* @return {@link HttpURLConnection#connect()} された後のインスタンス
* @throws IOException
*/
public HttpURLConnection httpPost(URL url, byte[] data) throws IOException {
LOGD(TAG, "HttpPost: "+url+"\nwith data: "+new String(data, Config.Api.Charset.DEFAULT));
// 接続用HttpURLConnectionオブジェクト作成
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// リクエストメソッドの設定
conn.setRequestMethod("POST");
// リクエストヘッダの設定
conn.setRequestProperty("Authorization", "Bearer " + PreferencesUtils.User.getAuthToken(mContext, ""));
// リダイレクトを自動で許可しない設定
conn.setInstanceFollowRedirects(false);
// URL接続からデータを読み取る場合はtrue
conn.setDoInput(true);
// URL接続にデータを書き込む場合はtrue
conn.setDoOutput(true);
// 接続
conn.connect();
// データ送信
OutputStream out = null;
try {
out = conn.getOutputStream();
out.write(data);
out.flush();
} finally {
if (out != null) {
out.close();
}
}
if (sessionExpired(conn) && !mSessionRenewed) {
conn.disconnect();
onSessionExpired();
mSessionRenewed = true;
return httpPost(url, data);
} else {
return conn;
}
}
/**
* GET メソッドでリクエストを送る
* @param url URL
* @param clazz JSON エンティティクラス
* @param <T> JSON エンティティ
* @return オブジェクト
* @throws IOException
*/
protected <T> T httpGet(URL url, Class<T> clazz) throws IOException {
HttpURLConnection conn = httpGet(url);
return deserialize(conn.getInputStream(), clazz);
}
/**
* POST メソッドでリクエストを送る
* @param url URL
* @param data 送信するデータ
* @param clazz JSON エンティティクラス
* @param <T> JSON エンティティ
* @return オブジェクト
* @throws IOException
*/
protected <T> T httpPost(URL url, byte[] data, Class<T> clazz) throws IOException {
HttpURLConnection conn = httpPost(url, data);
return deserialize(conn.getInputStream(), clazz);
}
/**
* POST メソッドでリクエストを送る
* @param url URL
* @param entity 送信するデータ
* @param clazz JSON エンティティクラス
* @param <T> JSON エンティティ
* @return オブジェクト
* @throws IOException
*/
protected <T> T httpPost(URL url, Entity entity, Class<T> clazz) throws IOException {
byte[] data = entity.toJson().getBytes(Config.Api.Charset.DEFAULT);
return httpPost(url, data, clazz);
}
/**
* {@link InputStream} から読み込んだJSONから {@link T} を作る
* @param in unmarshalする{@link InputStream}
* @param clazz JSON のエンティティクラス
* @param <T> JSONのエンティティ
* @return オブジェクト
* @throws IOException
*/
protected <T> T deserialize(InputStream in, Class<T> clazz) throws IOException {
try {
return JacksonFactory.create().readValue(in, clazz);
} finally {
if (in != null) {
in.close();
}
}
}
private boolean sessionExpired(HttpURLConnection conn) throws IOException {
return (!conn.getURL().toString().equals(Config.Api.URL.LOGIN) && conn.getResponseCode() == 401);
}
private void onSessionExpired() throws IOException {
jp.ac.nitech.itolab.mwitter.io.request.Login request = new jp.ac.nitech.itolab.mwitter.io.request.Login();
request.username = PreferencesUtils.User.getAuthUsername(mContext, null);
request.password = PreferencesUtils.User.getAuthPassword(mContext, null);
jp.ac.nitech.itolab.mwitter.io.response.Login response = new UserHandler(mContext).login(request);
if (!response.result) {
LOGE(TAG, "Auto Login Failed");
}
}
}
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/service/TweetHelper.java
package jp.ac.nitech.itolab.mwitter.service;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.os.ResultReceiver;
import com.activeandroid.ActiveAndroid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import jp.ac.nitech.itolab.mwitter.Config;
import jp.ac.nitech.itolab.mwitter.io.TweetHandler;
import jp.ac.nitech.itolab.mwitter.model.entity.Tweet;
import jp.ac.nitech.itolab.mwitter.util.PreferencesUtils;
import static jp.ac.nitech.itolab.mwitter.util.LogUtils.LOGD;
import static jp.ac.nitech.itolab.mwitter.util.LogUtils.LOGE;
import static jp.ac.nitech.itolab.mwitter.util.LogUtils.makeLogTag;
/**
* {@link TweetService} 用のヘルパー
* Created by masayuki on 12/02/2016.
*/
public class TweetHelper {
private static final String TAG = makeLogTag(TweetHelper.class);
private final Context mContext;
TweetHelper(Context context) {
mContext = context;
}
public void updateTimeline(ResultReceiver receiver) {
long limit = Config.App.Tweet.LIMIT;
Date referenceTime = PreferencesUtils.Tweet.getReferenceTime(mContext, null);
LOGD(TAG, "Begin updating timeline");
TweetHandler handler = new TweetHandler(mContext);
try {
// 現在時刻取得
Date newReferenceTime = new Date();
// タイムライン取得
List<jp.ac.nitech.itolab.mwitter.io.response.Tweet> timeline =
handler.getTimeline(limit, 0, referenceTime);// FIXME: 13/02/2016 limitとoffsetを正しく実
// モデルへ変換して保存
ActiveAndroid.beginTransaction();
try {
for (jp.ac.nitech.itolab.mwitter.io.response.Tweet t : timeline) {
Tweet tweet = Tweet.fromResponse(t);
tweet.save();
}
ActiveAndroid.setTransactionSuccessful();
} finally {
ActiveAndroid.endTransaction();
}
// ReferenceTime 更新
PreferencesUtils.Tweet.setReferenceTime(mContext, newReferenceTime);
LOGD(TAG, "Successfully updated timeline, adding "+timeline.size()+" tweets.");
receiver.send(TweetService.STATE_OK, new Bundle()); // FIXME: 13/02/2016 implement properly
} catch (IOException e) {
LOGE(TAG, "Error while updating timeline", e);
receiver.send(TweetService.STATE_NG, new Bundle()); // FIXME: 13/02/2016 implement properly
}
LOGD(TAG, "End updating timeline");
}
}
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/AppApplication.java
package jp.ac.nitech.itolab.mwitter;
import android.app.Application;
import com.activeandroid.ActiveAndroid;
import com.activeandroid.Configuration;
import com.activeandroid.serializer.TypeSerializer;
import jp.ac.nitech.itolab.mwitter.model.adapter.TweetUserSerializer;
/**
* Created by masayuki on 12/02/2016.
*/
public class AppApplication extends Application {
/** ActiveAndroid に登録する {@link TypeSerializer} */
private static Class<?>[] sTypeSerializers = new Class<?>[] {
TweetUserSerializer.class
};
@Override
public void onCreate() {
super.onCreate();
setupDatabase();
}
@Override
public void onTerminate() {
super.onTerminate();
disposeDatabse();
}
/**
* ORM 初期化
*/
private void setupDatabase() {
@SuppressWarnings("unchecked")
Configuration dbConfiguration = new Configuration.Builder(this)
.setDatabaseName(Config.App.DB.NAME)
.setDatabaseVersion(Config.App.DB.VERSION)
.addTypeSerializers((Class<? extends TypeSerializer>[]) sTypeSerializers)
.create();
ActiveAndroid.initialize(dbConfiguration);
}
/**
* ORM 破棄
*/
private void disposeDatabse() {
ActiveAndroid.dispose();
}
}
<file_sep>/README.md
# mwitter-android
A simple client app implementation for ordinary Server-Client systems with JSON used as the communication format. MVC designing pattern and ORM (Active Android) are used. Made for the training for the newcomers in my lab.
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/io/Entity.java
package jp.ac.nitech.itolab.mwitter.io;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import jp.ac.nitech.itolab.mwitter.util.JacksonFactory;
/**
* データ層の入出力用エンティティ
* Created by masayuki on 12/02/2016.
*/
public class Entity {
/**
* JSON 文字列にシリアライズする
* @return
*/
public String toJson() throws IOException {
return JacksonFactory.create().writeValueAsString(this);
}
/**
* JSON 文字列からシリアライズする
* @param json
* @return
*/
public static <T extends Entity> T fromJson(String json, Class<T> clazz) throws IOException {
return JacksonFactory.create().readValue(json, clazz);
}
}
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/io/adapter/DateAdapter.java
package jp.ac.nitech.itolab.mwitter.io.adapter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import jp.ac.nitech.itolab.mwitter.util.DateUtils;
/**
* Jackson 用のアダプタ
* Created by masayuki on 14/02/2016.
*/
public class DateAdapter {
public static class Serializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(DateUtils.formatISO8601(value));
}
}
public static class Deserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
try {
return DateUtils.parseISO8601(p.getText());
} catch (ParseException e) {
throw new IOException("Parse failed", e);
}
}
}
}
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/io/TweetHandler.java
package jp.ac.nitech.itolab.mwitter.io;
import android.content.Context;
import android.net.Uri;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import jp.ac.nitech.itolab.mwitter.Config;
import jp.ac.nitech.itolab.mwitter.io.response.Tweet;
import jp.ac.nitech.itolab.mwitter.util.DateUtils;
import jp.ac.nitech.itolab.mwitter.util.JacksonFactory;
/**
* {@link jp.ac.nitech.itolab.mwitter.io.response.Tweet} を処理する {@link JSONHandler}
* Created by masayuki on 12/02/2016.
*/
public class TweetHandler extends JSONHandler {
public TweetHandler(Context context) {
super(context);
}
/**
* タイムラインを取得する
* @param limit リミット
* @param offset オフセット
* @param referenceTime 最終取得時刻
* @return ツイートのリスト
* @throws IOException
*/
public List<Tweet> getTimeline(long limit, long offset, Date referenceTime) throws IOException {
Uri.Builder builder = Uri.parse(Config.Api.URL.TIMELINE).buildUpon();
if (0 < limit) {
builder.appendQueryParameter("limit", String.valueOf(limit));
}
if (0 < offset) {
builder.appendQueryParameter("offset", String.valueOf(offset));
}
if (referenceTime != null) {
builder.appendQueryParameter("reference_time", DateUtils.formatISO8601(referenceTime));
}
URI uri = URI.create(builder.build().toString());
URL url = uri.toURL();
Tweet[] response = httpGet(url, Tweet[].class);
return (List<Tweet>) Arrays.asList(response);
}
/**
* ツイートを投稿する
* @param request ツイート
* @return 投稿したツイート
* @throws IOException
*/
public Tweet postTweet(jp.ac.nitech.itolab.mwitter.io.request.Tweet request) throws IOException {
Uri.Builder builder = Uri.parse(Config.Api.URL.TWEET).buildUpon();
URI uri = URI.create(builder.build().toString());
URL url = uri.toURL();
Tweet response = httpPost(url, request, Tweet.class);
return response;
}
}
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/model/adapter/TweetUserSerializer.java
package jp.ac.nitech.itolab.mwitter.model.adapter;
import com.activeandroid.serializer.TypeSerializer;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import jp.ac.nitech.itolab.mwitter.model.entity.Tweet;
/**
* {@link Map} をJSON文字列としてSQLiteに保存する為の {@link TypeSerializer}
* Created by masayuki on 12/02/2016.
*/
public class TweetUserSerializer extends TypeSerializer {
@Override
public Class<?> getDeserializedType() {
return Tweet.User.class;
}
@Override
public Class<?> getSerializedType() {
return String.class;
}
@Override
public Object serialize(Object data) {
if (data == null) {
return null;
}
return new JSONObject((Map) data).toString();
}
@Override
public Object deserialize(Object data) {
if (data == null) {
return null;
}
try {
JSONObject json = new JSONObject((String) data);
Iterator<String> keys = json.keys();
Map<String, Object> params = new Tweet.User();
while (keys.hasNext()) {
String key = keys.next();
Object val = json.get(key);
params.put(key, val);
}
return params;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/util/LogUtils.java
package jp.ac.nitech.itolab.mwitter.util;
import android.util.Log;
/**
* ログ周り用ユーリティティ
* Created by masayuki on 13/02/2016.
*/
public class LogUtils {
/**
* ログ出力用タグを生成する
* @param clazz
* @return
*/
public static String makeLogTag(Class<?> clazz) {
return clazz.getSimpleName();
}
public static void LOGD(String tag, String msg) {
Log.d(tag, msg);
}
public static void LOGD(String tag, String msg, Throwable tr) {
Log.d(tag, msg, tr);
}
public static void LOGI(String tag, String msg) {
Log.i(tag, msg);
}
public static void LOGI(String tag, String msg, Throwable tr) {
Log.i(tag, msg, tr);
}
public static void LOGW(String tag, String msg) {
Log.w(tag, msg);
}
public static void LOGW(String tag, String msg, Throwable tr) {
Log.w(tag, msg, tr);
}
public static void LOGE(String tag, String msg) {
Log.e(tag, msg);
}
public static void LOGE(String tag, String msg, Throwable tr) {
Log.e(tag, msg, tr);
}
}
<file_sep>/app/src/main/java/jp/ac/nitech/itolab/mwitter/io/response/Login.java
package jp.ac.nitech.itolab.mwitter.io.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
import jp.ac.nitech.itolab.mwitter.io.Entity;
import jp.ac.nitech.itolab.mwitter.io.adapter.DateAdapter;
/**
* Created by masayuki on 20/02/2016.
*/
public class Login extends Entity {
@JsonProperty("result")
public boolean result;
@JsonProperty("auth_token")
public String authToken;
@JsonProperty("auth_token_expire_at")
@JsonDeserialize(using = DateAdapter.Deserializer.class)
public Date authTokenExpireAt;
}
| 6fe2dfc9146ef2027b057e53813405dd39b035b5 | [
"Markdown",
"Java"
] | 10 | Java | tglovernuppy/mwitter-android | e2fd4000a0a980e370595ca07e62b7091ef697d3 | 5bf113fef8c070936461734cd55852dcca49f657 |
refs/heads/master | <repo_name>hoylemd/C<file_sep>/PageRequester/makefile
all : samplerequest Shrike
samplerequest : 3210-samplerequest.c
gcc 3210-samplerequest.c -Wall -o samplerequest
Shrike: Shrike.c
gcc Shrike.c -Wall -o Shrike
clean :
rm samplerequest
rm Shrike
<file_sep>/MinecraftClone/Iteration2/a2.h
/* Derived from scene.c in the The OpenGL Programming Guide */
/* Keyboard and mouse rotation taken from Swiftless Tutorials #23 Part 2 */
/* http://www.swiftless.com/tutorials/opengl/camera2.html */
// Installed Libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Local includes
#include "graphics.h"
#include "perlin.h"
// Definitions because this aint C++ yet!
#define false 0
#define true 1
// Constants
#define SUN_ANCHOR_X 49
#define SUN_ANCHOR_Y 0
#define SUN_RADIUS 49
#define DAY_LENGTH 30
#define CLOUD_ALTITUDE 48
#define MEAN_GROUND_ALTITUDE 24
#define MAX_ROOMS 4
#define MAX_HALLS 50
typedef struct
{
int id;
int x;
int y;
int l;
int w;
} Room;
typedef struct
{
Room * r1;
Room * r2;
int xLength;
int yLength;
double dLength;
} Hall;
typedef struct
{
int id;
int numRooms;
Room * rooms[MAX_ROOMS];
int numHalls;
Hall * halls[MAX_HALLS];
} Dungeon;
// Graphics function links
extern void gradphicsInit(int *, char **); // Initialize the Graphics
extern void setLightPosition(GLfloat, GLfloat, GLfloat); // Set the light(sun)'s position
extern GLfloat* getLightPosition(); // Get the light(sun)'s position
extern void setViewPosition(float, float, float); // Set the viewpoint position
extern void getViewPosition(float *, float *, float *); // Get the viewpoint position
extern void getOldViewPosition(float *, float *, float *); // Get the viewpoint's last position
extern void getViewOrientation(float *, float *, float *); // Get the viewpoint's orientation
extern int addDisplayList(int , int , int ); // Add a cube to the display list
// flag which is set to 1 when flying behaviour is desired
extern int flycontrol;
// flag used to indicate that the test world should be used
extern int testWorld;
// list and count of polygons to be displayed, set during culling
extern int displayList[MAX_DISPLAY_LIST][3];
extern int displayCount;
<file_sep>/WebServerv2/A3.java
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.lang.reflect.Array;
public class A3 extends JFrame{
//Set the Size Variables
public static final int WIDTH = 550;
public static final int HEIGHT = 300;
//Set the serial number
public static final long serialVersionUID = 1;
//Pointer to the log area
private JTextArea logArea;
//Debug variable settings
//0 = no debug messages
//1 = standard debug messages
//2 = verbose mode
boolean serverUp;
//Constructor
public A3(){
super();
//pointers for creating the Frame
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
JPanel panel;
JScrollPane scroller;
//Load native library
System.loadLibrary("A3");
//Size the Frame
setSize(WIDTH,HEIGHT);
//Set the title
setTitle("Server GUI");
//Define x button behavior
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar.
menuBar = new JMenuBar();
//Build the server Menu.
menu = new JMenu("Server");
menuItem = new JMenuItem("Pause");
menuItem.addActionListener(new PauseListener());
menu.add(menuItem);
menuItem = new JMenuItem("Unpause");
menuItem.addActionListener(new UnpauseListener());
menu.add(menuItem);
menuItem = new JMenuItem("Shutdown");
menu.add(menuItem);
menuItem.addActionListener(new ShutdownListener(this));
menuBar.add(menu);
//Build the Includes Menu.
menu = MakeIncludeMenu("Includes");
menuBar.add(menu);
//Build the Logs Menu.
menu = new JMenu("Logs");
menuItem = new JMenuItem("View Logs");
menuItem.addActionListener(new LogListener());
menu.add(menuItem);
menuBar.add(menu);
//Add the menubar to the frame.
this.setJMenuBar(menuBar);
//Build the logs area.
panel = new JPanel();
logArea = new JTextArea(14,40);
logArea.setEditable(false);
scroller = new JScrollPane(logArea);
scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroller);
this.add(panel);
}
//Native Functions
native int sendCommand(String command);
native int openFifo(String name);
native int openLFifo(String name);
native String getlibs(String path);
native String readlogs();
native String readlogsfromfile();
//Main function
public static void main (String args[]){
A3 me;
//Load the Frame
me = new A3();
me.setVisible(true);
//Connect to the pipe
me.openFifo("Spipe");
me.openLFifo("Lpipe");
me.serverUp = true;
}
//Function to construct the Includes Menu
private JMenu MakeIncludeMenu(String name){
String[] names;
JMenu ret;
JMenuItem nmi;
int i = 0;
//get the names of the libraries
String allNames = getlibs("./lib");
//create the menu object
ret = new JMenu(name);
//tokenize the library name string
names = allNames.split(" ");
//add each library name to the menu
for(i = 0; i < Array.getLength(names); i++){
//add a new Menu Item
nmi = new JMenuItem(names[i]);
nmi.addActionListener(new IncludeListener(names[i]));
ret.add(nmi);
}
//return the constructed menu
return ret;
}
/**
* Event Handler for the Includes menu Options
*/
private class IncludeListener implements ActionListener
{
private String name;
//Constructor
public IncludeListener(String label){
super();
this.name = label;
}
//Action handler
public void actionPerformed(ActionEvent e)
{
//send the command through the pipe
sendCommand("t " + this.name + ";");
//log the action
logArea.append("toggled Library '" + this.name + "'\n");
}
}
/**
* Event Handler for the Pause menu Option
*/
private class PauseListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//send the command through the pipe
sendCommand("p");
//log the action
logArea.append("Paused server\n");
}
}
/**
* Event Handler for the Pause menu Option
*/
private class UnpauseListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//send the command through the pipe
sendCommand("u");
//log the action
logArea.append("Unpaused server\n");
}
}
/**
* Event Handler for the Shutdown menu Option
*/
private class ShutdownListener implements ActionListener
{
A3 parent;
ShutdownListener(A3 mommy){
super();
parent = mommy;
}
public void actionPerformed(ActionEvent e)
{
//send the command through the pipe
sendCommand("s");
parent.serverUp = false;
//log the action
logArea.append("Shutting down server\n");
}
}
/**
* Method to format a log string
*/
private String FormatLog(String log){
String parts[];
//tokenize the log string
parts = log.split(" ");
//if it is a log entry, return a formatted string ready to be displayed
if (Array.getLength(parts) == 3){
return ("Log Entry:\nPage: " + parts[0] + "\nBrowser: " + parts[1] +"\nDate: " + parts[2] + "\n\n");
} else return "";
}
/**
* Method to read a log file and generate a string to display all access logs*/
private String ReadLogs(String path){
String ret = "", logs[], allLogs;
int i = 0;
//read the log file
if (this.serverUp) allLogs = readlogs();
else allLogs = readlogsfromfile();
if (!allLogs.equals("None") && !allLogs.equals("S;")){
//tokenize the logs into individual log strings
logs = allLogs.split(";");
//format the log strings into a chain of displayable log blocks
for(i = 0; i < Array.getLength(logs); i++){
ret = ret + FormatLog(logs[i]);
}
} else if (allLogs.equals("S;")){
logArea.append("Server down, Reading logs from file\n");
this.serverUp = false;
} else ret = "No logs to display\n";
//return the displayable log block chain
return ret;
}
/**
* Event Handler for the Read Logs menu Option
*/
private class LogListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//load the logs and display them
logArea.append(ReadLogs("access.log"));
}
}
}
<file_sep>/WebServerv2/A3.c
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include "A3.h"
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "hstring.h"
#include <dlfcn.h>
#include <unistd.h>
#define MAX_LENGTH 1024
/*pipe name*/
char pipeName[64], lpipeName[64];
/*log pipe*/
FILE * lpipe = NULL;
/*log struct*/
typedef struct {
char pageName[MAX_LENGTH];
char browserName[MAX_LENGTH];
unsigned long date;
} Log;
/*global debug variable for printing out debug messages*/
/*0 = no debug messages*/
/*1 = main debug messages*/
/*2 = verbose mode*/
int debug = 0;
/*function to connect to the pipe*/
JNIEXPORT jint JNICALL Java_A3_openFifo(JNIEnv *env, jobject obj, jstring name){
jboolean iscopy;
int i = 0;
FILE * cpipe = NULL;
/*convert the string argument into a c string*/
const char *cName = (*env)->GetStringUTFChars(env, name, &iscopy);
/*save the pipe name*/
for (i=0; i < 64; i++) pipeName[i] = 0;
strncpy(pipeName, cName, strlen(cName));
if (debug)fprintf(stderr, "opening pipe '%s'\n", cName);
cpipe = fopen(pipeName, "w");
/*return success or failure, and failure message if applicable*/
if (cpipe){
if(debug) fprintf(stderr, "success\n");
fclose(cpipe);
return 1;
}else{
if(debug) perror("openFifo");
return 0;
}
}
/*function to send a command through the pipe*/
JNIEXPORT jint JNICALL Java_A3_sendCommand (JNIEnv *env , jobject obj, jstring command){
jboolean iscopy;
FILE * cpipe = NULL;
/*convert the string srgument to a c string*/
const char *cCom = (*env)->GetStringUTFChars(env, command, &iscopy);
return pushCommand(cCom);
}
int pushCommand (const char * string){
/*open the pipe*/
FILE * cpipe = fopen(pipeName, "w");
/*push the string into the pipe*/
if (cpipe){
if(debug) fprintf(stderr, "Sending '%s' through the pipe\n", string);
fputs(string, cpipe);
fclose(cpipe);
return 1;
}else{
if(debug) fprintf(stderr, "Pipe not connected; Can not send command.\n");
return 0;
}
}
/*function to load the names of all the libraries in a given directory*/
JNIEXPORT jstring JNICALL Java_A3_getlibs(JNIEnv *env, jobject obj, jstring path){
DIR * dp;
jboolean iscopy;
char libName[256], * ret = NULL, * tmp = NULL;
struct dirent *curlib;
int i;
/*convert the argument string into a c string*/
const char * cpath = (*env)->GetStringUTFChars(env, path, &iscopy);
/*open the directory*/
dp = opendir(cpath);
/*on success*/
if (dp){
do {
/*initialize libName string*/
for (i = 0; i < 256; i++){
libName[i] = 0;
}
/*read in the next entry*/
curlib = readdir(dp);
/*if an entry was read*/
if (curlib){
/*read only .so files*/
if (strstr(curlib->d_name, ".so")) {
if (strlen(strstr(curlib->d_name, ".so")) == 3){
if (ret){
/*add a space*/
tmp = happend(ret, " ");
if(ret) free(ret);
ret = tmp;
/*add the library name*/
tmp = happend(ret, curlib->d_name);
if(ret) free(ret);
ret = tmp;
tmp = NULL;
} else {
/*create the initial return string*/
ret = hstrclone(curlib->d_name);
}
}
}
}
}while (curlib);
if (debug) fprintf(stderr, "Library names read: %s\n", ret);
}
/*close the directory*/
closedir(dp);
/*return the appropriate string*/
if (ret) return (*env)->NewStringUTF(env, ret);
else return (*env)->NewStringUTF(env, "");
}
/*tool to clone a string*/
char * hstrclone(char * str){
char * ret = NULL;
if (str){
/*allocate the new string in memory*/
ret = malloc(sizeof(char)*(strlen(str)+1));
/*copy the old string in and null-term it*/
strcpy(ret, str);
ret[strlen(str)] = 0;
}
return ret;
}
/* tool to append a string onto another and creat a new string*/
char * happend(char * str1, char * str2){
char * ret = NULL;
int a = 0, len = 0;
/*calculate the length of the new string*/
if (str1 && str2){
len = (strlen(str1) +strlen(str2) + 1);
/*allocate and initialize*/
ret = malloc(sizeof(char)*len);
for (a = 0; a < len; a++){
ret[a] = 0;
}
/*stick the strings in there*/
strcat(ret,str1);
strcat(ret,str2);
/*null-terminate the string*/
ret[strlen(ret)] = 0;
} else if (str1){
return hstrclone(str1);
} else if (str2){
return hstrclone(str2);
}
return ret;
}
/*function to read a log file*/
JNIEXPORT jstring JNICALL Java_A3_readlogs(JNIEnv *env, jobject obj){
FILE * logpipe;
char ret[5000], chr;
int ctr = 0, i = 0;
for(i = 0; i < 5000; i++) ret[i] = 0;
pushCommand("l");
logpipe = fopen(lpipeName, "r");
/*read the log entry until end of string*/
while (!strlen(ret)){
do{
if (fread(&chr, sizeof(char), 1, logpipe)){
ret[ctr] = chr;
ctr += 1;
} else chr = 0;
} while(chr);
}
if (debug) fprintf(stderr, "read '%s' from the pipe\n", ret);
return (*env)->NewStringUTF(env, ret);
}
JNIEXPORT jint JNICALL Java_A3_openLFifo(JNIEnv *env, jobject obj, jstring name){
jboolean iscopy;
int i = 0;
char dummy;
/*convert the string argument into a c string*/
const char *cName = (*env)->GetStringUTFChars(env, name, &iscopy);
/*save the pipe name*/
for (i=0; i < 64; i++) lpipeName[i] = 0;
strncpy(lpipeName, cName, strlen(cName));
if (debug)fprintf(stderr, "opening pipe '%s'\n", cName);
mkfifo(cName, 0666 | O_RDWR);
lpipe = fopen(lpipeName, "r");
/*return success or failure, and failure message if applicable*/
if (lpipe){
if(debug) fprintf(stderr, "success\n");\
fread(&dummy, sizeof(char), 1, lpipe);
return 1;
}else{
if(debug) perror("openFifo");
return 0;
}
}
JNIEXPORT jstring JNICALL Java_A3_readlogsfromfile(JNIEnv *env, jobject obj){
FILE * fd = NULL;
int i = 0;
char logentry[5000], logstring[5000], temporary[5000];
Log * nLog = NULL;
for (i=0; i<5000; i++){ logentry[i] = 0; logstring[i] = 0; temporary[i] = 0;}
fd = fopen("access.log", "r");
if (fd){
if (debug) fprintf(stderr, "opened file successfully");
while(!feof(fd)){
/*initialize the log storage area and read in the next log entry*/
nLog= malloc(sizeof(Log));
for(i = 0; i < MAX_LENGTH; i++) {nLog->pageName[i] = 0; nLog->browserName[i] = 0;}
nLog->date = 0;
fread(nLog, sizeof(Log), 1, fd);
if (debug) fprintf(stderr, "read log entry\n");
/*generate a log entry string*/
sprintf(logentry, "%s %s %lu", nLog->pageName, nLog->browserName, nLog->date);
logentry[strlen(logentry)] = 0;
if (debug) fprintf(stderr, "constructed log entry\n");
/*if it is a valid log entry*/
if (strcmp(logentry, " 0")){
if (debug) fprintf(stderr, "valid log entry [%s]\n", logentry);
/*add it to the return string*/
if (strlen(logstring)){
sprintf(temporary, "%s;%s", logstring, logentry);
temporary[strlen(temporary)] = 0;
strncpy(logstring, temporary, 5000);
} else {
strncpy(logstring, logentry, 5000);
}
}
if (debug) fprintf(stderr, "done validation\n");
/*clear the temporary strings*/
for( i = 0; i < 5000; i++) {temporary[i] = 0; logentry[i] = 0;}
if (debug) fprintf(stderr, "cleared temp strings\n");
/*clear the log stroage area*/
if(nLog) free(nLog);
nLog = NULL;
}
fclose(fd);
} else sprintf(logstring,"None\n");
if (!strlen(logstring)) sprintf(logstring,"None\n");
return (*env)->NewStringUTF(env, logstring);
}
<file_sep>/WebServerv1/makefile
LIBS = -rdynamic -ldl
WARNS = -Wall -ansi
all: server libdate
server: a1c.c
gcc a1c.c -o server $(LIBS) $(WARNS)
libdate: libdate.c
gcc -fPIC -c libdate.c
gcc -shared -Wl,-soname,libdate.so -o ./lib/libdate.so libdate.o
clean:
rm *.o *.so main
<file_sep>/MinecraftClone/Iteration1/BaseCode/graphics.h
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
/* world size and storage array */
GLubyte world[100][50][100];
<file_sep>/SplitFileRequester/lysander.c
/************************************************************
* Early networking exercise to request a file from a server
* and have it delivered through multiple connections
************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<strings.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<fcntl.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#define BUFFSIZE 2000
#define NUMCHUNKS 6
#define MAX_FILE_SIZE 500000
#define DEBUG 1
#define DATAPORT 11808
#define FILENAME "Assignment2.pdf"
#define WRITENAME "Assignment2b.pdf"
#define DD(x) fprintf(stderr, "%s;%d: %s\n"m __FILE__, __LINE__, x);
int Open (char *, int);
char * buildReq (short, short, char*);
int Listen (int);
void printoutfromsocket(int);
int main (void){
char * req = NULL;
char mess[BUFFSIZE];
char * data = NULL;
char file[MAX_FILE_SIZE];
int sockNum = 0, recSock = 0;
int i = 0;
int rc=0, rcr = 0;
int accepted = 0;
int cs=0;
int chunkiterator = 0;
int offset= 0;
struct sockaddr_in from;
socklen_t fromlen;
FILE * fp = NULL;
int bytecounter = 0;
while(1){
req = NULL;
for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
data = NULL;
for(i = 0; i < MAX_FILE_SIZE ; i++) file[i] = 0;
sockNum = 0;
recSock = 0;
i = 0;
rc=0;
rcr = 0;
accepted = 0;
cs=0;
chunkiterator = 0;
offset= 0;
fromlen = 0;
fp = NULL;
bytecounter = 0;
//build the request string
req = buildReq(NUMCHUNKS, DATAPORT, FILENAME);
//report request
printf("sent request for \"%s\" in %d chunks over port %d\n", FILENAME, NUMCHUNKS, DATAPORT);
//initialize buffers
//open socket
sockNum = Open("localhost", 11708);
if (DEBUG) fprintf(stderr, "Socket Open\n");
//start listening for response
recSock = Listen(DATAPORT);
//send the request
rc = send( sockNum , req , (strlen(&req[4])+ 4) , 0 ) ;
printf( "Sent %d\n%s\n" , rc , req ) ;
//clean up
free(req);
req = NULL;
close(sockNum);
//start loop for each connection
for (chunkiterator = 0; chunkiterator < NUMCHUNKS; chunkiterator++){
//initialize variables
for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
accepted = 0;
offset =0;
//try to accept a connection
while (!accepted){
if (DEBUG) fprintf(stderr, "trying to accept connection. accepted = %d\n", accepted);
fromlen = sizeof(from);
cs = accept( recSock , (struct sockaddr *)&from , &fromlen );
if (DEBUG) fprintf(stderr, "cs = %d\n", cs);
//if it failed, report it
//if it succeeded, raise tthe flafg
if (cs == -1){
perror("accept:");
}else{
(accepted = 1);
}
}
if (DEBUG) fprintf(stderr, "done accepting. cs = %d\n", cs);
do {
//cleart buffer
if (DEBUG) fprintf(stderr, "clearing buffer\n");
for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
//read from the socket into the buffer
rc = recv( cs , &mess , sizeof(mess) , 0 ) ;
if (DEBUG) fprintf(stderr, "finished reading %d bytes from socket. offset is currently %d\n", rc, offset);
if (rc == -1)
perror("recv");
//if something was in fact read
if (rc){
//print it out
//if (DEBUG) fprintf(stderr, "recieved: [%s]\n", mess);
//if this is the start of the packet find the offset
if (offset == 0){
offset = ntohl(*((int*)mess));
if(DEBUG) fprintf(stderr, "firstoffset = %d\n", offset);
data = &mess[4];
rcr = rc - 4;
// otherwise deal with it as normal
} else {
data = mess;
rcr = rc;
}
if (DEBUG) fprintf(stderr, "done calculating offset and data pointers\n");
//copy the data character by character into the file buffer
for(i = 0; i < rcr; i++){
//if (DEBUG) fprintf(stderr, "112: writing \'%c\' from index %d in buffer to index %d in file\n", data[i], i, *offset+i);
file[offset] = data[i];
offset++;
bytecounter++;
}
if (DEBUG) fprintf(stderr, "done copying data\n");
}
} while (rc);
close(cs);
}
//fprintf(stderr, "Final File:\n%s\nEnd of File\n", file);
fp = fopen(WRITENAME, "w+");
fwrite(file, bytecounter, 1, fp);
fclose(fp);
printf("wrote %d bytes to the file\n", bytecounter);
close(recSock);
usleep(5000000);
}
return 0;
}
void printoutfromsocket(int cs){
char mess[50000];
int a;
int rc;
for (a=0;a<50000;a++)mess[a]=0;
rc = recv(cs, &mess, sizeof(mess), 0);
fprintf(stderr, "Recieved %d bytes:\n[%s]\n", rc, mess);
if (rc == -1) perror ("recv in printoutfromsocket:");
}
int Listen( int port)
{
struct sockaddr_in lsSA ;
int ls ;
if (DEBUG) fprintf(stderr, "Lysander listening to port number %d\n" , port ) ;
ls = socket( PF_INET , SOCK_STREAM , 0 ) ; // 0 = TCP
if( ls == -1 ) {
perror( "Socket" ) ;
exit( -1 ) ;
}
bzero( &lsSA , sizeof lsSA ) ;
lsSA.sin_family = AF_INET ;
lsSA.sin_addr.s_addr = htonl( INADDR_ANY ) ;
lsSA.sin_port = htons( port ) ;
if( bind( ls , (void *) &lsSA , sizeof lsSA ) == -1 ) {
perror( "Bind" ) ;
exit( -1 ) ;
}
if( listen( ls , 5 ) < 0 ) {
perror( "Listen" ) ;
exit( -1 ) ;
}
if (DEBUG) fprintf(stderr, "Lysander done listening\n");
return ls ;
}
char * buildReq(short num, short port, char * file){
int mun = 0, trop = 0;
int i = 0;
char * req = NULL;
req = malloc(sizeof(char) * 64);
mun = htons(num);
trop = htons(port);
req[0] = mun % 256;
req[1] = mun / 256;
req[2] = trop % 256;
req[3] = trop / 256;
printf("file:%s\n", file);
for (i=0; i< strlen(file); i++){
req[i+4] = file[i];
}
req[strlen(file)+4] = 0;
return req;
}
int Open( char *url, int port )
{
int cs;
struct sockaddr_in *csSA ;
struct hostent *server ;
//fprintf(stderr, "35\n");
bzero( &csSA , sizeof csSA ) ;
//fprintf(stderr, "37\n");
csSA = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in));
memset( (char *)csSA , 0 , sizeof( struct sockaddr_in) ) ;
csSA->sin_family = AF_INET;
csSA->sin_port = htons(port);
//fprintf(stderr, "44\n");
server = gethostbyname(url);
//fprintf(stderr, "45\n");
memcpy( (char *) &csSA->sin_addr , server->h_addr , server->h_length ) ;
//fprintf(stderr, "47\n");
cs = socket(PF_INET , SOCK_STREAM , 0); // Stolen arguments!!!
if( cs == -1 ) {
printf( "Socket failed\n" ) ;
exit( -1 ) ;
}
//fprintf(stderr, "53\n");
if( connect( cs , (struct sockaddr*) csSA , sizeof( struct sockaddr_in))){ // Stolen arguments!!!
printf( "Connect failed c\n") ;
exit( -1 ) ;
}
//fprintf(stderr, "58\n");
free(csSA);
return cs ;
}
<file_sep>/PageRequester/Shrike.c
/**********************************************************
* Early networking exercise
* requests a page from www.cbc.ca and prints it to stdout
***********************************************************/
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#define Debug 0
#define OpenDebug 0
#define BUFFSIZE 500
//Current task: functionalize the request
int Open( char * ) ;
int Send( char *, int ) ;
int main(void){
int cs, a;
char req[] = "GET http://www.cbc.ca/news/ HTTP/1.1\r\nHost: www.cbc.ca\r\nContent-Length: 0\r\nKeep-Alive: timeout=10000\r\n\r\n" ;
char req2[] = "GET http://www.cbc.ca/money/ HTTP/1.1\r\nHost: www.cbc.ca\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ;
int rc ;
char *mess = NULL, *mess2 = NULL;
int dflag = 0;
char * target = NULL;
//Initialize buffers
if(Debug) fprintf(stderr, "Initializing buffers...");
mess = malloc(sizeof(char) * BUFFSIZE);
mess2 = malloc(sizeof(char) * BUFFSIZE);
for(a=0; a<BUFFSIZE;a++) {mess[a] = 0; mess2[a] = 0;}
//Establish Connection
if(Debug) fprintf(stderr, "Done.\nEstablishing connection...");
cs = Open( "www.cbc.ca" ) ; // creates a socket
// and opens a connection to the http server specified
//Send( req, cs);
///Send Request
if(Debug) fprintf(stderr, "Done.\nSending request packet...");
rc = send( cs , req , sizeof req , 0 ) ;
if(Debug) fprintf(stderr, "Done.\n");
printf( "Sent %d\n%s\n" , rc , req ) ;
//Recieve Response and print it to screen
do {
//Buffer a block of the response
rc = recv( cs , mess , BUFFSIZE , 0 ) ;
if (Debug) fprintf(stderr, "Read from buffer\n");
//If anything was read (nothing indicating the end of the response)
if (rc){
//Check if this is the beginning of the packet
if (strstr(mess, "HTTP/1.1")){
strncpy(mess2, strstr(mess, "HTTP/1.1" ), BUFFSIZE);
target = strstr(mess2, "00004000");
*target = 0;
printf("%s\n", mess2);
printf("..........\n");
} else if (strstr(mess, "</body>")){
dflag = 1;
if (Debug) fprintf(stderr, "</body> tag found...\n");
strncpy(mess2, strstr(mess, "</body>"), BUFFSIZE);
printf("End:\n%s", mess2);
} else if (dflag){
if (Debug) fprintf(stderr, "Last little bit...\n");
printf("%s", mess);
}
for (a=0; a<BUFFSIZE; a++) mess2[a] = 0;
for (a=0; a<BUFFSIZE; a++) mess[a] = 0;
}
} while (rc && !dflag);
dflag = 0;
printf("\n..........\n\n\n");
//Restart connection
close( cs ) ;
cs = Open( "www.cbc.ca" ) ;
if(Debug) fprintf(stderr, "Done.\nSending request packet...");
rc = send( cs , req2 , sizeof req2 , 0 ) ;
rc = send( cs , req2 , sizeof req2 , 0 ) ;
if(Debug) fprintf(stderr, "Done.\n");
printf( "Sent %d\n%s\n" , rc , req2 ) ;
//Recieve Response and print it to screen
do {
//Buffer a block of the response
//if (Debug) fprintf(stderr, "Reading Response\n");
rc = recv( cs , mess , BUFFSIZE , 0 ) ;
//If anything was read (nothing indicating the end of the response)
if (rc){
if (Debug) fprintf(stderr, "Buffer Full...{%s}\n", mess);
//Check if this is the beginning of the packet
if (strstr(mess, "HTTP/1.1 200")){
fprintf(stderr, "HEADER FOUND\n");
strncpy(mess2, strstr(mess, "HTTP/1.1 200" ), BUFFSIZE);
target = strstr(mess2, "00004000");
*target = 0;
printf("%s\n", mess2);
printf("..........\n");
} else if (strstr(mess, "</body>")){
fprintf(stderr, "TRAILER FOUND\n");
dflag = 1;
if (Debug) fprintf(stderr, "</body> tag found...\n");
strncpy(mess2, strstr(mess, "</body>"), BUFFSIZE);
printf("End:\n%s", mess2);
} else if (dflag){
fprintf(stderr, "DFLAG IS UP\n");
if (Debug) fprintf(stderr, "Last little bit...\n");
printf("%s", mess);
}
for (a=0; a<BUFFSIZE; a++) mess2[a] = 0;
for (a=0; a<BUFFSIZE; a++) mess[a] = 0;
}
} while (rc && !dflag);
printf("\n..........\n\n");
if(Debug) fprintf(stderr, "Finished. Closing Connection...");
close( cs ) ;
if(Debug) fprintf(stderr, "Done. \nFreeing Memory...");
free(mess);
mess = NULL;
free(mess2);
mess2 = NULL;
if(Debug) fprintf(stderr, "Done. \nExiting\n");
return 0;
}
/*Function to convert a string into an ip address useable by the system*/
unsigned long atoip( char *text )
{
unsigned long ip ;
int i , t ;
i = 0 ;
ip = t = 0 ;
while( text[i] != '\0' ) {
if( text[i] == '.' ) {
ip = (ip<<8) + t ;
t = 0 ;
} else
t = t*10 + text[i] - '0' ;
i++ ;
}
return (ip<<8) + t ;
}
int Open( char *url )
{
int cs;
struct sockaddr_in *csSA ;
struct hostent *server ;
if(OpenDebug) fprintf(stderr, "Open subroutine initialized\n");
bzero( &csSA , sizeof csSA ) ;
if(OpenDebug) fprintf(stderr, "Zeroed Socket structure\n");
csSA = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in));
memset( (char *)csSA , 0 , sizeof( struct sockaddr_in) ) ;
csSA->sin_family = AF_INET;
csSA->sin_port = htons(80);
server = gethostbyname(url);
memcpy( (char *) &csSA->sin_addr , server->h_addr , server->h_length ) ;
if(OpenDebug) fprintf(stderr, "Socket initialized\n");
cs = socket(PF_INET , SOCK_STREAM , 0); // Stolen arguments!!!
if( cs == -1 ) {
printf( "Socket failed\n" ) ;
exit( -1 ) ;
}
if(OpenDebug) fprintf(stderr, "Socket Locked. Chevron 1 Encoded...");
if( connect( cs , (struct sockaddr*) csSA , sizeof( struct sockaddr_in))){ // Stolen arguments!!!
printf( "Connect failed c\n") ;
exit( -1 ) ;
}
if(OpenDebug) fprintf(stderr, "Chevron 1 Locked. Wormhole Established.\n");
free(csSA);
return cs ;
}
int Send( char * req, int cs ){
int rc = 0, a = 0, dflag = 0;
char * mess = NULL, * mess2 = NULL, * target = NULL;
//Initialize buffers
if(Debug) fprintf(stderr, "Initializing buffers...");
mess = malloc(sizeof(char) * BUFFSIZE);
mess2 = malloc(sizeof(char) * BUFFSIZE);
for(a=0; a<BUFFSIZE;a++) {mess[a] = 0; mess2[a] = 0;}
//Send Request
if(Debug) fprintf(stderr, "Done.\nSending request packet...");
rc = send( cs , req , sizeof req , 0 ) ;
if(Debug) fprintf(stderr, "Done.\n");
printf( "Sent %d\n%s\n" , rc , req ) ;
//Recieve Response and print it to screen
do {
if(Debug) fprintf(stderr, "Processing response\n");
//Buffer a block of the response
rc = recv( cs , mess , BUFFSIZE , 0 ) ;
if(Debug) fprintf(stderr, "Read from Socket %d\n%s\n", rc, mess);
//If anything was read (nothing indicating the end of the response)
if (rc){
if (Debug) fprintf(stderr, "Buffer Full...\n");
//Check if this is the beginning of the packet
if (strstr(mess, "HTTP/1.1 200 OK")){
strncpy(mess2, strstr(mess, "HTTP/1.1 200 OK" ), BUFFSIZE);
target = strstr(mess2, "00004000");
*target = 0;
printf("Header:\n%s\n", mess2);
printf("***************************************************************\n");
} else if (strstr(mess, "</body>")){
dflag = 1;
if (Debug) fprintf(stderr, "</body> tag found...\n");
strncpy(mess2, strstr(mess, "</body>"), BUFFSIZE);
printf("End:\n%s", mess2);
} else if (dflag){
if (Debug) fprintf(stderr, "Last little bit...\n");
printf("%s", mess);
}
for (a=0; a<BUFFSIZE; a++) mess2[a] = 0;
for (a=0; a<BUFFSIZE; a++) mess[a] = 0;
}
} while (rc);
printf("\n");
if(Debug) fprintf(stderr, "Done. \nFreeing Memory...");
free(mess);
mess = NULL;
free(mess2);
mess2 = NULL;
return 0;
}
<file_sep>/MinecraftClone/Iteration3/Vector3.c
//vector3 source file
#include "Vector3.h"
// function too create a new vector3 object
Vector3 * newVector3(float x, float y, float z)
{
// allocate
Vector3 * v = malloc(sizeof(Vector3));
// save
v->x = x;
v->y = y;
v->z = z;
// return the new Vector
return v;
}
// function to destroy a vector
Vector3 * destroyVector3(Vector3 * v)
{
if (v)
free(v);
return NULL;
}
// function to calculate the distance between 2 vectors
float VectorDistance( Vector3 * first, Vector3 * second)
{
float deltaX, deltaY, deltaZ;
float value;
// calculate deltas
deltaX = second->x - first->x;
deltaY = second->y - first->y;
deltaZ = second->z - first->z;
// sum them
value = (deltaX * deltaX) + (deltaY * deltaY) + (deltaZ * deltaZ);
// return the square root
return sqrt(value);
}
// function to check if 2 vectors are equal
int VectorIsEqual(Vector3 *first, Vector3 *second)
{
// if they both exist
if (first && second)
{
// and all components are equal
if (first->x == second->x &&
first->y == second->y &&
first->z == second->z)
// they be equal
return true;
}
// otherwise they're not
return false;
}
// function to calculate the 2D angle between the 2 vectors in radians
float VectorAngle(Vector3 *first, Vector3 *second)
{
float dx, dy;
float mx, my;
// if both exist
if (first && second)
{
// calculate the deltas
dx = first->x - second->x;
dy = first->z - second->z;
// handle a delta x of 0
if (dx == 0)
{
if (dy >= 0)
return 0;
else {
return -0.5 * 3.14159;
}
}
// handle a delta y of 0
if (dy == 0)
{
if (dx >= 0)
return (3.14159 / 2);
else {
return 0;;
}
}
// calculate the magnitudes of the deltas
if (dx > 0)
mx = dx;
else
mx = - dx;
if (dy > 0)
my = dy;
else
my = -dy;
// positive x
if (dx > 0)
{
if (dy > 0)
{
// quadrant 0
return atan(mx/my);
}
else
{
// quadrant 1
return - (atan(mx/my));
}
}
else
{
if (dy > 0)
{
// quadrant 3
return (3.14159 / 2) + atan(mx/my);
}
else
{
// quadrant 2
return - ((3.14159 / 2) + atan(mx/my));
}
}
return atan(dx / dy);
}
}<file_sep>/MinecraftClone/Iteration1/graphics.h
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
/* world size and storage array */
GLubyte world[100][50][100];
<file_sep>/SplitFileRequesterRobust/assignment3-server.c
#include"assignment3-server.h"
int main(void)
{
int sid ;
sid = startserver() ;
while( 1 )
getrequest( sid ) ;
close(sid);
return 0;
}
int startserver()
{
int sid;
struct addrinfo hints, *servinfo ;
int i , rv ;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use the host's IP
if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) == -1) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit( -1 ) ;
}
if ((sid = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
perror("server: socket");
exit( -1 ) ;;
}
if (bind(sid, servinfo->ai_addr, servinfo->ai_addrlen) == -1) {
perror("server: bind");
close(sid);
exit( -1 ) ;
}
freeaddrinfo(servinfo);
for( i = 0 ; i < MAXCLIENTS ; i++ )
Client[i].inuse = 0 ;
printf( "Server starts using port %s\n" , MYPORT ) ;
fflush( stdout ) ;
return sid ;
}
void getrequest( int sid )
{
char buf[MAXBUFLEN];
int i , numbytes;
struct sockaddr_in from ;
size_t from_len ;
printf("server: waiting to recvfrom...\n");
fflush( stdout ) ;
waitforinput( sid ) ; // returns when recvfrom() will not block
from_len = sizeof from;
if ((numbytes = recvfrom(sid, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&from, &from_len)) == -1) {
perror("recvfrom");
return ;
}
printf("server: request from %s:%d "
, inet_ntoa( from.sin_addr ) , from.sin_port ) ;
printf(" %d bytes\n", numbytes );
fflush( stdout ) ;
buf[numbytes] = '\0' ;
for( i = 0 ; i < MAXCLIENTS ; i++ )
if( Client[i].inuse
&& Client[i].addr.sin_addr.s_addr
== from.sin_addr.s_addr
&& Client[i].addr.sin_port == from.sin_port )
break ; // existing client
if( buf[0] == '\0' ) { // cryptic: network = bigendian
if( i == MAXCLIENTS ) {
printf( "Unknown client wants a retransmission\n" ) ;
return ;
}
Client[i].idle = 0 ;
retransmit( sid , Client[i] , buf ) ;
} else { // request for object
printf( "New request %s\n" , buf ) ;
printf(" \"%s\"\n", buf);
if( i == MAXCLIENTS ) { // new client
for( i = 0 ; i < MAXCLIENTS ; i++ )
if( !Client[i].inuse ) break ;
if( i == MAXCLIENTS ) {
for( i = 0 ; i < MAXCLIENTS ; i++ )
if( Client[i].idle > MAXWAIT ) {
printf( "Closing client %d\n" , i ) ;
Client[i].inuse = 0 ;
}
for( i = 0 ; i < MAXCLIENTS ; i++ )
if( !Client[i].inuse ) break ;
if( i == MAXCLIENTS ) {
printf( "No more clients allowed\n" ) ;
return ;
}
}
printf( "New client %d\n" , i ) ;
} else
printf( "Existing client %d\n" , i ) ;
Client[i].idle = 0 ;
Client[i].inuse = 1 ;
Client[i].addr = from ;
Client[i].addr_len = from_len ;
copyimage( buf , &Client[i] ) ;
sendimage( sid , &Client[i] ) ;
}
}
void copyimage( char *image , struct Client *C )
{
int isock ;
int n ;
int i , j ;
printf( "server: getting %s\n" , image ) ;
fflush( stdout ) ;
if( image[0] == 'h' && image[1] == 't'
&& image[2] == 't' && image[3] == 'p' ) {
char req[300] = "GET " ;
char host[100] ;
for( i = 0 ; image[i] != ':' ; i++ ) ;
if( image[i+1] != '/' || image[i+2] != '/' ) {
strcpy( C->Im , "Incorrect format of url" ) ;
C->Imlen = strlen( C->Im ) ;
} else {
i += 3 ;
for( j = 0 ; image[i] != '/' ; j++ , i++ )
host[j] = image[i] ;
host[j] = '\0' ;
strcat( req , image ) ;
strcat( req , " HTTP/1.1\r\nHost: " ) ;
strcat( req , host ) ;
strcat( req , "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ) ;
printf( "Contacting %s with request:\n%s" , host , req ) ;
fflush( stdout ) ;
isock = Open( host ) ;
n = send( isock , req , strlen( req ) , 0 ) ;
printf( "server sent %d bytes to %s\n" , n , host ) ;
C->Imlen = recv( isock , C->Im , MAXSIZE , MSG_WAITALL ) ;
printf( "Received from the web %d bytes\n" , C->Imlen ) ;
for( i = 0 ; i < C->Imlen-4 ; i++ )
if( C->Im[i] == '\r' && C->Im[i+1] == '\n'
&& C->Im[i+2] == '\r' && C->Im[i+3] == '\n' )
break ;
if( i < C->Imlen-5 ) {
j = 0 ;
for( i = i + 4 ; i < C->Imlen ; i++ )
C->Im[j++] = C->Im[i] ;
C->Imlen = j ;
}
fflush( stdout ) ;
}
C->Im[C->Imlen] = '\0' ;
printf( "server received from the web: %s\n" , C->Im ) ;
} else { // it must be a local file
int fd ;
printf( "opening %s\n" , image ) ;
fflush( stdout ) ;
if( (fd = open( image , O_RDONLY )) < 0 ) {
perror( "open" ) ;
strcpy( C->Im , "File could not be opened" ) ;
C->Imlen = strlen( C->Im ) ;
} else if( (n = read( fd , C->Im , MAXSIZE )) < 0 ) {
perror( "Could not get image" ) ;
strcpy( C->Im , "File could not be read" ) ;
C->Imlen = strlen( C->Im ) ;
} else {
printf( "copied %d bytes from a local file\n" , n ) ;
fflush( stdout ) ;
C->Imlen = n ;
}
close( fd ) ;
}
return ;
}
void sendimage( int sid , struct Client *C )
{
int i ;
partition( C ) ;
for( i = 0 ; i < C->numdat ; i++ )
if( C->Dlen[i] > 0 )
if( (sendto( sid , C->Im+C->Dptr[i] , C->Dlen[i]
, 0, (struct sockaddr*)&C->addr , C->addr_len )) < 0 ) {
perror( "send" ) ;
return ;
}
}
void partition( struct Client *C )
{
int N , F , L /*, R*/ ;
int i , ind , count ;
int P[8] ;
// 3 datagrams are necessary
if( C->Imlen < 16 ) {
printf( "No way to send %d bytes in 3 datagrams\n" , C->Imlen ) ;
C->numdat = 0 ;
return ;
} else if( C->Imlen > 500000 ) {
printf( "This protocol cannot handle %d bytes\n" , C->Imlen ) ;
C->numdat = 0 ;
return ;
}
printf( "Dividing image of %d bytes into datagrams\n" , C->Imlen ) ;
for( ind = 0 ; ind < 7 ; P[ind++] = 0 ) ;
F = 1024 ;
ind = 7 ;
count = 0 ;
while( F > 4 ) {
N = C->Imlen - F - (F - 1) ;
for( L = F-2 ; L < N && L > 1 ; L-- )
N -= L ;
if( N > 0 && L > 1 ) { // Success
P[ind] = 1 ;
count++ ;
}
F = F / 2 ;
ind-- ;
}
srand( getpid() ) ;
ind = 1 + rand() % count ;
F = 4 ;
for( i = 0 ; ind > 0 ; i++ ) {
F *= 2 ;
if( P[i] )
ind-- ;
}
N = C->Imlen - F ;
C->Dlen[0] = F ;
for( i = 3 , L = F-1 ; L < N && L > 1 ; i++ , L-- ) {
N -= L ;
C->Dlen[i] = L ;
}
C->Dlen[1] = L + 1 ;
C->Dlen[2] = N ;
C->numdat = F - L + 1 ;
C->Dptr[0] = 0 ;
for( i = 1 ; i < C->numdat ; i++ )
C->Dptr[i] = C->Dptr[i-1] + C->Dlen[i-1] ;
for( i = 0 ; i < C->numdat ; i++ )
printf( " %d (%d) " , C->Dptr[i] , C->Dlen[i] ) ;
printf( "\n" ) ;
for( i = 0 ; i < 3 ; i++ )
Three[i] = C->Dlen[i] ;
if( SHUFFLE > 0 ) shuffle( C ) ;
if( LOST > 0 ) lose( C ) ;
}
void shuffle( struct Client *C )
{
int i , j , k , t ;
for( i = 0 ; i < SHUFFLE ; i++ ) {
k = rand() % (C->numdat < 5 ? C->numdat-1 : 4) + 1 ;
j = rand() % (C->numdat-k) ;
printf( "Swapping %d %d\n" , j , j+k ) ;
t = C->Dlen[j] ;
C->Dlen[j] = C->Dlen[j+k] ;
C->Dlen[j+k] = t ;
t = C->Dptr[j] ;
C->Dptr[j] = C->Dptr[j+k] ;
C->Dptr[j+k] = t ;
}
printf( "SHUFFLE: " ) ;
for( i = 0 ; i < C->numdat ; i++ )
printf( "%d[%d] " , C->Dlen[i] , C->Dptr[i] ) ;
printf( "\n" ) ;
}
void lose( struct Client *C )
{
int i , k ;
for( i = 0 ; i < LOST ; i++ ) {
do {
k = rand() % C->numdat ;
} while( C->Dlen[k] == 0 ) ;
C->Dlen[k] = -C->Dlen[k] ;
}
printf( "DELETED: " ) ;
for( i = 0 ; i < C->numdat ; i++ )
printf( "%d " , C->Dlen[i] ) ;
printf( "\n" ) ;
}
void retransmit( int sid , struct Client C , char buf[] )
{
short Breq[256] ;
int i , j , n , len ;
bcopy( buf , (char *)Breq , 2 ) ;
n = ntohs( Breq[0] ) ;
printf( "server: retransmission list length=%d\n" , n ) ;
fflush( stdout ) ;
bcopy( buf , (char *)Breq , 2*n+2 ) ;
for( i = 1 ; i <= n ; i++ ) {
len = ntohs(Breq[i]) ;
printf( "%d " , len ) ;
if( len == 1024 || len == 2 || len == 1 ) {
if( len == 1024 )
len = Three[0] ;
else if( len == 2 )
len = Three[1] ;
else
len = Three[2] ;
}
for( j = 0 ; j < C.numdat ; j++ )
if( C.Dlen[j] == len || C.Dlen[j] == -len )
break ;
if( j < C.numdat && len > 0 ) {
printf( "\nretransmitting %d bytes\n" , len ) ;
fflush( stdout ) ;
if( (sendto( sid , C.Im+C.Dptr[j] , len , 0, (struct sockaddr*)&C.addr , C.addr_len )) < 0 ) {
perror( "send" ) ;
return ;
}
} else
printf( "unknown datagram\n" ) ;
}
fflush( stdout ) ;
return ;
}
void waitforinput( int sid )
{
fd_set fds , tfds ;
struct timeval timeout ;
int i , rv ;
int elapsed = 0 ;
#define WAIT 30
FD_ZERO( &fds ) ;
FD_SET( sid , &fds ) ;
while( 1 ) {
tfds = fds ;
timeout.tv_sec = WAIT ;
timeout.tv_usec= 0 ;
rv = select( sid+1 , &tfds , NULL , &tfds , &timeout ) ;
switch( rv ) {
case -1:
perror( "Select failed" ) ;
close( sid ) ;
exit( -1 ) ;
case 0:
elapsed += WAIT ;
continue ;
default:
for( i = 0 ; i < MAXCLIENTS ; i++ )
Client[i].idle += elapsed ;
return ;
}
}
}
int Open( char *url )
{
int cs ;
struct sockaddr_in csSA ;
struct hostent *server ;
bzero( &csSA , sizeof csSA ) ;
csSA.sin_family = AF_INET ;
csSA.sin_port = htons( HTTPPORT ) ;
server = gethostbyname( url ) ;
memcpy( (char *) &csSA.sin_addr , server->h_addr , server->h_length ) ;
if( (cs = socket( PF_INET , SOCK_STREAM , 0 )) == -1 ) { // 0 = TCP
printf( "Socket failed\n" ) ;
exit( -1 ) ;
}
if( connect( cs , (void *) &csSA , sizeof csSA ) == -1 ) {
printf( "Connect failed\n" ) ;
exit( -1 ) ;
}
printf( "server: connected to %s\n" , url ) ;
return cs ;
}
<file_sep>/MinecraftClone/Iteration1/BaseCode/a1.c
/* Derived from scene.c in the The OpenGL Programming Guide */
/* Keyboard and mouse rotation taken from Swiftless Tutorials #23 Part 2 */
/* http://www.swiftless.com/tutorials/opengl/camera2.html */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "graphics.h"
extern void gradphicsInit(int *, char **);
extern void setLightPosition(GLfloat, GLfloat, GLfloat);
extern GLfloat* getLightPosition();
/* background process, it is called when there are no other events */
void update() {
/* your code goes here */
/* uncomment the next line if you want the screen to be redrawn */
/* at the end of the update */
// glutPostRedisplay();
}
int main(int argc, char** argv)
{
int i;
/* Initialize the graphics system */
gradphicsInit(&argc, argv);
/* your code goes here, before the mainloop */
/* some sample objects */
/* create two green boxes and one blue box */
world[50][25][50] = 1;
world[52][25][52] = 1;
world[52][26][52] = 2;
/* blue box shows xy bounds of the world */
for(i=0; i<99; i++) {
world[0][25][i] = 2;
world[i][25][0] = 2;
world[99][25][i] = 2;
world[i][25][99] = 2;
}
/* starts the graphics processing loop */
/* code after this will not run until the program exits */
glutMainLoop();
return 0;
}
<file_sep>/WheresParallaldo/Makefile
#Makefile for CIS 4450 Assignment 1
# Path to pilot libraries
PILOTHOME = /home/mhoyle/pilothome
#flags
CC = mpicc -intel
CPPFLAGS = -I$(PILOTHOME)/include
LDFLAGS = -L$(PILOTHOME)/lib -lpilot
FC = mpif90 -intel
FFLAGS = -fpp -I$(PILOTHOME)/include
# LDFLAGS same as above
# "make wp" will compile wp.c using implicit make rules
wp: wp.o
$(CC) $< $(LDFLAGS) -o $@
# "make runwp" will run wp
runwp: clean wp
sqsub -q mpi -r 10 -n 4 -o wplog.txt ./wp parallaldos targets
# "make clean" will clean up all but source files
clean:
$(RM) wp.o wp wplog.txt
<file_sep>/WebServerv2/liblastupdate.c
/*liblastupdate.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include "hstring.h"
char * searchString() {
return "LASTUPDATE str";
}
/*format: name path*/
char * replaceString(char * params) {
char * ret = NULL, *name = NULL, *path = NULL;
int ctr = 0, i= 0, fd = 0;
struct stat buffer;
/*parse the first word as the name*/
while(params[ctr] != ' ' && params[ctr] != 0) ctr += 1;
name = malloc(sizeof(char)*(ctr+1));
for (i = 0; i <= ctr; i++) name[i] = 0;
for (i = 0; i < ctr; i++) name[i] = params[i];
/*parse the second word as the path name*/
if (strchr(params, ' ')) path = hftrim(strchr(params, ' '));
else path = NULL;
/*translate the stat's time into human time*/
if(stat(path, &buffer) == 0)
return ctime(&(buffer.st_mtime));
else {
return "FILE DOES NOT EXIST";
}
}
<file_sep>/WebServerv2/hstring.h
/*hstring.c*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*String appending tool*/
/*creates a new string of the appropriate length, derived by appending str2 to the snd of str1*/
/*Does not affect input strings. creates new return string*/
/*don't forget to free the new string in the upper function*/
char * happend(char * str1, char * str2);
/*String cloning tool*/
/*creates a new string of the appropriate length, and copies the contents of the old one into it*/
/*Does not affect the input string. creates a new return string*/
/*don't forget to free the new string in the upper function*/
char * hstrclone(char * str);
/*Substring removal tool*/
/*creates a new string of the appropriate length, derived by removing targ from str*/
/*Does not affect input strings. creates new return string*/
/*don't forget to free the new string in the upper function*/
char * hremovestr(char * str, char * targ);
/*tool to save a string as a textfile*/
void hwritefile(char * filename, char * file);
/*tool to append a string to the end of a file*/
void happendfile(char * filename, char *str, int);
/*tool to trim whitespace off the front of a string*/
char * hftrim(char *);
int hreadfile(char * filename, char * buf, int size);
int hreplacestring(char * str, char * targ, char * new, char * buf, int size);
<file_sep>/MinecraftClone/Iteration1/a1.c
/* Derived from scene.c in the The OpenGL Programming Guide */
/* Keyboard and mouse rotation taken from Swiftless Tutorials #23 Part 2 */
/* http://www.swiftless.com/tutorials/opengl/camera2.html */
// Global includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Local includes
#include "graphics.h"
#include "perlin.h"
// Links to graphics functions
extern void gradphicsInit(int *, char **);
extern void setLightPosition(GLfloat, GLfloat, GLfloat);
extern GLfloat* getLightPosition();
// global variables
// TODO: make this C++ and OO it up!
int tim = 0;
int prevtime = 0;
int currtime = 0;
int lightpos = 0;
int prevsunypos = 0;
int prevsunxpos = 0;
// variables to control behavior of world generation
const int SUN_ANCHOR_X = 49;
const int SUN_ANCHOR_Y = 0;
const int SUN_RADIUS = 49;
const int DAY_LENGTH = 30;
const int CLOUD_ALTITUDE = 48;
const int MEAN_GROUND_ALTITUDE=24;
// background process, it is called when there are no other events */
void update() {
// iterators
int i = 0, k = 0;
// coordinate containers
int sunypos = 0;
int sunxpos = 0;
// time marches on
currtime = time(0);
// if we're at time 0, ensure we dont hav an initial quantum leap going on
if (prevtime == 0) prevtime = currtime;
tim += currtime - prevtime;
// Draw time (only if a second has passed since the last one)
if (currtime - prevtime)
{
// Perlin-generate the clouds
for(i=0;i<100;i++)
for(k=0;k<100;k++)
if(PerlinNoise3D(i/55.0,k/65.0, tim/50.0,1.23,1.97,4) > 0) // I should really make constants instead of literals here
world[i][CLOUD_ALTITUDE][k] = 5;
else
world[i][CLOUD_ALTITUDE][k] = 0;
// position the sun
// calculate next x and y coordinates for it
sunxpos = (int)((((double)(tim % DAY_LENGTH))/DAY_LENGTH)*99.0);
sunypos = (sqrt(pow(SUN_RADIUS,2)-pow((sunxpos - SUN_ANCHOR_X),2)))+(SUN_ANCHOR_Y);//sqrt((double)((36 ^ 2) - ((sunxpos-49)^2)))+ 15;
// move it!
world[sunxpos][sunypos][49] = 6;
world[prevsunxpos][prevsunypos][49] = 0;
setLightPosition(sunxpos, sunypos, 49);
// save the current position so this sun can be deleted on next draw
prevsunypos = sunypos;
prevsunxpos = sunxpos;
// force a screen redraw
glutPostRedisplay();
}
// save the current time for next round
prevtime = currtime;
}
// Main loop
int main(int argc, char** argv)
{
// local iterator
int i,j,k;
double dbl;
/* Initialize the graphics system */
gradphicsInit(&argc, argv);
// generate perlin noise terrain
for(i=0;i<100;i++)
for(k=0;k<100;k++){
dbl = PerlinNoise2D(i/75.0,k/75.0,0.98,2.11,3)*5+MEAN_GROUND_ALTITUDE;
world[i][(int)dbl][k] = 1;
}
/* starts the graphics processing loop */
/* code after this will not run until the program exits */
glutMainLoop();
return 0;
}
<file_sep>/WebServerv2/db.c
/* program to facilitate usage of a database*/
/*Command line arguments:
clear : remove all records frm the database
add # filename : adds the contents of the file named filename to the database with a primarykey of #
remove # : removes the record qith the primary key #
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>
#include "hstring.h"
#define MAX_QUERY 512
#define BLOB_SIZE 65535
#define CHAR_SIZE 255
#define HOSTNAME "dursley.cis.uoguelph.ca"
#define DEBUG 0
/*
HOSTNAME can be defined with IP or hostname.
eg: #define HOSTNAME "172.16.58.3"
#define HOSTNAME "gradpc-38.cis.uoguelph.ca"
*/
#define USERNAME "mhoyle"
#define PASSWORD "<PASSWORD>"
#define DATABASE "mhoyle"
int main(int argc, char* argv[]){
MYSQL mysql;
char query[MAX_QUERY];
char fbuffer[BLOB_SIZE], fbuffer2[BLOB_SIZE], filequery[BLOB_SIZE + MAX_QUERY];
int i = 0, errnum = 0;
/*initializing strings*/
for(i=0;i<MAX_QUERY;i++) query[i] = 0;
for(i=0;i<BLOB_SIZE;i++) {fbuffer[i] = 0; fbuffer2[i] = 0;}
for(i=0;i<(MAX_QUERY+BLOB_SIZE);i++) filequery[i] = 0;
/*
Connect to database server.
Username and password must be filled in here.
If no username or password is stored in DB then use NULL.
*/
if (DEBUG) fprintf(stderr, "Connecting...\n");
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, "mydb");
if (!mysql_real_connect(&mysql, HOSTNAME, USERNAME, PASSWORD, DATABASE, 0, NULL, 0)) {
if (DEBUG) fprintf(stderr, "Failed connecting to database\n");
}
/*create the table if it doesn't exist*/
for(i=0;i<MAX_QUERY;i++) query[i] = 0;
strcat(query, "create table if not exists pages (id int not null auto_increment,");
sprintf(query, "%spage_content blob(%d),", query, BLOB_SIZE);
sprintf(query, "%spage_name char(%d),", query, CHAR_SIZE);
strcat(query, " primary key(id) )");
if(mysql_query(&mysql, query)){
if(DEBUG)fprintf(stderr, "Could not create table!\n");
}
if (argc == 2){
/*clear command*/
if (!strcmp(argv[1], "clear")){
if (DEBUG) fprintf(stderr, "clearing table\n");
/*
remove the table
*/
for(i=0;i<MAX_QUERY;i++) query[i] = 0;
strncpy(query, "drop table pages", MAX_QUERY);
if(mysql_query(&mysql,query))
if(DEBUG) fprintf(stderr,"query failed: '%s'\n", query);
/*
recreate it
*/
for(i=0;i<MAX_QUERY;i++) query[i] = 0;
strcat(query, "create table if not exists pages (id int not null auto_increment,");
sprintf(query, "%spage_content blob(%d),", query, BLOB_SIZE);
sprintf(query, "%spage_name char(%d),", query, CHAR_SIZE);
strcat(query, " primary key(id) )");
if(mysql_query(&mysql, query))
if(DEBUG) fprintf(stderr,"query failed: '%s'\n", query);
}
/*remove command*/
} else if (argc == 3){
if (!strcmp(argv[1], "remove")){
/*build the query*/
for(i=0;i<MAX_QUERY;i++)query[i] = 0;
sprintf(query, "delete from pages where id = %s", argv[2]);
if (DEBUG) fprintf(stderr, "removing entry with primary key %s\n", argv[2]);
/*send the query*/
if(mysql_query(&mysql,query))
if(DEBUG) fprintf(stderr, "query failed: '%s'\n", query);
}
} else if (argc == 4){
/*add command*/
if (!strcmp(argv[1], "add")){
if (DEBUG) fprintf(stderr, "adding new entry '%s'\n", argv[3]);
/*read in the file*/
errnum = hreadfile(argv[3], fbuffer, BLOB_SIZE);
/*handle errors*/
if (errnum){
if (errnum == -1 && DEBUG) fprintf(stderr, "File too large. could not read\n");
else if (errnum == -2 && DEBUG) fprintf(stderr, "File does not exist. could not read\n");
else if (DEBUG) fprintf(stderr, "Unknown error. error number: %d\n", errnum);
}
if (errnum == 0){
/*fix any ' in the file*/
(hreplacestring(fbuffer, "'", "\\'",fbuffer2, BLOB_SIZE));
if (DEBUG) fprintf(stderr, "file read. adding\n");
if (DEBUG > 1) fprintf(stderr, "%s\n", fbuffer2);
/*clear the query buffer*/
for(i=0;i<MAX_QUERY;i++) query[i] = 0;
/*build the initial query*/
sprintf(query, "insert into pages values (%s,'PLACEHOLDER','%s')", argv[2], argv[3]);
/*add the entry*/
if(mysql_query(&mysql,query)){
if(DEBUG) fprintf(stderr,"query failed: '%s'\n", query);
errnum = -3;
}
/*on success...*/
if (!errnum){
/*load the page content into ther large query buffer*/
sprintf(filequery, "update pages set page_content = '%s' where page_name = '%s'", fbuffer2, argv[3]);
if (DEBUG > 1) fprintf(stderr, "file query:\n%s\n\n", filequery);
/*insert the page content*/
if(mysql_query(&mysql,filequery)){
if(DEBUG) fprintf(stderr,"query failed: '%s'\n", filequery);
/*on failure, attempt to remove the bad entry*/
for(i=0;i<MAX_QUERY;i++)query[i]=0;
sprintf(query, "delete from pages where page_name = '%s'", argv[3]);
/*send bad page removal query*/
if(mysql_query(&mysql,query))
if(DEBUG) fprintf(stderr,"query failed: '%s'\n", query);
/*set the error number*/
errnum = -4;
}
}
}
}
}
/*
Finally close connection to server
*/
mysql_close(&mysql);
/*print exit state on error*/
if (DEBUG){
fprintf(stderr, "exit state:");
if (errnum == 0) fprintf(stderr, " OK\n");
else if (errnum == -1) fprintf(stderr, " error: could not read file, file too large\n");
else if (errnum == -2) fprintf(stderr, " error: could not read file, file does not exist\n");
else if (errnum == -3) fprintf(stderr, " error: failed to insert new entry\n");
else if (errnum == -4) fprintf(stderr, " error: failed to insert page content to new entry\n");
}
return 0;
}
<file_sep>/SplitFileRequesterRobust/calgar.c
/*********************************************************************
* Early networking exercise
* Requests a file to be sent in short packages, handles lost packets
********************************************************************/
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#define BUFF 1024
#define PORT 4950
#define DEBUGMODE 1
#define SERVERADDY "127.0.0.1"
#define byte unsigned char
#define FILENAME "spacemarine.jpg"
#define WRITENAME "kantor.jpg"
//function to print an error message and quit
void diep(char *s){
perror(s);
exit(1);
}
void sendRequest(short * packets, short numpackets, int sock, const struct sockaddr* si, int slen){
short * req;
int i = 0;
req = (short *) malloc(sizeof(short)*256);
req[0] = htons(numpackets);
for (i=0; i< numpackets; i++){
req[i+1] = htons(packets[i]);
}
if (sendto(sock, req, 2*(numpackets+1), 0, si, slen) ==-1){
diep("request sendto()");
}
free(req);
}
int recieveDgrams(int s, char ** map, int mapsize, int fieldsize, int * sizes, int entries){
int recflag = 1, numbytes = 0, numpackets = 0, i;
fd_set sset;
struct timeval timeout;
struct sockaddr * from;
socklen_t *flen;
char * buffer;
from = malloc(sizeof(struct sockaddr));
flen = malloc(sizeof(socklen_t));
while (recflag){
FD_ZERO(&sset); //set up the fd set
FD_SET(s,&sset);
timeout.tv_sec = 5; //set the timeout
timeout.tv_usec = 0;
//printf("timeout set\n");
buffer = (char *) malloc(sizeof(char) * fieldsize);
for(i=0;i<fieldsize;i++) buffer[i] = 0;
//printf("fd set up\n");
//check if the socket has stuff
//times out after 10 seconds
if(select(s+1, &sset, (fd_set *) 0, (fd_set *) 0, &timeout)){
//printf("select done\n");
//read data from the buffer
if ((numbytes = recvfrom(s, buffer, fieldsize, 0,from, flen)) == -1) {
diep("recvfrom");
} else {
//printf("recieved %d bytes\n", numbytes);
//store the data in a map slot
buffer[numbytes] = 0;
map[entries+numpackets] = buffer;
sizes[entries+numpackets] = numbytes;
//printf("copied\n");
numpackets++; //increment the packet counter
}
} else { //if it timed out
//printf("timeout\n");
recflag = 0;
}
}
return numpackets;
}
char * getChunk(char ** map, int * sizes, short size, int numchunks){
int i = 0;
//printf("finding chunk %d\n", size);
for (i = 0; i < numchunks; i++){
//printf("comparing %d, to target %d\n", (short)strlen(map[i]), size);
if (sizes[i] == size){
//printf("match\n");
return map[i];
}
}
return NULL;
}
//main function
int main(void){
struct sockaddr_in si_other; //address structs
int s = 0, slen = sizeof(si_other); //socket fd and address struct size
int numpackets = 0, totalpacks = 0, offset = 0; //counter for packets recieved
int i = 0, n = 0, f, l, r, nummissing=0; //loop controllers
char * buff, * file, *chunk = NULL; //buffer for recieved data
char ** map, **dummy; //map to store incoming data
short list[500], mlist[500]; //list of packets to request
FILE* fp;
int * sizes, *dsizes;
//malloc the buffer
buff = (char *) malloc(sizeof(char) * BUFF);
map = (char **) malloc(sizeof(char * ) * 500);
sizes = (int *) malloc(sizeof(int) * 500);
dummy = (char**) malloc(sizeof(char * ) * 500);
dsizes = (int *) malloc(sizeof(int) * 500);
file = (char*) malloc(sizeof(char) * (1024 * 500));
//initialize the map and buffer
memset((char *) map, 0, sizeof(map));
memset((char *) buff, 0, sizeof(buff));
memset((char *) list, 0, sizeof(list));
memset((char *) mlist, 0, sizeof(mlist));
memset((char *) dummy, 0, sizeof(dummy));
//set up the socket
if ((s=socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP))==-1){
diep("Socket");
}
//initialize the address struct
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if (inet_aton(SERVERADDY, &si_other.sin_addr) == 0){
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
printf("sending initial request\n"); //send the request
sprintf(buff, FILENAME);
//printf("packet construicted\n");
if (sendto(s, buff, BUFF, 0, (const struct sockaddr*)&si_other, slen) ==-1){
diep("sendto()");
}
printf("recieving datagrams\n");
numpackets = recieveDgrams(s, map, 500, BUFF, sizes, 0);
printf("data recieved\n");
/*printf("data recieved:\n"); //printf out the data recieved
for(i=0;i<numpackets;i++){
printf("%s", map[i]);
}*/
//set up the list of packets to request
list[0] = 1024;
list[1] = 2;
list[2] = 1;
sendRequest(list, 3, s, (const struct sockaddr *)&si_other, slen);
while (recieveDgrams(s, dummy, 500, BUFF, dsizes,0) != 3);
f = dsizes[0];
l = dsizes[1];
r = dsizes[2];
printf("f = %d, l = %d, r = %d\n", f, l, r);
//compose packet list
list[0] = f;
list[1] = l;
list[2] = r;
totalpacks = 3;
for(i = f-1; i > l; i--){
list[totalpacks] = i;
totalpacks++;
}
//printf("list composed\n");
//ensure all packets were recieved
while (numpackets != totalpacks){
//printf("we have some missing packets\n");
for (i=0; i <totalpacks; i++){
//printf("checking for packet %d\n", list[i]);
chunk = getChunk(map,sizes,list[i], totalpacks);
if (chunk == NULL){
//printf("chunk %d is missing\n", list[i]);
mlist[nummissing] = list[i];
//printf("added missing chunk to list");
nummissing++;
}
}
for(i=0; i< nummissing; i++) printf("Missing datagram %d\n", mlist[i]);
sendRequest(mlist, nummissing, s, (const struct sockaddr *)&si_other, slen);
//printf("sent request for missing\n");
numpackets += recieveDgrams(s,map,500,BUFF,sizes, numpackets);
//printf("reieved response of %d\n", numpackets);
}
//for(i=0; i< totalpacks; i++) printf("%d\n", list[i]);
printf("saving file\n");
//print the file
for (i=0; i <totalpacks; i++){
chunk = getChunk(map,sizes,list[i], totalpacks);
for(n=0; n < list[i]; n++){
file[offset] = chunk[n];
offset++;
}
}
//printf("\n%s\n", file);
fp = fopen(WRITENAME, "w+");
fwrite(file, offset, 1, fp);
fclose(fp);
printf("\n");
free(buff); //clean up
free(map);
free(dummy);
free(file);
close(s);
return 0; // Exit
}
<file_sep>/MinecraftClone/Iteration2/makefile
all : a2
INCLUDES = -F/System/Library/Frameworks -lglut -lGLU
a2: a2.c graphics.c graphics.h perlin.c
gcc a2.c graphics.c perlin.c -o a2 -g $(INCLUDES)
clean:
rm -f a2 *~
<file_sep>/MinecraftClone/Iteration2/graphics.c
/* Derived from scene.c in the The OpenGL Programming Guide */
/* Keyboard and mouse rotation taken from Swiftless Tutorials #23 Part 2 */
/* http://www.swiftless.com/tutorials/opengl/camera2.html */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "graphics.h"
extern void update();
extern void collisionResponse();
extern void buildDisplayList();
/* flags used to control the appearance of the image */
int lineDrawing = 0; // draw polygons as solid or lines
int lighting = 1; // use diffuse and specular lighting
int smoothShading = 1; // smooth or flat shading
int textures = 0;
/* texture data */
GLubyte Image[64][64][4];
GLuint textureID[1];
/* viewpoint coordinates */
float vpx = -50.0, vpy = -50.0, vpz = -50.0;
float oldvpx, oldvpy, oldvpz;
/* mouse direction coordiates */
float mvx = 0.0, mvy = 45.0, mvz = 0.0;
/* location for the light source (the sun), the first three
values are the x,y,z coordinates */
GLfloat lightPosition[] = {0.0, 100.0, 0.0, 0.0};
/* command line flags */
int flycontrol = 0; // allow viewpoint to move in y axis when 1
int displayAllCubes = 0; // draw all of the cubes in the world when 1
int testWorld = 0; // sample world for timing tests
/* list of cubes to display */
int displayList[MAX_DISPLAY_LIST][3];
int displayCount = 0; // count of cubes in displayList[][]
/* allows user to set position of the light */
void setLightPosition(GLfloat x, GLfloat y, GLfloat z) {
lightPosition[0] = x;
lightPosition[1] = y;
lightPosition[2] = z;
glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);
}
/* returns current position of the light */
GLfloat* getLightPosition() {
return(lightPosition);
}
/* functions store and return the current location of the viewpoint */
void getViewPosition(float *x, float *y, float *z) {
*x = vpx;
*y = vpy;
*z = vpz;
}
void setViewPosition(float x, float y, float z) {
vpx = x;
vpy = y;
vpz = z;
}
/* returns the previous location of the viewpoint */
void getOldViewPosition(float *x, float *y, float *z) {
*x = oldvpx;
*y = oldvpy;
*z = oldvpz;
}
/* returns the current orientation of the viewpoint */
void getViewOrientation(float *xaxis, float *yaxis, float *zaxis) {
*xaxis = mvx;
*yaxis = mvy;
*zaxis = mvz;
}
/* add the cube at world[x][y][z] to the display list and */
/* increment displayCount */
int addDisplayList(int x, int y, int z) {
displayList[displayCount][0] = x;
displayList[displayCount][1] = y;
displayList[displayCount][2] = z;
displayCount++;
if (displayCount > MAX_DISPLAY_LIST) {
printf("You have put more items in the display list then there are\n");
printf("cubes in the world. Set displayCount = 0 at some point.\n");
exit(1);
}
}
/* Initialize material property and light source. */
void init (void)
{
GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat light_diffuse[] = { 0.8, 0.8, 0.8, 1.0 };
GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_full_off[] = {0.0, 0.0, 0.0, 1.0};
GLfloat light_full_on[] = {1.0, 1.0, 1.0, 1.0};
/* if lighting is turned on then use ambient, diffuse and specular
lights, otherwise use ambient lighting only */
if (lighting == 1) {
glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular);
} else {
glLightfv (GL_LIGHT0, GL_AMBIENT, light_full_on);
glLightfv (GL_LIGHT0, GL_DIFFUSE, light_full_off);
glLightfv (GL_LIGHT0, GL_SPECULAR, light_full_off);
}
glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
}
/* draw cube in world[i][j][k] */
void drawCube(int i, int j, int k) {
GLfloat blue[] = {0.0, 0.0, 1.0, 1.0};
GLfloat red[] = {1.0, 0.0, 0.0, 1.0};
GLfloat green[] = {0.0, 1.0, 0.0, 1.0};
GLfloat white[] = {1.0, 1.0, 1.0, 1.0};
GLfloat black[] = {0.0, 0.0, 0.0, 1.0};
/* select colour based on value in the world array */
if (world[i][j][k] == 1)
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green);
else if (world[i][j][k] == 2)
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
else if (world[i][j][k] == 3)
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red);
else if (world[i][j][k] == 4)
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, black);
else
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, white);
glPushMatrix ();
/* offset cubes by 0.5 so the centre of the */
/* cube falls in the centre of the world array */
glTranslatef(i + 0.5, j + 0.5, k + 0.5);
glutSolidCube(1.0);
glPopMatrix ();
}
/* called each time the world is redrawn */
void display (void)
{
GLfloat skyblue[] = {0.52, 0.74, 0.84, 1.0};
GLfloat black[] = {0.0, 0.0, 0.0, 1.0};
int i, j, k;
buildDisplayList();
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* position viewpoint based on mouse rotation and keyboard
translation */
glLoadIdentity ();
glRotatef(mvx, 1.0, 0.0, 0.0);
glRotatef(mvy, 0.0, 1.0, 0.0);
/* Subtract 0.5 to raise viewpoint slightly above objects. */
/* Gives the impression of a head on top of a body. */
glTranslatef(vpx, vpy - 0.5, vpz);
/* draw surfaces as either smooth or flat shaded */
if (smoothShading == 1)
glShadeModel(GL_SMOOTH);
else
glShadeModel(GL_FLAT);
/* draw polygons as either solid or outlines */
if (lineDrawing == 1)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
/* give all objects the same shininess value and specular colour */
glMaterialf(GL_FRONT, GL_SHININESS, 30.0);
/* set starting location of objects */
glPushMatrix ();
/* make a blue sky cube */
glShadeModel(GL_SMOOTH);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, skyblue);
glPushMatrix ();
/* move the cube center to middle of world space */
glTranslatef(50, 25, 50);
glutSolidCube(150.0);
glPopMatrix ();
glShadeModel(GL_SMOOTH);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
/* draw all cubes in the world array */
if (displayAllCubes == 1) {
/* draw all cubes */
for(i=0; i<100; i++) {
for(j=0; j<50; j++) {
for(k=0; k<100; k++) {
if (world[i][j][k] != 0) {
drawCube(i, j, k);
}
}
}
}
} else {
/* draw only the cubes in the displayList */
/* these should have been selected in the update function */
for(i=0; i<displayCount; i++) {
drawCube(displayList[i][0],
displayList[i][1],
displayList[i][2]);
}
}
glPopMatrix();
glutSwapBuffers();
}
/* sets viewport information */
void reshape(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(45.0, (GLfloat)w/(GLfloat)h, 0.1, 300.0);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
}
/* respond to keyboard events */
void keyboard(unsigned char key, int x, int y)
{
float rotx, roty;
switch (key) {
case 27:
case 'q':
exit(0);
break;
case '1': // draw polygons as outlines
lineDrawing = 1;
lighting = 0;
smoothShading = 0;
textures = 0;
init();
glutPostRedisplay();
break;
case '2': // draw polygons as filled
lineDrawing = 0;
lighting = 0;
smoothShading = 0;
textures = 0;
init();
glutPostRedisplay();
break;
case '3': // diffuse and specular lighting, flat shading
lineDrawing = 0;
lighting = 1;
smoothShading = 0;
textures = 0;
init();
glutPostRedisplay();
break;
case '4': // diffuse and specular lighting, smooth shading
lineDrawing = 0;
lighting = 1;
smoothShading = 1;
textures = 0;
init();
glutPostRedisplay();
break;
case '5': // texture with smooth shading
lineDrawing = 0;
lighting = 1;
smoothShading = 1;
textures = 1;
init();
glutPostRedisplay();
break;
case 'w': // forward motion
oldvpx = vpx;
oldvpy = vpy;
oldvpz = vpz;
//XXX
rotx = (mvx / 180.0 * 3.141592);
roty = (mvy / 180.0 * 3.141592);
vpx -= sin(roty) * 0.3;
// turn off y motion so you can't fly
if (flycontrol == 1)
vpy += sin(rotx) * 0.3;
vpz += cos(roty) * 0.3;
collisionResponse();
glutPostRedisplay();
break;
case 's': // backward motion
oldvpx = vpx;
oldvpy = vpy;
oldvpz = vpz;
rotx = (mvx / 180.0 * 3.141592);
roty = (mvy / 180.0 * 3.141592);
vpx += sin(roty) * 0.3;
// turn off y motion so you can't fly
if (flycontrol == 1)
vpy -= sin(rotx) * 0.3;
vpz -= cos(roty) * 0.3;
collisionResponse();
glutPostRedisplay();
break;
case 'a': // strafe left motion
oldvpx = vpx;
oldvpy = vpy;
oldvpz = vpz;
roty = (mvy / 180.0 * 3.141592);
vpx += cos(roty) * 0.3;
vpz += sin(roty) * 0.3;
collisionResponse();
glutPostRedisplay();
break;
case 'd': // strafe right motion
oldvpx = vpx;
oldvpy = vpy;
oldvpz = vpz;
roty = (mvy / 180.0 * 3.141592);
vpx -= cos(roty) * 0.3;
vpz -= sin(roty) * 0.3;
collisionResponse();
glutPostRedisplay();
break;
case 'f': // toggle flying controls
if (flycontrol == 0) flycontrol = 1;
else flycontrol = 0;
break;
}
}
/* load a texture from a file */
/* not currently used */
void loadTexture() {
FILE *fp;
int i, j;
int red, green, blue;
if ((fp = fopen("image.txt", "r")) == 0) {
printf("Error, failed to find the file named image.txt.\n");
exit(0);
}
for(i=0; i<64; i++) {
for(j=0; j<64; j++) {
fscanf(fp, "%d %d %d", &red, &green, &blue);
Image[i][j][0] = red;
Image[i][j][1] = green;
Image[i][j][2] = blue;
Image[i][j][3] = 255;
}
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1,textureID);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 64, 64, 0, GL_RGBA,
GL_UNSIGNED_BYTE, Image);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
fclose(fp);
}
void motion(int x, int y) {
static float oldx, oldy;
mvx += (float) y - oldy;
mvy += (float) x - oldx;
oldx = x;
oldy = y;
glutPostRedisplay();
}
void mouse(int button, int state, int x, int y) {
/* capture mouse button events - not currently used */
/*
if (button == GLUT_LEFT_BUTTON)
printf("left button - ");
else if (button == GLUT_MIDDLE_BUTTON)
printf("middle button - ");
else
printf("right button - ");
if (state == GLUT_UP)
printf("up - ");
else
printf("down - ");
printf("%d %d\n", x, y);
*/
}
void gradphicsInit(int *argc, char **argv) {
int i, fullscreen;
/* set GL window information */
glutInit(argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
/* parse command line args */
fullscreen = 0;
for(i=1; i<*argc; i++) {
if (strcmp(argv[i],"-full") == 0)
fullscreen = 1;
if (strcmp(argv[i],"-drawall") == 0)
displayAllCubes = 1;
if (strcmp(argv[i],"-testworld") == 0)
testWorld = 1;
if (strcmp(argv[i],"-help") == 0) {
printf("Usage: a2 [-full] [-drawall] [-testworld]\n");
exit(0);
}
}
if (fullscreen == 1) {
glutGameModeString("1024x768:32@75");
glutEnterGameMode();
} else {
glutInitWindowSize (1024, 768);
glutCreateWindow (argv[0]);
}
init();
/* not used at the moment */
// loadTexture();
/* attach functions to GL events */
glutReshapeFunc (reshape);
glutDisplayFunc(display);
glutKeyboardFunc (keyboard);
glutPassiveMotionFunc(motion);
glutMouseFunc(mouse);
glutIdleFunc(update);
}
<file_sep>/WebServerv2/hstring.c
/*hstring.c*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "hstring.h"
#define BLOB_SIZE 65535
/*String appending tool*/
/*creates a new string of the appropriate length, derived by appending str2 to the snd of str1*/
/*Does not affect input strings. creates new return string*/
/*don't forget to free the new string in the upper function*/
char * happend(char * str1, char * str2){
char * ret = NULL;
int a = 0, len = 0;
/*calculate the length of the new string*/
if (str1 && str2){
len = (strlen(str1) +strlen(str2) + 1);
/*allocate and initialize*/
ret = malloc(sizeof(char)*len);
for (a = 0; a < len; a++){
ret[a] = 0;
}
/*stick the strings in there*/
strcat(ret,str1);
strcat(ret,str2);
/*null-terminate the string*/
ret[strlen(ret)] = 0;
} else if (str1){
return hstrclone(str1);
} else if (str2){
return hstrclone(str2);
}
return ret;
}
/*String cloning tool*/
/*creates a new string of the appropriate length, and copies the contents of the old one into it*/
/*Does not affect the input string. creates a new return string*/
/*don't forget to free the new string in the upper function*/
char * hstrclone(char * str){
char * ret = NULL;
if (str){
/*allocate the new string in memory*/
ret = malloc(sizeof(char)*(strlen(str)+1));
/*copy the old string in and null-term it*/
strcpy(ret, str);
ret[strlen(str)] = 0;
}
return ret;
}
/*Substring removal tool*/
/*creates a new string of the appropriate length, derived by removing targ from str*/
/*Does not affect input strings. creates new return string*/
/*don't forget to free the new string in the upper function*/
char * hremovestr(char * str, char * targ){
char * end = NULL, * ret = NULL, * tmp = NULL;
int a = 0, len = 0;
if (str && targ){
/*clone the string to avoid messing with input*/
ret = hstrclone(str);
/*find the target string*/
tmp = strstr(ret, targ);
/*if it's found...*/
if (tmp){
/*calc length of trailing string*/
len = strlen(tmp) - strlen(targ) + 1;
/*allocate and initialize trailing string*/
end = malloc(sizeof(char)*len);
for (a=0; a< len; a++){
end[a] = 0;
}
/*copy the end of the old string into the trail*/
strcat(end, &tmp[strlen(targ)]);
/*terminate the pre-target string*/
tmp[0] = 0;
/*append the trail to the new 'end' of the string*/
tmp = happend(ret,end);
/*clean up*/
if(ret) free(ret);
ret = tmp;
tmp = NULL;
free(end);
}
}
return ret;
}
int hreplacestring(char * str, char * targ, char * new, char * buf, int size){
char temp[size], ret[size], * tmp = NULL;
int i = 0, len = 0, flag = 0;
for(i=0;i<size;i++){ temp[i] = 0; ret[i] = 0; }
strncpy(ret, str, size);
tmp = &ret[0];
while(tmp){
if (tmp){
tmp = strstr(tmp, targ);
if (tmp){
flag = 1;
len = strlen(ret) - strlen(tmp);
for(i=0;i<len;i++) temp[i] = ret[i];
strncat(temp, new, size - strlen(temp));
tmp = &tmp[strlen(targ)];
strncat(temp, tmp, size - strlen(temp));
strncpy(ret, temp, size);
tmp = &tmp[strlen(new)-1];
for(i=0;i<size;i++) temp[i] = 0;
}
}
}
strncpy(buf, ret, size);
return flag;
}
/*reads at most size characters from a file and strores them in buf*/
int hreadfile(char * filename, char * buf, int size){
FILE * fp = NULL;
int i = 0;
char file[size], ch = 0;
for(i=0;i<size;i++) file[i] = 0;
fp = fopen(filename, "r");
if (fp){
for(i=0;ch!=EOF && i < size;i++){
ch = fgetc(fp);
file[i] = ch;
}
if (i == size){
/*if file is too large, return -1*/
if (fp) fclose(fp);
return -1;
}
/*zero the rest of the string*/
for(i=i-1;i<size;i++)file[i] = 0;
for (i=0;i<strlen(file);i++){
buf[i] = file[i];
}
/*close the file*/
if (fp) fclose(fp);
return 0;
} else {
buf = NULL;
return -2; /*error -2, file does not exist*/
}
}
/*tool to save a string as a textfile*/
void hwritefile(char * filename, char * file){
FILE * fp = fopen(filename, "w");
/*open the file, push the string into it, and null-term it*/
if (fp){;
fputs(file, fp);
fputc(0, fp);
fclose(fp);
}
}
/*tool to append a string to the end of a file*/
void happendfile(char * filename, char *str, int size){
char * file = NULL, * new = NULL;
int rval = 0;
rval = hreadfile(filename, file, size);
/*read in the file to a string*/
if (file && !rval){
/*append the tail string to the file string*/
new = happend(file, str);
free(file);
/*write the new file*/
hwritefile(filename, new);
} else {
/*if the file doesnt alreayd exist, just create it with the given string*/
hwritefile(filename, str);
}
}
/*tool to remove any whitespace at the beginning of a string*/
/*NOTE: THIS WILL BE UPGRADED TO REMOVE WHITESPACE AT THE BIGINNING AND END, INCLUDING NEWLINES AND TABS*/
char * hftrim(char * input){
char * start = NULL;
start = input;
while(start[0] == ' ') start = &start[1];
return hstrclone(start);
}
/*Functions to make:
queues, stacks, linked lists*/
<file_sep>/MinecraftClone/Iteration1/BaseCode/readme.txt
Building and Running the Graphics System
----------------------------------------
The program consists of two .c files. The a1.c file contains the main()
routine and the update() function. All of the changes necessary for the
assignment can be made to this file. The graphics.c file contains all
of the code to create the 3D graphics for the assignment. You should not
need to change this code for assignment 1.
There is a makefile which will compile the code on the Macs.
The executable is named a1. If the program is run with the -full
command line option then it will run in fullscreen.
When the program runs the view is controlled through the mouse and
keyboard. The mouse moves the viewpoint left-right and up-down.
The keyboard controls do the following:
w move forward
a strafe left
s move forward
d strafe right
q quit
The 1,2,3 buttons also change the rendering options.
Note: If the controls appear to be reversed then the viewpoint is upside down.
Pull or push the mouse until you turn over.
There are a few sample boxes drawn in the middle of the world and a
set of boxes which show the outer width and depth of the world.
These are defined in a1.c and should be removed before your
assignment is submitted.
Programming Interface to the Graphics System
--------------------------------------------
1. Drawing the world
--------------------
The only shape drawn by the graphics system is the cube. The data
structure which holds all of the objects is the three dimensional array:
GLubyte world[100][50][100]
The GLubyte is an unsigned byte defined by OpenGL. It is the same as
any other unsigned byte.
The indices of the array correspond to the dimensions of the world.
In order from left to right they are x,y,z. This means the world is 100 units
in the x dimension (left to right), 50 units in the y dimension (up and down),
and 100 units in z (back to front).
The cube at location world[0][0][0] is in the lower corner of the 3D world.
The cube at location world[99][49][99] is diagonally across from
world[0][0][0] in the upper corner of the world.
Each cube drawn in the world is one unit length in each dimension.
Values are stored in the array to indicate if that position in the
world is occupied or are empty. The following would mean that
position 25,25,25 is empty:
world[25][25][25] = 0
If the following were used:
world[25][25][25] = 1
then position 25,25,25 would contain a green cube.
Cubes can be drawn in different colours depending on that value stored
in the world array. The current colours which can be drawn are:
0 empty
1 green
2 blue
3 red
4 black
5 white
2. Setting the Light Position
-----------------------------
There is a single light in the world. The position of the light
is controlled through two functions:
void setLightPosition(GLfloat x, GLfloat y, GLfloat z);
GLfloat* getLightPosition();
The setLightPosition() function moves the light source to location x,y,z in the
world. The getLightPosition() function returns a pointer to an array
of floats containing current the x,y,z location of the light source.
To see the effect of a change through setLightPosition() you will
need to call glutPostRedisplay() to update the screen.
3. Timing Events
----------------
OpenGL is event driven. The events which this program will respond to
include keyboard and mouse input. The glutMainLoop() function receives
these inputs and processes them.
The glutMainLoop() function will loop until the program ends. This means
that all of your code to initialize the world must be run before this
function is called. It also means that changes to the world must occur
inside function called by OpenGL. The only function which you have
access to to make these updates is named update() in a1.c.
When it is not otherwise drawing the scene the system will call the
update() function. This is where you can make changes to the world
array and lighting while program is running.
If you make changes to the world or the light in the udpate()
function then you should call glutPostRedisplay() to refresh the screen.
The update() function is not called on a predictable schedule. You will
need to check the time during updates to control the rate at which
the world changes.
Changing graphics.c
-------------------
You can make changes to graphics.c if you wish but you are responsible
for making them work. If you break the graphics system then you have
to fix it yourself.
<file_sep>/SplitFileRequesterRobust/makefile
all: Server Calgar Empra
run: all
./Calgar
runEmpra: Empra
./Empra
runServer: Server
./Server
Server: assignment3-server.c assignment3-server.h
gcc assignment3-server.c -o Server -Wall
Calgar: calgar.c
gcc calgar.c -o Calgar -Wall
Empra: empra.c
gcc empra.c -o Empra -Wall
clean:
rm -rf Server
rm -rf Calgar
rm -rf Empra
rm -rf *~
<file_sep>/WebServerv2/server.c
/* Web Server application by <NAME> January 21st 2008 */
/* Derived from Web Server Example by <NAME> */
/* ftp://ftp.isi.edu/in-notes/rfc2616.txt */
/* http://ftp.ics.uci.edu/pub/ietf/http/rfc1945.html */
/* Make the necessary includes and set up the variables. */
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <mysql/mysql.h>
#include "hstring.h"
/*SQL defines*/
#define USERNAME "mhoyle"
#define PASSWORD "<PASSWORD>"
#define DATABASE "mhoyle"
#define MAX_LENGTH 1024
#define MAX_QUERY 512
#define BLOB_SIZE 65535
#define CHAR_SIZE 255
#define HOSTNAME "dursley.cis.uoguelph.ca"
/*prototype for the fileno function. Compiler complains about it's use if it's not prototyped*/
int fileno(FILE* stream);
/*prototype the SSInclude Function*/
char * SSInclude( char * page, char *libName );
/*global debug variable for printing out debug messages*/
/*0 = no debug messages*/
/*1 = main debug messages*/
/*2 = verbose mode*/
int debug = 0;
int socketnumber = 8888;
/*struct to store tag tokens*/
typedef struct{
char * tag;
char * attributes;
} Tag;
/*struct to store tag tokens or string tokens*/
typedef struct{
Tag * tagp;
char * strp;
} Token;
/*linked list struct for the tokens list*/
typedef struct toklist{
Token * val;
struct toklist * next;
} TList;
/*Log struct*/
typedef struct {
char pageName[MAX_LENGTH];
char browserName[MAX_LENGTH];
unsigned long date;
} Log;
/*prototype the getDate function (FOR USE IN LOGGING ONLY)*/
unsigned long getDate();
/*Blacklist object struct*/
typedef struct bllist{
struct bllist * next;
char lib[256];
} Blist;
/*blacklist linked list functions*/
/*function to make a new list object*/
Blist * makeBlackEntry(char * name){
Blist * ret = NULL;
int i = 0;
if (debug) fprintf(stderr, "Making new blacklist entry for '%s'\n", name);
/*malloc the object*/
ret = malloc(sizeof(Blist));
/*initialize it's fields*/
for ( i = 0; i < 256; i++){
ret->lib[i] = 0;
}
strncpy(ret->lib, name, strlen(name));
ret->next = NULL;
/*return the object*/
return ret;
}
/*function to add a new entry to a Blacklist*/
Blist * addEntry(Blist * top, char * libr){
Blist * curr = top, * new = NULL;
if (debug) fprintf(stderr, "Adding entry '%s' to blacklist\n", libr);
/*create the object*/
new = makeBlackEntry(libr);
/*add it to the end of the list and return a pointer to the top of the new list*/
if (curr){
while (curr->next) curr = curr->next;
curr->next = new;
if (debug) fprintf(stderr, "added new to blacklist\n");
return top;
} else {
return new;
}
}
/*function to remove an entry from a Blacklist*/
Blist * removeEntry(Blist * top, char * targ){
Blist * curr = top, * tmp = NULL;;
if (debug) fprintf(stderr, "removing entry '%s' from the blacklist\n", targ);
/*step through the list*/
while (curr){
/*if the given string exists in the list, remove it*/
if (curr == top){
if (!strcmp(targ, curr->lib)){
tmp = curr;
curr = curr->next;
if (tmp)free(tmp);
/*if the first entry was the target, we return a pointer to the second entry, which is now the top*/
return curr;
} else {
tmp = curr;
curr = curr->next;
}
} else {
if (!strcmp(targ, curr->lib)){
tmp->next = curr->next;
if (curr) free(curr);
return top;
} else {
tmp = tmp->next;
curr = curr->next;
}
}
}
/*return A pointer to the top of the list*/
return top;
}
/*function to check if a string exists in the list*/
int blacklisted(Blist * top, char * targ){
Blist * curr = top;
if (debug) fprintf(stderr, "Checking if entry '%s' is blacklisted\n", targ);
/*step through the list, comparing the entry strings. if a match is founbd return 1*/
while (curr){
if (!strcmp(targ, curr->lib)) return 1;
else curr = curr->next;
}
return 0;
}
/*function to print out the contents of a blacklist*/
void printlist(Blist * list){
Blist * curr = list;
fprintf(stderr, "Library Blacklist:\n");
/*step through the list printing out each entry*/
while (curr){
fprintf(stderr,"%s\n", curr->lib);
curr = curr->next;
}
}
/*function to destroy a blacklist*/
Blist * destroylist(Blist * list){
Blist * curr = list, * tmp = NULL;
if (debug) fprintf(stderr, "Destroying a blacklist\n");
/*step through the list, freeing each struct*/
while(curr){
if (curr->next) tmp = curr->next;
if (curr) free(curr);
curr = tmp;
tmp = NULL;
}
/*return the current pointer; should be NULL*/
return curr;
}
/*Main Function*/
int main() {
/*Set up Socket Variables*/
int server_sockfd, client_sockfd, server_len, count, i, size, newlineCount, ctr, exitflag = 0, pauseflag = 0, cont = 0, dbflag = 0, fileopened = 0;
socklen_t client_len;
struct sockaddr_in server_address, client_address;
/*set up strings*/
char ch, chr, request[2048], dnsname[2048], *path = NULL, *endChar = NULL, *file = NULL, *temp = NULL, libName[256], *browser =NULL, input[256], logstring[5000], temporary[5000],logentry[5000];
/*set up file/directory pointers*/
FILE * fp = NULL, *fd = NULL, *pipe = NULL, *lpipe = NULL;
DIR * dp = NULL;
struct dirent * curLib = NULL;
/*set up Log pointer*/
Log * nLog = NULL;
/*set up the blacklist pointer*/
Blist * blacklist;
/*constant strings*/
/* http header which is sent in response to a browser request */
char *response1 = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n\r\n";
/*hardcoded 404 error page*/
char *E404 = "<HTML><HEAD><TITLE>404 error!</title></head><BODY BACKGROUND=\"#E0E0E0\"TEXT= \"#000000\" LINK= \"#FF0000\" ALINK= \"#FF0000\" VLINK= \"#0000FF\"><CENTER><H2>404 Error<BR>File not found</H2></center><BR>fore oh fore! I'm soooooooooooooo sorry. <br>that page doesnt exist. <br> It's ok to feel sad. I feel like a huge jerk not having what you want.<br> hug? <br></body></html>";
/*sql variables*/
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char query[MAX_QUERY];
char fbuffer[BLOB_SIZE], fbuffer2[BLOB_SIZE], filequery[BLOB_SIZE + MAX_QUERY];
int p_keys[256], numpkeys =0;
/*open the log file*/
fd = fopen("access.log", "a+");
/*initialize request string*/
for (i = 0; i < 2048; i++){
request[i] = 0;
dnsname[i] = 0;
}
/*initialize libName string*/
for (i = 0; i < 256; i++){
libName[i] =0;
input[i] = 0;
p_keys[i] = 0;
}
/*destroy any lingering pipes*/
unlink("Spipe");
if(debug) fprintf(stderr,"opening the pipes...");
/*connect to the pipe*/
if (!mkfifo("Spipe", 0666 | O_RDWR)){
if (debug) fprintf(stderr, "connecting to Spipe...");
if (!debug) fprintf(stderr, "Please load the GUI now.\n");
pipe = fopen("Spipe", "r");
if (pipe) {if(debug) fprintf(stderr, "done\n");}
else{
if(debug) fprintf(stderr, "failed: unable to open file. exiting.\n");
exitflag = 1;
}
} else{
if(debug) fprintf(stderr, "failed: Unable to establish fifo pipe. exiting.\n");
exitflag = 1;
}
if (debug) fprintf(stderr, "connecting to Lpipe...");
while(!lpipe){
lpipe = fopen("Lpipe", "w");
}
if (debug) fprintf(stderr, "done\n");
fclose(lpipe);
if (debug) fprintf(stderr, "done\n");
/*set input to non-blocking */
; if (pipe) if (fcntl(fileno(pipe), F_SETFL, O_NONBLOCK)) perror("fcntl for pipe");
/* Remove any old socket and create an unnamed socket for the server. Set it to non-blocking*/
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(server_sockfd, F_SETFL, O_NONBLOCK);
/* Name the socket. */
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(socketnumber);
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
/* Create a connection queue and wait for clients. */
listen(server_sockfd, 5);
/*main program loop*/
while(!exitflag) {
/*initialize variables*/
if (file != NULL){
free(file);
file = NULL;
}
file = NULL;
if (fp) fclose(fp);
fp = NULL;
size = 0;
for (i = 0; i < 2048; i++){ request[i] = 0; dnsname[i] = 0;}
for (i = 0; i < 256; i++){libName[i] =0; input[i] = 0; p_keys[i] = 0;}
for(i=0;i<MAX_QUERY;i++) query[i] = 0;
for(i=0;i<BLOB_SIZE;i++) {fbuffer[i] = 0; fbuffer2[i] = 0;}
for(i=0;i<(MAX_QUERY+BLOB_SIZE);i++) filequery[i] = 0;
newlineCount = 0;
path = NULL;
endChar = NULL;
cont = 0;
chr = 0;
ctr = 0;
dbflag = 0;
fileopened = 0;
numpkeys = 0;
/*check the pipe for incoming commands*/
count = fread(&chr, sizeof(char), 1, pipe);
if (debug && chr != 0) fprintf(stderr, "'%c' read from pipe\n", chr);
/*shutdown command*/
if (chr == 's'){ if (debug) fprintf(stderr, "s recieved thru pipe\n"); exitflag = 1;}
/*pause command*/
if (chr == 'p'){ if (debug) fprintf(stderr, "p recieved thru pipe\n"); pauseflag = 1;}
/*unpause command*/
if (chr == 'u'){ if (debug) fprintf(stderr, "u recieved thru pipe\n"); pauseflag = 0;}
/*toggle library command*/
if (chr == 't'){ if (debug) fprintf(stderr, "t recieved thru pipe\n");
/*read the library name until semicolon (end of library name)*/
while(1){
fread(&chr, sizeof(char), 1, pipe);
if (chr){
if (chr == ';') break;
if (chr != ' '){
libName[ctr] = chr;
ctr+=1;
}
}
}
if (debug) fprintf(stderr, "toggling library '%s'\n", libName);
/*check the blacklist for the library. if it's there, remove it. if not, add it*/
if (blacklisted(blacklist, libName)) blacklist = removeEntry(blacklist, libName);
else blacklist = addEntry(blacklist, libName);
if (debug) printlist(blacklist);
}
/*readlogs command*/
if (chr == 'l'){ if (debug) fprintf(stderr, "l recieved thru pipe\n");
/*initialize strings*/
for( i = 0; i < 5000; i++) {temporary[i] = 0; logentry[i] = 0; logstring[i] = 0;}
fclose(fd);
fd = fopen("access.log", "r");
/*on success*/
if (fd){
if (debug) fprintf(stderr, "opened pipe successfully");
while(!feof(fd)){
/*initialize the log storage area and read in the next log entry*/
nLog= malloc(sizeof(Log));
for(i = 0; i < MAX_LENGTH; i++) {nLog->pageName[i] = 0; nLog->browserName[i] = 0;}
nLog->date = 0;
fread(nLog, sizeof(Log), 1, fd);
if (debug) fprintf(stderr, "read log entry\n");
/*generate a log entry string*/
sprintf(logentry, "%s %s %lu", nLog->pageName, nLog->browserName, nLog->date);
logentry[strlen(logentry)] = 0;
if (debug) fprintf(stderr, "constructed log entry\n");
/*if it is a valid log entry*/
if (strcmp(logentry, " 0")){
if (debug) fprintf(stderr, "valid log entry [%s]\n", logentry);
/*add it to the return string*/
if (strlen(logstring)){
sprintf(temporary, "%s;%s", logstring, logentry);
temporary[strlen(temporary)] = 0;
strncpy(logstring, temporary, 5000);
} else {
strncpy(logstring, logentry, 5000);
}
}
if (debug) fprintf(stderr, "done validation\n");
/*clear the temporary strings*/
for( i = 0; i < 5000; i++) {temporary[i] = 0; logentry[i] = 0;}
if (debug) fprintf(stderr, "cleared temp strings\n");
/*clear the log stroage area*/
if(nLog) free(nLog);
nLog = NULL;
}
fclose(fd);
fd =fopen("access.log", "a+");
lpipe = fopen("Lpipe", "w");
/*push the string into the pipe*/
if (lpipe){
if (strlen(logstring)){
if(debug) fprintf(stderr, "Sending '%s' through the pipe...", logstring);
fputs(logstring, lpipe);
if (debug) fprintf(stderr, "done\n");
fclose(lpipe);
if (debug) fprintf(stderr, "pipe closed\n");
} else {
if(debug) fprintf(stderr, "No logs in file. sending error code");
fputs("None", lpipe);
fclose(lpipe);
if (debug) fprintf(stderr, "pipe closed\n");
}
}else{
if(debug) fprintf(stderr, "Pipe not connected; Can not send command.\n");
}
}
if (debug) fprintf(stderr, "log entries read:%s\n", logstring);
}
/*reinitialize variables*/
chr = 0;
ctr = 0;
/*if the server is paused, skip the networking sections*/
if (!pauseflag){
/* Accept a connection. */
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
/* We can now read/write to client on client_sockfd.*/
/* read query from the client */
while(!cont) {
count = read(client_sockfd, &ch, 1);
if (count == -1) cont = 1;
if (count == 0) break;
/* remove CR from CR-LF end of line markers */
if (ch == '\r') count = read(client_sockfd, &ch, 1);
/* look for empty line which signals the end of the request */
if (ch == '\n') newlineCount++;
else newlineCount = 0;
if (newlineCount == 2) break;
/*save the character read from the buffer*/
if (ch) request[strlen(request)] = ch;
}
if(debug && strlen(request)>1) fprintf(stderr, "request length %d: \n::::::::::::::::::::::\n%s::::::::::::::::::::::\n",(int)strlen(request), request);
/*if a request was recieved*/
if(!cont){
if(debug) fprintf(stderr, "Logging request...");
/*isolate the browser name from the path*/
browser = strstr(request, "User-Agent:");
browser = strchr(browser, ' ');
browser = &browser[1];
while(browser[ctr] != 0 && browser[ctr] != ' ') ctr += 1;
path = malloc(sizeof(char)*(ctr+1));
for(i = 0; i <=ctr; i++) path[i] = 0;
for(i = 0; i < ctr; i++) path[i] = browser[i];
browser = path;
path = NULL;
/*isolate the URL used to find the server*/
temp = strstr(request, "Host:");
temp = &temp[6];
strncpy(dnsname, temp, 2048);
*strchr(dnsname, '\n') = 0;
temp = NULL;
if(debug) fprintf(stderr, "browser name isolated...");
/*isolate the path from the request*/
path = strchr(request, ' ');
path = &path[2];
endChar = strchr(path, ' ');
*endChar = 0;
if(debug) fprintf(stderr, "path isolated...");
/*log the request*/
nLog = malloc(sizeof(Log));
strncpy(nLog->browserName, browser, (MAX_LENGTH -1));
strncpy(nLog->pageName, path, (MAX_LENGTH -1));
nLog->date = getDate();
if(debug) fprintf(stderr, "request logged...");
/*write the log to the file*/
fwrite(nLog, sizeof(Log), 1, fd);
if (nLog) free(nLog);
nLog = NULL;
if (browser) free(browser);
browser = NULL;
if(debug) fprintf(stderr, "done.\nOpening requested file (%s)...", path);
/*if a path was given*/
if (strlen(path)){
/*check if it's a database path*/
if (strlen(path) >= 4){
if(path[0] == 'd' && path[1] == 'b' && path[2] == '-'){
/*raise the database flag*/
dbflag = 1;
/*grab the database path*/
temp = hstrclone(&path[3]);
path = temp;
temp = NULL;
if (debug) fprintf(stderr, "database path: '%s'\n", path);
/*connect to the database*/
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, "mydb");
if (!mysql_real_connect(&mysql, HOSTNAME, USERNAME, PASSWORD, DATABASE, 0, NULL, 0)) {
if (debug) fprintf(stderr, "Failed connecting to database\n");
}
if (path[0] == '-'){
/*index path*/
/*construct the query*/
sprintf(query, "select id from pages");
/*query the database*/
if (mysql_query(&mysql,query))
if (debug) fprintf(stderr, "failed to get primary keys from database\n");
/*Store results from query into res structure.*/
if (!(res = mysql_store_result(&mysql)))
if(debug) fprintf(stderr,"store failed\n");
/*put the returned keys into an array of ints*/
if (res){
while ((row = mysql_fetch_row(res))) {
for (i=0; i < mysql_num_fields(res); i++){
p_keys[numpkeys] = atoi(row[i]);
numpkeys++;
}
}
} else {
if (debug) fprintf(stdout,"No pages stored\n");
}
/*build the index page*/
file = malloc(sizeof(char)*2048);
for(i=0;i<2048;i++)file[i] = 0;
strncat(file, "<HTML><HEAD><TITLE>Database Index</TITLE></HEAD><BODY><PRE> Page Number\n", 2048);
for(i = 0; i< numpkeys; i++) sprintf(file, "%s <a href = \"http://%s/db-%d\">%d</a>\n", file, dnsname, p_keys[i], p_keys[i]);
sprintf(file, "%s</PRE></BODY></HTML>\n", file);
} else {
/*link to a page in the Database*/
if (debug) fprintf(stderr, "retrieveing page %s...", path);
/*build the query*/
sprintf(query, "select page_content from pages where id = %s", path);
/*query the database. null the file on failure*/
if(mysql_query(&mysql,query)){
if(debug) fprintf(stderr, "failed to retrieve page from database. returning 404\n");
file = NULL;
} else {
/*on success, Store results from query into res structure.*/
if (debug) fprintf(stderr, "sucess!...");
file = malloc(sizeof(char) * BLOB_SIZE);
if (!(res = mysql_store_result(&mysql)))
if(debug) fprintf(stderr,"store failed\n");
/*store the returned file in the sending buffer*/
if (res){
while ((row = mysql_fetch_row(res))) {
for (i=0; i < mysql_num_fields(res); i++){
strncpy(file, row[i], BLOB_SIZE);
}
}
} else {
if (debug) fprintf(stdout,"No pages stored\n");
if (file) free(file);
file = NULL;
}
if (debug) fprintf(stderr, "size = %d\n", strlen(file));
/*confirm a file was actually returned. if not, free and null the buffer*/
if (!strlen(file)){
free(file);
file = NULL;
} else if ((strstr(file, "<HTML>") && strstr(file,"</HTML"))){
free(file);
file = NULL;
}
}
}
/*disconnect from the database*/
mysql_close(&mysql);
}
}
if (!dbflag){
/*if it was a normal request*/
/*add the /cache directory to the path*/
browser = happend("./cache/", path);
path = browser;
browser = NULL;
if (debug) fprintf(stderr, "path contructed...");
/*read the file indicated by the path*/
if (file) free (file);
file = malloc(sizeof(char)*1048576);
for(i=0;i<1048576;i++) file[i]=0;
fileopened = hreadfile(path, file, 1048576 );
if (path) free(path);
path = NULL;
}
/*attempt to open the library directory*/
dp = opendir("./lib");
if (debug && dp) fprintf(stderr, "directory opened...");
/*on success...*/
if (dp && !fileopened){
if(debug) fprintf(stderr, "done (%d)\n", fileopened);
do {
/*reinitialize libName string*/
for (i = 0; i < 256; i++){
libName[i] = 0;
}
/*get the next dir entry*/
curLib = readdir(dp);
/*if there is one*/
if (curLib){
/*disregard . and .. entries*/
if (strcmp(curLib->d_name, ".") && strcmp(curLib->d_name, "..") && strcmp(curLib->d_name, ".") ) {
if (debug) fprintf(stderr, "Integrating library \"%s\"...", curLib->d_name);
/*build the path string*/
strcat(libName, "./lib/");
strcat(libName, curLib->d_name);
/*check if the dir entry is a .so*/
if (strstr(libName, ".so")){
if ( strlen(strstr(libName, ".so")) == 3 ){
if (debug) fprintf(stderr, "comparing '%s' to the blacklisted libraries...", curLib->d_name);
/*initiate server-side includes if the library in question is not blacklisted.*/
if (!blacklisted(blacklist, curLib->d_name)) temp = SSInclude(file, libName);
/*if it is, simply give back the file supplied, unchanged*/
else temp = hstrclone(file);
if(debug) fprintf(stderr, "done\n");
} else { if (debug) fprintf(stderr, "Failed. is not a shared object file\n"); }
} else { if (debug) fprintf(stderr, "Failed. is not a shared object file\n"); }
/*clean up*/
if (temp){
if (file) free(file);
file = temp;
temp = NULL;
}
}
}
} while (curLib); /*do for every entry in this directory*/
} else {
if(debug) fprintf(stderr, "could not open file\n");
file = NULL;
}
} else {
/*if no file given, return a null file string*/
if (debug) fprintf(stderr, "No file specified. sending 404.\n");
file = NULL;
}
if(debug) fprintf(stderr,"sending response...");
/* send header */
write(client_sockfd, response1, strlen(response1));
/*if the file was found, send it. if not, send the 404 page*/
if (file) write(client_sockfd, file, (strlen(file)));
else write(client_sockfd, E404, (strlen(E404)));
/*clean up*/
if (file) free(file);
file = NULL;
/*close the socket*/
close(client_sockfd);
if(debug) fprintf(stderr, "done\n");
}
}
}
/*more cleanup*/
if (fd) fclose(fd);
if (pipe) fclose(pipe);
unlink("Spipe");
destroylist(blacklist);
/*put message in log pipe to tell Gui the server is down*/
lpipe = fopen("Lpipe", "w");
/*push the string into the pipe*/
if (lpipe){
if(debug) fprintf(stderr, "Sending s through the pipe...");
fputs("S;", lpipe);
if (debug) fprintf(stderr, "done\n");
fclose(lpipe);
if (debug) fprintf(stderr, "pipe closed\n");
}else{
if(debug) fprintf(stderr, "Pipe not connected; Can not send command.\n");
}
return 0;
}
/*tool to convert a month 3-letter string into it's numerical representation*/
int MonthtoNum(char * month){
if (!strcmp(month, "Jan")) return 1;
else if (!strcmp(month, "Feb")) return 2;
else if (!strcmp(month, "Mar")) return 3;
else if (!strcmp(month, "Apr")) return 4;
else if (!strcmp(month, "May")) return 5;
else if (!strcmp(month, "Jun")) return 6;
else if (!strcmp(month, "Jul")) return 7;
else if (!strcmp(month, "Aug")) return 8;
else if (!strcmp(month, "Sep")) return 9;
else if (!strcmp(month, "Oct")) return 10;
else if (!strcmp(month, "Nov")) return 11;
else if (!strcmp(month, "Dec")) return 12;
else return 0;
}
/*function to get the date in the form of MMddyyhrmnsc*/
unsigned long getDate(){
unsigned long ret;
unsigned long i = 0, sec=0, min=0, hour=0, day=0, month=0, year=0;
char * datestr = NULL, * curr = NULL, name[4];
for (i = 0; i < 4; i++) name[i] = 0;
/*get the time string*/
time_t tyme = (time_t)(-1);
while(tyme == (time_t)(-1)){
tyme = (int)time(NULL);
}
datestr = hstrclone(ctime(&tyme));
if (debug) fprintf(stderr, "date: %s\n", datestr);
/*parse to the month token*/
curr = strchr(datestr, ' ');
curr = &curr[1];
/*parse the parts of the string into their numerical slots*/
for(i = 0; i < 3; i++) name[i] = curr[i];
month = MonthtoNum(name);
curr = &curr[4];
day = atoi(curr);
curr = &curr[3];
hour = (atoi(curr));
curr = &curr[3];
min = (atoi(curr));
curr = &curr[3];
sec = atoi(curr);
curr = &curr[5];
year = (atoi(curr));
/*kill the string*/
if (datestr)free(datestr);
datestr = NULL;
ret = (sec);
ret += (100*min);
ret += (10000*hour);
ret += (1000000*year);
ret += (100000000*day);
ret += (10000000000*month);
/*pass the number back*/
return (ret);
}
/*function to tokenize the contents if < > into a tag struct for easy handling*/
Tag * tokenizeTag(char * tstr){
int ctr = 0, i = 0;
char * tag1 = NULL, *tag2 = NULL;
Tag * rtag = NULL;
/*split the tag contents into a tag and attribute substring*/
tag1 = hftrim(tstr);
while(tag1[ctr] != ' ' && tag1[ctr] != 0) ctr += 1;
tag1 = malloc(sizeof(char)*(ctr+1));
for(i = 0; i <= ctr; i++) tag1[i] = 0;
for(i = 0; i < ctr; i++) tag1[i] = tstr[i];
tag2 = hstrclone(hftrim(&tstr[strlen(tag1)]));
/*create the tag struct and store the strings in it*/
rtag = malloc(sizeof(Tag));
rtag->tag = tag1;
tag1 = NULL;
if(strlen(tag2)) rtag->attributes = tag2;
else {
rtag->attributes = NULL;
if (tag2) free (tag2);
}
tag2 = NULL;
return rtag;
}
/*Function to implement server-side includes with a specific dynamically loaded library*/
char * SSInclude( char * page, char *libName ){
/*set up variables*/
/* handle used to reference library */
void *handle = NULL;
/* function pointesr - used to point at functions in the library */
char * (*search)() = NULL;
char * (*replace)() = NULL;
/*pointer to an instance of the search string*/
char * curr = NULL, *temp = NULL;
/*return string and temporary page string*/
char * ret = NULL, * work = NULL;
/* character counter */
int ctr = 0, i = 0;
/*tags list*/
TList * tagsq = NULL, * tmptlist = NULL, * tmptlist2 = NULL;
Tag * searchtag;
/*handle null input*/
if (page == NULL) return NULL;
/* open library */
if (debug) fprintf(stderr, "opening library...(%s)", page);
handle = dlopen(libName, RTLD_LAZY);
if (debug) fprintf(stderr, "opened library...");
/*parse the tags into a list*/
curr = page;
while (*curr != 0){
if(curr[0] == '<'){
if (debug > 1) fprintf(stderr, "found a tag, tokenizing...");
ctr = 0;
/*find how long the tags contents are*/
while(curr[ctr+1] != '>')ctr+= 1;
/*read the tags contents into a temporary string*/
temp = malloc(sizeof(char)*(ctr+1));
for (i = 0; i <= ctr; i++) temp[i] = 0;
for(i = 0; i < ctr; i++){
temp[i] = curr[i+1];
}
/*create the token queue object*/
tmptlist = malloc(sizeof(TList));
tmptlist->next = NULL;
tmptlist->val = malloc(sizeof(Token));
tmptlist->val->tagp = tokenizeTag(temp);
tmptlist->val->strp = NULL;
/*add it to the queue*/
if (tagsq){
tmptlist2 = tagsq;
while (tmptlist2->next) tmptlist2 = tmptlist2->next;
tmptlist2->next = tmptlist;
tmptlist2 = NULL;
} else {
tagsq = tmptlist;
}
tmptlist = NULL;
/*clean up*/
if (temp) free(temp);
temp = NULL;
ctr = 0;
/*advance the pointer past the tag*/
curr = strchr(curr, '>');
curr = &curr[1];
} else {
if (debug> 1) fprintf(stderr, "found a string, tokenizing...");
/*find how long the strings content is*/
while(curr[ctr] != 0 && curr[ctr] != '<') ctr+= 1;
temp = malloc(sizeof(char) * (ctr+1));
for (i = 0; i <= ctr; i++) temp[i] = 0;
for (i = 0; i < (ctr); i++) temp[i] = curr[i];
/*create the token queue object and store the string in it*/
tmptlist = malloc(sizeof(TList));
tmptlist->val = malloc(sizeof(Token));
tmptlist->next = NULL;
tmptlist->val->strp = temp;
tmptlist->val->tagp = NULL;
temp = NULL;
/*add it to the queue*/
if (tagsq){
tmptlist2 = tagsq;
while (tmptlist2->next) tmptlist2 = tmptlist2->next;
tmptlist2->next = tmptlist;
tmptlist2 = NULL;
} else {
tagsq = tmptlist;
}
/*advance past the string*/
tmptlist = NULL;
curr = &curr[ctr];
ctr = 0;
}
}
if (debug) fprintf(stderr, "done tokenizing. Tokens List:\n");
curr = NULL;
if(debug>1){
tmptlist = tagsq;
while (tmptlist){
if (tmptlist->val->tagp){
fprintf(stderr, "Token: Tag: tag:<%s> attribute:[%s]\n", tmptlist->val->tagp->tag, tmptlist->val->tagp->attributes);
tmptlist = tmptlist->next;
} else if (tmptlist->val->strp){
fprintf(stderr, "Token: String:[%s]\n", tmptlist->val->strp);
tmptlist = tmptlist->next;
}
}
fprintf(stderr, "end of tokens list\n");
}
tmptlist = NULL;
/* link the functions named searchString and replaceString to the function pointers */
if (handle) {
search = dlsym(handle, "searchString");
replace = dlsym(handle, "replaceString");
/* call the function in the library to get the search tag*/
searchtag = tokenizeTag(search());
/*step through the token list and replace the tokens that correspond to the correct tag*/
if (!searchtag->attributes){
/*simple tag(*/
tmptlist = tagsq;
while (tmptlist){
if (tmptlist->val->tagp){
if (!strcmp(tmptlist->val->tagp->tag, searchtag->tag)){
/*put the replace string in the string field*/
tmptlist->val->strp = hstrclone(replace());
/*get rid of the tag token*/
if (tmptlist->val->tagp->tag) free (tmptlist->val->tagp->tag);
tmptlist->val->tagp->tag = NULL;
if (tmptlist->val->tagp->attributes) free (tmptlist->val->tagp->attributes);
tmptlist->val->tagp->attributes = NULL;
if (tmptlist->val->tagp) free (tmptlist->val->tagp);
tmptlist->val->tagp = NULL;
}
}
tmptlist = tmptlist->next;
}
} else {
/*not-so simple tag*/
tmptlist = tagsq;
while (tmptlist){
if (tmptlist->val->tagp){
if (!strcmp(tmptlist->val->tagp->tag, searchtag->tag)){
/*put the replace string in the string field*/
tmptlist->val->strp = hstrclone(replace(tmptlist->val->tagp->attributes));
/*get rid of the tag token*/
if (tmptlist->val->tagp->tag) free (tmptlist->val->tagp->tag);
tmptlist->val->tagp->tag = NULL;
if (tmptlist->val->tagp->attributes) free (tmptlist->val->tagp->attributes);
tmptlist->val->tagp->attributes = NULL;
if (tmptlist->val->tagp) free (tmptlist->val->tagp);
tmptlist->val->tagp = NULL;
}
}
tmptlist = tmptlist->next;
}
}
/*close the handle pointing to the library */
dlclose(handle);
}
/*reconstruct the page from the tokens*/
while (tagsq){
if (tagsq->val->tagp){
/*if the token is a tag*/
/*start with the opening angle bracket*/
temp = happend(work, "<");
if(work) free(work);
work = temp;
temp = NULL;
/*append the tag*/
temp = happend(work, tagsq->val->tagp->tag);
if (work) free(work);
work = temp;
temp = NULL;
if (tagsq->val->tagp->tag) free (tagsq->val->tagp->tag);
tagsq->val->tagp->tag = NULL;
/*append a space*/
temp = happend(work, " ");
if(work) free(work);
work = temp;
/*append the attributes, if any*/
temp = happend(work, tagsq->val->tagp->attributes);
if (work) free(work);
work = temp;
if (tagsq->val->tagp->attributes) free (tagsq->val->tagp->attributes);
/*close the angle braces*/
temp = happend(work, ">");
/*clean up*/
if (work) free(work);
work = temp;
temp = NULL;
if (tagsq->val->tagp) free (tagsq->val->tagp);
tagsq->val->tagp = NULL;
} else if (tagsq->val->strp){
/*for string tokens, just append the string and nuke the token*/
temp = happend(work, tagsq->val->strp);
if (work) free(work);
work = temp;
temp = NULL;
if (tagsq->val->strp) free (tagsq->val->strp);
tagsq->val->strp = NULL;
}
/*nuke the remaning parts of the token*/
tmptlist = tagsq;
tagsq = tagsq->next;
if (tmptlist->val) free(tmptlist->val);
tmptlist->val = NULL;
if (tmptlist) free(tmptlist);
tmptlist = NULL;
}
/*clean up*/
ret = NULL;
/*make sure the string is terminated*/
work[strlen(work)]=0;
/*return the temp pointer, as this has the new file whether it was mdoified or not*/
return work;
}
<file_sep>/MinecraftClone/Iteration1/makefile
all : a1
INCLUDES = -F/System/Library/Frameworks -lglut -lGLU
a1: a1.c graphics.c perlin.c
gcc a1.c graphics.c perlin.c -o a1 $(INCLUDES)
clean:
rm a1
<file_sep>/MinecraftClone/Iteration3/dungeon.h
// dungeons header
// includes
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#ifndef GRAPHICS_H
#define GRAPHICS_H
#include "graphics.h"
#endif
#ifndef CUBELIST_H
#define CUBELIST_H
#include "cubeList.h"
#endif
#ifndef VECTOR3_H
#define VECTOR3_H
#include "Vector3.h"
#endif
#include "adjacencyMatrix.h"
// Generation constants
#define MAX_ROOMS 4
#define MAX_HALLS 6
#define MAX_WIDTH 15
#define MIN_WIDTH 3
#define MAX_LENGTH 15
#define MIN_LENGTH 3
#define DUNGEON_FLOOR 16
#define DUNGEON_HEIGHT 2
// Definitions because this aint C++ yet!
#ifndef false
#define false 0
#endif
#ifndef true
#define true 1
#endif
// Room structure
typedef struct room
{
int id;
int x;
int y;
int l;
int w;
} Room;
// Hall structure
typedef struct hall
{
Room * r1;
Room * r2;
int xLength;
int yLength;
double dLength;
} Hall;
// Dungeon structure
typedef struct dungeon
{
int id;
int numRooms;
Room * rooms[MAX_ROOMS];
int numHalls;
Hall * halls[MAX_HALLS];
cubeList * map;
} Dungeon;
// Lists for Dungeon generation
Room * roomsList[MAX_ROOMS];
int roomsCount;
Hall * hallsList[MAX_HALLS];
int hallsCount;
// Functions to affect Dungeon Component Lists
// Add a room to the room list
int addRoomList(Room *);
// Add a Hall to the hall List
int addHallList(Hall *);
// Functions to generate and destroy dungeons
Dungeon * generateDungeon();
Dungeon * deleteDungeon();
// Function to create an adjacency Matrix out of a dungeon
AdjacencyMatrix * generateDungeonMatrix(Dungeon *);
// function to determine if 2 cubes are adjacent to one another
int cubeAdjacent(int x1, int y1, int z1, int x2, int y2, int z2);
<file_sep>/WebServerv2/libfont.c
/*liblastupdate.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "hstring.h"
char * searchString() {
return "FONT =x str";
}
/*format: = NUM STR*/
char * replaceString(char * params) {
char *returntag = NULL, *temp2 = NULL, *temp = NULL, *temp3 = NULL;
int ctr = 0, i= 0, fd = 0;
if (params){
/*start building the font tag*/
returntag = hstrclone("<font size = ");
/*append the size number*/
temp = ¶ms[1];
while(*temp == ' ') temp = &temp[1];
while(temp[ctr] != ' ') ctr+=1;
temp2 = malloc(sizeof(char)*(ctr+1));
for(i = 0; i <=ctr; i++) temp2[i] = 0;
for(i = 0; i < ctr; i++) temp2[i] = temp[i];
temp3 = happend(returntag, temp2);
if (returntag) free(returntag);
returntag = temp3;
temp3 = NULL;
/*append the face attribute*/
if (temp2) free(temp2);
temp2 = NULL;
temp2 = happend(returntag, " face = ");
if (returntag) free(returntag);
returntag = temp2;
temp2 = NULL;
/*append the font face string*/
temp = &temp[ctr+1];
while(*temp == ' ') temp = &temp[1];
temp2 = happend(returntag, temp);
temp = NULL;
if(returntag) free(returntag);
returntag = temp2;
temp2 = NULL;
/*close the tag*/
temp2 = happend(returntag, ">");
if (returntag) free(returntag);
returntag = temp2;
temp2 = NULL;
} else returntag = "</font>"; /*if there are no parameters, return it as a closing tag*/
return returntag;
}
<file_sep>/WebServerv2/makefile
LIBS = -rdynamic -ldl -g
WARNS = -Wall -ansi
all: server libdate libserver liblastupdate libfilesize libowner libfont hstring.o A3.class A3.h A3 db
server: server.c hstring.o
gcc -c server.c -o server.o $(WARNS)
gcc -o server server.o hstring.o $(LIBS) -lmysqlclient -lmysys -lmystrings -L/usr/lib/mysql
db: db.c hstring.o
gcc -c db.c -o db.o $(WARNS)
gcc -o db db.o hstring.o -lmysqlclient -lmysys -lmystrings -L/usr/lib/mysql
libdate: libdate.c
gcc -fPIC -c libdate.c
gcc -shared -Wl,-soname,libdate.so -o ./lib/libdate.so libdate.o
liblastupdate: liblastupdate.c
gcc -fPIC -c liblastupdate.c
gcc -shared -Wl,-soname,liblastupdate.so -o ./lib/liblastupdate.so liblastupdate.o
libserver: libserver.c
gcc -fPIC -c libserver.c
gcc -shared -Wl,-soname,libserver.so -o ./lib/libserver.so libserver.o
libservername: libservername.c
gcc -fPIC -c libservername.c
gcc -shared -Wl,-soname,libservername.so -o ./lib/libservername.so libservername.o
libfilesize: libfilesize.c
gcc -fPIC -c libfilesize.c
gcc -shared -Wl,-soname,libfilesize.so -o ./lib/libfilesize.so libfilesize.o
libowner: libowner.c
gcc -fPIC -c libowner.c
gcc -shared -Wl,-soname,libowner.so -o ./lib/libowner.so libowner.o
libfont: libfont.c
gcc -fPIC -c libfont.c
gcc -shared -Wl,-soname,libfont.so -o ./lib/libfont.so libfont.o
hstring.o: hstring.c hstring.h
gcc -c hstring.c -o hstring.o $(WARNS)
clean:
rm -f *.o *.so server access.log reader *~ Spipe Lpipe *.class A3*.h ./jlibs/*.so db
go: clean all run
rfb: rfb.c hstring.o
gcc -c rfb.c -o rfb.o $(WARNS)
gcc -o rfb rfb.o hstring.o $(LIBS)
A3.class: A3.java
javac A3.java
A3.h: A3.class
javah A3
A3: A3.o hstring.o
gcc -shared -Wl,-soname,libSGVui.so \
-I. \
-I/usr/lib/jvm/java-6-sun-1.6.0.07/include/linux \
-I/usr/lib/jvm/java-6-sun-1.6.0.07/include \
-o ./jlibs/libA3.so \
A3.o
A3.o: A3.c
gcc A3.c -o A3.o -c -fPIC \
-I/usr/lib/jvm/java-6-sun-1.6.0.07/include/linux \
-I/usr/lib/jvm/java-6-sun-1.6.0.07/include <file_sep>/WebServerv2/libserver.c
/*libdate.c*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
char * searchString() {
return "SERVER";
}
char * replaceString() {
char * hname;
int a;
hname = malloc(sizeof(char)*256);
for (a=0; a<128; a++) hname[a] = 0;
/*grab the host name from the system and return it*/
if (!gethostname(hname, 256)) return hname;
else return "Host Name Error";
}
<file_sep>/MinecraftClone/Iteration2/a2.c
//TODO: make this C++
/* Derived from scene.c in the The OpenGL Programming Guides */
/* Keyboard and mouse rotation taken from Swiftless Tutorials #23 Part 2 */
/* http://www.swiftless.com/tutorials/opengl/camera2.html */
#include "a2.h"
// global variables
int tim = 0; // Seconds passed counter
int prevtime = 0; // The time of the last "tick"
int currtime = 0; // Current time variable
int lightpos = 0; // The x-position of the light(sun)
int prevsunypos = 0; // The previous y-position of the light(sun)
int prevsunxpos = 0; // The previous x-position of the light(sun)
// player position
int playerX = 0;
int playerY = 0;
int playerZ = 0;
// player frustum
float frustum[6][4];
// List for things in the frustum
int frustumList[MAX_DISPLAY_LIST][3];
int frustumCount = 0;
// List for potentially visible cubes
int visibleList[MAX_DISPLAY_LIST][3];
int visibleCount = 0;
// List for Animated cubes
int animatedList[MAX_DISPLAY_LIST][3];
int animatedCount = 0;
// Lists for Dungeon generation
Room * roomsList[MAX_ROOMS];
int roomsCount;
Hall * hallsList[MAX_HALLS];
int hallsCount;
// Cube Lists
// Function to add a cube to the frustum list
int addFrustumList(int x, int y, int z) {
// copy the cube coordinates
frustumList[frustumCount][0] = x;
frustumList[frustumCount][1] = y;
frustumList[frustumCount][2] = z;
// increment the counter
frustumCount++;
// panic if too many have been added
if (frustumCount > MAX_DISPLAY_LIST) {
printf("You have put more items in the frustum list then there are\n");
printf("cubes in the world. Set frustumCount = 0 at some point.\n");
exit(1);
}
}
// Function to add a cube to the visible list
int addVisibleList(int x, int y, int z) {
// copy the cube coordinates
visibleList[visibleCount][0] = x;
visibleList[visibleCount][1] = y;
visibleList[visibleCount][2] = z;
// increment the counter
visibleCount++;
// panic if too many have been added
if (visibleCount > MAX_DISPLAY_LIST) {
printf("You have put more items in the visible list then there are\n");
printf("cubes in the world. Set frustumCount = 0 at some point.\n");
exit(1);
}
}
// Function to add a cube to the animated list
int addAnimatedList(int x, int y, int z) {
// copy the coordinated
animatedList[animatedCount][0] = x;
animatedList[animatedCount][1] = y;
animatedList[animatedCount][2] = z;
// increment the counter
animatedCount++;
// panic if there's been too many
if (animatedCount > MAX_DISPLAY_LIST) {
printf("You have put more items in the animated list then there are\n");
printf("cubes in the world. Set frustumCount = 0 at some point.\n");
exit(1);
}
}
// Dungeon Component Lists
// Function to add a room to the room list
int addRoomList(Room * rm) {
// store the pointer to the room
roomsList[roomsCount] = rm;
// increment the counter
roomsCount++;
// if there's been too many, panic
if (roomsCount > MAX_ROOMS) {
printf("too many rooms\n");
exit(1);
}
}
// Function to add a hall to the hall list
int addHallList(Hall * hl) {
// store the hall pointer
hallsList[hallsCount] = hl;
// increment the counter
hallsCount++;
// panic if there's been too many
if (hallsCount > MAX_HALLS) {
printf("too many Halls\n");
exit(1);
}
}
// Culling Functions
// Get the frustum
// taken from http://www.crownandcutlass.com/features/technicaldetails/frustum.html
ExtractFrustum() {
float proj[16];
float modl[16];
float clip[16];
float t;
/* Get the current PROJECTION matrix from OpenGL */
glGetFloatv( GL_PROJECTION_MATRIX, proj );
/* Get the current MODELVIEW matrix from OpenGL */
glGetFloatv( GL_MODELVIEW_MATRIX, modl );
/* Combine the two matrices (multiply projection by modelview) */
clip[ 0] = modl[ 0] * proj[ 0] + modl[ 1] * proj[ 4] + modl[ 2] * proj[ 8] + modl[ 3] * proj[12];
clip[ 1] = modl[ 0] * proj[ 1] + modl[ 1] * proj[ 5] + modl[ 2] * proj[ 9] + modl[ 3] * proj[13];
clip[ 2] = modl[ 0] * proj[ 2] + modl[ 1] * proj[ 6] + modl[ 2] * proj[10] + modl[ 3] * proj[14];
clip[ 3] = modl[ 0] * proj[ 3] + modl[ 1] * proj[ 7] + modl[ 2] * proj[11] + modl[ 3] * proj[15];
clip[ 4] = modl[ 4] * proj[ 0] + modl[ 5] * proj[ 4] + modl[ 6] * proj[ 8] + modl[ 7] * proj[12];
clip[ 5] = modl[ 4] * proj[ 1] + modl[ 5] * proj[ 5] + modl[ 6] * proj[ 9] + modl[ 7] * proj[13];
clip[ 6] = modl[ 4] * proj[ 2] + modl[ 5] * proj[ 6] + modl[ 6] * proj[10] + modl[ 7] * proj[14];
clip[ 7] = modl[ 4] * proj[ 3] + modl[ 5] * proj[ 7] + modl[ 6] * proj[11] + modl[ 7] * proj[15];
clip[ 8] = modl[ 8] * proj[ 0] + modl[ 9] * proj[ 4] + modl[10] * proj[ 8] + modl[11] * proj[12];
clip[ 9] = modl[ 8] * proj[ 1] + modl[ 9] * proj[ 5] + modl[10] * proj[ 9] + modl[11] * proj[13];
clip[10] = modl[ 8] * proj[ 2] + modl[ 9] * proj[ 6] + modl[10] * proj[10] + modl[11] * proj[14];
clip[11] = modl[ 8] * proj[ 3] + modl[ 9] * proj[ 7] + modl[10] * proj[11] + modl[11] * proj[15];
clip[12] = modl[12] * proj[ 0] + modl[13] * proj[ 4] + modl[14] * proj[ 8] + modl[15] * proj[12];
clip[13] = modl[12] * proj[ 1] + modl[13] * proj[ 5] + modl[14] * proj[ 9] + modl[15] * proj[13];
clip[14] = modl[12] * proj[ 2] + modl[13] * proj[ 6] + modl[14] * proj[10] + modl[15] * proj[14];
clip[15] = modl[12] * proj[ 3] + modl[13] * proj[ 7] + modl[14] * proj[11] + modl[15] * proj[15];
/* Extract the numbers for the RIGHT plane */
frustum[0][0] = clip[ 3] - clip[ 0];
frustum[0][1] = clip[ 7] - clip[ 4];
frustum[0][2] = clip[11] - clip[ 8];
frustum[0][3] = clip[15] - clip[12];
/* Normalize the result */
t = sqrt( frustum[0][0] * frustum[0][0] + frustum[0][1] * frustum[0][1] + frustum[0][2] * frustum[0][2] );
frustum[0][0] /= t;
frustum[0][1] /= t;
frustum[0][2] /= t;
frustum[0][3] /= t;
/* Extract the numbers for the LEFT plane */
frustum[1][0] = clip[ 3] + clip[ 0];
frustum[1][1] = clip[ 7] + clip[ 4];
frustum[1][2] = clip[11] + clip[ 8];
frustum[1][3] = clip[15] + clip[12];
/* Normalize the result */
t = sqrt( frustum[1][0] * frustum[1][0] + frustum[1][1] * frustum[1][1] + frustum[1][2] * frustum[1][2] );
frustum[1][0] /= t;
frustum[1][1] /= t;
frustum[1][2] /= t;
frustum[1][3] /= t;
/* Extract the BOTTOM plane */
frustum[2][0] = clip[ 3] + clip[ 1];
frustum[2][1] = clip[ 7] + clip[ 5];
frustum[2][2] = clip[11] + clip[ 9];
frustum[2][3] = clip[15] + clip[13];
/* Normalize the result */
t = sqrt( frustum[2][0] * frustum[2][0] + frustum[2][1] * frustum[2][1] + frustum[2][2] * frustum[2][2] );
frustum[2][0] /= t;
frustum[2][1] /= t;
frustum[2][2] /= t;
frustum[2][3] /= t;
/* Extract the TOP plane */
frustum[3][0] = clip[ 3] - clip[ 1];
frustum[3][1] = clip[ 7] - clip[ 5];
frustum[3][2] = clip[11] - clip[ 9];
frustum[3][3] = clip[15] - clip[13];
/* Normalize the result */
t = sqrt( frustum[3][0] * frustum[3][0] + frustum[3][1] * frustum[3][1] + frustum[3][2] * frustum[3][2] );
frustum[3][0] /= t;
frustum[3][1] /= t;
frustum[3][2] /= t;
frustum[3][3] /= t;
/* Extract the FAR plane */
frustum[4][0] = clip[ 3] - clip[ 2];
frustum[4][1] = clip[ 7] - clip[ 6];
frustum[4][2] = clip[11] - clip[10];
frustum[4][3] = clip[15] - clip[14];
/* Normalize the result */
t = sqrt( frustum[4][0] * frustum[4][0] + frustum[4][1] * frustum[4][1] + frustum[4][2] * frustum[4][2] );
frustum[4][0] /= t;
frustum[4][1] /= t;
frustum[4][2] /= t;
frustum[4][3] /= t;
/* Extract the NEAR plane */
frustum[5][0] = clip[ 3] + clip[ 2];
frustum[5][1] = clip[ 7] + clip[ 6];
frustum[5][2] = clip[11] + clip[10];
frustum[5][3] = clip[15] + clip[14];
/* Normalize the result */
t = sqrt( frustum[5][0] * frustum[5][0] + frustum[5][1] * frustum[5][1] + frustum[5][2] * frustum[5][2] );
frustum[5][0] /= t;
frustum[5][1] /= t;
frustum[5][2] /= t;
frustum[5][3] /= t;
}
// check if a point is in the frustum
// taken from http://www.crownandcutlass.com/features/technicaldetails/frustum.html
int PointInFrustum( float x, float y, float z )
{
int p;
for( p = 0; p < 6; p++ )
if( frustum[p][0] * x + frustum[p][1] * y + frustum[p][2] * z + frustum[p][3] < 0 )
return false;
return true;
}
// Check if a cube is in the frustum
// taken from http://www.crownandcutlass.com/features/technicaldetails/frustum.html
int CubeInFrustum( float x, float y, float z, float size )
{
int p;
for( p = 0; p < 6; p++ )
{
if( frustum[p][0] * (x - size) + frustum[p][1] * (y - size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 )
continue;
if( frustum[p][0] * (x + size) + frustum[p][1] * (y - size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 )
continue;
if( frustum[p][0] * (x - size) + frustum[p][1] * (y + size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 )
continue;
if( frustum[p][0] * (x + size) + frustum[p][1] * (y + size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 )
continue;
if( frustum[p][0] * (x - size) + frustum[p][1] * (y - size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 )
continue;
if( frustum[p][0] * (x + size) + frustum[p][1] * (y - size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 )
continue;
if( frustum[p][0] * (x - size) + frustum[p][1] * (y + size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 )
continue;
if( frustum[p][0] * (x + size) + frustum[p][1] * (y + size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 )
continue;
return false;
}
return true;
}
// Collision detection and Gravity
void collisionResponse() {
float x, y, z;
float ox, oy, oz;
int ix,iy,iz;
int iox,ioy,ioz;
// get the player's position
getViewPosition(&x,&y,&z);
// normalize for the world cube array
ix = (int) x * (-1);
iy = (int) y * (-1);
iz = (int) z * (-1);
// if we're not in ghost mode
if (!flycontrol)
{
// Collisions
// check that we're not trying to enter an occupied cube
if (world[ix][iy][iz] != 0)
{
// DEBUGGING: report a collision has ocurred
//fprintf(stderr,"collision at %d %d %d (%d)\n",ix,iy,iz,world[ix][iy][iz]);
// get the last position
getOldViewPosition(&ox,&oy,&oz);
// normalize for the world array
iox = (int) ox * (-1);
ioy = (int) oy * (-1);
ioz = (int) oz * (-1);
// check if there is space above the cube so we can climb onto it
if (world[ix][iy+1][iz] == 0 && world[iox][ioy+1][ioz] == 0)
{
// DEBUGGING: report a climb has occurred
//printf("climbing from %f,%f,%f to %f,%f,%f\n", ox,oy,oz,x,y-1,z);
// increase the player's vertical position
setViewPosition(x,y-1,z);
// remember this change has occurred
y-= 1;
iy = (int) y * (-1);
}
else
{
// if the climb was not possible, bump back to previous location
setViewPosition(ox,oy,oz);
// remember that we've been moved back
ix = (int) ox * (-1);
iy = (int) oy * (-1);
iz = (int) oz * (-1);
// TODO: make is so that there can be wall sliding.
}
}
// Gravity
// if there is nothing underneath the player
if (world[ix][iy-1][iz] == 0)
{
// drop the player half a unit
setViewPosition(x,y+0.5,z);
// TODO: implement gravitational accelleration
}
}
}
// Idle update function
void update() {
// Position indicators for gravity
float x, y, z;
int ix,iy,iz;
// iterators
int i = 0, k = 0, j = 0;
// sun coordinate containers
int sunypos = 0;
int sunxpos = 0;
// time marches on
currtime = time(0);
// if we're at time 0, ensure we dont hav an initial quantum leap going on
if (prevtime == 0) prevtime = currtime;
tim += currtime - prevtime;
// if a second has passed, update the world
if (currtime - prevtime/* && !testWorld*/)
{
// clear the animaded list
animatedCount = 0;
// Perlin-generate the clouds
// TODO: change these literals to constants
for(i=0;i<100;i++)
for(k=0;k<100;k++)
if(PerlinNoise3D(i/55.0,k/65.0, tim/50.0,1.23,1.97,4) > 0)
{
// generate the cubes
world[i][CLOUD_ALTITUDE][k] = 5;
// add them to the animated list
addAnimatedList(i,CLOUD_ALTITUDE,k);
}else
world[i][CLOUD_ALTITUDE][k] = 0;
// position the sun
// calculate next x and y coordinates
sunxpos = (int)((((double)(tim % DAY_LENGTH))/DAY_LENGTH)*99.0);
sunypos = (sqrt(pow(SUN_RADIUS,2)-pow((sunxpos - SUN_ANCHOR_X),2)))+(SUN_ANCHOR_Y);
// move the sun
world[sunxpos][sunypos][49] = 6;
world[prevsunxpos][prevsunypos][49] = 0;
setLightPosition(sunxpos, sunypos, 49);
// add it to the animated list
addAnimatedList(sunxpos,sunypos,49);
// save the current position so this sun can be deleted on next draw
prevsunypos = sunypos;
prevsunxpos = sunxpos;
// force a screen redraw
glutPostRedisplay();
}
// Gravity
// if we are not in ghost mode
if(!flycontrol)
{
// get the player's position
getViewPosition(&x,&y,&z);
// normalize for the world cube array
ix = (int) x * (-1);
iy = (int) y * (-1);
iz = (int) z * (-1);
// if there is nothing underneath the player
if (world[ix][iy-1][iz] == 0)
{
// drop the player half a unit
setViewPosition(x,y+0.5,z);
// TODO: implement gravitational accelleration
}
}
// save the current time for next round
prevtime = currtime;
}
// Cube Culling and performance measuring
void buildDisplayList() {
// used to calculate frames per second
static int frame=0, time, timebase=0;
// iterators
int i, j, k;
int x,y,z;
// get the frustum
ExtractFrustum();
// clear the display list
displayCount = 0;
// go through the visible list and check which ones are in the frustum
for(i = 0; i< visibleCount; i++)
{
// grab the coordinates of this cube
x = visibleList[i][0];
y = visibleList[i][1];
z = visibleList[i][2];
// check if it's in the frustum
if (CubeInFrustum( ((float)x)+0.5, ((float)y)+0.5,((float)z)+0.5, 0.5))
{
// add it to the display list
addDisplayList(x,y,z);
}
}
// go through the animated list and check what's in the frustum
for(i=0; i<animatedCount; i++)
{
// grab the coordinates of the cube
x = animatedList[i][0];
y = animatedList[i][1];
z = animatedList[i][2];
// check if it's in the frustum
if (CubeInFrustum( ((float)x)+0.5, ((float)y)+0.5,((float)z)+0.5, 0.5))
{
// add it to the display list
addDisplayList(x,y,z);
}
}
// FPS calculation
// taken from http://www.lighthouse3d.com/opengl/glut/index.php?fps
// increment the frame counter
frame++;
// get the glut time
time=glutGet(GLUT_ELAPSED_TIME);
// if sufficient time has passed, calulate and display the FPS
if (time - timebase > 1000) {
printf("FPS:%4.2f\n", frame*1000.0/(time-timebase));
timebase = time;
frame = 0;
}
// redraw the screen at the end of the update
glutPostRedisplay();
}
// Funtion to check if two rooms overlap
int overlap(Room * r1, Room* r2)
{
// check x-coords
if (
((r1->x <= r2->x) && // if room 1 is to the left of room 2
((r2->x + r2->l) <= r1->x)) // and it's rightmost side is left of room 2's rightmost
||
(((r1->x + r1->l) <= r2->x) && // if room 1 is to the right of room 2
((r2->x + r2->l) <= (r1->x + r1->l))) // and it's leftmost side is right of room 2's leftmost
)
{
// check y-coords
if (
((r1-> y <= r2-> y) && // if room 1 is below room 2
((r2-> y + r2->w) <= r1-> y)) // and it's upper side is above room 2's lower side
||
(((r1-> y + r1->w) <= r2-> y) &&// if room 1 is above room 2
((r2-> y + r2->w) <= (r1-> y + r1->w))) //and it's lower side is below room 2's upper side
)
{
// if all this is true, they are overlaping
return true;
}
}
// one or more tests failed, there is no overlap.
return false;
}
// Functions to print out dungeon components
// Funtion to print out a room
int printRoom(Room * r)
{
printf("Room:\n ID: %d\n X: %d\n Y: %d\n L: %d\n W: %d\n", r->id, r->x, r->y, r->l, r->w);
return 0;
}
// Function to print out a list of rooms
int printRooms(Room * list[], int count)
{
int i = 0;
Room * currentRoom = NULL;
// print the header and count
printf("Rooms (%d):::\n", count);
// iterate through the list and print all rooms out
for(i=0; i<count; i++)
{
currentRoom = list[i];
printRoom(currentRoom);
}
}
// Function to print out a hall
int printHall(Hall * h)
{
printf("Hall:\n R1: %d\n R2: %d\n Dist: %f\n", h->r1->id, h->r2->id, h->dLength);
return 0;
}
// Function to print out a lst of halls
int printHalls(Hall * list[], int count)
{
int i = 0;
Hall * currentHall = NULL;
// print the header and count
printf("Halls (%d):::\n", count);
// iterate through the list and print the halls
for(i=0; i<count; i++)
{
currentHall = list[i];
printHall(currentHall);
}
return 0;
}
// Function to print out a dungeon
int printDungeon(Dungeon * d)
{
if (d)
{
// print out the header
printf("Dungeon:-------------------\n");
// print out the rooms
printRooms(d->rooms, d->numRooms);
printf("\n");
// print out the halls
printHalls(d->halls, d->numHalls);
// print out the footer
printf("\nEnd of Dungeon Block-------\n");
}
else {
// print out error if a null dungoen was passed
printf("Dungeon is NULL\n");
}
return 0;
}
// Functions to generate a random dungeon
// Function to generate roooms for the dungeon
int generateRooms(int rooms)
{
Room * newRoom = NULL;
int i = 0, j = 0, success = 0;
// generate the starting room
newRoom = malloc(sizeof(Room));
newRoom->id = 0;
newRoom->x = 48;
newRoom->y = 48;
newRoom->w = 3;
newRoom->l = 3;
// add it to the list
addRoomList(newRoom);
// randomly generate the remaining rooms
for(i = roomsCount; i<MAX_ROOMS; i++)
{
// clear success flag
success = false;
// Allocate the new room
newRoom = malloc(sizeof(Room));
// loop until successful
while (!success)
{
// generate the room size & coords
newRoom->id = i;
newRoom->w = (rand() % 10) + 3;
newRoom->l = (rand() % 10) + 3;
newRoom->x = (rand() % (97 - newRoom->l))+1;
newRoom->y = (rand() % (97 - newRoom->w))+1;
// check for overlap
for(j=0;j<roomsCount;j++)
{
if (overlap(newRoom,roomsList[j]))
{
success = false;
// exit the loop on failure
j = roomsCount;
} else {
success = true;
}
}
// if it did not overlap, add it to the list;
if (success)
{
addRoomList(newRoom);
}
else
{
//fprintf(stderr, "... unsuccessful\n", i);
}
}
}
return 0;
}
// Function to merge two dungoens together
Dungeon * mergeDungeons(Dungeon * d1, Dungeon * d2)
{
int i = 0, j = 0;
int dupe = 0;
Room * currentRoom = NULL;
Hall * currentHall = NULL;
// Allocate & initialize the new dungeon
Dungeon * newD = malloc(sizeof(Dungeon));
newD->numRooms = 0;
newD->numHalls = 0;
//add rooms from d1;
for(i=0;i<d1->numRooms;i++)
{
// get next room;
currentRoom = d1->rooms[i];
// add it
newD->rooms[newD->numRooms] = currentRoom;
newD->numRooms++;
}
//add rooms from d2;
for(i=0;i< d2->numRooms;i++)
{
// clear dupe flag
dupe = 0;
// get next room
currentRoom = d2->rooms[i];
// ensure we arent duplicating
for(j=0; j< newD->numRooms; j++)
if (currentRoom == newD->rooms[j])
{
dupe = 1;
j = newD->numRooms;
}
// add it if it's not a duplicate
if (!dupe)
{
newD->rooms[newD->numRooms] = d2->rooms[i];
newD->numRooms++;
}
}
//add halls from d1;
for(i=0;i<d1->numHalls;i++)
{
// get next hall;
currentHall = d1->halls[i];
// add it
newD->halls[newD->numHalls] = currentHall;
newD->numHalls++;
}
//add halls from d2;
for(i=0;i<d2->numHalls;i++)
{
// clear dupe flag
dupe = 0;
// get next hall
currentHall = d2->halls[i];
// ensure we arent duplicating
for(j=0; j< newD->numHalls; j++)
if (currentHall == newD->halls[j])
{
dupe = 1;
j = newD->numHalls;
}
// add it if it's not a duplicate
if (!dupe)
{
newD->halls[newD->numHalls] = d2->halls[i];
newD->numHalls++;
}
}
return newD;
}
// Function to delete a dungeon
// Not stable/ incomplete
Dungeon * deleteDungeon (Dungeon * d)
{
int i;
// disconnect rooms
for(i=0; i < d->numRooms; i++)
d->rooms[i] = NULL;
//fprintf(stderr, "Rooms disconnected. %d halls\n", d->numHalls);
// disconnect halls
for(i=0; i < d->numHalls; i++)
d->halls[i] = NULL;
fprintf(stderr, "Halls disconnected\n");
// derez it!
if (d)free(d);
return NULL;
}
// Function to generate halls for a dungeon
// not optimized or *good*, but stable
// TODO: fix how it finds the next shortest hall
// TODO: also, functionalize this. it's huge
int generateHalls()
{
Hall* potentials[roomsCount][roomsCount];
Hall * currentHall = NULL;
Hall * newHall = NULL;
Hall * shortest = NULL;
int lastI = 0, lastJ = 0;
Dungeon * forest[roomsCount], *newD = NULL, *finalDungeon = NULL;
int dungeons = 0;
int i = 0, j = 0, roomToConnect = 0, graphConnected = 0;
int k = 0, l = 0;
Room * r1= NULL, * r2 = NULL;
// Populate the halls list;
// Initialize it
for(i=0;i<roomsCount;i++)
for(j=0;j<roomsCount;j++)
potentials[i][j] = NULL;
// generate a hall for each possible room-room connection
for(i = 0; i<roomsCount; i++)
{
// start with the next room, so we only have one hallway per room pair
for(j = i+1; j <roomsCount; j++)
{
// if we're not trying to connect a room to itself
if (i != j)
{
// allocate the room
currentHall = malloc(sizeof(Hall));
// insert the room pointers
r1 = roomsList[i];
r2 = roomsList[j];
currentHall->r1 = r1;
currentHall->r2 = r2;
// calculate displacement between rooms
currentHall->xLength = r2->x - r1->x;
currentHall->yLength = r2->y - r1->y;
currentHall->dLength = sqrt(pow((double)currentHall->xLength,2.0) + pow((double)currentHall->yLength,2.0));
// add the new hall to the list
potentials[i][j] = currentHall;
}
else {
// put nulls in invalid hall places
potentials[i][j] = NULL;
}
}
}
// Generate the hallways between rooms via Prim's algorithm
// generate the dungeons
for(i=0; i< MAX_ROOMS; i++)
{
// allocate dungeons
forest[i] = malloc(sizeof(Dungeon));
// add the rooms
forest[i]->rooms[0] = roomsList[i];
forest[i]->numRooms = 1;
// add the halls
forest[i]->numHalls = 0;
}
// loop until the first dungeon is connected to all rooms
while(forest[0]->numRooms < roomsCount)
{
// initialize the shortest pointer
shortest = NULL;
// find the shortest hall, picking up from where we last left off
for(i=lastI; i < roomsCount; i++)
{
for(j=lastJ+1; j <roomsCount; j++)
{
// if such a hall exists
if(i != j && potentials[i][j])
{
// if a shortest hall has not yet been found, grab the next hall as the shortest
if (!shortest) shortest = potentials[i][j];
// grab the next hall
currentHall = potentials[i][j];
// if this one is shorter, save it as the new shortest
if (currentHall->dLength < shortest->dLength && forest[i] != forest[j])
shortest = currentHall;
}
}
// reset the leaveoff flag
lastJ = 0;
}
// if no shortest was found (?) just stop.
if (!shortest) break;
// extract the indicies of the rooms
i = shortest->r1->id;
j = shortest->r2->id;
// remember where we left off
lastI = i;
lastJ = j;
// add it to it's connected dungeons
forest[i]->halls[forest[i]->numHalls] = shortest;
forest[i]->numHalls++;
forest[j]->halls[forest[j]->numHalls] = shortest;
forest[j]->numHalls++;
// add the connected rooms to the dungeons
newD = mergeDungeons(forest[i], forest[j]);
// clean up the old dungeons
// TODO: this is broken
/*if (forest[i] != forest[j])
{
if(forest[i])
forest[i] = deleteDungeon(forest[i]);
if(forest[j])
forest[j] = deleteDungeon(forest[j]);
//fprintf(stderr, "deleted old dungeons\n");
} else
{
if(forest[i])
forest[i] = deleteDungeon(forest[i]);
forest[j] = forest[i];
}*/
// store the new dungeon in the old one's places
forest[i] = newD;
forest[j] = newD;
}
// grab the newly made MST
finalDungeon = forest[0];
// transcribe the dungeon to the global lists
for (i=0; i<finalDungeon->numHalls; i++)
{
// allocate a hall object for transcription
newHall = malloc(sizeof(Hall));
// get the next hall to transcribe
currentHall = finalDungeon->halls[i];
// copy the data and pointers
newHall-> r1 = currentHall -> r1;
newHall-> r2 = currentHall -> r2;
newHall-> xLength = currentHall ->xLength;
newHall-> yLength = currentHall ->yLength;
newHall-> dLength = currentHall ->dLength;
// add the hall to the hall list
addHallList(newHall);
}
// clean up
// dungeons
deleteDungeon(finalDungeon);
// halls
for(i=0; i<roomsCount; i++)
for(j=0; j<roomsCount-1; j++)
if (potentials[i][j]) free(potentials[i][j]);
return 0;
}
// Function to dig hallways.
// TODO: make this not suck
int drawAt(int x, int y, int z, int val)
{
world[x][y][z] = val;
world[x][y+1][z] = val;
fprintf(stderr, "drew %d at (%d,%d,%d)\n",val,x,y,z);
}
// Function to dig out all the hallways
int subtractHalls()
{
Hall * hallCurrent = NULL;
Room * r1 = NULL, *r2 = NULL;
int i = 0;
int x, y, z;
int xLen = 0, yLen = 0;
int sourceX, sourceY;
int destX, destY;
int dist;
int dir = 0; //North = 0, East = 1, West = 2, South = 3
int leftTurn = 0;
// go through the list of halls
for(i=0; i<hallsCount; i++)
{
// initialize the left turn signal
leftTurn = 0;
// grab the next hall
hallCurrent = hallsList[i];
// grab the rooms
r1 = hallCurrent->r1;
r2 = hallCurrent->r2;
// grab the displacement components
xLen = hallCurrent->xLength;
yLen = hallCurrent->yLength;
// grab the source and destination coords
sourceX = r1->x;
sourceY = r1->y;
destX = r2->x;
destY = r2->y;
// dig out the halls
// X axis
if (xLen > 0)
for(x = sourceX; x < destX; x++)
drawAt(x,14,sourceY,0);
else
for(x = sourceX; x > destX; x--)
drawAt(x,14,sourceY,0);
// Y axis
if (yLen > 0)
for(y = sourceY; y < destY; y++)
drawAt(destX,14,y,0);
else
for(y = sourceY; y > destY; y--)
drawAt(destX,14,y,0);
}
}
// Function to dig out a dungeon
int subtractDungeon()
{
Room * currentRoom = NULL;
int i = 0, x = 0, y = 0, z = 0;
// dig out the rooms
for (i = 0; i < roomsCount; i++)
{
currentRoom = roomsList[i];
for(x = 0; x < currentRoom->l; x++)
for(y = 0; y < currentRoom->w; y++)
for(z = MEAN_GROUND_ALTITUDE - 10 ; z < MEAN_GROUND_ALTITUDE - 7; z++)
world[x+currentRoom->x][z][y+currentRoom->y] = 0;
}
// dig out the halls
subtractHalls();
// clean up the rooms
for(i=0; i< roomsCount; i++)
{
if (currentRoom)
free(currentRoom);
currentRoom = NULL;
roomsList[i] = NULL;
}
// dig out the entrance hole & place the marker obelisk
for(i = 15; i< 30;i++)
{
world[49][i][49] = 0;
if (i > 20)
world[48][i][49] = 3;
}
}
// Function to generate a dungeon
int generateDungeon(int rooms)
{
// generate rooms
generateRooms(rooms);
// generate halls
generateHalls();
// subtract from world
subtractDungeon();
return 0;
}
// Main program loop
int main(int argc, char** argv)
{
int i, j, k;
double dbl;
/* Initialize the graphics system */
gradphicsInit(&argc, argv);
// seed random
srand(time(NULL));
/* the first part of this if statement builds a sample */
/* world which will be used for testing */
/* DO NOT remove this code. It will be used to test the timing */
/* of your culling solution. Put your code in the else statment below */
if (testWorld == 1) {
/* initialize world to empty */
for(i=0; i<100; i++)
for(j=0; j<50; j++)
for(k=0; k<100; k++)
world[i][j][k] = 0;
/* some sample objects */
/* create some green and blue cubes */
world[50][25][50] = 1;
world[49][25][50] = 1;
world[49][26][50] = 1;
world[52][25][52] = 1;
world[52][26][52] = 2;
/* red platform */
for(i=0; i<100; i++) {
for(j=0; j<100; j++) {
world[i][24][j] = 3;
}
}
/* fill in world under platform */
for(i=0; i<100; i++) {
for(j=0; j<100; j++) {
for(k=0; k<24; k++) {
world[i][k][j] = 3;
}
}
}
/* blue box shows xy bounds of the world */
for(i=0; i<99; i++) {
world[0][25][i] = 2;
world[i][25][0] = 2;
world[99][25][i] = 2;
world[i][25][99] = 2;
}
} else {
// generate perlin noise terrain
for(i=0;i<100;i++)
for(k=0;k<100;k++){
dbl = PerlinNoise2D(i/75.0,k/75.0,0.98,2.11,3)*5+MEAN_GROUND_ALTITUDE;
for(j=0;j<(int)dbl;j++)
world[i][j][k] = 1;
}
}
// generate the dungeon
generateDungeon(MAX_ROOMS);
// generate the visible list
visibleCount = 0;
// add the bottom
j = 0;
for (i=0; i< 100; i++) {
for (k=0;k<100; k++) {
if(world[i][j][k])
{
addVisibleList(i,j,k);
}
}
}
// add the top
j = 49;
for (i=0; i< 100; i++) {
for (k=0;k<100; k++) {
if(world[i][j][k])
{
addVisibleList(i,j,k);
}
}
}
// add the left side
k = 0;
for (i=0; i< 100; i++) {
for (j=0;j<49; j++) {
if(world[i][j][k])
{
addVisibleList(i,j,k);
}
}
}
// add the right side
k = 99;
for (i=0; i< 100; i++) {
for (j=0;j<49; j++) {
if(world[i][j][k])
{
addVisibleList(i,j,k);
}
}
}
// add the front
i = 0;
for (j=0; j< 49; j++) {
for (k=0;k<100; k++) {
if(world[i][j][k])
{
addVisibleList(i,j,k);
}
}
}
// add the back
i = 99;
for (j=0; j< 49; j++) {
for (k=0;k<100; k++) {
if(world[i][j][k])
{
addVisibleList(i,j,k);
}
}
}
// figure out which cubes are visible
// look at each position
for(i = 1; i < 99; i++)
for(j = 1; j< 49; j++)
for(k = 1; k < 99; k++)
{
// if there's something here
if (world[i][j][k])
{
// and one of it's 6 faces are exposed
if(!(world[i+1][j][k]) || !(world[i-1][j][k]) ||
!(world[i][j+1][k]) || !(world[i][j-1][k]) ||
!(world[i][j][k+1]) || !(world[i][j][k-1])
)
{
// add it to the visible list
addVisibleList(i,j,k);
}
}
}
//exit(0);
/* starts the graphics processing loop */
/* code after this will not run until the program exits */
glutMainLoop();
return 0;
}
<file_sep>/WebServerv1/a1c.c
/* Web Server application by <NAME> January 21st 2008 */
/* Derived from Web Server Example by <NAME> */
/* ftp://ftp.isi.edu/in-notes/rfc2616.txt */
/* http://ftp.ics.uci.edu/pub/ietf/http/rfc1945.html */
/* Make the necessary includes and set up the variables. */
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <dirent.h>
/*prototype the SSInclude Function*/
char * SSInclude( char * page, char *libName );
/*Main Function*/
int main() {
/*Set up Socket Variables*/
int server_sockfd, client_sockfd, server_len, count, i, size, newlineCount;
socklen_t client_len;
struct sockaddr_in server_address, client_address;
/*set up strings*/
char ch, request[2048], *path = NULL, *endChar = NULL, *file = NULL, libName[265];
/*set up file/directory pointers*/
FILE * fp = NULL;
DIR * dp = NULL;
struct dirent * curLib = NULL;
/*constant strings*/
/* http header which is sent in response to a browser request */
char *response1 = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n\r\n";
/*hardcoded 404 error page*/
char *E404 = "<HTML><HEAD><TITLE>404 error!</title></head><BODY BACKGROUND=\"#E0E0E0\"TEXT= \"#000000\" LINK= \"#FF0000\" ALINK= \"#FF0000\" VLINK= \"#0000FF\"><CENTER><H2>404 Error<BR>File not found</H2></center><BR>fore oh fore! I'm soooooooooooooo sorry. <br>that page doesnt exist. <br> It's ok to feel sad. I feel like a huge jerk not having what you want.<br> hug? <br></body></html>";
/*initialize request string*/
for (i = 0; i < 2048; i++){
request[i] = 0;
}
/*initialize libName string*/
for (i = 0; i < 265; i++){
libName[265] =0;
}
/* Remove any old socket and create an unnamed socket
for the server. */
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
/* Name the socket. */
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(8888);
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
/* Create a connection queue and wait for clients. */
listen(server_sockfd, 5);
/*main program loop*/
while(1) {
/*initialize variables*/
if (file != NULL){
free(file);
file = NULL;
}
file = NULL;
if (fp) fclose(fp);
fp = NULL;
size = 0;
for (i = 0; i < 2048; i++){
request[i] = 0;
}
newlineCount = 0;
path = NULL;
endChar = NULL;
/*printf("server waiting\n");*/
/* Accept a connection. */
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
/* We can now read/write to client on client_sockfd. */
/* read query from the client */
while(1) {
count = read(client_sockfd, &ch, 1);
if (count == 0) break;
/* remove CR from CR-LF end of line markers */
if (ch == '\r') count = read(client_sockfd, &ch, 1);
/* look for empty line which signals the end of the request */
if (ch == '\n') newlineCount++;
else newlineCount = 0;
if (newlineCount == 2) break;
/*print out the request (for debugging)*/
/*fprintf(stderr, "%c", ch);*/
/*save the character read from the buffer*/
request[strlen(request)] = ch;
}
/*fprintf(stderr, "outside while loop\n\n");*/
/*isolate the path from the request*/
path = strchr(request, ' ');
path = &path[2];
endChar = strchr(path, ' ');
*endChar = 0;
/*open the file indicated by the path*/
fp = fopen(path, "r");
/*if the file is found...*/
if (fp) {
/*calculate the file size*/
fseek(fp,0,SEEK_END);
size = ftell(fp);
fseek(fp,0,SEEK_SET);
size = (size / sizeof(char));
/*allocate memory for the file*/
file = malloc(sizeof(char)*size);
for (i = 0; i < size; i++){
file[i] = 0;
}
/*read the file from memory*/
fread(file, size, sizeof(char), fp);
file[size] = 0;
/*close the file*/
fseek(fp,0,SEEK_SET);
/*fclose(fp);*/
/*attempt to open the library directory*/
dp = opendir("./lib");
/*on success...*/
if (dp){
do {
/*reinitialize libName string*/
for (i = 0; i < 265; i++){
libName[i] = 0;
}
curLib = readdir(dp);
if (curLib){
/*disregard . and .. entries*/
if (strcmp(curLib->d_name, ".") && strcmp(curLib->d_name, "..")) {
/*build the path string*/
strcat(libName, "./lib/");
strcat(libName, curLib->d_name);
/*initialte server side includes with the current library*/
file = SSInclude(file, libName);
}
}
} while (curLib); /*do for every entry in this directory*/
}
}
/* send header */
write(client_sockfd, response1, strlen(response1));
/*if the file was found, send it. if not, send the 404 page*/
if (fp) write(client_sockfd, file, (strlen(file)));
else write(client_sockfd, E404, (strlen(E404)));
/*close the socket*/
close(client_sockfd);
}
}
/*Function to implement serrver-side includes with a specific dynamically loaded library*/
/*Derived from Dynamically Linked Library examples by <NAME>*/
char * SSInclude( char * page, char *libName ){
/*set up variables*/
/* handle used to reference library */
void *handle = NULL;
/* function pointesr - used to point at functions in the library */
char * (*search)() = NULL;
char * (*replace)() = NULL;
/* points to the return values of functions */
char * srch = NULL;
char * rplc = NULL;
/*pointer to an instance of the search string*/
char * curr = NULL;
/*string size counter*/
int ctr = 0, newlen = 0;
/*return string and temporary page string*/
char * ret = NULL, * work = NULL;
/*loop iterator and controller*/
int i = 0;
/* open library */
handle = dlopen(libName, RTLD_LAZY);
/*fprintf(stderr, "library open: [%s]\n", libName);*/
/* link the functions named searchString and replaceString to the function pointers */
if (handle) {
search = dlsym(handle, "searchString");
replace = dlsym(handle, "replaceString");
/* call the function in the library to get the search String*/
srch = search();
curr = page;
/*create initial temporary file*/
work = malloc(sizeof(char) * strlen(page));
strcpy(work, page);
/*parse the document for that search string*/
do {
curr = work;
/*search for the target string*/
curr = strstr(curr,srch);
/*if not found, exit*/
if (!curr) break;
/*get the replacement string*/
rplc = replace();
/*calculate the # of characters before the target string*/
ctr = strlen(work) - strlen(curr);
/*create/initialize the new file*/
newlen = (ctr + strlen(rplc) + strlen(&curr[strlen(srch)]));
ret = malloc(sizeof(char)*(newlen));
for (i = 0; i < (newlen); i++){
ret[i] = 0;
}
/*scan the star of the old file into the new one*/
for (i = 0; i < ctr; i++){
ret[i] = work[i];
}
/*append the replacment string and the rest of the file*/
strcat(ret, rplc);
strcat(ret, &curr[strlen(srch)]);
/*destroy old temp and replace it with the new ret*/
if (work) free(work);
work = NULL;
work = ret;
} while (1);
/* close the handle pointing to the library */
dlclose(handle);
}
/*clean up*/
if (page) free(page);
page = NULL;
ret = NULL;
/*make sure the string is terminated*/
work[strlen(work)]=0;
/*return the temp pointer, as this has the new file whether it was mdoified or not*/
return work;
}
<file_sep>/WebServerv2/libowner.c
/*liblastupdate.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <pwd.h>
#include "hstring.h"
char * searchString() {
return "OWNER str";
}
/*format: name path*/
char * replaceString(char * params) {
char ret[32], *name = NULL, *path = NULL;
int ctr = 0, i= 0, fd = 0;
struct stat buffer;
struct passwd *user;
/*parse the first word as the name*/
while(params[ctr] != ' ' && params[ctr] != 0) ctr += 1;
name = malloc(sizeof(char)*(ctr+1));
for (i = 0; i <= ctr; i++) name[i] = 0;
for (i = 0; i < ctr; i++) name[i] = params[i];
/*parse the second word as the path name*/
if (strchr(params, ' ')) path = hftrim(strchr(params, ' '));
else path = NULL;
/*find the name of the owner by their uid*/
if(stat(path, &buffer) == 0){
user = getpwuid(buffer.st_uid);
return (user->pw_name);
}
else {
return "FILE DOES NOT EXIST";
}
}
<file_sep>/MinecraftClone/Iteration3/makefile
all : a3
SOURCES = a3.c graphics.c perlin.c dungeon.c cubeList.c adjacencyMatrix.c culling.c mob.c Vector3.c
INCLUDES = -F/System/Library/Frameworks -framework OpenGL -framework GLUT -lm
a3: $(SOURCES)
gcc $(SOURCES) -o a3 $(INCLUDES)
clean:
rm -f a3 *~
<file_sep>/WebServerv2/libdate.c
/*libdate.c*/
#include <time.h>
#include <stdio.h>
char * searchString() {
return "CURRENTDATE";
}
char * replaceString() {
time_t tyme = (time_t)(-1);
while(tyme == (time_t)(-1)){
tyme = (int)time(NULL);
}
return ctime(&tyme);
}
<file_sep>/WheresParallaldo/wp.c
/* <NAME>
0553453
wp.c
Desription:
A working version of the Where's Parallaldo! program. searches for image patterns in other images... with parallalism!
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <math.h>
#include "pilot.h"
#define DEBUG 0
// Pilot variables
PI_PROCESS ** Workers; // Worker processes
PI_CHANNEL ** ToWorker; // Worker Channels
PI_CHANNEL ** Results; // Result channels
PI_BUNDLE * Selector; // selectir bundle
// struct to hold information about the location of a parallaldo
typedef struct
{
int x;
int y;
int rotation;
} parallaldo_loc;
// struct to hold information about an image (target or parallaldo)
typedef struct
{
int height;
int width;
char ** matrix;
} image;
void DebugMessage(char * mess)
{
if(DEBUG) printf("%s\n", mess);
}
// function to read in a file as an image struct
image * parseImage(char * filename, int index)
{
FILE * fp;
int i = 0;
char buffer[8192];
image * ret = malloc(sizeof(image));
if (DEBUG) printf("parseImage (%d)", index);
DebugMessage(filename);
// open the file
fp = fopen(filename, "r");
DebugMessage("File Opened:");
// read in the header
fgets(buffer, 8192, fp);
DebugMessage("header read");
// parse out the height and width
sscanf(buffer, "%d %d", &ret->height, &ret->width);
DebugMessage("Allocating Matrix");
// allocate the rows
ret-> matrix = malloc(sizeof(char*)*ret->height);
if(DEBUG) printf("Matrix Allocated (%d x %d)\n", ret->height, ret->width);
// allocate and read in the columns
for(i=0; i< ret->height; i++)
{
//if(DEBUG)printf("allocating row %d of %d\n", i+1, ret->height);
ret->matrix[i] = malloc(sizeof(char)*ret->width);
//printf("58(%d)\n", i);
fgets(buffer, ret->width + 2, fp);
strncpy(ret->matrix[i], buffer, ret->width);
}
// close the file
fclose(fp);
DebugMessage("Parse Complete");
// return the image struct
return ret;
}
// function to deconstruct an image struct
void freeImage(image * target)
{
int i = 0;
DebugMessage("freeImage");
// free the columns
for (i=0; i < target->height; i++)
{
free(target->matrix[i]);
}
// free the rows
free(target->matrix);
// free the struct
free(target);
DebugMessage("Image Freed");
}
// image to rotate an image struct 90 degrees
// returns a new one
image * rotateImage( image * original )
{
int i = 0, j = 0;
image * new = malloc(sizeof(image));
DebugMessage("rotateImage");
// switch the height and width in the new one
new ->height = original ->width;
new ->width = original ->height;
// allocate the rows in the new one
new -> matrix = malloc(sizeof(char*)*new->height);
// place the matrix from the old one itno the new one, rotated 90 degrees
for (i=0; i < new->height; i++)
{
new->matrix[i] = malloc(sizeof(char)*new->width);
for (j=0; j< new->width; j++)
{
new->matrix[i][j] = original->matrix[original->height - (1 + j)][i];
}
}
// return the new image struct
return new;
}
void printImage(image * target)
{
int i = 0;
for (i=0; i < target->height; i++)
printf(">>> %s\n",target->matrix[i]);
}
// function to find the first occurance of a parallaldo in a target image
parallaldo_loc * findParallaldo( image * target, image * parallaldo)
{
parallaldo_loc * ret = NULL;
image * rot0, * rot90, *rot180, * rot270;
int i = 0, j = 0, okRows = 0;
char potential[8192];
DebugMessage("findParallaldo");
// calculate the rotations of the parallaldo
rot0 = parallaldo;
rot90 = rotateImage(rot0);
rot180 = rotateImage(rot90);
rot270 = rotateImage(rot180);
//if(DEBUG) printImage(target);
//if(DEBUG) printf("\n");
//if(DEBUG) printImage(parallaldo);
if (DEBUG) printf("target height %dx%d\n", target->height, target->width);
DebugMessage("images Loaded");
// step through each point of the target matrix
for (i=0; i< target->height; i++)
{
//printf("164\n");
//printf("%d:::rot90->width: %d\n", i, rot90->width);
//printf("\n");
for(j=0; j < target->width; j++)
{
//printf("!!!!!!!!!!!!!!!Checking at [%d][%d] in file sized %d by %d\n", i, j, target->height, target->width);
// check for unrotated parallaldo
okRows = 0;
ret = NULL;
//printf("173(%d)(%d)\n",i, j);
strncpy(potential, &(target->matrix[i][j]), strlen(&(target->matrix[i][j])));
//printf("175(%d)(%d) pot: %s targ %s\n", i, j, potential, &(target->matrix[i][j]));
potential[rot0->width] = 0;
//printf("176(%d)(%d) rot90->width = %d\n",i, j, rot90->width);
if ((rot0-> height <= (target->height - i))&& (rot0-> width <= (target->width - j)))
{
while ((!strncmp(potential, rot0->matrix[okRows], rot0->width)) && ((okRows+1) < rot0->height))
{
DebugMessage("potential rot0");
okRows++;
strncpy(potential, &target->matrix[i+okRows][j], strlen(&target->matrix[i+okRows][j]));
potential[rot0->width] = 0;
}
if ((okRows+1) == rot0->height)
{
// we've found it, construct the return struct
ret = malloc(sizeof(parallaldo_loc));
ret-> y = (j+1);
ret-> x = (i+1);
ret-> rotation = 0;
DebugMessage("found unrotated parallaldo!!!!!");
// advance the indicies of the loops to the end
i = target->height;
j = target->width;
break;
}
}
//printf("203(%d)(%d) rot90->width = %d\n",i, j, rot90->width);
// check for parallaldo rotated 90 degrees
okRows = 0;
//printf("207 strlen = %c, @ij = ", target->matrix[i][j]);
strncpy(potential, &target->matrix[i][j], strlen(&target->matrix[i][j]));
//printf("b4208\n");
//printf("208(%d) - %d\n", j, rot90->width);
potential[rot90->width] = 0;
//printf("210(%d)\n", j);
if ((rot90-> height <= (target->height - i))&& (rot90-> width <= (target->width - j)))
{
while ((!strncmp(potential, rot90->matrix[okRows], rot90->width)) && ((okRows+1) < rot90->height))
{
DebugMessage("potential find 90");
okRows++;
strncpy(potential, &target->matrix[i+okRows][j], strlen(&target->matrix[i+okRows][j]));
potential[rot90->width] = 0;
}
if ((okRows+1) == rot90->height)
{
// we've found it, construct the return struct
ret = malloc(sizeof(parallaldo_loc));
ret-> y = (j+1);
ret-> x = (i+1);
ret-> rotation = 90;
DebugMessage("found rotated 90 parallaldo!!!!!");
// advance the indicies of the loops to the end
i = target->height;
j = target->width;
break;
}
}
//printf("234(%d)\n", j);
// check for parallaldo rotated 180 degrees
okRows = 0;
strncpy(potential, &target->matrix[i][j], strlen(&target->matrix[i][j]));
potential[rot180->width] = 0;
if ((rot180-> height <= (target->height - i))&& (rot180-> width <= (target->width - j)))
{
while ((!strncmp(potential, rot180->matrix[okRows], rot180->width)) && ((okRows+1) < rot180->height))
{
DebugMessage("potential find 180\n");
okRows++;
strncpy(potential, &target->matrix[i+okRows][j], strlen(&target->matrix[i+okRows][j]));
potential[rot180->width] = 0;
}
if ((okRows+1) == rot180->height)
{
// we've found it, construct the return struct
ret = malloc(sizeof(parallaldo_loc));
ret-> y = (j+1);
ret-> x = (i+1);
ret-> rotation = 180;
DebugMessage("found rotated 180 parallaldo!!!!!");
// advance the indicies of the loops to the end
i = target->height;
j = target->width;
break;
}
}
//printf("266(%d)\n", j);
// check for parallaldo rotated 270 degrees
okRows = 0;
strncpy(potential, &target->matrix[i][j], strlen(&target->matrix[i][j]));
potential[rot270->width] = 0;
if ((rot270-> height <= (target->height - i))&& (rot270-> width <= (target->width - j)))
{
while ((!strncmp(potential, rot270->matrix[okRows], rot270->width)) && ((okRows+1) < rot270->height))
{
DebugMessage("potential find 270");
okRows++;
strncpy(potential, &target->matrix[i+okRows][j], strlen(&target->matrix[i+okRows][j]));
potential[rot270->width] = 0;
}
if ((okRows+1) == rot270->height)
{
// we've found it, construct the return struct
ret = malloc(sizeof(parallaldo_loc));
ret-> y = (j+1);
ret-> x = (i+1);
ret-> rotation = 270;
DebugMessage("found rotated 270 parallaldo!!!!!");
// advance the indicies of the loops to the end
i = target->height;
j = target->width;
break;
}
}
//DebugMessage("not here!");
//ret = NULL;
}
}
// deconstruct the rotated parallaldos
freeImage(rot90);
freeImage(rot180);
freeImage(rot270);
DebugMessage("done findParallaldo");
// return the location structure of the parallaldo
// will be null if not found
return ret;
}
// function to run a worker process
int doWork(int index, void * arg2)
{
int DONE_FLAG = 0, i = 0;
char buffer[128], target[128], parallaldo[128];
image * targetImage, *parallaldoImage;
parallaldo_loc * ret = NULL;
char reporting[128];
sprintf(reporting, "Worker # %d started%c", index, 0);
DebugMessage(reporting);
// main loop
while (!DONE_FLAG)
{
// Rinitialize buffers.
for(i=0; i<128; i++)
{
buffer[i] = 0;
target[i] = 0;
parallaldo[i] = 0;
}
// read in a string from the channel
PI_Read(ToWorker[index], "%128c", buffer);
// if it's not an end-of-line char we have a job to do
if (strncmp(buffer, "ALL_DONE", 9) && strncmp( buffer, "", 1))
{
// save the string read as the target filename
strncpy(target, buffer, strlen(buffer));
// read in the parallaldo filename
PI_Read(ToWorker[index], "%128c", parallaldo);
// construct the image structs
targetImage = parseImage(target, index);
parallaldoImage = parseImage(parallaldo, index);
// find parallaldo!
ret = findParallaldo(targetImage, parallaldoImage);
if(DEBUG) printf("findParallaldo complete %d\n", index);
// deconstruct the image structs
freeImage(targetImage);
targetImage = NULL;
freeImage(parallaldoImage);
parallaldoImage = NULL;
DebugMessage(" images deconstructed");
// if parallaldo was found
if (ret != NULL)
{
DebugMessage("parallaldo Found.");
if (ret == NULL) printf("Null\n");
ret->y = 5;
if(DEBUG) printf("parallaldo at: %d,%d . %drotated degrees\n", ret->y, ret->x, ret->rotation);
// report that it was found
PI_Write(Results[index], "%6c", "found");
PI_Write(Results[index], "%d %d %d %128c %128c", ret->y, ret->x, ret->rotation, parallaldo, target);
DebugMessage("success reported");
} else
{
DebugMessage("parallaldo not found\n");
PI_Write(Results[index], "%6c", "not");
DebugMessage("failure message sent\n");
}
} else
{ // if the process recieved an end-of-line, it's all done and can exit.
DONE_FLAG = 1;
// write "not found" to the result channel so if it gets queried stuff doesnt dealock.
PI_Write(Results[index], "%6c", "not");
}
}
return 0;
}
int main( int argc, char *argv[] )
{
// Pilot configuration phase; return no. of processes available
int N = PI_Configure( &argc, &argv );
int i = 0, j = 0, k = 0;
int W = N-1;
int y = 0, x = 0, r = 0;
int lastWorker = 0, numRounds = 0, taskNum = 0;
DIR * dp = NULL;
struct dirent * file;
char targetList[128][128], parallaldoList[128][128], filename[128];
char taskList[1024][2][128]; //task list: [task id][parallaldo(0)/target(1)][filename]
double op1 = 0, op2;
char * targ, * paral, report[32], buff1[128], buff2[128];
int numTargets = 0, numParallaldos = 0, numTasks = 0, finished = 0, numDone = 0;
parallaldo_loc * result = NULL;
image * laldo = NULL, *arget = NULL;
DebugMessage("wp Process initiated");
// Create the procs and channels, if we have enough processors for parallelization
if (W)
{
// allocate the process pointer array
Workers = malloc(sizeof(PI_PROCESS*)*W);
// allocate channel arrays
ToWorker = malloc(sizeof(PI_CHANNEL*)*W);
Results = malloc(sizeof(PI_CHANNEL*)*W);
// allocate selector bundle
Selector = malloc(sizeof(PI_BUNDLE*));
// create the processes and channels
for(i = 0; i< W; i++)
{
Workers[i] = PI_CreateProcess(doWork, i, (void*)NULL);
ToWorker[i] = PI_CreateChannel(PI_MAIN, Workers[i]);
Results[i] = PI_CreateChannel(Workers[i], PI_MAIN);
}
Selector = PI_CreateBundle(PI_SELECT, Results, W);
// Otherwise, it's serial time!
}
// read in the directories
dp = opendir(argv[argc-2]);
while((file = readdir(dp)) != NULL)
{
if (strncmp(file->d_name, ".", strlen(file->d_name)) && strncmp(file->d_name, "..", strlen(file->d_name)))
{
sprintf(filename, "%s/%s", argv[argc-2], file->d_name);
strncpy(parallaldoList[numParallaldos], filename, strlen(filename));
numParallaldos++;
}
}
closedir(dp);
dp = opendir(argv[argc-1]);
while((file = readdir(dp)) != NULL)
{
if (strncmp(file->d_name, ".", strlen(file->d_name)) && strncmp(file->d_name, "..", strlen(file->d_name)))
{
sprintf(filename, "%s/%s", argv[argc-1], file->d_name);
strncpy(targetList[numTargets], filename, strlen(filename));
numTargets++;
}
}
closedir(dp);
// Compile task list
for (i = 0; i < numParallaldos; i++)
{
for(j = 0; j < numTargets; j++)
{
strncpy(taskList[numTasks][0], parallaldoList[i], strlen(parallaldoList[i]));
strncpy(taskList[numTasks][1], targetList[j], strlen(targetList[j]));
numTasks++;
}
}
// PI_MAIN stuff
if (W)
{
lastWorker = 0;
op1 = numTasks;
op2 = W;
numRounds = ceil(op1 / op2);
PI_StartAll();
if (strncmp("-b", argv[1], 2))
{
if (DEBUG) printf("MASTER: numRounds = %d numTasks = %d\n", numRounds, numTasks);
for (i=0; i < numRounds; i++)
{
// assign tasks round-robin
for (j = 0; j < W; j++)
{
taskNum = (i * W)+j;
if(DEBUG) printf("MASTER: assigning task %d to Worker %d\n", taskNum, j);
if (taskNum <= numTasks)
{
PI_Write(ToWorker[j], "%128c", taskList[taskNum][1]);
PI_Write(ToWorker[j], "%128c", taskList[taskNum][0]);
} else
{
PI_Write(ToWorker[j], "%128c", "ALL_DONE");
}
}
// collect results round-robin
for (j = 0; j < W; j++)
{
for( k = 0; k < 7; k++) report[k] = 0;
taskNum = (i*W)+j;
if(DEBUG) printf("MASTER: retrieving result %d from Worker %d\n", taskNum, j);
PI_Read(Results[j], "%32c", report);
if(DEBUG) printf("MASTER: result recieved: [%s]\n", report);
if (!strncmp(report, "found", strlen("found")))
{
//parallaldo found!
DebugMessage("MASTER: reporting found parellaldo");
PI_Read(Results[j], "%d %d %d %128c %128c", &y, &x, &r, buff1, buff2);
paral = strchr(taskList[taskNum][0], '/');
paral = ¶l[1];
targ = strchr(taskList[taskNum][1], '/');
targ = &targ[1];
printf("$%s %s (%d,%d,%d)\n", paral,targ,y, x, r);
} else DebugMessage("MASTER: task completed, no parellaldo");
}
}
free(result);
} else
{
//distribvute initial jobs
for (i=0; i<W; i++)
{
PI_Write(ToWorker[i], "%128c", taskList[i][1]);
PI_Write(ToWorker[i], "%128c", taskList[i][0]);
taskNum++;
}
while(numDone < W)
{
DebugMessage("MASTER: waiting for results\n");
finished = PI_Select(Selector);
PI_Read(Results[finished], "%32c", report);
if(DEBUG) printf("MASTER: result recievedi: %s\n", report);
if (!strncmp(report, "found", strlen("found")))
{
DebugMessage("MASTER: parallaldo found. printinf information");
//parallaldo found!
PI_Read(Results[finished], "%d %d %d %128c %128c", &y, &x, &r, buff1, buff2);
if(DEBUG) printf("MASTER: results, last task assigned - %d: y = %d x = %d r = %d\n",numTasks, y, x, r);
paral = strchr(buff1, '/');
if(DEBUG) printf("MASTER: %s\n", paral);
paral = ¶l[1];
if(DEBUG) printf("MASTER: parapath constructed: %s\n", paral);
targ = strchr(buff2, '/');
targ = &targ[1];
if(DEBUG)printf("MASTER: targetpath constructed: %s\n", targ);
printf("$%s %s (%d,%d,%d)\n", paral,targ,y, x, r);
DebugMessage("MASTER: Parallaldo info reported");
}
if (taskNum < numTasks)
{
if (DEBUG) printf("MASTER: Assigning new task %d of %d to Worker %d\n", taskNum, numTasks, finished);
PI_Write(ToWorker[finished], "%128c", taskList[taskNum][1]);
PI_Write(ToWorker[finished], "%128c", taskList[taskNum][0]);
taskNum++;
if (DEBUG) printf("MASTER: New Task Assigned\n");
} else
{
if (DEBUG) printf("MASTER: Worker %d is done.\n", finished);
PI_Write(ToWorker[finished], "%128c", "ALL_DONE");
numDone++;
if (DEBUG)printf("Worker %d done\n", finished);
}
}
}
} else
{
for(i=0; i<numTasks; i++)
{
DebugMessage("GETTING IMAGES");
laldo = parseImage(taskList[i][1], 0);
arget = parseImage(taskList[i][0], 0);
result = findParallaldo(laldo, arget);
freeImage(laldo);
freeImage(arget);
if (result)
{
paral = strchr(taskList[i][0], '/');
paral = ¶l[1];
targ = strchr(taskList[i][1], '/');
targ = &targ[1];
printf("$%s %s (%d,%d,%d)\n", paral,targ,result->y, result->x, result->rotation);
}
if(result) free(result);
}
}
// end program
return 0;
}
<file_sep>/SplitFileRequester/makefile
all: Server Lysander
Server: a2-server2.c
gcc a2-server2.c -o Server -Wall
Lysander: lysander.c
gcc lysander.c -o Lysander -Wall
clean:
rm -rf Server
rm -rf Lysander
rm -rf blarg2.txt
rm -rf Assignment2b.pdf
rm -rf *~
<file_sep>/SplitFileRequesterRobust/assignment3-server.h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#define MYPORT "4950" // the port users will be connecting to
#define HTTPPORT 80
#define MAXWAIT 300
#define SHUFFLE 25
#define LOST 15
#define MAXBUFLEN 200
#define MAXDTGRMS 700
#define MAXCLIENTS 20
#define MAXSIZE 500000
struct Client {
int inuse ;
int idle ;
struct sockaddr_in addr ;
size_t addr_len ;
char Im[MAXSIZE] ;
int Imlen ;
int numdat ;
int Dlen[MAXDTGRMS] ;
int Dptr[MAXDTGRMS] ;
} Client[MAXCLIENTS] ;
int Three[3] ;
int startserver() ;
void waitforinput( int ) ;
void getrequest( int ) ;
void sendimage( int , struct Client * ) ;
void retransmit( int , struct Client , char * ) ;
void copyimage( char * , struct Client * ) ;
void partition( struct Client * ) ;
void shuffle( struct Client * ) ;
void lose( struct Client * ) ;
int Open( char * ) ;
| 81bcdf724bd78ef00f8a21b05394b1ec5ee9cdb4 | [
"Java",
"C",
"Text",
"Makefile"
] | 37 | Makefile | hoylemd/C | 863e6ae2c4afaf5abfa1d74a4a8a2c8023cbe0f1 | c56373d52e7644c80e32cd92f70fb89a5c04e76f |
refs/heads/master | <repo_name>kboyko99/mattermost-deploy-and-administration<file_sep>/step-4-stop-everything.sh
#!/bin/bash
#cd ./backup; ./backup.sh
docker stop mattermost mattermost-mysql
docker rm mattermost mattermost-mysql
<file_sep>/run-mattermost.sh
#!/bin/bash
source ./mattermost.secrets
source ./mattermost.conf
[ "$FIRST" = "true" ] && cmd="/sbin/entrypoint.sh app:start"
[ -z "$FIRST" ] && cmd="./bin/platform --config /opt/mattermost/config/config.json"
echo "mattermost command: $cmd"
docker run --name mattermost -d --link mattermost-mysql:mysql --publish 80:80 --publish 443:443 \
--env "MATTERMOST_EMAIL=$MATTERMOST_EMAIL" --env "SMTP_SECURITY=$SMTP_SECURITY" --env "SMTP_HOST=$SMTP_HOST" --env "SMTP_PORT=$SMTP_PORT" \
--env "SMTP_USER=$SMTP_USER" --env "SMTP_PASS=$SMTP_PASS" \
--env "MATTERMOST_SECRET_KEY=$SECRET_KEY" --env "MATTERMOST_LINK_SALT=$LINK_SALT" --env "MATTERMOST_RESET_SALT=$RESET_SALT" --env "MATTERMOST_INVITE_SALT=$INVITE_SALT" \
--volume "/srv/docker/mattermost/config:/opt/mattermost/config" --volume "/srv/docker/mattermost/mattermost:/opt/mattermost/data" \
--volume "/srv/docker/mattermost/logs:/var/log/mattermost/" \
"$MATTERMOSTIMAGE" $cmd
#debug
docker ps -a
<file_sep>/step-9-cleanup.sh
#!/bin/bash
docker rm -f $(docker ps -a |awk '{print $1;}')
# optionally remove images..
#docker rmi $(docker images |awk '{print $3;}')
rm -rf /srv/docker/mattermost
<file_sep>/step-3-run-mattermost-and-db-first-time-only.sh
#!/bin/bash
source ./run-mysql.sh
source ./mattermost.conf
mkdir -p /srv/docker/mattermost/mattermost
echo "$MATTERMOSTVERSION" > /srv/docker/mattermost/mattermost/VERSION
FIRST=true
source ./run-mattermost.sh
<file_sep>/step-5-start-everything-again.sh
#!/bin/bash
source ./run-mysql.sh
source ./run-mattermost.sh
<file_sep>/step-1-prepare-server.sh
#!/bin/bash
apt-get update -y
sudo apt-get install -y mc zip unzip expect git curl htop
<file_sep>/run-mysql.sh
#!/bin/bash
source ./mattermost.secrets
source ./mattermost.conf
docker run --name mattermost-mysql -d \
--env "MYSQL_USER=mattermost" --env "MYSQL_PASSWORD=${MYSQL_MM_PASS}" --env 'MYSQL_DATABASE=mattermost' --env "MYSQL_ROOT_PASSWORD=${MYSQL_MM_ROOTPASS}" \
--volume /srv/docker/mattermost/mysql:/var/lib/mysql \
mysql:latest
<file_sep>/step-2-select-and-prepare-mattermost-3.6.2.sh
#!/bin/bash
echo 'MATTERMOSTIMAGE="mattermost"' >> mattermost.conf
echo 'MATTERMOSTVERSION="3.6.2"' >> mattermost.conf
source mattermost.conf
# version 3.6.2
git clone https://github.com/funkyfuture/docker-mattermost.git
cd docker-mattermost
git checkout update_to_3.6.2
git pull
docker build -t "$MATTERMOSTIMAGE" .
<file_sep>/step-2-select-and-prepare-mattermost-3.5.1.sh
#!/bin/bash
echo 'MATTERMOSTIMAGE="jasl8r/mattermost:latest"' >> mattermost.conf
echo 'MATTERMOSTVERSION="3.5.1"' >> mattermost.conf
source mattermost.conf
docker pull "$MATTERMOSTIMAGE"
<file_sep>/upgrade.sh
#!/bin/bash
source ./step-4-stop-everything.sh
source ./backup.sh
#на случай если latest перестанет быть 3.5.1
source ./step-2-select-and-prepare-mattermost-3.5.1.sh
source ./step-5-start-everything-again.sh | da8fe9fd2c25bdfe1552430a750bac2fc747128b | [
"Shell"
] | 10 | Shell | kboyko99/mattermost-deploy-and-administration | de254ab338fb97ae0dd7de8d18b30e41c31560d8 | ff35f073873c06304babe77360fca9a469c277f5 |
refs/heads/master | <file_sep>package com.example.owner.exam;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.sql.Time;
public class MainActivity extends AppCompatActivity {
Switch sw1;
Chronometer ch1;
LinearLayout layout1, layout3;
String setBlue = "#0000FF";
String setGray = "#A9A9A9";
EditText et1, et2, et3;
RadioButton rb1, rb2, rb3, rb4, rb5;
ImageView iv1;
Button bt1, bt2, bt3, bt4;
String num1, num2, num3;
Integer total,price, discount;
Integer check = 0;
Integer cv_year, cv_month, cv_day;
TextView tv1, tv2, tv3;
CalendarView cv1;
TimePicker tp1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sw1 = (Switch) findViewById(R.id.switch2);
ch1 = (Chronometer) findViewById(R.id.chronometer3);
layout1 = (LinearLayout) findViewById(R.id.lo1);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);
rb1 = (RadioButton) findViewById(R.id.radioButton);
rb2 = (RadioButton) findViewById(R.id.radioButton2);
rb3 = (RadioButton) findViewById(R.id.radioButton3);
rb4 = (RadioButton) findViewById(R.id.radioButton4);
rb5 = (RadioButton) findViewById(R.id.radioButton5);
iv1 = (ImageView) findViewById(R.id.imageView2);
bt1 = (Button) findViewById(R.id.button2);
bt2 = (Button) findViewById(R.id.button3);
bt3 = (Button) findViewById(R.id.button);
bt4 = (Button) findViewById(R.id.button4);
tv1 = (TextView) findViewById(R.id.textView10);
tv2 = (TextView) findViewById(R.id.textView11);
tv3 = (TextView) findViewById(R.id.textView12);
layout3 = (LinearLayout) findViewById(R.id.layout3);
cv1 = (CalendarView) findViewById(R.id.calendarView4);
tp1 = (TimePicker) findViewById(R.id.timePicker2);
sw1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
layout1.setVisibility(View.VISIBLE);
ch1.setBase(SystemClock.elapsedRealtime());
ch1.start();
ch1.setTextColor(Color.parseColor(setBlue));
} else {
layout1.setVisibility(View.INVISIBLE);
ch1.stop();
ch1.setBase(SystemClock.elapsedRealtime());
ch1.setTextColor(Color.parseColor(setGray));
rb1.setChecked(true);
num1 = null;
num2 = null;
num3 = null;
discount = null;
price = null;
check = 0;
et1.setText("");
et2.setText("");
et3.setText("");
tv1.setText("총 명수 : ");
tv2.setText("할인 금액 : ");
tv3.setText("결제 금액 : ");
}
}
});
rb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
iv1.setImageResource(R.drawable.iv_park);
}
}
});
rb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
iv1.setImageResource(R.drawable.iv_money);
}
}
});
rb3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
iv1.setImageResource(R.drawable.iv_card);
}
}
});
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (et1.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "인원을 입력하세요.", Toast.LENGTH_SHORT).show();
} else if (et2.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "인원을 입력하세요.", Toast.LENGTH_SHORT).show();
} else if (et3.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "인원을 입력하세요.", Toast.LENGTH_SHORT).show();
} else {
check = 1;
num1 = et1.getText().toString();
num2 = et2.getText().toString();
num3 = et3.getText().toString();
total = Integer.parseInt(num1) + Integer.parseInt(num2) + Integer.parseInt(num3);
price = (Integer.parseInt(num1) * 15000) + (Integer.parseInt(num2) * 12000) + (Integer.parseInt(num3) * 8000);
if (rb1.isChecked()) {
discount = price * 5 / 100;
price = price - discount;
tv1.setText("총 명수 : " + total);
tv2.setText("할인 금액 : " + discount);
tv3.setText("결제 금액 : " + price);
} else if (rb2.isChecked()) {
discount = price * 10 / 100;
price = price - discount;
tv1.setText("총 명수 : " + total);
tv2.setText("할인 금액 : " + discount);
tv3.setText("결제 금액 : " + price);
} else {
discount = price * 20 / 100;
price = price - discount;
tv1.setText("총 명수 : " + total);
tv2.setText("할인 금액 : " + discount);
tv3.setText("결제 금액 : " + price);
}
}
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout1.setVisibility(View.INVISIBLE);
layout3.setVisibility(View.VISIBLE);
}
});
cv1.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
cv_year = year;
cv_month = month;
cv_day = dayOfMonth;
}
});
bt3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(check == 0){
Toast.makeText(getApplicationContext(), "인원예약을 먼저 하세요.", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), cv_year+"년"+cv_month+"월"+cv_day+"일"+tp1.getCurrentHour()+"시"+tp1.getCurrentMinute()+"분 예약이 완료되었습니다.", Toast.LENGTH_SHORT).show();
}
}
});
bt4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout3.setVisibility(View.INVISIBLE);
layout1.setVisibility(View.VISIBLE);
}
});
rb4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cv1.setVisibility(View.VISIBLE);
tp1.setVisibility(View.INVISIBLE);
}
}
});
rb5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cv1.setVisibility(View.INVISIBLE);
tp1.setVisibility(View.VISIBLE);
}
}
});
}
}
<file_sep># opensource_exam
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274869.png" width=200>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274873.png" width=200>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274877.png" width=200><br>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274901.png" width=200>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274912.png" width=200>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274914.png" width=200><br>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274917.png" width=200>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481274924.png" width=200>
<img src="https://github.com/ykk2006/opensource_exam/blob/master/app/Screenshots/Screenshot_1481275137.png" width=200>
| d223d3ae98f6b6a9726dd5c0da9b2f71c9b3d578 | [
"Markdown",
"Java"
] | 2 | Java | ykk2006/opensource_exam | 2f7269b6db92bc458a662da7b5add65d356ace91 | 32f01357af13ca08f0f2c395ad6501a9d98fb89b |
refs/heads/master | <file_sep>import './App.css';
import firebase from "firebase";
import {Component} from "react";
class App extends Component {
constructor() {
super();
this.state = {
user:null
}
}
componentWillUnmount() {
firebase.auth().onAuthStateChanged(user => {
this.setState({user});
})
}
handleAuth(){
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.then(result =>
console.log(`${result.user.email} ha iniciado sesion , ${result.user.displayName} , ${result.user.photoURL}`)
)
.catch(error => console.log(`Error ${error.code} : ${error.message}`))
}
renderLoginButton(){
if(this.state.user !== null){
}else{
console.log(this.state)
return(<button onClick={this.handleAuth}>Login con Google</button>);
}
}
render() {
return (
<div>
<h1>PruebaGram</h1>
{this.renderLoginButton()}
</div>
);
}
}
export default App;
| 16d189234d0d95864c3462a4d51a3a8832a62c28 | [
"JavaScript"
] | 1 | JavaScript | sebas99cano/pruebagram | 770591878fdbb141345c079cbeac6a968a0f55e4 | fd518af95286aad33e606ffaeb61b528661a2d5e |
refs/heads/android-6.0 | <file_sep>#!/sbin/sh
finish()
{
umount /s
rmdir /s
setprop crypto.ready 1
exit 0
}
syspath="/dev/block/bootdevice/by-name/system"
mkdir /s
mount -t ext4 -o ro "$syspath" /s
is_fastboot_twrp=$(getprop ro.boot.fastboot)
if [ ! -z "$is_fastboot_twrp" ]; then
osver=$(getprop ro.build.version.release_orig)
patchlevel=$(getprop ro.build.version.security_patch_orig)
resetprop ro.build.version.release "$osver"
sed -i "s/ro.build.version.release=.*/ro.build.version.release="$osver"/g" /default.prop ;
resetprop ro.build.version.security_patch "$patchlevel"
sed -i "s/ro.build.version.security_patch=.*/ro.build.version.security_patch="$patchlevel"/g" /default.prop ;
finish
fi
if [ -f /s/build.prop ]; then
# TODO: It may be better to try to read these from the boot image than from /system
osver=$(grep -i 'ro.build.version.release' /s/build.prop | cut -f2 -d'=')
patchlevel=$(grep -i 'ro.build.version.security_patch' /s/build.prop | cut -f2 -d'=')
resetprop ro.build.version.release "$osver"
sed -i "s/ro.build.version.release=.*/ro.build.version.release="$osver"/g" /default.prop ;
resetprop ro.build.version.security_patch "$patchlevel"
sed -i "s/ro.build.version.security_patch=.*/ro.build.version.security_patch="$patchlevel"/g" /default.prop ;
finish
else
# Be sure to increase the PLATFORM_VERSION in build/core/version_defaults.mk to override Google's anti-rollback features to something rather insane
osver=$(getprop ro.build.version.release_orig)
patchlevel=$(getprop ro.build.version.security_patch_orig)
resetprop ro.build.version.release "$osver"
sed -i "s/ro.build.version.release=.*/ro.build.version.release="$osver"/g" /default.prop ;
resetprop ro.build.version.security_patch "$patchlevel"
sed -i "s/ro.build.version.security_patch=.*/ro.build.version.security_patch="$patchlevel"/g" /default.prop ;
finish
fi
| 73cbddecf010797e38f1818b2869e5911fbf6a78 | [
"Shell"
] | 1 | Shell | CaptainThrowback/android_device_htc_hima | dd3abe8aef5cc19e81e06057d669c373ca056509 | afd2a427ddc789cddb619aea44d9f423a17bb6a9 |
refs/heads/master | <repo_name>TheWeirdestShit/The-Weirdest-Shit<file_sep>/The Weirdest Shit/Assets/Scripts/FlipOut.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider))]
public class FlipOut : MonoBehaviour {
BoxCollider bc;
public bool flipOut{
get {
if (bc==null){
bc = GetComponent<BoxCollider>();
}
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
return !GeometryUtility.TestPlanesAABB(planes, bc.bounds);
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/RandomPlaySound.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class RandomPlaySound : MonoBehaviour {
AudioSource asource;
public AudioClip[] ac;
public float minTime;
public float maxTime;
float time;
// Use this for initialization
void Start () {
asource = GetComponent<AudioSource>();
time = Mathf.Lerp(minTime, maxTime, Random.value);
}
// Update is called once per frame
void Update () {
if (!asource.isPlaying){
time -= Time.deltaTime;
if (time<=0){
asource.clip = ac.pickRandom();
asource.Play();
time = Mathf.Lerp(minTime, maxTime, Random.value);
}
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/HighlightSwitcher.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HighlightSwitcher : MonoBehaviour {
public GameObject normal;
public GameObject hover;
// Update is called once per frame
void Update () {
bool isUI = false;
RaycastHit rch;
if (Physics.Raycast(transform.position, transform.forward, out rch)){
Button butt = rch.collider.GetComponent<Button>();
if (butt != null)
isUI = true;
}
normal.SetActive(!isUI);
hover.SetActive(isUI);
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/RotateOnFlipout.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(FlipOut))]
public class RotateOnFlipout : MonoBehaviour {
FlipOut fo;
public Vector3[] rotations;
// Use this for initialization
void Start () {
fo = GetComponent<FlipOut>();
}
// Update is called once per frame
void Update () {
if (fo.flipOut){
transform.rotation = Quaternion.Euler(rotations.pickRandom());
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/Shake.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct ShakeParams {
[Range(0,10)]
public float frequency;
[Range(0,1)]
public float amplitude;
}
public class Shake : MonoBehaviour {
public bool shakePos;
public bool shakeRot;
public ShakeParams[] positionShakes;
public ShakeParams[] rotationShakes;
Vector3[] positionPhases;
Vector3[] rotationPhases;
Vector3 originalPosition;
Vector3 originalRotation;
// Use this for initialization
void Start () {
positionPhases = new Vector3[positionShakes.Length];
for (int i=0; i<positionPhases.Length; i++){
positionPhases[i] = new Vector3(
Random.value*Mathf.PI*2,
Random.value*Mathf.PI*2,
Random.value*Mathf.PI*2
);
}
rotationPhases = new Vector3[rotationShakes.Length];
for (int i=0; i<rotationPhases.Length; i++){
rotationPhases[i] = new Vector3(
Random.value*Mathf.PI*2,
Random.value*Mathf.PI*2,
Random.value*Mathf.PI*2
);
}
originalPosition = transform.localPosition;
originalRotation = transform.localRotation.eulerAngles;
}
// Update is called once per frame
void Update () {
if (shakePos){
Vector3 pos = originalPosition;
for (int i = 0; i<positionShakes.Length; i++){
ShakeParams param = positionShakes[i];
Vector3 phase = positionPhases[i];
pos += new Vector3(
Mathf.Sin(Time.time*Mathf.PI*2*param.frequency+phase.x)*param.amplitude,
Mathf.Sin(Time.time*Mathf.PI*2*param.frequency+phase.y)*param.amplitude,
Mathf.Sin(Time.time*Mathf.PI*2*param.frequency+phase.z)*param.amplitude
);
}
transform.localPosition = pos;
}
if (shakeRot){
Vector3 rot = originalRotation;
for (int i = 0; i<rotationShakes.Length; i++){
ShakeParams param = rotationShakes[i];
Vector3 phase = rotationPhases[i];
rot += new Vector3(
Mathf.Sin(Time.time*Mathf.PI*2*param.frequency+phase.x)*param.amplitude,
Mathf.Sin(Time.time*Mathf.PI*2*param.frequency+phase.y)*param.amplitude,
Mathf.Sin(Time.time*Mathf.PI*2*param.frequency+phase.z)*param.amplitude
);
}
transform.localRotation = Quaternion.Euler(rot);
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/GazeClick.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GazeClick : MonoBehaviour {
public Image gazeDisplay;
public float clickIn;
float time;
// Update is called once per frame
void Update () {
bool isUI = false;
RaycastHit rch;
if (Physics.Raycast(transform.position, transform.forward, out rch)){
Button butt = rch.collider.GetComponent<Button>();
if (butt != null){
time = time-Time.deltaTime;
if (time<=0){
time = clickIn;
butt.onClick.Invoke();
}
} else {
time = clickIn;
}
} else {
time = clickIn;
}
if (gazeDisplay!=null){
Material mat = new Material(gazeDisplay.material);
mat.SetFloat("_Value",Mathf.Clamp01(1-(time/clickIn)));
gazeDisplay.material = mat;
}
}
}
<file_sep>/README.md
The Weirdest Shit
=================
An experimental game about pooping
<file_sep>/The Weirdest Shit/Assets/Scripts/Creeper.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PopInUI))]
public class Creeper : MonoBehaviour {
AudioSource asource;
PopInUI piu;
public GameObject flash;
public float minTime;
public float maxTime;
public float creepTime;
public float firstCreep = 15;
float rpick;
float time;
// Use this for initialization
void Start () {
piu = GetComponent<PopInUI>();
Reset();
time = -firstCreep;
asource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
time += Time.deltaTime;
float teatime = Mathf.LerpUnclamped(minTime, maxTime, rpick);
if (flash!=null){
flash.SetActive(time>teatime+Mathf.Lerp(0,creepTime,0.45f) && time<teatime+Mathf.Lerp(0,creepTime,0.55f));
if (asource!=null && !asource.isPlaying){
//asource.Play();
}
}
if (time<teatime){
piu.popped = false;
} else {
piu.popped = true;
if (time>teatime+creepTime){
Reset();
}
}
}
void Reset(){
rpick = Random.value;
time = 0;
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/RatMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RatMovement : MonoBehaviour
{
public GameObject Target;
public float Speed;
private Vector3 targetPos;
// Use this for initialization
void Start ()
{
targetPos = Target.transform.position;
}
//
void Update ()
{
if( transform.position != targetPos)
{
transform.position = Vector3.MoveTowards( transform.position, targetPos, Speed * Time.deltaTime);
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/PivotInSequence.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PopInUI))]
public class PivotInSequence : MonoBehaviour {
PopInUI piu;
public float delay;
float timeTill;
public PopInUI childPiu;
// Use this for initialization
void Start () {
piu = GetComponent<PopInUI>();
if (childPiu == null)
childPiu = GetComponentInChildren<PopInUI>();
timeTill = delay;
}
// Update is called once per frame
void Update () {
Debug.Log(timeTill);
Debug.Log(childPiu.name);
if (childPiu.popped != piu.popped){
Debug.Log("counting");
timeTill -= Time.deltaTime;
if (timeTill<=0){
childPiu.popped = piu.popped;
}
} else {
Debug.Log("resetting");
timeTill = delay;
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/ProjectorImageOnFlipout.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectorImageOnFlipout : MonoBehaviour {
public Texture2D[] images;
FlipOut fo;
Projector proj;
// Use this for initialization
void Start () {
fo = GetComponent<FlipOut>();
proj = GetComponent<Projector>();
Material mat = new Material(proj.material);
mat.SetTexture("_ShadowTex", images.pickRandom());
proj.material = mat;
}
// Update is called once per frame
void Update () {
if (fo.flipOut){
Material mat = new Material(proj.material);
mat.SetTexture("_ShadowTex", images.pickRandom());
proj.material = mat;
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/FirstPoopsonCamera.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstPoopsonCamera : MonoBehaviour
{
public Transform cameraAnchor;
float xRot;
float yRot;
public float sensitivity = 1;
[Range(0,90)]
public float maxAngle = 85;
// Use this for initialization
void Start ()
{
//Cursor.lockState = CursorLockMode.Locked;
//Cursor.visible = true;
if (cameraAnchor==null)
{
cameraAnchor = GetComponentInChildren<Transform>();
}
}
// Update is called once per frame
void Update ()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
xRot += Input.GetAxis("Mouse X")*sensitivity;
yRot += Input.GetAxis("Mouse Y")*sensitivity;
yRot = Mathf.Clamp(yRot, -maxAngle, maxAngle);
cameraAnchor.localRotation = Quaternion.AngleAxis(-yRot,Vector3.right);
cameraAnchor.localRotation = Quaternion.AngleAxis(xRot,Vector3.up) * cameraAnchor.localRotation;
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/Clicky.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Clicky : MonoBehaviour {
public Vector3 lastHit;
// Use this for initialization
void Start () {
lastHit = Vector3.zero;
}
// Update is called once per frame
void Update () {
bool click = Input.GetMouseButtonDown(0);
DrawCross(lastHit);
if (click) {
DoClick();
}
}
public void DoClick(){
RaycastHit rch;
if (Physics.Raycast(transform.position, transform.forward, out rch)){
lastHit = rch.point;
Button butt = rch.collider.GetComponent<Button>();
if (butt != null)
butt.onClick.Invoke();
}
}
void DrawCross(Vector3 pos, float size = 1){
Debug.DrawLine(pos+Vector3.up*size,pos+Vector3.down*size, Color.blue);
Debug.DrawLine(pos+Vector3.left*size,pos+Vector3.right*size, Color.green);
Debug.DrawLine(pos+Vector3.back*size,pos+Vector3.forward*size, Color.red);
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/ArrayExtensions.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class ArrayExtensions {
public static T pickRandom<T>(this T[] array){
return array[Random.Range(0,array.Length)];
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/PopSequencer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct PopDelay {
public PopInUI piu;
public float turnOn;
public float turnOff;
}
public class PopSequencer : MonoBehaviour {
public bool popped;
public PopDelay[] pops;
bool prev;
float time;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (prev != popped){
prev = popped;
time = 0;
}
time += Time.deltaTime;
for (int i = 0; i<pops.Length; i++){
PopDelay pop = pops[i];
if (time > (popped ? pop.turnOn : pop.turnOff)){
pop.piu.popped = popped;
}
}
}
}
<file_sep>/The Weirdest Shit/Assets/Scripts/PopInUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PopInUI : MonoBehaviour {
public AudioClip popIn;
public AudioClip popOut;
AudioSource asource;
bool wasPopped = false;
public Vector3 fromScale;
public Vector3 toScale;
public Vector3 fromRotation;
public Vector3 toRotation;
public float spring;
public float damp;
float position;
float scalePos;
float velocity;
public bool popped;
RectTransform rct;
// Use this for initialization
void Start () {
rct = GetComponent<RectTransform>();
position = (popped ? 1 : 0);
scalePos = position;
velocity = 0;
wasPopped = popped;
asource = GetComponent<AudioSource>();
}
void FixedUpdate(){
float error = (popped ? 1 : 0) - position;
velocity += error * spring * Time.fixedDeltaTime;
velocity -= velocity * damp * Time.fixedDeltaTime;
if (asource!=null && popped != wasPopped){
if (popped){
if (popOut!=null)
asource.clip = popOut;
} else {
if (popIn!=null)
asource.clip = popIn;
}
wasPopped = popped;
asource.Play();
}
}
// Update is called once per frame
void Update () {
position += velocity * Time.deltaTime;
position = Mathf.Max(position, 0);
if (popped){
scalePos = Mathf.Max(scalePos, position);
} else {
scalePos = Mathf.Min(scalePos, position);
}
if (rct != null)
{
rct.localScale = Vector3.Lerp(fromScale, toScale, scalePos);
rct.localRotation = Quaternion.SlerpUnclamped(Quaternion.Euler(fromRotation), Quaternion.Euler(toRotation), position);
} else {
transform.localScale = Vector3.Lerp(fromScale, toScale, scalePos);
transform.localRotation = Quaternion.SlerpUnclamped(Quaternion.Euler(fromRotation), Quaternion.Euler(toRotation), position);
}
}
}
<file_sep>/The Weirdest Shit/Assets/Textures/Graffitti/vert.sh
for i in *.jpg;
do convert "$i" -gravity center -extent 2048x2048 "$i";
done
for i in *.PNG;
do convert "$i" -gravity center -extent 2048x2048 "$i";
done
<file_sep>/The Weirdest Shit/Assets/Scripts/Dialogger.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[System.Serializable]
public struct InteractionStep {
public string Prompt;
public string[] Responses;
public float wait;
}
public class Dialogger : MonoBehaviour {
public AudioClip[] ac;
public PopSequencer sequencer;
AudioSource asource;
public Text promptText;
public Button[] responseButtons;
int current = -1;
float time;
bool showing;
bool switched;
public List<InteractionStep> Interactions;
// Use this for initialization
void Start () {
asource = GetComponent<AudioSource>();
foreach (Button butt in responseButtons) {
butt.onClick.AddListener(Press);
}
Press();
}
public void Press(){
showing = false;
sequencer.popped = false;
if (current+1<Interactions.Count)
StartCoroutine(StepAndDisplayAfter(Interactions[current+1].wait));
}
void NextStep(){
current++;
if (current<Interactions.Count){
InteractionStep istep = Interactions[current];
promptText.text = istep.Prompt;
int m = Mathf.Min(istep.Responses.Length, responseButtons.Length);
for (int i = 0; i<m; i++){
responseButtons[i].gameObject.SetActive(true);
Text text = responseButtons[i].GetComponentInChildren<Text>();
if (text!=null){
text.text = istep.Responses[i];
}
}
for (int i = m; i<responseButtons.Length;i++){
responseButtons[i].gameObject.SetActive(false);
}
}
}
IEnumerator StepAndDisplayAfter(float seconds){
yield return new WaitForSeconds(seconds);
NextStep();
sequencer.popped = true;
if (asource!=null && ac.Length>0){
asource.clip = ac.pickRandom();
asource.Play();
}
}
}
| d2b914dd00117cccbca59631a0f9ed83c5e1fbce | [
"Markdown",
"C#",
"Shell"
] | 18 | C# | TheWeirdestShit/The-Weirdest-Shit | 58c9b655c2ec87258bb7891d16055e50b2689567 | 3f73b60af84afc36da52f77e37ae437519e025eb |
refs/heads/master | <repo_name>lindbergan/FunFacts<file_sep>/app/src/main/java/com/example/lindberg/funfacts/MainActivity.java
package com.example.lindberg.funfacts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// Declare our view variables
private TextView mFactTextView;
private Button mShowFactButton;
private FactBook mFactBook;
private RelativeLayout mRelativeLayout;
private ColorWheel mColorWheel;
public static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFactBook = new FactBook();
mColorWheel = new ColorWheel();
// Assign the Views from the layout file to the corresponding variables
mFactTextView = (TextView) findViewById(R.id.factTextView);
mShowFactButton = (Button) findViewById(R.id.showFactButton);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String fact = mFactBook.getFact();
mFactTextView.setText(fact);
mRelativeLayout.setBackgroundColor(mColorWheel.changeToRandomColor());
mShowFactButton.setTextColor(mColorWheel.changeToRandomColor());
}
};
mShowFactButton.setOnClickListener(clickListener);
Toast.makeText(MainActivity.this, "Waddupp this is a toast!", Toast.LENGTH_SHORT).show();
Log.v(TAG, "yodawg");
}
}
<file_sep>/app/src/main/java/com/example/lindberg/funfacts/FactBook.java
package com.example.lindberg.funfacts;
import java.util.Random;
public class FactBook {
// Fields (Member Variables) - Properties about the object
private int[] mShownNrs = new int[0];
private final String[] mFacts = {
"Banging your head against a wall burns 150 calories an hour.",
"In the UK, it is illegal to eat mince pies on Christmas Day!",
"Pteronophobia is the fear of being tickled by feathers!",
"When hippos are upset, their sweat turns red.",
"A flock of crows is known as a murder.",
"'Facebook Addiction Disorder' is a mental disorder identified by Psychologists.",
"The average woman uses her height in lipstick every 5 years.",
"29th May is officially 'Put a Pillow on Your Fridge Day'.",
"Cherophobia is the fear of fun.",
"Human saliva has a boiling point three times that of regular water."
};
//Methods - Actions the object can take
public String getFact() {
int randNr;
Random randomGenerator = new Random();
randNr = randomGenerator.nextInt(mFacts.length);
while (containsNr(randNr)) {
randNr = randomGenerator.nextInt(mFacts.length);
}
if (isFull()) {
clearArray();
}
saveNr(randNr);
return mFacts[randNr];
}
public void saveNr(int nr) {
mShownNrs = new int[mShownNrs.length + 1];
mShownNrs[mShownNrs.length - 1] = nr;
}
public boolean containsNr(int nr) {
for (int shownNr : mShownNrs) {
if (shownNr == nr) return true;
}
return false;
}
public boolean isFull() {
return mFacts.length == mShownNrs.length;
}
public void clearArray() {
mShownNrs = new int[0];
}
public String[] getFacts() {
return mFacts;
}
}
| 9fc7d90ab1e52976a0a321433a514ae0ade5b591 | [
"Java"
] | 2 | Java | lindbergan/FunFacts | e9bb5df8b69fcf4cd39e5c377cdcb60cc65e1489 | fb7f5839b99c01b5641c6d7aa4dcb2147bc653ee |
refs/heads/master | <repo_name>ignacio19975/practicas-hechas-en-python<file_sep>/contarvocales.py
palabra=input ("Ingrese palabra")
n=0
for letra in palabra.lower() :
if (letra=="a" or letra=="e" or letra=="i" or letra=="o" or letra=="u"):
n=n+1
print ("la palabra ",palabra, "tiene ", n, "vocales")<file_sep>/verificar clave.py
clave=input("Ingrese la clave")
hay_num=False
hay_may=False
hay_min=False
largo=len(clave)>=6
for letra in clave:
if("a"<= letra and letra <= "z"):
hay_min=True
if("A" <= letra and letra <="Z"):
hay_may=True
if("0"<= letra and letra <= "9"):
hay_num=True
if(largo and hay_min and hay_may and hay_num):
print ("la clave", clave, "ES VALIDA")
else:
print ("la clave", clave, "NO ES VALIDA")<file_sep>/intercambiar lista.py
def intercambiar(lista,n1,n2):
aux=lista[n1]
lista[n1]=lista[n2]
lista[n2]=aux
s=["a","b","c","d","e","f","g"]
print("inicial ",s)
a=2
b=5
intercambiar(s,a,b)
print("modificada",s)<file_sep>/encriptar palabra.py
def letra2numero(letra,abcd):
for i in range(len(abcd)):
if(letra == abcd[i]):
return(i+1)
def palabra2numeros(cadena,abcd):
lista = []
for elem in cadena:
lista.append(letra2numero(elem,abcd))
return(lista)
def restoPalabras(listanum1,listanum2):
lista = []
for i in range(len(listanum1)):
a = listanum1[i]-listanum2[i]
if(a>0):
lista.append(a)
else:
lista.append(a+26)
return(lista)
def numero2palabra(lista,abcd):
listaPalabra = []
for i in range(len(lista)):
listaPalabra.append(abcd[lista[i]-1])
return(listaPalabra)
encriptada = "DIOSES"
clave = "BTBQDZ"
abcd=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
#encrNum = palabra2numeros(encriptada,abcd)
#claveNum = palabra2numeros(clave,abcd)
#otraLista = restoPalabras(encrNum,claveNum)
#textoOculto = numero2palabra(otraLista,abcd)
#print(textoOculto)
print(numero2palabra(restoPalabras(palabra2numeros(encriptada,abcd),
palabra2numeros(clave,abcd)),abcd))
<file_sep>/serie.py
S=0
n=int(input("cantidad de terminos"))
for i in range (1,n+1):
S=S+1/i
print("la serie para",n,"terminos es:",S)<file_sep>/factorial.py
n=int (input("Ingresa el numero al que desea calcularle su factorial"))
factorial=1
for i in range(1,n+1):
factorial=factorial*i
print ("El factorial de ",n,"es: ",factorial)<file_sep>/mezcla lista mientras y para.py
lista=[]
l=0
while l==0:
x=int(input("ingrese el termino a agregar"))
lista.append(x)
print("usted ingreso",len(lista),"terminos")
c=lista.count(4)
print(c)
if c>2:
lista.remove(4)
if x==" ":
lista.remove(" ")
print(lista)
<file_sep>/indice maximo de una lista.py
def maximo(list):
max=list[0]
for elem in list:
if(max<elem):
max=elem
return max
def indiceDelMax(lista):
pos=0
for i in range(len(lista)):
if(lista[i]>lista[pos]):
pos=i
return pos
l2=[3, 0, 8, 6, 0, 9, 1, 0, 6, 0]
m=maximo(l2)
print("el maximo de la lista",l2,"es",m)
p=indiceDelMax(l2)
print("el indice del maximo de la lista es",p)<file_sep>/reemplazar palabra.py
pal=input("Ingrese la palabra")
le=input("Ingresde letra a reemplazar")
while(len(le)!=1):
le=input("Ingresde letra a reemplazar")
nueva=""
for letra in pal:
if le.upper()==letra.upper():
nueva=nueva+"*"
else:
nueva=nueva+letra
print(nueva)<file_sep>/invertir.py
pal=input("Ingrese palabra")
nueva=""
for letra in pal:
nueva=letra+nueva
print(pal, nueva)<file_sep>/README.md
# practicas-hechas-en-python<file_sep>/apariciones.py
def cantApariciones(letra, cadena):
cant=0
for i in range(len(cadena)):
if (letra==cadena[i]):
cant+=1
return (cant)
def imprimeCantApariciones(cadena):
listaAparecidos=[]
for i in range(len(cadena)):
letra=cadena[i]
if (cantApariciones(letra,listaAparecidos)==0):
print (letra, ": ", cantApariciones(letra,cadena))
listaAparecidos.append(letra)
palabra=input("Ingrese una palabra")
print(palabra)
imprimeCantApariciones(palabra)<file_sep>/esta.py
palabra=input("Ingrese una palabra")
b=input ("Ingrese una letra")
print (palabra)
print (b)
cont=0
for letra in palabra:
if (letra==b):
cont+=1
print (b, "aparece en ",palabra, cont, "veces") | 20dbbf8159288ba954b213404569a9ddec2b98c7 | [
"Markdown",
"Python"
] | 13 | Python | ignacio19975/practicas-hechas-en-python | 05466e1d6c8f95d2f8fec8cbf41979f93b081039 | a0e85aa563adcff9d5951d2d8f30124046e20eb0 |
refs/heads/master | <file_sep>from django.db import models
# Create your models here.
class Campaign(models.Model):
external_id = models.CharField(max_length=255)
title = models.CharField(max_length=255)
multiplier = models.IntegerField()
max_options = models.IntegerField()
class CampaignOption(models.Model):
campaign = models.ForeignKey(Campaign)
title = models.CharField(max_length=255)
description = models.TextField()
display_order = models.IntegerField()
class FormSubmission(models.Model):
submission_id = models.CharField(max_length=64)
campaign = models.ForeignKey(Campaign)
item = models.ForeignKey(CampaignOption)
rank = models.IntegerField()
points = models.IntegerField()<file_sep># Django settings for rankserver project.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
if DEBUG:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
ADMINS = (
('', ''),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
<file_sep>from svc.models import Campaign, CampaignOption, FormSubmission
from django.db.models import Count, Sum
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
import uuid
def _get_by_external_id(external_id):
campaigns = Campaign.objects.filter(external_id=external_id)
if len(campaigns) > 0:
campaign = campaigns[0]
else:
campaign = None
return campaign
def campaign(request):
id = request.GET['id']
campaigns = Campaign.objects.filter(external_id=id)
if len(campaigns) > 0:
campaign = campaigns[0]
else:
campaign = None
print id
r = render_to_response('svc/campaign.json', {'campaign': campaign})
r.mimetype = "application/json"
return r
def results(request, format):
resultset = []
campaign = _get_by_external_id(request.GET['id'])
points = FormSubmission.objects.values('item_id').annotate(total_points=Sum('points')).filter(campaign=campaign).order_by('-total_points')
first_place = FormSubmission.objects.values('item_id').annotate(fp_votes=Count('points')).filter(campaign=campaign).filter(rank=1).order_by('-fp_votes')
scale = float(100)/float(points[0]['total_points'])
for i in points:
item = CampaignOption.objects.get(pk=i['item_id'])
first_place_votes = 0
for j in first_place:
if j['item_id'] == i['item_id']:
first_place_votes = j['fp_votes']
result_item = {}
result_item['id'] = item.id
result_item['title'] = item.title
result_item['description'] = item.description
result_item['rank'] = 1
result_item['points'] = i['total_points']
result_item['scaled'] = int(i['total_points'] * scale)
result_item['first_place_votes'] = first_place_votes
resultset.append(result_item)
result_dict = {'id':campaign.id, 'external_id':campaign.external_id, 'title':campaign.title, 'items':resultset}
mime = 'text/html'
if format == 'json':
mime = 'application/json'
r = render_to_response('svc/results.%s' % format, {'results':result_dict})
r.mimetype = mime
return r
@csrf_exempt
def submit(request):
def _convert_to_points(campaign, rank):
rank = int(rank)
multiplier = int(campaign.multiplier)
max_options = int(campaign.max_options)
return (max_options - rank + 1) * multiplier
if request.POST:
submission_id = uuid.uuid4()
campaign = Campaign.objects.get(pk=int(request.POST['id']))
for k,v in request.POST.items():
if k.split('_')[0] == 'item':
item_id = int(k.split('_')[1])
item_value = v
fs = FormSubmission()
fs.campaign = campaign
fs.submission_id = submission_id
fs.item = CampaignOption.objects.get(pk=item_id)
fs.rank = item_value
fs.points = _convert_to_points(fs.campaign, fs.rank)
fs.save()
if request.is_ajax():
format = 'json'
else:
format = 'html'
return HttpResponseRedirect('../results.%s?id=%s' % (format, campaign.external_id))
else:
return HttpResponseNotFound("not found")
| c749d4198ffbc13861018f1bd493e3eee0677418 | [
"Python"
] | 3 | Python | jroo/rankserver | 274b31e370a8f182e105825e569c812bef9cc1e2 | aee2584fdcda9255f82f152480b5041b9ac8d2ff |
refs/heads/master | <file_sep>#用来将训练集的groundtruth.txt的所有文件集中到TrainResylt中
import os
count=0
for parent, dirnames, filenames in os.walk('trainval'):
for dirname in dirnames:
print(len(dirnames))
for parent, dirnames, filenames in os.walk("trainval/"+dirname):
for filename in filenames:
if filename=="groundtruth.txt":
count=count+1
f = open( "TrainResult/" + dirname + ".txt", 'w')
f1=open("trainval/"+dirname+"/"+filename)
f.write(f1.read())
f.close()
f1.close()
print(count)<file_sep>import cv2
import os
def point8tobbox(array):
x = int(array[0])
y = int(array[1])
z = int(array[2] - array[0])+1
w=int(array[5]-array[3])+1
return x,y,z,w
def bboxtopoint8(bbox):
x1=float(bbox[0])
x2=float(bbox[0])+float(bbox[2])
y1=float(bbox[1])
y2=float(bbox[1])+float(bbox[3])
return x1,y1,x2,y1,x2,y2,x1,y2
def point8tobbox1(array):
x = int((array[2]+array[0])/2)
y = int((array[1]+array[5])/2)
z = int(array[2] - array[0])+1
w=int(array[5]-array[3])+1
return x,y,z,w
def bboxtopoint81(bbox):
x1=float(bbox[0])-float(bbox[2])/2
x2=float(bbox[0])+float(bbox[2])/2
y1=float(bbox[1])-float(bbox[3])/2
y2=float(bbox[1])+float(bbox[3])/2
return x1,y1,x2,y1,x2,y2,x1,y2
def Txtfile(Dir,g,dirname):
f = open(Dir+"/" + dirname + ".txt",'w')
for line in g:
for j in range(len(line)):
if j!=len(line)-1:
f.write(str(line[j])+",")
else:
f.write(str(line[j]) + "\n")
def Singletargettracking(Dir,dirname):
#tracker = cv2.TrackerMIL_create()
#tracker = cv2.TrackerKCF_create()
tracker = cv2.TrackerCSRT_create()
groundtruth=[]
# Read first frame.
frame =cv2.imread(Dir+"/"+dirname+"/00000001.jpg")
f=open(Dir+"/"+dirname+"/groundtruth.txt")
line=[float(i) for i in f.readline().split(',')]
f.close()
print(line)
groundtruth.append(line)
# Define an initial bounding box
if dirname=="uwhgtyrn":
return groundtruth
x,y,z,w=point8tobbox(line)
bbox = (x, y, z, w)
# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)
for parent, dirnames, filenames in os.walk(Dir+"/" + dirname):
for i in range(2,len(filenames)):
# Read a new frame
s=str(i)
s=(8-len(s))*'0'+s
frame = cv2.imread(Dir+"/" + dirname +"/"+s+".jpg")
# Start timer
timer = cv2.getTickCount()
# Update tracker
ok, bbox = tracker.update(frame)
temp=[i for i in bboxtopoint8(bbox)]
groundtruth.append(temp)
# print(bbox)
# Calculate Frames per second (FPS)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);
# Draw bounding box
if ok:
# Tracking success
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, (255, 0, 0), 2, 1)
# print(p1)
# print(p2)
else:
# Tracking failure
cv2.putText(frame, "Tracking failure detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255),
2)
# Display tracker type on frame
cv2.putText(frame, tracker_type + " Tracker", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);
# Display FPS on frame
cv2.putText(frame, "FPS : " + str(int(fps)), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);
# Display result
cv2.imshow("Tracking", frame)
# Exit if ESC pressed
k = cv2.waitKey(1) & 0xff
return groundtruth
if __name__ == '__main__':
Dir='test_public'
for parent, dirnames, filenames in os.walk(Dir):
for dirname in dirnames:
print(dirname)
g=Singletargettracking(Dir,dirname)
Txtfile("181250004曹克安",g,dirname)
| 9c34e5f1a3c3616303e84a4867a878917c903133 | [
"Python"
] | 2 | Python | caokean107/cv6 | 92f54d2b136e966ee14891bc551d5d372f3afc7f | 573bba4af6bc4e7f39aa7ec97200503ad3227703 |
refs/heads/master | <repo_name>gaguser/CDN<file_sep>/.optimize.sh
#!/bin/bash
for i in $(find _site/assets -name '*.png'); do optipng $i; done | 24ba8110cae83d8aa9dbf1c6f03c0a483ebbda18 | [
"Shell"
] | 1 | Shell | gaguser/CDN | a6e381417e3ce07c0941f5d8b326cf9b9aa305b4 | 579d17d6f532c1c0f302fff0e1705827cadf28d5 |
refs/heads/master | <repo_name>jcox250/bash_profile<file_sep>/bash_profile
#Show git branch
export GITAWAREPROMPT=~/.bash/git-aware-prompt
source "${GITAWAREPROMPT}/main.sh"
[[ -s "$HOME/.profile" ]] && source "$HOME/.profile" # Load the default .profile
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
export PS1="\[\033[1;35m\]\u\[\033[0m\]:\[\033[1;92m\]\W\[\033[0m\]\[$txtcyn\]\$git_branch\[$txtrst\] \\$ \[\e[0m\]"
LS_COLORS="di=46"
test -e "${HOME}/.iterm2_shell_integration.bash" && source "${HOME}/.iterm2_shell_integration.bash"
eval $(/usr/libexec/path_helper -s)
# Alias'
alias ls="ls -G"
alias docker_login="$(aws ecr get-login --no-include-email)"
alias vim="/Applications/MacVim.app/Contents/MacOS/Vim"
# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/jcox/Downloads/google-cloud-sdk/path.bash.inc' ]; then source '/Users/jcox/Downloads/google-cloud-sdk/path.bash.inc'; fi
# The next line enables shell command completion for gcloud.
if [ -f '/Users/jcox/Downloads/google-cloud-sdk/completion.bash.inc' ]; then source '/Users/jcox/Downloads/google-cloud-sdk/completion.bash.inc'; fi
# Go
export GOPATH="/Users/jcox/work/go"
export PATH=$PATH:$GOPATH/bin
# Enable git autocompletion
if [ -f ~/.git-completion.bash ]; then
. ~/.git-completion.bash
fi
# Maven
export PATH=/usr/local/apache-maven-3.5.4/bin:$PATH
# Java
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
# Python User Base for Sam CLI
USER_BASE_PATH=$(python -m site --user-base)
export PATH=$PATH:$USER_BASE_PATH/bin
VIMRUNTIMEDIR=/usr/local/share/vim/vim81
ksetctx() {
kubectl config use-context $1
}
awslogin() {
$(aws ecr get-login --no-include-email)
}
sshclone() {
git clone git@github.com:$1.git
}
clone() {
git clone https://github.com/$1
}
getuuid(){
python -c 'import uuid; print(uuid.uuid4())'
}
prettyjson() {
python -m json.tool
}
# open vscode from terminal
code () {
if [[ $# = 0 ]]
then
open -a "Visual Studio Code"
else
[[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
open -a "Visual Studio Code" --args "$F"
fi
}
# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH
| 0f64f7e8f3ae6fb1ac9a50cbfab20839cf45ef2a | [
"Shell"
] | 1 | Shell | jcox250/bash_profile | 426e8e4dc7f75008577dd38eb8749b79d758412f | 4dc0d6da2698fd98b7a6f3009d18d441741b532d |
refs/heads/master | <file_sep><?php namespace Nuwbs\Providers;
abstract class BaseProvider {
}<file_sep><?php namespace Nuwbs\Sanitizers;
class BaseSanitizer {
}<file_sep><?php namespace Nuwbs\Filters;
abstract class BaseFilters {
}<file_sep><?php namespace Nuwbs\Model;
use Illuminate\Database\Eloquent\Model;
abstract class BaseModel extends Model {
}<file_sep><?php namespace Nuwbs\Exceptions;
abstract class BaseException {
}<file_sep><?php namespace Nuwbs\Validators;
abstract class BaseValidator {
}<file_sep><?php namespace Nuwbs\ServiceProviders;
abstract class BaseServiceProvider {
}<file_sep><?php
//environment.php
return 'development';
//return 'production';
//return 'staging';<file_sep><?php
namespace Nuwbs\NewsLetters\Mailchimp;
use Mailchimp;
use Nuwbs\NewsLetters\NewsletterList as NewsletterListInterface;
class NewsletterList implements NewsletterListInterface
{
/**
* @var
*/
protected $mailchimp;
protected $list = [
// 'lessonSubscribers' => '000',
'comingSoon' => 'c6763e8b8d'
];
/**
* @param Mailchimp $mailchimp
*/
function __construct(Mailchimp $mailchimp)
{
$this->mailchimp = $mailchimp;
}
/**
* Subscribe a user to a Mailchimp list
*
* @param $listName
* @param $email
* @return mixed
*/
public function subscribeTo($listName, $email)
{
return $this->mailchimp->lists->subscribe(
$this->list[$listName],
['email' => $email],
null, //merge vars
'html',
false, // require double opt in?
true //update existing customers?
);
}
/**
* @param $list
* @param $email
* @return mixed
*/
public function unsubscribeFrom($list, $email)
{
return $this->mailchimp->lists->subscribe(
$this->list[$listName],
['email' => $email],
false, //delete the member permanently?
false, // send a goodbye email?
false //send unsubscribe notification email?
);
}
}<file_sep><?php namespace Nuwbs\Services;
class BaseService {
}<file_sep><?php namespace Nuwbs\Repositories;
abstract class BaseRepository {
}<file_sep><?php namespace Nuwbs\Newsletters;
use Illuminate\Support\ServiceProvider;
class NewsletterListServiceProvider extends ServiceProvider{
public function register()
{
$this->app->bind(
'Nuwbs\Newsletters\NewsletterList',
'Nuwbs\Newsletters\Mailchimp\NewsletterList'
);
}
}<file_sep><?php namespace Nuwbs\Utilities;
abstract class BaseUtility {
}<file_sep>
Theme Style - http://leaders.modernwebtemplates.com/
Business Models:
* pluralsight.com
- Authors
- Record whats on your mind and get paid for it
- Kids Courses
- Study Groups - http://www.pluralsight.com/training/Community/StudyGroups
- https://www.youtube.com/watch?v=-b02xZ55rVg
- https://www.youtube.com/watch?v=B1JeuKOm--M
Envato.com
- http://themeforest.net/make_money/become_an_author
* Laracast.com
Price Competitors:
Lynda.com - http://www.lynda.com/plans
* Work for NUWBS
- feel as though your work is impacting lives in a positive way
* Main Banner
* Why would I subscribe.
Slogans
- You wanna code, We wanna teach... I think we can work this out.
SAAS
* newrelic.com
* bugsnag.com
* Mailchimp (new letters)
* mandrillapp.com (good for transanctions [signup (send hello), cancel (send goodbye)])
* nuwbs.uservoice.com<file_sep><?php
/**
* Created by PhpStorm.
* User: dustinwoodard
* Date: 7/1/14
* Time: 10:58 PM
*/
namespace Nuwbs\Notifications\Mailchimp;
use Mailchimp;
use Nuwbs\Notifications\ComingSoon as ComingSoonInterface;
class ComingSoon implements ComingSoonInterface
{
/**
* List ID
*/
const COMING_SOON_ID = 'c6763e8b8d';
protected $mailchimp;
function __construct(Mailchimp $mailchimp)
{
$this->mailchimp = $mailchimp;
}
/**
* @param $title
* @param $body
* @return mixed
*/
public function notify($title, $body)
{
/** @var $options Array */
$options = [
'list_id' => self::COMING_SOON_ID,
'subject' => 'Coming Soon: ' . $title,
'from_name' => "NUWBS",
'from_email' => '<EMAIL>',
'to_name' => 'Nuwbs Subscriber'
];
/** @var $content Array */
$content = [
'html' => $body,
'text' => strip_tags($body)
];
// Create a new campaign
$campaign = $this->mailchimp->campaigns->create('regular', $options, $content);
$this->mailchimp->campaigns->send($campaign['id']);
}
}<file_sep><?php namespace Nuwbs\Repositories;
/**
* Class DbRepository
* @package Nuwbs\Repositories
*/
class DbRepository extends BaseRepository {
function __construct() {
dd('Repo');
}
}<file_sep>nuwbs.net
=========
<file_sep><?php namespace Nuwbs\Observers;
abstract class BaseObserver {
}<file_sep><?php namespace Nuwbs\Notifications;
use Illuminate\Support\ServiceProvider;
class NotificationsServiceProvider extends ServiceProvider{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bind(
'Nuwbs\Notifications\ComingSoon',
'Nuwbs\Notifications\Mailchimp\LessonPublished'
);
}
} | ef46ef821281fb572bd2a8a4abab2da9dd85e479 | [
"Markdown",
"Text",
"PHP"
] | 19 | PHP | dwoodard/nuwbs.net | 7c513a89c969af1bef20d4437a14dc2de0b623a1 | e9cfbd8cdd730e7d619151c7d426cf56786f78f0 |
refs/heads/master | <repo_name>victormath12/yoga<file_sep>/README.md
<p align="center">
<img src="packages/doc/src/images/lotus.png" />
</p>
[](#contributors)

Design system at Gympass, our main intent is to support our projects.
We have open-sourced our project for those who are interested in checkout how we do things and organize our code and documentation here.
### What does it mean?
> Yoga is a scientific system of practices made to help each one of us achieve our highest potential and experience.
## Documentation
Yoga is documented at [http://gympass.github.io/yoga](https://gympass.github.io/yoga).
## Architecture
Our codebase is a monorepo and individually versioned libraries.
Here's an overview of our packages:
| Package | Version | Size |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| [`@gympass/yoga`](/packages/yoga) | [](https://www.npmjs.com/package/@gympass/yoga) | [](https://bundlephobia.com/result?p=@gympass/yoga) |
| [`@gympass/yoga-tokens`](/packages/tokens) | [](https://www.npmjs.com/package/@gympass/yoga-tokens) | [](https://bundlephobia.com/result?p=@gympass/yoga-tokens) |
| [`@gympass/yoga-common`](/packages/common) | [](https://www.npmjs.com/package/@gympass/yoga-common) | [](https://bundlephobia.com/result?p=@gympass/yoga-common) |
| [`@gympass/yoga-icons`](/packages/icons) | [](https://www.npmjs.com/package/@gympass/yoga-icons) | [](https://bundlephobia.com/result?p=@gympass/yoga-icons) |
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://twitter.com/ggdaltoso"><img src="https://avatars0.githubusercontent.com/u/6536985?v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Gympass/yoga/commits?author=ggdaltoso" title="Code">💻</a> <a href="#ideas-ggdaltoso" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/Gympass/yoga/commits?author=ggdaltoso" title="Documentation">📖</a> <a href="https://github.com/Gympass/yoga/pulls?q=is%3Apr+reviewed-by%3Aggdaltoso" title="Reviewed Pull Requests">👀</a></td>
<td align="center"><a href="https://twitter.com/_allyssonsantos"><img src="https://avatars1.githubusercontent.com/u/13424727?v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Gympass/yoga/commits?author=allyssonsantos" title="Code">💻</a> <a href="#ideas-allyssonsantos" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/Gympass/yoga/commits?author=allyssonsantos" title="Documentation">📖</a> <a href="https://github.com/Gympass/yoga/pulls?q=is%3Apr+reviewed-by%3Aallyssonsantos" title="Reviewed Pull Requests">👀</a></td>
<td align="center"><a href="https://br.linkedin.com/in/victor-matheus-jesus-caetano-9633b5118"><img src="https://avatars0.githubusercontent.com/u/11219999?v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Gympass/yoga/commits?author=victormath12" title="Code">💻</a> <a href="#ideas-victormath12" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/Gympass/yoga/commits?author=victormath12" title="Documentation">📖</a> <a href="https://github.com/Gympass/yoga/pulls?q=is%3Apr+reviewed-by%3Avictormath12" title="Reviewed Pull Requests">👀</a></td>
<td align="center"><a href="https://twitter.com/oalanoliv"><img src="https://avatars3.githubusercontent.com/u/4368481?v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Gympass/yoga/commits?author=alan-oliv" title="Code">💻</a> <a href="#ideas-alan-oliv" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/Gympass/yoga/commits?author=alan-oliv" title="Documentation">📖</a> <a href="https://github.com/Gympass/yoga/pulls?q=is%3Apr+reviewed-by%3Aalan-oliv" title="Reviewed Pull Requests">👀</a></td>
<td align="center"><a href="http://linkedin.com/in/kaicbastidas"><img src="https://avatars2.githubusercontent.com/u/9873486?v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Gympass/yoga/commits?author=tcK1" title="Code">💻</a> <a href="#ideas-tcK1" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/Gympass/yoga/commits?author=tcK1" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/luispiresgympass"><img src="https://avatars0.githubusercontent.com/u/58981184?v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Gympass/yoga/commits?author=luispiresgympass" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/invilliaanajacobsen"><img src="https://avatars2.githubusercontent.com/u/57181206?v=4" width="100px;" alt=""/><br /><sub><b>invilliaanajacobsen</b></sub></a><br /><a href="https://github.com/Gympass/yoga/issues?q=author%3Ainvilliaanajacobsen" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="http://www.caioalexandre.com"><img src="https://avatars1.githubusercontent.com/u/31045534?v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/Gympass/yoga/commits?author=caioalexandrebr" title="Documentation">📖</a></td>
</tr>
</table>
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
<file_sep>/packages/yoga/src/Input/web/Input.test.jsx
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { ThemeProvider, Input } from '../..';
describe('<Input />', () => {
describe('Snapshots', () => {
it('should match with default input', () => {
const { container } = render(
<ThemeProvider>
<Input />
</ThemeProvider>,
);
expect(container).toMatchSnapshot();
});
it('should match with label', () => {
const { container } = render(
<ThemeProvider>
<Input label="Input" />
</ThemeProvider>,
);
expect(container).toMatchSnapshot();
});
it('should match with disabled input', () => {
const { container } = render(
<ThemeProvider>
<Input disabled />
</ThemeProvider>,
);
expect(container).toMatchSnapshot();
});
it('should match with error', () => {
const { container } = render(
<ThemeProvider>
<Input error="Error message" />
</ThemeProvider>,
);
expect(container).toMatchSnapshot();
});
it('should match with helper text and max length', () => {
const { container } = render(
<ThemeProvider>
<Input helper="Helper text" maxLength={20} />
</ThemeProvider>,
);
expect(container).toMatchSnapshot();
});
it('should match with full width', () => {
const { container } = render(
<ThemeProvider>
<Input label="Label" full />
</ThemeProvider>,
);
expect(container).toMatchSnapshot();
});
});
describe('Events', () => {
it('should call onChange', () => {
const onChangeMock = jest.fn();
const { getByTestId } = render(
<ThemeProvider>
<Input label="Input" onChange={onChangeMock} data-testid="input" />
</ThemeProvider>,
);
fireEvent.change(getByTestId('input'), { target: { value: 'foo' } });
expect(onChangeMock).toHaveBeenCalled();
});
it('should call onFocus', () => {
const onFocusMock = jest.fn();
const { getByTestId } = render(
<ThemeProvider>
<Input label="Input" data-testid="input" onFocus={onFocusMock} />
</ThemeProvider>,
);
fireEvent.focus(getByTestId('input'));
expect(onFocusMock).toHaveBeenCalled();
});
it('should call onBlur', () => {
const onBlurMock = jest.fn();
const { getByTestId } = render(
<ThemeProvider>
<Input label="Input" data-testid="input" onBlur={onBlurMock} />
</ThemeProvider>,
);
fireEvent.focus(getByTestId('input'));
fireEvent.blur(getByTestId('input'));
expect(onBlurMock).toHaveBeenCalled();
});
});
describe('maxLength', () => {
it('should update maxLength counter when add character', () => {
const { getByTestId, getByText } = render(
<ThemeProvider>
<Input label="Input" data-testid="input" maxLength={10} />
</ThemeProvider>,
);
expect(getByText('0/10').textContent).toBe('0/10');
fireEvent.change(getByTestId('input'), { target: { value: 'foo' } });
expect(getByText('3/10').textContent).toBe('3/10');
});
});
describe('clean button', () => {
it('should call onClean when press clean button', () => {
const onCleanMock = jest.fn();
const { getByTestId, getByRole } = render(
<ThemeProvider>
<Input label="Input" data-testid="input" onClean={onCleanMock} />
</ThemeProvider>,
);
fireEvent.change(getByTestId('input'), { target: { value: 'foo' } });
fireEvent.click(getByRole('button'));
expect(onCleanMock).toHaveBeenCalledWith('');
});
});
});
| 8ac29a272ee37beabf291272353c6080de6ec6f0 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | victormath12/yoga | 2d6ca378466d0ebe71a26fe762a9a3c573551a4b | 17333c697aa76b483a198a72dab3dd5cb4091fbf |
refs/heads/master | <repo_name>aion3181/Ansible<file_sep>/day-4/callback_plugins/demo.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.callback import CallbackBase
import sys
import json
RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'demo'
def show(self, task, host, result, caption):
buf = "<<< {0} | {1} | {2} | rc={3} >>>\n".format(task, host, caption,
result.get('rc', 'n/a'))
buf1 = ""
buf += result.get('stdout', '')
if not "% Total" in result.get('stderr', ''):
buf += result.get('stderr', '')
if not type(result.get('msg', '')) == type(dict()):
buf += result.get('msg', '')
else:
buf1 = result.get('msg', '')
print((buf + "\n"), buf1)
def v2_runner_on_failed(self, result, ignore_errors=False):
sys.stdout.write(RED)
self.show(result._task, result._host.get_name(), result._result, "FAILED")
sys.stdout.write(RESET)
def v2_playbook_on_notify(self, result, handler):
host = result._host.get_name()
sys.stdout.write(CYAN)
self.show(result._host.get_name(), handler)
sys.stdout.write(RESET)
def v2_playbook_on_handler_task_start(self, task):
pass
def v2_runner_on_ok(self, result):
sys.stdout.write(GREEN)
self.show(result._task, result._host.get_name(), result._result, "OK")
sys.stdout.write(RESET)
def v2_runner_on_skipped(self, result):
sys.stdout.write(BLUE)
self.show(result._task, result._host.get_name(), result._result, "SKIPPED")
sys.stdout.write(RESET)
def v2_runner_on_unreachable(self, result):
sys.stdout.write(BLUE)
self.show(result._task, result._host.get_name(), result._result, "UNREACHABLE")
sys.stdout.write(RESET)
<file_sep>/day3/README.md
# Ansible
# Lab Work Task. Web Server Provisioning
## Review
## Developing custom modules and filters. Learning by doing.
## Task
#### On Host Node (Control Machine):
#### Develop custom filter to select an url to download mongodb depends on OS name and S/W version from https://www.mongodb.org/dl/linux/
#### Requirements:
#### - Write a playbook (name: mongodb.yml) to prove that this module works
#### - At least 9 versions of MongoDB for 3 different Linux distributives (list with links)
#### - Filter should process a list of urls and takes 3 options: os_family (discovered by ansible, variable, produced by setup module), os release number and mongodb_version (set in play vars)
#### See example in Appendix A
#### Develop custom module to manage VirtualBox:
#### Arguments:
#### path to vagrantfile
#### state: started, stopped, destroyed
#### Return values:
#### state: running, stopped, not created
#### - ip address, port
#### - path to ssh key file
#### - username to connect to VM
#### - os_name
#### - RAM size
#### Errors:
#### - file doesn’t exists
#### - failed on creation
#### - etc
#### Create a playbook (name: stack.yml) to provision Tomcat stack (nginx + tomcat) on VirtualBox VM
#### Requirements:
#### - 2 Plays: provision VM, roll out Tomcat stack (using roles from previous lab work)
#### - 2nd play should work with dynamically composed Inventory (connection settings to VM), http://docs.ansible.com/ansible/add_host_module.html
#### Verification Procedure: playbook will be checked by instructor’s CI system as follows:
#### 5.1 Connect to student’s host by ssh
#### 5.2 Go into the folder ...
#### 5.3 Destroy: vagrant destroy
#### 5.4 Execute VM provisioning: ansible-playbook stack.yml -i localhost, -c local -vv
#### 5.5 If previous steps are done successfully, instructor will check report (pdf-file)
#### Feedback: report issues/problems you had during the development of playbook and time spent for development.
# Results:
## [filter_plugins/filter_plugins.py](https://github.com/aion3181/Ansible/blob/master/day3/filter_plugins/filter_plugins.py)
## [mongodb.yml](https://github.com/aion3181/Ansible/blob/master/day3/mongodb.yml)
## [library/vm_vagrant](https://github.com/aion3181/Ansible/blob/master/day3/library/vm_vagrant)
## [stack.yml](https://github.com/aion3181/Ansible/blob/master/day3/stack.yml)
<file_sep>/day1/README.md
# Lab Work Task. Tomcat AS Provisioning
## Install Ansible v2.3.1 with python pip. Report details where ansible has been installed.
<img src="pics/1.jpg">
<img src="pics/2.jpg">
## Spin up clear CentOS7 VM using vagrant (“vagrant init sbeliakou/centos-7.3-minimal”). Verify connectivity to the host using ssh keys (user: vagrant)
[Vagrantfile](https://github.com/aion3181/Ansible/blob/master/day1/Vagrantfile)
```
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://atlas.hashicorp.com/search.
config.vm.define "tomcat" do |tomcat|
tomcat.vm.box = "tomcat"
tomcat.vm.hostname = 'tomcat'
tomcat.vm.box_url = "/home/student/cm/ansible/day-1/sbeliakou-vagrant-centos-7.3-x86_64-minimal.box"
tomcat.vm.network "private_network", ip: "192.168.56.10"
tomcat.vm.provider :virtualbox do |vb|
vb.memory = "2048"
end
end
end
```
## Create ansible inventory file (name: inventory) with remote host connection details.
[inventory](https://github.com/aion3181/Ansible/blob/master/day1/inventory)
```
[all]
tomcat ansible_port=22 ansible_host=192.168.56.10 ansible_connection=ssh ansible_user=vagrant
ansible_ssh_private_key_file=.vagrant/machines/tomcat/virtualbox/private_key
```
### Test ansible connectivity to the VM with ad-hoc command: $ ansible VM-name -i inventory -m setup
<img src="pics/3.jpg">
### Find out host details:
<img src="pics/4.jpg">
## Develop a playbook (name: tomcat_provision.yml) which is supposed to run against any host (specified in inventory)
[tomcat_provision.yml](https://github.com/aion3181/Ansible/blob/master/day1/tomcat_provision.yml)
```
- name: host details
hosts: all
tasks:
- name: Number of CPUs
debug: var=ansible_processor_cores
- name: Host name
debug: var=ansible_hostname
- name: Host IP(s)
debug: var=ansible_default_ipv4['address']
- name: Total RAM
debug: var=ansible_memtotal_mb
- name: provisioning
hosts: all
vars:
tomcat_version: 8.5.0
java_version: java-1.8.0-openjdk-devel.x86_64
become: true
tasks:
- name: Ensure java is installed
yum:
name: "{{java_version}}"
state: present
- name: Ensure tomcat_as_group group exist
group:
name: tomcat_as_group
state: present
- name: Ensure tomcat_as user exist
user:
name: tomcat_as
group: tomcat_as_group
state: present
- name: Download Tomcat AS
get_url:
url: http://archive.apache.org/dist/tomcat/tomcat-8/v{{tomcat_version}}
/bin/apache-tomcat-{{tomcat_version}}.tar.gz
dest: /home/vagrant/
- name: Ensure /opt/tomcat/$version is present
file:
path: /opt/tomcat/{{tomcat_version}}
owner: tomcat_as
group: tomcat_as_group
state: directory
mode: 0755
- name: Ensure tomcat is unarchived
unarchive:
remote_src: yes
src: /home/vagrant/apache-tomcat-{{tomcat_version}}.tar.gz
dest: /home/vagrant/
owner: tomcat_as
group: tomcat_as_group
- name: Copy tomcat to (CATALINA_HOME)=/opt/tomcat/$version
shell: cp -R /home/vagrant/apache-tomcat-{{tomcat_version}}/*
/opt/tomcat/{{tomcat_version}} && chown -R tomcat_as:tomcat_as_group
/opt/tomcat/{{tomcat_version}}
- name: Ensure tomcat.service script is present
copy:
src: tomcat.service
dest: /etc/systemd/system/tomcat.service
- name: Ensure tomcat.service script have right ExecStart
lineinfile:
path: /etc/systemd/system/tomcat.service
regexp: '^ExecStart='
line: 'ExecStart=/opt/tomcat/{{tomcat_version}}/bin/startup.sh'
- name: Ensure tomcat.service script have right ExecStop
lineinfile:
path: /etc/systemd/system/tomcat.service
regexp: '^ExecStop='
line: 'ExecStop=/opt/tomcat/{{tomcat_version}}/bin/shutdown.sh'
- name: Ensure tomcat.service script have right User
lineinfile:
path: /etc/systemd/system/tomcat.service
regexp: '^User='
line: 'User=tomcat_as'
- name: Ensure tomcat.service script have right Group
lineinfile:
path: /etc/systemd/system/tomcat.service
regexp: '^Group='
line: 'Group=tomcat_as_group'
- name: Ensure tomcat.service is enabled
systemd:
name: tomcat.service
state: started
daemon_reload: yes
enabled: yes
- name: Ensure tomcat is started
service:
name: tomcat
state: started
- name: Checking if tomcet.service is active
shell: if [[ `systemctl is-active tomcat.service` -ne 'active' ]]; then exit 1; fi
- name: Check (runtime)
shell: systemctl status tomcat.service | grep Active
- name: Check http responce
shell: if [[ `curl -IL localhost:8080 | grep "HTTP/1.1 200"` > 0 ]];
then echo 'success'; else exit1; fi
```
<img src="pics/5.jpg">
<img src="pics/6.jpg">
<file_sep>/day2/roles/java/README.md
### installs java
<file_sep>/day3/filter_plugins/filter_plugins.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import errors
def get_mongo_src(arg, os_family, os_release, mongodb_version):
osv = os_family + os_release
for lin in arg:
if (osv in lin) and (mongodb_version in lin):
result = lin
return result
class FilterModule(object):
def filters(self):
return {
'get_mongo_src': get_mongo_src
}
<file_sep>/day3/roles/nginx/README.md
### Installing nginx to proxy tomcat<file_sep>/mntlab-exam-hpashuto/library/war_deploy
#!/bin/bash
### Check arguments #######
source $1
if [ -z "$url" ]; then
printf '{"failed": true, "msg": "missing required arguments: url"}'
exit 1
fi
if [ -z "$war" ]; then
printf '{"failed": true, "msg": "missing required arguments: war"}'
exit 1
fi
if [ -z "$user" ]; then
printf '{"failed": true, "msg": "missing required arguments: user"}'
exit 1
fi
if [ -z "$pass" ]; then
printf '{"failed": true, "msg": "missing required arguments: pass"}'
exit 1
fi
##########################
if [[ ! -f $war ]]; then
msg="no such file"
deployed="0"
else
msg=$(curl -s --upload-file "${war}" -u "${user}":"${pass}" "${url}/manager/text/deploy?path=/mnt-exam&update=true" 2>&1)
deployed="1"
if [[ $msg == "OK - Deployed application at context path /mnt-exam" ]]; then
deployed="ok"
fi
fi
###########################
printf '{"msg": "%s", "deployed": "%b"}' "$msg" "$deployed"
exit 0<file_sep>/day3/roles/java_test/README.md
### only checks that java installed and running properly<file_sep>/mntlab-exam-hpashuto/roles/tomcat_test/README.md
### only checks that tomcat installed and running properly<file_sep>/day2/README.md
# Lab Work Task. Web Server Provisioning
### Review
#### Using Ansible v2.3.1 for provisioning nginx + tomcat application stack.
#### Learning by doing.
### Task
#### Create ansible inventory file (name: inventory) with remote host connection details:
###### Remote VM hostname/ip/port
###### Remote ssh login username
###### Connection type
#### Develop a playbook (name: site.yml) which is supposed to run against any host (specified in inventory)
#### Develop roles:
###### - java (installs java)
###### - java_test (does only checks that java installed and running properly)
###### - tomcat (installs tomcat)
###### - tomcat_test (does only checks that tomcat installed and running properly)
###### - nginx (installs nginx)
###### - nginx_test (does only checks that nginx installed and running properly)
#### Playbook should consist of 2 Plays:
###### - Installation
###### - Verification
#### Use handlers to manage tomcat/nginx configuration changes
#### Use module debug to check configuration during the installation
#### Define play/roles variables (at least):
###### - tomcat_version
###### - tomcat_home
###### - tomcat_user
###### - tomcat_group
###### - java_version
#### Every task/handler should have a name section with details of task purpose.
#### Software installation requirements:
##### Tomcat AS should be installed from sources (tar.gz) – download from the official site (http://archive.apache.org/dist/tomcat/).
##### Tomcat AS should be owned (and run) by user specified in variable (default: tomcat_as:tomcat_as_group).
##### Tomcat AS version should be 7.x, 8.x (at least 5 versions), exact version to be installed is taken from appropriate variable.
##### Tomcat installation folder (CATALINA_HOME) is /opt/tomcat/$version, where $version is the version of tomcat defined in playbook.
##### Java can be installed from CentOS Repositories
##### Use module yum to install Nginx
##### Use module template for management of nginx cofigs
##### Tomcat home page should be available on port 80 (accessible from Control Machile) via nginx.
# Result:
### [Vagrantfile](https://github.com/aion3181/Ansible/blob/master/day2/Vagrantfile)
<img src="pics/1.jpg">
<img src="pics/2.jpg">
### [site.yml:](https://github.com/aion3181/Ansible/blob/master/day2/site.yml)
```
- name: Ensuring connectivity to the host using ssh keys
hosts: tomcat
tasks:
- name: Host name
debug: var=ansible_hostname
- name: Installation
hosts: tomcat
become: true
roles:
- nginx
- name: Verification
hosts: tomcat
roles:
- nginx_test
```
### [inventory:](https://github.com/aion3181/Ansible/blob/master/day2/inventory)
```
localhost
[tomcat]
192.168.56.10
[tomcat:vars]
ansible_port=22
ansible_connection=ssh
ansible_user=vagrant
ansible_ssh_private_key_file=.vagrant/machines/tomcat/virtualbox/private_key
```
## ===============================================================
## java role:
### [roles/java/defaults/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/java/defaults/main.yml)
```
java_version: java-1.6.0-openjdk-devel.x86_64
```
### [roles/java/tasks/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/java/tasks/main.yml)
```
- name: Ensure java is installed
yum:
name: "{{java_version}}"
state: present
- name: Java info
shell: java -version
register: output
- name: Installed java version
debug: var=output
```
### [roles/java/vars/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/java/vars/main.yml)
```
java_version: java-1.7.0-openjdk-devel.x86_64
```
## ===============================================================
## java_test role:
### [roles/java_test/tasks/main.yml:](https://github.com/aion3181/Ansible/tree/master/day2/roles/java_test/tasks)
```
- name: Checking java installation
shell: java -version
register: output4
- name: Show result
debug: var=output4
```
## ===============================================================
## nginx role:
### [roles/nginx/handlers/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/nginx/handlers/main.yml)
```
- name: nginx_service
service:
name: nginx
state: started
- name: nginx_restart
service:
name: nginx
state: restarted
```
### [roles/nginx/meta/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/nginx/meta/main.yml)
```
dependencies:
- { role: tomcat }
```
### [roles/nginx/tasks/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/nginx/tasks/main.yml)
```
- name: Ensure nginx is installed
yum:
name: nginx
state: present
notify: nginx_service
- name: Ensure nginx config is updated
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify:
- nginx_restart
- name: Nginx config
shell: cat /etc/nginx/nginx.conf
register: output2
- name: Show Nginx config
debug: var=output2
```
## ===============================================================
## nginx_test role:
### [roles/nginx_test/meta/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/nginx_test/meta/main.yml)
```
dependencies:
- { role: tomcat_test }
```
### [roles/nginx_test/tasks/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/nginx_test/tasks/main.yml)
```
- name: Checking nginx service
shell: if [[ `systemctl is-active tomcat.service` -ne 'active' ]];
then exit 1; fi
- name: Check nginx http responce
shell: if [[ `curl -IL localhost:80 | grep "HTTP/1.1 200"` > 0 ]];
then echo 'success'; else exit 1; fi
- name: Check nginx http proxy page
shell: if [[ `curl localhost:80 | grep "Apache Tomcat/"` > 0 ]];
then echo 'success'; else exit 1; fi
```
## ===============================================================
## tomcat role:
### [roles/tomcat/defaults/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/tomcat/defaults/main.yml)
```
tomcat_version: 7
tomcat_release: 7.0.50
tomcat_home: /opt/tomcat/{{tomcat_release}}/
tomcat_name: apache-tomcat-{{tomcat_release}}
tomcat_url: http://archive.apache.org/dist/tomcat/tomcat-{{tomcat_version}}
/v{{tomcat_release}}/bin/{{tomcat_name}}.tar.gz
tomcat_user: tomcat_as
tomcat_group: tomcat_as_group
```
### [roles/tomcat/handlers/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/tomcat/handlers/main.yml)
```
- name: systemd_service
systemd:
name: tomcat.service
state: started
daemon_reload: yes
enabled: yes
- name: tomcat_service
service:
name: tomcat
state: started
```
### [roles/tomcat/meta/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/tomcat/meta/main.yml)
```
dependencies:
- { role: java, java_version: java-1.8.0-openjdk-devel.x86_64 }
```
### [roles/tomcat/tasks/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/tomcat/tasks/main.yml)
```
- name: Ensure tomcat_group exist
group:
name: "{{tomcat_group}}"
state: present
- name: Ensure tomcat_user exist
user:
name: "{{tomcat_user}}"
group: "{{tomcat_group}}"
state: present
- name: Download Tomcat AS
get_url:
url: "{{tomcat_url}}"
dest: /home/vagrant/
- name: Ensure CATALINA_HOME is present
file:
path: "{{tomcat_home}}"
owner: "{{tomcat_user}}"
group: "{{tomcat_group}}"
state: directory
mode: 0755
- name: Ensure tomcat is unarchived
unarchive:
remote_src: yes
src: /home/vagrant/{{tomcat_name}}.tar.gz
dest: "{{tomcat_home}}"
owner: "{{tomcat_user}}"
group: "{{tomcat_group}}"
- name: Ensure owner of tomcat files is "{{tomcat_user}}"
shell: chown -R "{{tomcat_user}}":{{tomcat_group}} {{tomcat_home}}{{tomcat_name}}
- name: Ensure tomcat.service script is present
template:
src: templates/tomcat.service.j2
dest: /etc/systemd/system/tomcat.service
notify:
- systemd_service
- tomcat_service
- name: tomcat.service config
shell: cat /etc/systemd/system/tomcat.service
register: output3
- name: Show tomcat.service config
debug: var=output3
- name: force all notified handlers to run at this point, not waiting for normal sync points
meta: flush_handlers
- name: Checking if tomcet.service is active
shell: if [[ `systemctl is-active tomcat.service` -ne 'active' ]]; then exit 1; fi
```
### [roles/tomcat/vars/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/tomcat/vars/main.yml)
```
tomcat_version: 8
tomcat_release: 8.5.0
```
## ===============================================================
## tomcat_test role:
### [roles/tomcat_test/meta/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/tomcat_test/meta/main.yml)
```
dependencies:
- { role: java_test }
```
### [roles/tomcat_test/tasks/main.yml:](https://github.com/aion3181/Ansible/blob/master/day2/roles/tomcat_test/tasks/main.yml)
```
- name: Checking tomcat service
shell: if [[ `systemctl is-active tomcat.service` -ne 'active' ]];
then exit 1; fi
- name: Check tomcat http responce
shell: if [[ `curl -IL localhost:8080 | grep "HTTP/1.1 200"` > 0 ]];
then echo 'success'; else exit 1; fi
- name: Check tomcat http page
shell: if [[ `curl localhost:8080 | grep "Apache Tomcat/"` > 0 ]];
then echo 'success'; else exit 1; fi
```
## ===============================================================
## templates:
### [templates/nginx.conf.j2:](https://github.com/aion3181/Ansible/blob/master/day2/templates/nginx.conf.j2)
### [templates/tomcat.service.j2:](https://github.com/aion3181/Ansible/blob/master/day2/templates/tomcat.service.j2)
```
# Systemd unit file for tomcat
[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target
[Service]
Type=forking
ExecStart={{tomcat_home}}{{tomcat_name}}/bin/startup.sh
ExecStop={{tomcat_home}}{{tomcat_name}}/bin/shutdown.sh
User={{tomcat_user}}
Group={{tomcat_group}}
UMask=0007
RestartSec=10
Restart=always
[Install]
WantedBy=multi-user.target
```
<file_sep>/mntlab-exam-hpashuto/roles/nginx_test/README.md
### only checks that nginx installed and running properly<file_sep>/day1/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://atlas.hashicorp.com/search.
config.vm.define "tomcat" do |tomcat|
tomcat.vm.box = "tomcat"
tomcat.vm.hostname = 'tomcat'
tomcat.vm.box_url = "/home/student/cm/ansible/day-1/sbeliakou-vagrant-centos-7.3-x86_64-minimal.box"
tomcat.vm.network "private_network", ip: "192.168.56.10"
tomcat.vm.provider :virtualbox do |vb|
vb.memory = "2048"
end
end
end
<file_sep>/mntlab-exam-hpashuto/library/vm_vagrant
#!/bin/bash
function status_VM
{
if [[ `vagrant status | grep "running (virtualbox)"` > 0 ]]; then
status="running"
elif [[ `vagrant status | grep "poweroff (virtualbox)"` > 0 ]]; then
status="stopped"
elif [[ `vagrant status | grep "not created (virtualbox)"` > 0 ]]; then
status="not created"
else
status="Unexpected error"
fi
}
function start_VM
{
status_VM
if [[ $status != "running" ]]; then
a=$(vagrant up)
changed="true"
status_VM
msg="Started"
if [[ $status -ne "running" ]]; then
msg="failed: Something goes wrong on running stage"
fi
else
msg="Already started"
status_VM
fi
}
function stop_VM
{
status_VM
if [[ $status != "stopped" ]]; then
start_VM
a=$(vagrant halt)
changed="true"
status_VM
msg="Stopped"
if [[ $status != "stopped" ]]; then
msg="failed: Something goes wrong on stopping stage"
fi
else
msg="Already stopped"
status_VM
fi
}
function destroy_VM
{
stop_VM
status_VM
if [[ $status != "not created" ]]; then
a=$(vagrant destroy -f)
changed="true"
status_VM
msg="VM destroyed"
if [[ $status != "not created" ]]; then
msg="failed: Something goes wrong on destroying stage"
fi
else
msg="There is no VM"
status_VM
fi
}
### default output ###
changed="false"
msg=""
status=""
###########################
### Check arguments #######
source $1
if [ -z "$path" ]; then
printf '{"failed": true, "msg": "missing required arguments: path"}'
exit 1
fi
if [ -z "$state" ]; then
printf '{"failed": true, "msg": "missing required arguments: state"}'
exit 1
fi
##########################
### Check if Vagrantfile exist ###
b=`basename $path`
if [[ $b -ne "Vagrantfile" ]]; then
vagrantfolder=$path
path="$path/Vagrantfile"
else
vagrantfolder=`dirname $path`
fi
if [[ ! -f $path ]]; then
printf '{"failed": "true", "path": '$path', "msg": "missing Vagrantfile"}'
exit 1
fi
cd $vagrantfolder
############################
#### Return values #########
# ip address, port
ip_ad=`cat Vagrantfile | grep ip: | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"`
port=22
# path to ssh key file
if [[ `cat Vagrantfile | grep config.vm.define` > 0 ]]; then
vmn=`cat Vagrantfile | grep config.vm.define | grep -oE "\"[a-A]+\""`
vmn=${vmn:1:-1}
ssh_key_file="${vagrantfolder}/.vagrant/machines/${vmn}/virtualbox/private_key"
else
ssh_key_file="${vagrantfolder}/.vagrant/machines/default/virtualbox/private_key"
fi
# username to connect to VM
username="vagrant"
# os_name
os_name=$(basename `cat Vagrantfile | grep vm.box_url | grep -oE "\".+\""`)
os_name=${os_name:0:-1}
# RAM size
RAM=`cat Vagrantfile | grep vb.memory | grep -oE "\b([0-9]){4}\b"`
###########################
case $state in
started)
start_VM
;;
stopped)
stop_VM
;;
destroyed)
stop_VM
destroy_VM
;;
*)
printf '{"failed": true, "msg": "invalid state: %s"}' "$state"
exit 1
;;
esac
printf '{"changed": "%s", "msg": "%s", "status": "%s", "username": "%s", "RAM": "%b", "IP": "%s", "port": "%s", "ssh_key_file": "%s", "os_name": "%s"}' "$changed" "$msg" "$status" "$username" "$RAM" "$ip_ad" "$port" "$ssh_key_file" "$os_name"
exit 0<file_sep>/day3/roles/tomcat/README.md
### installs tomcat 7.0.50/8.5.0
| 3a0e848e12383e4bf7c69807b5037da504b6874b | [
"Markdown",
"Python",
"Ruby",
"Shell"
] | 14 | Python | aion3181/Ansible | eaa382d5dfce3c75ee0f4f6b2b00f843e6d74933 | 59e3f7cefe0f9700767d23333e2636045a5d51e7 |
refs/heads/master | <repo_name>carrilhorafael/nuuvem-challenge<file_sep>/app/views/orders/_order.json.jbuilder
json.extract! order, :id, :client, :product_id, :quantity, :created_at, :updated_at
json.url order_url(order, format: :json)
<file_sep>/README.md
# Nuuvem Dev Challenge
## Sobre o teste
É necessário gerar um projeto em Rails Full Stack capaz de gerenciar pedidos de restaurantes, utilizando, como entrada de informações arquivos de texto separados por tab.
## Documentação do projeto
1. Após baixar o projeto, utilize o comando abaixo para instalar as dependencias do projeto e criar o banco de dados.
```bash
bundle
rails db:migrate
```
2. Os models do back end estão cobertos por testes usando a gem RSpec. Para rodar os testes criados, utilize o comando abaixo.
```bash
rspec
```
3. Inicialize o projeto com o comando abaixo, e entre em localhost:3000 ou 127.0.0.1:3000
```bash
rails s
```
4. Clique no link para acessar a página de orders, clique no + para entrar no formulário de criação de novos pedidos e envie o arquivo .txt separado por tabs no formato que foi informado no escopo do projeto.
5. Verifique as orders criadas em /orders (orders_path)
<file_sep>/app/models/order.rb
class Order < ApplicationRecord
belongs_to :product
validates :client, :product, :quantity, presence: true
validates :quantity, numericality: {greater_than: 0}
def order_price
self.quantity * self.product.price
end
def self.total_price
sum = 0
all_prices = Order.all.map{|order| order.order_price}
all_prices.each do |price|
sum += price
end
sum
end
end
<file_sep>/app/controllers/orders_controller.rb
class OrdersController < ApplicationController
before_action :set_order, only: %i[ show edit update destroy ]
# GET /orders or /orders.json
def index
@orders = Order.all
end
# GET /orders/1 or /orders/1.json
def show
end
# GET /orders/new
def new
@order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders or /orders.json
def create
file = File.open(order_params[:file], 'r')
file_data = file.read.split("\n")
line_number = 0
file_data.each do |line|
if line_number != 0
line_data = line.split("\t")
merchant_params = {
name: line_data[4],
address: line_data[5]
}
@merchant = Merchant.create!(merchant_params)
product_params = {
description: line_data[1],
price: line_data[2].to_d,
merchant: @merchant
}
@product = Product.create!(product_params)
new_order_params = {
quantity: line_data[3].to_i,
client: line_data[0],
product: @product
}
@order = Order.create!(new_order_params)
end
line_number += 1
end
respond_to do |format|
format.html { redirect_to orders_path, notice: "Orders created"}
format.json { render :show, status: :created, location: @order }
end
end
# PATCH/PUT /orders/1 or /orders/1.json
def update
respond_to do |format|
if @order.update(order_params)
format.html { redirect_to @order, notice: "Order was successfully updated." }
format.json { render :show, status: :ok, location: @order }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1 or /orders/1.json
def destroy
@order.destroy
respond_to do |format|
format.html { redirect_to orders_url, notice: "Order was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
@order = Order.find(params[:id])
end
# Only allow a list of trusted parameters through.
def order_params
params.require(:order).permit(:file)
end
end
<file_sep>/spec/models/product_spec.rb
require 'rails_helper'
RSpec.describe Product, type: :model do
it 'is valid with all params' do
merchant = Merchant.create(name: "<NAME>", address: "351 Park Avenue, NY")
product = Product.create(description: "Chocolate Donuts", price: 5.32, merchant: merchant)
expect(product).to be_valid
end
it 'is invalid without description' do
merchant = Merchant.create(name: "<NAME>", address: "351 Park Avenue, NY")
product = Product.create(description: nil, price: 5.32, merchant: merchant)
expect(product).to_not be_valid
end
it 'is invalid without price' do
merchant = Merchant.create(name: "<NAME>", address: "351 Park Avenue, NY")
product = Product.create(description: "Chocolate Donuts", price: nil, merchant: merchant)
expect(product).to_not be_valid
end
it 'is invalid without merchant' do
product = Product.create(description: "Chocolate Donuts", price: 5.32, merchant: nil)
expect(product).to_not be_valid
end
end
<file_sep>/spec/models/order_spec.rb
require 'rails_helper'
RSpec.describe Order, type: :model do
before(:each) do
merchant = Merchant.create(address: "351 Park Avenue, NY", name: "Donuts House")
@product = Product.create(description: "A little donut", price: 1.30, merchant: merchant)
end
it 'is valid with all params' do
order = Order.create(client: "<NAME>", quantity: 20, product: @product)
expect(order).to be_valid
end
context 'validations test' do
it 'when without client' do
order = Order.create(client: nil, quantity: 20, product: @product)
order.valid?
expect(order.errors[:client]).to include("can't be blank")
end
it 'when without quantity' do
order = Order.create(client: "<NAME>", quantity: nil, product: @product)
expect(order.errors[:quantity]).to include("can't be blank")
end
it 'when negative quantity' do
order = Order.create(client: "<NAME>", quantity: -20, product: @product)
order.valid?
expect(order.errors[:quantity]).to include("must be greater than 0")
end
it 'when without product' do
order = Order.create(client: "<NAME>", quantity: 20, product: nil)
order.valid?
expect(order.errors[:product]).to include("must exist")
end
end
context 'when need to render prices' do
it 'render order_price on each order' do
order = Order.create(client: "<NAME>", quantity: 20, product: @product)
expect(order.order_price).to eq(order.quantity * @product.price)
end
it 'render total_price on order' do
merchant = Merchant.create(address: "351 Park Avenue, NY", name: "<NAME>")
product1 = Product.create(description: "A little donut", price: 1.30, merchant: merchant)
product2 = Product.create(description: "A little donut", price: 1.30, merchant: merchant)
product3 = Product.create(description: "A little donut", price: 1.30, merchant: merchant)
order1 = Order.create(client: "<NAME>", quantity: 20, product: product1)
order2 = Order.create(client: "<NAME>", quantity: 30, product: product2)
order3 = Order.create(client: "<NAME>", quantity: 40, product: product3)
expect(Order.total_price).to eq(order1.quantity * product1.price + order2.quantity * product2.price + order3.quantity * product3.price)
end
end
end
<file_sep>/spec/models/merchant_spec.rb
require 'rails_helper'
RSpec.describe Merchant, type: :model do
it 'is valid with all params' do
merchant = Merchant.create(name: "<NAME>", address: "351 Park Avenue, NY")
expect(merchant).to be_valid
end
context 'validations test' do
it 'when without name' do
merchant = Merchant.create(name: nil, address: "351 Park Avenue, NY")
merchant.valid?
expect(merchant.errors[:name]).to include("can't be blank")
end
it 'when without address' do
merchant = Merchant.create(name: "<NAME>", address: nil)
merchant.valid?
expect(merchant.errors[:address]).to include("can't be blank")
end
end
end
<file_sep>/app/models/product.rb
class Product < ApplicationRecord
belongs_to :merchant
has_many :orders
validates :description, :price, :merchant, presence: true
end
| 8f9e2fb06a935754f933333372de95ef6e6f952a | [
"Markdown",
"Ruby"
] | 8 | Ruby | carrilhorafael/nuuvem-challenge | 084b533034b9e8318936b54ddf174d08023c8943 | 4199c7863fcd1df72312e1737f2398c7dcac382d |
refs/heads/master | <file_sep>class EmployeesController < ApplicationController
def index
@employees_data = Employee.all
@employees=Hash new
@employees_data.each do |employee_data|
if @employees.has_key?(employee_data[:lead_name])
@employees[employee_data[:lead_name]].push({"name":employee_data[:name],"skills":employee_data[:skills].split(',').length})
else
@employees[employee_data[:lead_name]]=[]
@employees[employee_data[:lead_name]].push({"name":employee_data[:name],"skills":employee_data[:skills].split(',').length})
end
end
@employees.each do |k,v|
puts k
puts v
@employees[k]=v.sort_by { |ob| ob[:skills] }.reverse
end
@lead_names=@employees.keys
puts @employees
end
def show
@employee = Employee.find(params[:id])
puts @employee
end
def new
end
def create
@employee = Employee.new(employee_params)
@employee.save
redirect_to @employee
end
private
def employee_params
params.require(:employee).permit(:name,:project_name,:lead_name,:skills)
end
end
| 695d8ee4535f36bb6ae74bf808faa920e19319e2 | [
"Ruby"
] | 1 | Ruby | RamakrishnaAvenger/ruby_on_rails_assignment2 | b146a4157b6af280b5f290d8b7a28ce5b5a91d91 | ca71472900f62a1f423501acebb938f49ea30a39 |
refs/heads/master | <repo_name>risaito74/CubeActionRpg<file_sep>/Assets/GameOverManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameOverManager : MonoBehaviour {
public GameObject gameManager;
public GameObject cubeEnemy;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//トリガー接触
void OnTriggerEnter(Collider other) {
Debug.Log(other.gameObject.tag);
if (other.gameObject.tag == "Player") {
gameManager.GetComponent<GameManager>().GameOver();
}
if (other.gameObject.tag == "Enemy") {
cubeEnemy.transform.position = new Vector3(0, 3, 0);
}
}
}
<file_sep>/Assets/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
public GameObject cubeHero;
public GameObject textGameOver;
public GameObject buttonRestart;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//
public void GameOver() {
textGameOver.SetActive(true);
buttonRestart.SetActive(true);
cubeHero.GetComponent<HeroManager>().SetControllHero(false);
Time.timeScale = 0;
}
//リスタート押下処理
public void PushRestartButton() {
Time.timeScale = 1.0f;
SceneManager.LoadScene("main");
}
}
<file_sep>/README.md
# CubeActionRpg
uniryroomで公開している「勇者と姫とマモノ」プロジェクト
https://unityroom.com/games/cubearpg
操作方法
* 方向キー上下左右で主人公(青いCube)を操作します
* 詳細はunityroomの説明を参照
<file_sep>/Assets/EnemyManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyManager : MonoBehaviour {
public GameObject gameManager;
public Rigidbody enemyRigidbody;
float moveTime = 0.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
moveTime += Time.deltaTime;
if (moveTime >= 3.0f) {
moveTime = 0;
Vector3 moveVector3 = new Vector3(Random.Range(-200f, 200f), 0, Random.Range(-300f, 200f));
enemyRigidbody.AddForce(moveVector3);
Debug.Log("Enemy: x=" + moveVector3.x + " z=" + moveVector3.z);
}
}
//コリジョン接触
void OnCollisionEnter(Collision other) {
Debug.Log(other.gameObject.tag);
if (other.gameObject.tag == "Player") {
gameManager.GetComponent<GameManager>().GameOver();
}
}
}
<file_sep>/Assets/HeroManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HeroManager : MonoBehaviour {
public Text textLove;
//
int loveNum = 0;
bool isControlHero = true;
// Use this for initialization
void Start () {
UpdateLoveNum();
}
// Update is called once per frame
void Update () {
if (isControlHero && Input.GetKey("up")) {
transform.Translate(0, 0, 0.1f);
}
if (isControlHero && Input.GetKey("down")) {
transform.Translate(0, 0, -0.1f);
}
if (isControlHero && Input.GetKey("left")) {
transform.Translate(-0.1f, 0, 0);
}
if (isControlHero && Input.GetKey("right")) {
transform.Translate(0.1f, 0, 0);
}
}
//コリジョン接触
void OnCollisionEnter(Collision other) {
Debug.Log(other.gameObject.tag);
if (other.gameObject.tag == "Player") {
loveNum++;
UpdateLoveNum();
}
}
//Love数の更新
void UpdateLoveNum() {
textLove.text = loveNum + " Love";
}
//ヒーロー操作フラグ
public void SetControllHero(bool flag) {
isControlHero = flag;
}
}
| 65dc8f33f56ecdec65a38404e8e7356dea64d5bf | [
"Markdown",
"C#"
] | 5 | C# | risaito74/CubeActionRpg | 737fb079fe8c1f499c0d8a42af37e60158f6f7fc | 4a0dfac3596246a4d9b29d028e8784ebd4514459 |
refs/heads/main | <repo_name>Dheerajkota001/TaskMangementAPI<file_sep>/README.md
# TaskMangementAPI
PreRequisites
Install JDK 1.8 or above
Install Maven or Gradle and H2 as follows below
Execute using Gradel:
./gradlew clean bootRun
Notes:
DB Design :
CREATE TABLE IF NOT EXISTS Task
(
Task_Id char(50),
Description char(100),
Created_By char(50),
Created_Time datetime,
Due_Date datetime,
Reminder_Time int,
Reminder_Type char(100),
Place char(50),
RecurrenceType char(50),
Task_Status char(50),
Action_Type char(50),
);
API Design :
Rest APIs: CRUD
Retrieve -> GET
Create -> POST
Update -> PUT
Delete -> Delete
Notification Job Design:
Create Job :
Due Date:
Query
Current Time > "2021-10-05 13:11:35.422" -> 20 Tasks
Make 20 calls
https://api.kaleyra.io/v1/%s/voice/outbound?to=%s&bridge=%s&api-key=%s&target=[{"message":{"text":"%s"}}]
Different Layers:
API Layer
Service Layer
DAO Layer
Connectors Layer
Full Technical Stack:
Java 8
Gradle - Build Tool
SprintBoot - API
Embedded - Tomcat
Rest - Spring
JPA -
Making external API call -> Okhttp Framework
DBConnection Pool
<file_sep>/src/main/java/com/mytech/taskmanagement/TaskManager.java
package com.mytech.taskmanagement;
import com.mytech.taskmanagement.service.NotificationJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@Slf4j
public class TaskManager implements CommandLineRunner{
@Autowired
NotificationJobService notificationJobService;
public static void main(String[] args) {
SpringApplication.run(TaskManager.class, args);
}
@Override
public void run(String... args) throws Exception {
log.info("Starting sending the notification");
notificationJobService.processRequest();
log.info("Finished sending the notification");
}
}<file_sep>/src/main/java/com/mytech/taskmanagement/connector/model/Message.java
package com.mytech.taskmanagement.connector.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.AllArgsConstructor;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"text"
})
@AllArgsConstructor
public class Message {
@JsonProperty("text")
private String text;
@JsonProperty("text")
public String getText() {
return text;
}
@JsonProperty("text")
public void setText(String text) {
this.text = text;
}
}
<file_sep>/src/main/java/TimeTest.java
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class TimeTest {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now();
// 1. ZonedDateTime to TimeStamp
Timestamp timestamp = Timestamp.valueOf(now.toLocalDateTime());
// 2. ZonedDateTime to TimeStamp , no different
Timestamp timestamp2 = Timestamp.from(now.toInstant());
System.out.println(now); // 2019-06-19T14:12:13.585294800+08:00[Asia/Kuala_Lumpur]
System.out.println(timestamp); // 2019-06-19 14:12:13.5852948
System.out.println(timestamp2); // 2019-06-19 14:12:13.5852948
Timestamp timestamp1 = Timestamp.from(Instant.now());
LocalDateTime localDateTimeNoTimeZone = timestamp1.toLocalDateTime();
ZonedDateTime zonedDateTime1 = localDateTimeNoTimeZone.atZone(ZoneId.of("+08:00"));
ZonedDateTime zonedDateTime2 = localDateTimeNoTimeZone.atZone(ZoneId.of("Asia/Kuala_Lumpur"));
ZonedDateTime zonedDateTime3 = localDateTimeNoTimeZone.atZone(ZoneId.systemDefault());
ZonedDateTime zonedDateTime4 = localDateTimeNoTimeZone.atZone(ZoneId.of("-08:00"));
System.out.println(timestamp1); // 2019-06-19 14:08:23.4458984
System.out.println(zonedDateTime1); // 2019-06-19T14:08:23.445898400+08:00
System.out.println(zonedDateTime2); // 2019-06-19T14:08:23.445898400+08:00[Asia/Kuala_Lumpur]
System.out.println(zonedDateTime3); // 2019-06-19T14:08:23.445898400+08:00[Asia/Kuala_Lumpur]
System.out.println(zonedDateTime4); // 2019-06-19T14:08:23.445898400-08:00
}
}
<file_sep>/src/main/java/com/mytech/taskmanagement/service/NotificationJobService.java
package com.mytech.taskmanagement.service;
import java.io.IOException;
public interface NotificationJobService {
void sendRemainders() throws IOException;
void processRequest();
}
<file_sep>/src/main/java/com/mytech/taskmanagement/configuration/TaskManagementConfig.java
package com.mytech.taskmanagement.configuration;
import okhttp3.OkHttpClient;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class TaskManagementConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
@Bean
public OkHttpClient okHttpClient(){
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
return client;
}
}
<file_sep>/src/main/java/com/mytech/taskmanagement/service/TaskManagementService.java
package com.mytech.taskmanagement.service;
import com.mytech.taskmanagement.model.TaskRequestDto;
import com.mytech.taskmanagement.model.TaskResponseDto;
import java.io.IOException;
import java.util.List;
public interface TaskManagementService {
List<TaskResponseDto> getAllTasks(String zone);
void saveTask(TaskRequestDto task) throws IOException;
void updateTask(Long taskId, TaskRequestDto task);
void deleteTask(Long taskId);
}
<file_sep>/src/main/java/com/mytech/taskmanagement/connector/VoiceRestConnector.java
package com.mytech.taskmanagement.connector;
import com.mytech.taskmanagement.dao.entity.Task;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
@Service
@Slf4j
@RequiredArgsConstructor
public class VoiceRestConnector {
private final RestTemplate restTemplate;
@Value("${com.tech.voice.kaleyra.url}")
private String kaleyraApiEndpoint;
private final OkHttpClient okHttpClient;
@Value("${com.tech.voice.kaleyra.apikey}")
private String apiKey;
private final static String TO = "+919999196461";
private final static String BRIDGE = "+918046983237";
private final static String SSID = "HXIN1709604395IN";
/**
* This to send a voice notification
*
* @param taskRequestDto
* @throws IOException
*/
public void postVoiceRemainderWithOkhttp(Task taskRequestDto) throws IOException {
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
//Create the endpoint
String endPointNew = String.format(
kaleyraApiEndpoint, SSID, TO, BRIDGE,apiKey,taskRequestDto.getDescription());
Request request = new Request.Builder()
.url(endPointNew)
.method(HttpMethod.POST.toString(), body)
.build();
Response response = okHttpClient.newCall(request).execute();
String responseBody = response.body() == null ? null : response.body().string();
log.info("responseBody" + responseBody);
}
}
| 224fc2f45d5bd32254b3e17a04ea8190e17630cf | [
"Markdown",
"Java"
] | 8 | Markdown | Dheerajkota001/TaskMangementAPI | 62d7b326b5db4c9c14a15d8e6b3e232efc285a01 | 9efa13ef2a2a08311525677ab513b052f8411417 |
refs/heads/master | <repo_name>cha63506/stock<file_sep>/README.md
stock
=====
Software Comercial desenvolvido em Java
<file_sep>/src/util/LookAndFeel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package util;
import com.java.io.JavaIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* Alterar o Look And Feel da Aplicacao.
*
* @author <NAME>
*/
public class LookAndFeel {
private String look = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
public void lookAndFeel(JFrame view) {
try {
if (JavaIO.isWindows()){
UIManager.setLookAndFeel(look);
SwingUtilities.updateComponentTreeUI(view);
}
} catch (Exception erro) {
JOptionPane.showMessageDialog(null, "Erro ao tentar mudar o Look And Feel!" + erro);
}
}
}
<file_sep>/src/estoque/Estoque.java
package estoque;
import views.SistemaView;
/**
*
* @author xpto
*/
public class Estoque {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SistemaView view = new SistemaView();
view.setVisible(true);
}
}
| 321bf48cc71cd491b0d94c37e5368ad62a71dd1c | [
"Markdown",
"Java"
] | 3 | Markdown | cha63506/stock | 45d6bb0f44fd38f4114f9ec0d78cf4ef43ff7f3f | 865d149594c72aa921f49345ff00d7a1a47f1ba8 |
refs/heads/master | <file_sep>package com.mkfree.apiservice.service.permission;
import com.mkfree.apiservice.domain.SysUser;
/**
* 系统用户服务接口
*
* @author hk
*
* 2012-12-15 下午6:06:09
*/
public interface SysUserService {
/**
* 通过帐号密码,去查找用户
*
* @param account
* @param password
* @return
*/
public SysUser getUserByAccountAndPassword(String account, String password);
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mkfree</groupId>
<artifactId>free-main</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>free-apiservice</artifactId>
<packaging>jar</packaging>
<properties>
<!-- 第三方 jar -->
<cglib.version>2.2.2</cglib.version>
</properties>
<build>
<plugins>
<!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.mkfree.apiservice.ApiServiceServer</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.mkfree</groupId>
<artifactId>free-framework</artifactId>
<version>${framework.version}</version>
<exclusions>
<!-- <exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</exclusion> -->
<exclusion>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</exclusion>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.mkfree</groupId>
<artifactId>free-apithrift</artifactId>
<version>${apithrift.version}</version>
<exclusions>
<exclusion>
<artifactId>*</artifactId>
<groupId>*</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>${libthrift.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project><file_sep>package com.mkfree.apiservice.service.permission.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mkfree.apiservice.dao.SysUserDao;
import com.mkfree.apiservice.domain.SysUser;
import com.mkfree.apiservice.service.permission.SysUserService;
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
@Autowired
private SysUserDao sysUserDao;
public SysUser getUserByAccountAndPassword(String account, String password) {
return sysUserDao.findByAccountAndPassword(account, password);
}
}
| b61752a6b581c3ecd14deb5d315430279a94524d | [
"Java",
"Maven POM"
] | 3 | Java | LeohuaChao/free-main | 2e665dedd6cc27fef7b73bfd9cb5d7c8f9b9ce4b | 9b0aa7dfb43c14585a1d02443b4d1a444440d020 |
refs/heads/master | <file_sep>// INITIAL DECLARATIONS
const express = require('express');
const methodOverride = require('method-override');
const bodyParser = require('body-parser'); // initialize body-parser
const mongoose = require('mongoose'); // once was const or var...let is used
const exphbs = require('express-handlebars');
const app = express(); // include express.js stuff... adding dots after app (eg app.???)!
const port = process.env.PORT || 3000;
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/rotten-potatoes'
// MIDDLEWARE
mongoose.connect(mongoUri, { useNewUrlParser: true });
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(methodOverride('_method'))
// The following line must appear AFTER const app = express() and before your routes!
app.use(bodyParser.urlencoded({ extended: true }));
const reviews = require('./controllers/reviews')(app); // initialize reveiws
const movies = require('./controllers/movies')(app); // initialize movies
const comments = require('./controllers/comments')(app); // initialize movies
//listen
app.listen(port, () => {
console.log('App listening on port 3000!')
})
module.exports = app;
| 29c54dcb592cb9673c8cb7eb4ce6f527ff8554fd | [
"JavaScript"
] | 1 | JavaScript | capt-alien/rotten-potatoes | 1ba755fca8e33fcb282c75175d18720bf8b1e864 | 16f41dccd2a6207b5d98cd226de0d6d20056ada7 |
refs/heads/master | <repo_name>QueueSoftwareInc/isItNative<file_sep>/README.md
isItNative
==========
A bash script to check whether an iPhone app is native or not.
<file_sep>/isItNative.sh
#!/bin/bash
file="$1"
if [$file -eq ""] || [[ $file != *.ipa ]] ; then
echo "Please pass in an ipa file"
exit 2
fi
HTML=0
JS=0
CSS=0
EXE=0
mkdir "testScratch"
cp "$file" "testScratch/testScratch.zip"
cd "testScratch"
unzip "testScratch.zip" >/dev/null
#find . -name '*.png' -exec fun \;
#Check for HTML Files
for i in $(find . -name '*.html');
do HTML=$((HTML+1));
done;
#Check for JS Files
for i in $(find . -name '*.js');
do JS=$((JS+1));
done;
#Check for CSS Files
for i in $(find . -name '*.css');
do CSS=$((CSS+1));
done;
#Check for EXE Files
for i in $(find . -name '*.exe');
do EXE=$((EXE+1));
done;
if [ $HTML -eq 0 ] && [ $JS -eq 0 ] && [ $CSS -eq 0 ] && [ $EXE -eq 0 ] ; then
echo "native"
else
echo "not Native"
fi
cd ..
rm -rf "testScratch"
| 9e748f547ae06ec1955b577180cf827b065d5310 | [
"Markdown",
"Shell"
] | 2 | Markdown | QueueSoftwareInc/isItNative | 497d5eb6f2d756bce38d3519ad841ae4ba813fbc | 0dc74b7868c58589238a27a4c953433212b4f196 |
refs/heads/master | <file_sep><?php get_template_part('header'); ?>
<main role="main" aria-label="Content">
<!-- section -->
<section>
<h1>
<?php esc_html_e('Latest Posts', 'handmadestale'); ?>
<small>
<?php printf(
_n('%d post', '%d posts', hmt_published_post_count(), 'handmadestale'),
hmt_published_post_count()
); ?>
</small>
</h1>
<?php get_template_part('loop'); ?>
</section>
<!-- /section -->
</main>
<?php get_template_part('footer'); ?>
<file_sep><?php
require __DIR__ . '/classes/HMT_Walker_Nav_Menu.php';
require __DIR__ . '/classes/HMT_Language_Switcher_Widget.php';
// Load our text domain
load_theme_textdomain('handmadestale');
/**
* Register our menus.
*/
function hmt_nav_menus()
{
register_nav_menus(
array(
'main-menu' => __('Main Menu'),
)
);
}
add_action('init', 'hmt_nav_menus');
$hmt_published_post_count = null;
/**
* Retrieve cached number of published posts
*
* @return int
*/
function hmt_published_post_count()
{
global $hmt_published_post_count;
if (is_null($hmt_published_post_count)) {
$hmt_published_post_count = intval(wp_count_posts('post')->publish);
}
return $hmt_published_post_count;
}
/**
* Register our sidebars and widgetized areas.
*/
function hmt_widgets_init()
{
register_sidebar(array(
'name' => __('Trailing Main Navigation'),
'id' => 'trailing_main_nav',
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>',
));
}
add_action('widgets_init', 'hmt_widgets_init');
/**
* Register our widgets.
*/
function hmt_language_switcher_widget()
{
register_widget('HMT_Language_Switcher_Widget');
}
add_action('widgets_init', 'hmt_language_switcher_widget');<file_sep><?php
class HMT_Language_Switcher_Widget extends WP_Widget
{
public function __construct()
{
parent::__construct(
'HMT_Language_Switcher_Widget',
__("Handmade's Tale Language Switcher", 'handmadestale'),
array(
'description' => __(
"Custom language switcher for the Handmade's Tale website",
'handmadestale'
),
)
);
}
public function widget($args, $instance)
{
if (!function_exists('pll_the_languages')) {
throw new Exception(__('The Polylang plugin is needed to show a ' .
'language switcher.'));
}
$languages = pll_the_languages(array('raw' => 1));
if (count($languages) == 0) {
_e('No languages to display');
return;
}
// make local variables available to the template
include(locate_template('language-switcher.php'));
}
}<file_sep><?php if (!isset($languages)) {
throw new Exception(__('Expected $languages array for printing'));
} ?>
<ul class="pure-menu-list pure-menu-horizontal text-end">
<?php foreach ($languages as $language) : ?>
<li class="pure-menu-item">
<a class="pure-menu-link" href="<?php echo $language['url']; ?>">
<?php echo $language['name']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
| 6b1a0abe3bba2bb9a6258a53c2410b287d8a6f4c | [
"PHP"
] | 4 | PHP | ashour/wordpress-i18n-part-03 | 73428c727b43303c1b0513ee25655b7c1eb1198f | b99fd21648cb38d9daf73c944932d22291072825 |
refs/heads/master | <repo_name>blankslate222/delivery-system<file_sep>/src/main/java/com/nikhil/delivery/system/strategy/StrategyEnum.java
package com.nikhil.delivery.system.strategy;
public enum StrategyEnum {
FIFO,
MATCHED,
;
}
<file_sep>/src/main/java/com/nikhil/delivery/system/strategy/impl/MatchedStrategyImpl.java
package com.nikhil.delivery.system.strategy.impl;
import com.nikhil.delivery.system.actors.Courier;
import com.nikhil.delivery.system.model.Order;
import com.nikhil.delivery.system.strategy.MatchedStrategy;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
public class MatchedStrategyImpl implements MatchedStrategy {
private final ConcurrentHashMap<String, Order> courierMapping = new ConcurrentHashMap<>(200, 0.8f);
private final ConcurrentHashMap<String, BlockingQueue<Order>> readyOrders = new ConcurrentHashMap<>(200, 0.8f);
@Override
public void orderReady(Order order) throws Exception {
readyOrders.get(order.getId()).put(order);
}
@Override
public Order getReadyOrder(String courierId) throws Exception {
Order order = courierMapping.get(courierId);
// blocks until the order becomes ready
return readyOrders.get(order.getId()).take();
}
@Override
public void addOrderAssignmentToPool(Order order, Courier courier) {
courierMapping.putIfAbsent(courier.getId(), order);
BlockingQueue<Order> blockingQ = new ArrayBlockingQueue<>(1);
readyOrders.put(order.getId(), blockingQ);
}
}
<file_sep>/src/main/java/com/nikhil/delivery/system/callback/impl/KitchenCallbackImpl.java
package com.nikhil.delivery.system.callback.impl;
import com.nikhil.delivery.system.model.Order;
import com.nikhil.delivery.system.callback.KitchenCallback;
import com.nikhil.delivery.system.strategy.Strategy;
public class KitchenCallbackImpl implements KitchenCallback {
private Strategy strategy;
public KitchenCallbackImpl(Strategy strategy) {
this.strategy = strategy;
}
@Override
public void orderReadyCallback(Order order) {
try {
System.out.println("Order ready : " + order.getId());
strategy.orderReady(order);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
<file_sep>/src/main/java/com/nikhil/delivery/system/callback/KitchenCallback.java
package com.nikhil.delivery.system.callback;
import com.nikhil.delivery.system.model.Order;
public interface KitchenCallback {
void orderReadyCallback(Order order);
}
<file_sep>/src/main/java/com/nikhil/delivery/system/actors/impl/BasicKitchenImpl.java
package com.nikhil.delivery.system.actors.impl;
import com.nikhil.delivery.system.actors.Kitchen;
import com.nikhil.delivery.system.model.KitchenDetails;
import com.nikhil.delivery.system.model.Order;
import com.nikhil.delivery.system.callback.KitchenCallback;
import lombok.Data;
@Data
public class BasicKitchenImpl implements Kitchen {
private KitchenDetails kitchenDetails;
public BasicKitchenImpl(KitchenDetails kitchenDetails) {
this.kitchenDetails = kitchenDetails;
}
@Override
public KitchenDetails getKitchenDetails() {
return this.kitchenDetails;
}
@Override
public void prepOrder(Order order, KitchenCallback kitchenCallback) {
Kitchen.super.prepOrder(order, kitchenCallback);
}
}
<file_sep>/src/main/java/com/nikhil/delivery/system/service/impl/MatchedCourierHandlerServiceImpl.java
package com.nikhil.delivery.system.service.impl;
import com.nikhil.delivery.system.actors.Courier;
import com.nikhil.delivery.system.actors.factory.CourierFactory;
import com.nikhil.delivery.system.callback.CourierCallback;
import com.nikhil.delivery.system.callback.impl.CourierCallbackImpl;
import com.nikhil.delivery.system.model.KitchenDetails;
import com.nikhil.delivery.system.model.Order;
import com.nikhil.delivery.system.service.CourierHandlerService;
import com.nikhil.delivery.system.strategy.MatchedStrategy;
public class MatchedCourierHandlerServiceImpl implements CourierHandlerService {
private MatchedStrategy strategy;
public MatchedCourierHandlerServiceImpl(MatchedStrategy strategy) {
this.strategy = strategy;
}
@Override
public void handleCourier(Order order, KitchenDetails kitchen) {
Courier nextAvailableCourier = CourierFactory.getInstance().getNextAvailableCourier();
CourierCallback courierCallBack = new CourierCallbackImpl(this.strategy);
try {
this.strategy.addOrderAssignmentToPool(order, nextAvailableCourier);
System.out.println("Assigned order : " + order.getId() + " to courier : " + nextAvailableCourier.getId());
nextAvailableCourier.collectOrder(kitchen, courierCallBack);
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
<file_sep>/src/main/java/com/nikhil/delivery/system/callback/impl/CourierCallbackImpl.java
package com.nikhil.delivery.system.callback.impl;
import com.nikhil.delivery.system.actors.Courier;
import com.nikhil.delivery.system.model.KitchenDetails;
import com.nikhil.delivery.system.model.Order;
import com.nikhil.delivery.system.callback.CourierCallback;
import com.nikhil.delivery.system.strategy.Strategy;
public class CourierCallbackImpl implements CourierCallback {
private Strategy strategy;
public CourierCallbackImpl(Strategy strategy) {
this.strategy = strategy;
}
@Override
public void courierArrivedCallback(KitchenDetails kitchenDetails, Courier courier) {
try {
System.out.println(Thread.currentThread().getName() + ":Courier arrived : " + courier.getId());
courier.deliverOrder(null, strategy.getReadyOrder(courier.getId()), this);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public void orderDeliveredCallback(String courierId, Order order) {
System.out.println(Thread.currentThread().getName() + ":Courier : " + courierId + " Delivered order : " + order.getId());
}
}
<file_sep>/src/main/java/com/nikhil/delivery/system/actors/factory/KitchenFactory.java
package com.nikhil.delivery.system.actors.factory;
import com.nikhil.delivery.system.actors.Kitchen;
import com.nikhil.delivery.system.actors.impl.BasicKitchenImpl;
import com.nikhil.delivery.system.model.KitchenDetails;
import java.util.HashMap;
import java.util.Map;
public class KitchenFactory {
private static final KitchenFactory FACTORY = new KitchenFactory();
private final Map<String, Kitchen> kitchenInventory = new HashMap<>();
private KitchenFactory() {
}
public static KitchenFactory getInstance() {
return FACTORY;
}
public Kitchen getKitchen(String id) {
Kitchen kitchen = kitchenInventory.get(id);
// if (kitchen == null) {
// throw new RuntimeException("Kitchen not found");
// }
return kitchen;
}
public Kitchen getNextAvailableKitchen() {
return new BasicKitchenImpl(KitchenDetails.builder().id("kitchenId").name("kitchenName").build());
}
}
<file_sep>/src/main/java/com/nikhil/delivery/system/service/impl/OrderDispatchServiceImpl.java
package com.nikhil.delivery.system.service.impl;
import com.nikhil.delivery.system.actors.Kitchen;
import com.nikhil.delivery.system.actors.factory.KitchenFactory;
import com.nikhil.delivery.system.callback.impl.KitchenCallbackImpl;
import com.nikhil.delivery.system.model.Order;
import com.nikhil.delivery.system.service.CourierHandlerService;
import com.nikhil.delivery.system.service.OrderDispatchService;
import com.nikhil.delivery.system.strategy.FifoStrategy;
import com.nikhil.delivery.system.strategy.MatchedStrategy;
import com.nikhil.delivery.system.strategy.impl.FifoStrategyImpl;
import com.nikhil.delivery.system.strategy.impl.MatchedStrategyImpl;
import com.nikhil.delivery.system.strategy.Strategy;
import com.nikhil.delivery.system.strategy.StrategyEnum;
import java.util.concurrent.ExecutorService;
public class OrderDispatchServiceImpl implements OrderDispatchService {
private final ExecutorService kitchenThreadPool;
private final ExecutorService courierHandlerThreadPool;
private final Strategy strategy;
private final CourierHandlerService courierSvc;
public OrderDispatchServiceImpl(StrategyEnum strategyEnum,
ExecutorService kitchenThreadPool,
ExecutorService courierHandlerThreadPool) {
this.kitchenThreadPool = kitchenThreadPool;
this.courierHandlerThreadPool = courierHandlerThreadPool;
if (StrategyEnum.FIFO == strategyEnum) {
FifoStrategy fifoStrategy = new FifoStrategyImpl();
this.strategy = fifoStrategy;
this.courierSvc = new FifoCourierHandlerServiceImpl(fifoStrategy);
} else {
MatchedStrategy matchedStrategy = new MatchedStrategyImpl();
this.strategy = matchedStrategy;
this.courierSvc = new MatchedCourierHandlerServiceImpl(matchedStrategy);
}
}
@Override
public void placeOrder(String kitchenId, Order order) {
final Kitchen kitchen = getKitchen(kitchenId);
kitchenThreadPool.submit(() -> kitchen.prepOrder(order, new KitchenCallbackImpl(this.strategy)));
courierHandlerThreadPool.submit(() -> this.courierSvc.handleCourier(order, kitchen.getKitchenDetails()));
}
private Kitchen getKitchen(String kitchenId) {
Kitchen kitchen = KitchenFactory.getInstance().getKitchen(kitchenId);
// for the sake of simulation
if (kitchen == null){
kitchen = KitchenFactory.getInstance().getNextAvailableKitchen();
}
return kitchen;
}
}
<file_sep>/README.md
# delivery-system
- Simulates simple order delivery system
- Actors: Customer, Kitchen, Courier
- Services: Order dispatcher and Courier handler
- Order to courier mapping strategies available: FIFO, Matched
<file_sep>/src/main/java/com/nikhil/delivery/system/service/CourierHandlerService.java
package com.nikhil.delivery.system.service;
import com.nikhil.delivery.system.model.KitchenDetails;
import com.nikhil.delivery.system.model.Order;
public interface CourierHandlerService {
void handleCourier(Order order, KitchenDetails kitchenDetails);
}
| 31fb07018414fbfd2a8106347d447db0b55e32a6 | [
"Markdown",
"Java"
] | 11 | Java | blankslate222/delivery-system | 43f1ef49f7b2b6787228ab5dc85eec3889a851cf | 03bdec65af3e4d7335a37b63910f0bd55d7297c0 |
refs/heads/master | <repo_name>kaelaclement/ruby-object-attributes-lab-online-web-sp-000<file_sep>/lib/dog.rb
class Dog
#set name
def name=(name)
@name = name
end
#get name
def name
@name
end
#set breed
def breed=(breed)
@breed = breed
end
# get breed
def breed
@breed
end
end
<file_sep>/lib/person.rb
class Person
# set name
def name=(name)
@name = name
end
# get name
def name
@name
end
# set job
def job=(job)
@job = job
end
# get job
def job
@job
end
end
| 114a3ed8ca53b5b72390fbe88efa36aa02af927f | [
"Ruby"
] | 2 | Ruby | kaelaclement/ruby-object-attributes-lab-online-web-sp-000 | 53d5ea2faf2f64759e6c2487ab785ee20cfbfc64 | 4246dde1b31b76f63dc8ff9d452a81e5f9845fbf |
refs/heads/master | <file_sep>import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Raspberry Snake')
# Set the proper color values
redColor = pygame.Color(255,0,0)
blackColor = pygame.Color(0,0,0)
whiteColor = pygame.Color(255,255,255)
grayColor = pygame.color(150,150,150)
# Initialize Snake
snakePosition = [100,100]
snakeSegments = [[100,100], [80,100], [60,100]]
raspberryPosition = [300, 300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
def gameOver():
gameOverFont = pygame.fintFont('freesansbold.ttff', 72)
gameOverSurf = gameOverFont.render('Game Over', True, grayColor)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
sys.exit()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'<file_sep># Echo client program
import socket
HOST = '127.1.1.1' # the remote host
PORT = 8080 # the same port used by the server
def client():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
sendme = raw_input('What do you want to send?\n')
s.sendall(sendme)
data = s.recv(1024)
s.close()
print 'Received', repr(data)
if __name__ == "__main__":
client()<file_sep>a = [1, 20, 300, 'bbdcc']
def findLetterInMatrix(letterToFind):
for x in a:
if isinstance(x, str):
if letterToFind in x:
print letterToFind
findLetterInMatrix('b')
findLetterInMatrix('bdc')
<file_sep>
def convertStringToInt(chessString):
converted = chessString.split(' ')
result = map(int, converted)
return result
def convertIntListToStringList(intList):
convertedString = ''
for value in intList:
convertedString = convertedString + str(value) + ' '
return convertedString
def compareChessSets(pieces):
officialPieces = [1, 1, 2, 2, 2, 8]
diffChessPieces = []
for pieceKey in range(len(pieces)):
numOfPiecesForOfficial = officialPieces[pieceKey] - pieces[pieceKey]
diffChessPieces.append(numOfPiecesForOfficial)
return diffChessPieces
if __name__ == "__main__":
# The main function
pieces = raw_input()
pieces = convertStringToInt(pieces)
diffChessPieces = compareChessSets(pieces)
convertedString = convertIntListToStringList(diffChessPieces)
print convertedString
<file_sep># Echo server program
import socket
def server():
host = '127.1.1.1' # symbolic name meaning all available interfaces
port = 8080 # arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s = socket(AF_INET, SOCK_STREAM)
s.bind((host, port))
s.listen(1)
# print socket.getdefaulttimeout()
# socket.setdefaulttimeout(60)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
# conn, (rmip, rmpt) = s.accept()
# while 1:
# print ("connected by ", str(rmip) + ": " + str(rmpt))
# data = conn.recv(1024)
# print ("What was delivered: ", data.decode())
#
# if not data:
# break
# conn.close()
if __name__ == "__main__":
server()
<file_sep>from tkinter import *
import tkinter as tk
from tkinter.filedialog import asksaveasfile
from tkinter.filedialog import askopenfile
from tkinter import scrolledtext
import urllib.request as ul
from bs4 import BeautifulSoup as bs
root = tk.Tk()
root.title("Search Articles")
frame = Frame(master=root)
frame.pack(fill=BOTH, expand=TRUE)
# Create widgets
label = Label(frame, text="The feature of this program includes \
1) Scraping webpage text for a URL \
2) Reading web URLs from a file \
3) Reading search keywords from a file \
", bg="#ff9911")
search = scrolledtext.ScrolledText(master=frame, wrap=tk.WORD, width=20, height=40)
url = scrolledtext.ScrolledText(master=frame, wrap=tk.WORD, width=30, height=40)
article = scrolledtext.ScrolledText(master=frame, wrap=tk.WORD, width=60, height=40)
countLabel = Label(master=frame, text="Statistics: total")
# Place widgets in proper location on frame
label.grid(columnspan=4, row=0, sticky=W)
search.grid(column=0, row=1, sticky=W)
url.grid(column=1, row=1, sticky=(W, E))
article.grid(column=2, row=1)
cntOUT = StringVar()
tk.Label(frame, text="Statistics: total").grid(column=0,row=2, sticky=W)
tk.Label(frame, textvariable=cntOUT).grid(column=1,row=2,sticky=W)
tk.Label(frame, text="found").grid(column=2,row=2, sticky=W)
# Keep track of keyword occurrences
cnt = 0
# def appendKey():
# print(0)
# # implement here
def createKey():
search.delete(1.0, END)
def openKey():
global search
f = askopenfile(mode='r')
if f is None:
return
text2open = str(f.read())
search.insert(INSERT, text2open)
def createURL():
url.delete(1.0, END)
def openURL():
# global aurl
f = askopenfile(mode='r')
if f is None:
return
text2open = str(f.read())
url.delete(1.0, END)
url.insert(INSERT, text2open)
def createFile():
article.delete(1.0, END)
def file_save():
f = asksaveasfile(mode="w", defaultextension=".txt")
if f is None: # close if cancel
return
text2save = str(url.get(1.0, END))
f.write(text2save)
f.close()
def getURL(urls):
"""Return a list of proper url strings.
Keyword arguments
:param urls: list of possible url strings
:return: formatted url strings
"""
# NOTE: This does not use regex!
global article, soup
article.delete(1.0, END)
readAddr = str(urls)
for webLink in readAddr.split():
if webLink[0:7] != "http://":
webLink = "http://" + webLink # check if prefix starts with http
print(webLink)
urlAdd = "----------------" + webLink + "----------------"
article.insert(END, urlAdd)
htmlFile = ul.urlopen(webLink)
soup = bs(htmlFile, "html.parser")
article.insert(END, soup.get_text())
def readAll():
try:
getURL(url.get(1.0, END))
except TclError:
print("Please input website address.")
def readOne():
try:
getURL(url.selection_get())
except TclError:
print("Please input website address.")
def addTags(widget, keywords, isCaseSensitive):
""" Sets tags on the matched pattern
:param widget: tkinter widget holding text
:param keywords: list of keywords to search for
:param isCaseSensitive: true if keywords search is case sensitive, false otherwise
"""
global cnt
cnt = 0
widget.tag_remove("yellow", 1.0, END)
widget.tag_configure("yellow", background="#ffff00") # color code highlight
for keyword in keywords:
pos = 1.0
while True:
idx = widget.search(keyword, pos, END, nocase=FALSE) if isCaseSensitive \
else widget.search(keyword, pos, END, nocase=TRUE)
if not idx:
break
cnt += 1
pos = '{}+{}c'.format(idx, len(keyword))
widget.tag_add("yellow", idx, pos)
def getKeywords():
"""Scans the keyword column in search of keywords.
Keyword arguments
:return: a list of keywords
"""
try:
searchKeys = search.get(1.0, END)
return searchKeys.split()
except TclError:
print("Please input any keyword.")
def caseHighlight():
keywords = getKeywords()
addTags(article, keywords, True)
def nocaseHighlight():
keywords = getKeywords()
addTags(article, keywords, False)
def searchStatistic():
global cnt
try:
cntOUT.set(cnt)
except ValueError:
pass
def getOut():
print("Good-bye")
root.quit()
def explainHelp():
helpwin = Toplevel (root)
button = Button (helpwin, text ="This is a sample program \n written for IASP 505.")
button.pack()
myMenu = Menu(root)
keyMenu= Menu (myMenu, tearoff=0)
keyMenu.add_command(label="New", command=createKey, accelerator="Ctrl+N")
# keyMenu.add_command(label="Append...", command=appendKey)
keyMenu.add_command(label="Open...", command=openKey, accelerator="Ctrl+O")
keyMenu.add_separator()
keyMenu.add_command(label="Exit", command=getOut)
myMenu.add_cascade(label="Keyword", menu=keyMenu)
urlMenu= Menu (myMenu, tearoff=0)
urlMenu.add_command(label="New", command=createURL, accelerator="Ctrl+N")
urlMenu.add_command(label="Open...", command=openURL, accelerator="Ctrl+O")
myMenu.add_cascade(label="URL", menu=urlMenu)
artiMenu= Menu (myMenu, tearoff=0)
artiMenu.add_command(label="Fetch Selected", command=readOne, accelerator="Ctrl+O")
artiMenu.add_command(label="Fetch All", command=readAll, accelerator="Ctrl+S")
artiMenu.add_command(label="Save As...", command=file_save)
artiMenu.add_separator()
artiMenu.add_command(label="Page Setup...", command=createFile)
artiMenu.add_command(label="Print...", command=createFile, accelerator="Ctrl+P")
artiMenu.add_separator()
artiMenu.add_command(label="Exit", command=getOut)
myMenu.add_cascade(label="WebPage", menu=artiMenu)
srchMenu= Menu (myMenu, tearoff=0)
srchMenu.add_command(label="Case-sensitive", accelerator="Ctrl+io", command=caseHighlight)
srchMenu.add_command(label="All Matches", accelerator="Ctrl+io", command=nocaseHighlight)
srchMenu.add_separator()
srchMenu.add_command(label="Statistics", accelerator="Ctrl+ix", command=searchStatistic)
myMenu.add_cascade(label="Search", menu=srchMenu)
helpMenu= Menu (myMenu, tearoff=0)
helpMenu.add_command(label="View Help", command=createFile)
helpMenu.add_separator()
helpMenu.add_command(label="About Notepad", command=explainHelp)
myMenu.add_cascade(label="Help", menu=helpMenu)
root.config(menu=myMenu)
root.mainloop()<file_sep>import sqlite3
conn = sqlite3.connect('the sql connection goes here')
cur = conn.cursor()
cur.execute('CREATE TABLE STUDENT(cwid int, age int, major text(255))')
cur.execute('CREATE TABLE DEPARTMENT (name TEXT(255), chair TEXT(255))')
cur.execute('INSERT INTO STUDENT(20096020, 24, \'Cybersecurity\')')
cur.execute('SELECT st.cwid, dp.chair FROM student st, department dp, faculty fc, class cl WHERE st.cwid = cl.stud AND cl.fac = fc.name AND fc.dept = dp.name')
cur.execute('SELECT st.cwid FROM student st, department dp, faculty fc, class cl WHERE st.cwid = cl.stud AND cl.fac = fc.name AND fc.dept = dp.name AND fc.name = \'CS\'')
conn.close()<file_sep>def mult_func(s):
num_lst = s # Split the user input into a list by comma ( , )
# enumerate generates an integer relevant to the number of iterations starting at 0
# eg. 1st num, i = 0, 2nd num, i = 1, 3rd num, i = 2, etc
for i, num in enumerate(num_lst):
value = float(num)*(i+1)
print('{0} x {1} = {2}'.format(float(num), (i+1), value))
if __name__ == '__main__':
# The user entered numbers have to be separeted by commas ( , )
# The user entered numbers have to be separeted by commas ( , )
print input("s");
mult_func(input('Enter a list of numbers: '))<file_sep>def closed_form(n):
# 2^n = 2^(n+1) - 1
partOne = (pow(2,(n+1))-1)
print('2^n: ' + str(partOne))
# (-1)^n = ...
partTwo = (pow(-1, (n+1)) - 1)/(-2)
print('-1n: ' + str(partTwo) + '\n')
print(partOne + partTwo)
closed_form(1)
closed_form(2)
closed_form(3)<file_sep>## Practice
This project consists of practice sets of code and random problems.<file_sep>repeatSpell = input()
for value in range(1, repeatSpell + 1):
print str(value) + ' Abracadabra' | bd03084352cccf8434025e26aaca1b379d6c8324 | [
"Markdown",
"Python"
] | 11 | Python | SlinkyPotato/practice | 71e70c07f2bbba13687b2f7de9d0cc2ffb20b87b | b25aa6ac1015aa7ffdec91fabcedee55a8f6d91b |
refs/heads/master | <file_sep>///////////////////////////////////////////////////////////
// CCombEvent.cs
// Implementation of the Class CCombEvent
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine.Event;
using FlowEngine;
using System.Xml;
namespace FlowEngine.Event {
public class CCombEvent : CEvent {
private List<CNormlEvent> m_parlevents = new List<CNormlEvent>();
public CCombEvent(CWorkFlow parent) : base(parent) {
}
~CCombEvent(){
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public override void InstFromXmlNode(XmlNode xmlNode){
//1. 解析基类CEvent的成员
base.InstFromXmlNode(xmlNode);
//2. 解析CombEvent的成员
}
/// <summary>
/// 反解析到XML元素
/// </summary>
public override XmlNode WriteToXmlNode(){
//1. 反解析基类部分成员
XmlNode xn = base.WriteToXmlNode();
//2. 反解析CombEvent的成员
XmlElement xe = (XmlElement)xn;
xe.SetAttribute("type", "combevent");
return xn;
}
/// <summary>
/// 进入该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void EnterEvent(string strjson){
}
/// <summary>
/// 离开该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void LeaveEvent(string strjson){
}
}//end CCombEvent
}//end namespace Event<file_sep>///////////////////////////////////////////////////////////
// IXMLEntity.cs
// Implementation of the Interface IXMLEntity
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: Ailibuli
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
namespace FlowEngine {
/// <summary>
/// 对象实体的XML解析及生成的接口
/// </summary>
public interface IXMLEntity {
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
void InstFromXmlNode (XmlNode xmlNode);
/// <summary>
/// 反解析到XML元素
/// </summary>
XmlNode WriteToXmlNode();
}//end IXMLEntity
}//end namespace FlowEngine<file_sep>function myValidation() {
if ($('#cjname').length > 0 && ($('#cjname').find("option:selected").val() == null || $('#cjname').find("option:selected").val() == "")) {
alert('请选择车间!');
return false;
}
if ($('#zzId').length > 0 && ($('#zzId').find("option:selected").val() == null || $('#zzId').find("option:selected").val() == "")) {
alert('请选择装置!');
return false;
}
if ($('#Equip_GyCode').length > 0 && ($('#Equip_GyCode').find("option:selected").val() == null || $('#Equip_GyCode').find("option:selected").val() == "")) {
alert('请选择设备工艺编号!');
return false;
}
//if ($('#E_Code').length > 0 && ($('#E_Code').val() == null || $('#E_Code').val() == "")) {
// alert('请输入设备编号!');
// return false;
//}
//if ($('#E_Type').length > 0 && ($('#E_Type').val() == null || $('#E_Type').val() == "")) {
// alert('请输入设备型号!');
// return false;
//}
if ($("input:radio[name='zyoptionsRadiosinline']").length > 0 && ($("input:radio[name='zyoptionsRadiosinline']:checked").val() == null || $("input:radio[name='zyoptionsRadiosinline']:checked").val() == "")) {
alert('请选择问题专业分类!');
return false;
}
//由于其他专业的设备可能无专业分类子类,因此注释这一段
//if ($("input:radio[name='subzyoptionsRadiosinline']").length > 0 && ($("input:radio[name='subzyoptionsRadiosinline']:checked").val() == null || $("input:radio[name='subzyoptionsRadiosinline']:checked").val() == "")) {
// alert('请选择专业分类子类!');
// return false;
//}
if ($("input:radio[name='srcoptionsRadiosinline']").length > 0 && ($("input:radio[name='srcoptionsRadiosinline']:checked").val() == null || $("input:radio[name='srcoptionsRadiosinline']:checked").val() == "")) {
alert('请选择数据来源!');
return false;
}
if (($("textarea.form-control").length > 0 && ($("textarea.form-control:first").val() == null || $("textarea.form-control:first").val() == "")) && ($("#fileUpLoad_name").length > 0 && ($("#fileUpLoad_name").val() == null || $("#fileUpLoad_name").val() == ""))) {
alert('描述或附件,两者不能同时为空,请至少输入其中一项!');
return false;
}
//if ($("#fileUpLoad_name").length > 0 && ($("#fileUpLoad_name").val() == null || $("#fileUpLoad_name").val() == "")) {
// alert('请上传附件!');
// return false;
//}
if ($("#EquipMaintain_Time").length > 0 && ($("#EquipMaintain_Time").val() == null || $("#EquipMaintain_Time").val() == "")) {
alert('请输入设备维护时间!');
return false;
}
return true;
};<file_sep>
using MVCTest.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVCTest.Models
{
public class UserContext : DbContext
{
public UserContext() : base("UserContext")
{
}
public DbSet<UserInfo> users { get; set; }
public DbSet<Depart> department { get; set; }
public DbSet<Role> roles { get; set; }
}
}<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Interface
{
public interface ISpecialty
{
Speciaty_Info GetSpecialty(int id);
List<Speciaty_Info> GetSpecialty(string name);
List<Speciaty_Info> GetChildSpecialty(int id);
bool AddSpecialty(int parentID, Speciaty_Info newSpecialty);
bool DeleteSpecialty(int id);
bool ModifySpecialty(int id, Speciaty_Info nVal);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EquipModel.Entities;
using EquipModel.Context;
namespace EquipDAL.Implement
{
public class ERP_Infos : BaseDAO
{
//已知工单号,获取工单的用户状态和简要说明
//适用流程A8.2
public GongDan getGD_info(string gd_Id)
{
try
{
using (var db = new EquipWebContext())
{
var GongdanList= db.Database.SqlQuery<GongDan>("select * from GongDan where GD_Id ='"+gd_Id +"'");
List<GongDan> r= GongdanList.ToList<GongDan>();
return r.ElementAt(0);
}
}
catch (Exception )
{ return null; }
}
public List<OilInfo> getOilInfo_Overdue(string curDate)
{
try
{
using (var db = new EquipWebContext())
{
var oilInfoList = db.Database.SqlQuery<OilInfo>("select * from oilInfo where oil_NextDate <'" + curDate + "'");
List<OilInfo> r = oilInfoList.ToList<OilInfo>();
return r;
}
}
catch (Exception)
{ return null; }
}
public GongDan getGD_Notice_info(string gd_Notice_Id)
{
try
{
using (var db = new EquipWebContext())
{
var GongdanList= db.Database.SqlQuery<GongDan>("select * from GongDan where GD_NoticeId ='"+gd_Notice_Id +"'");
List<GongDan> r= GongdanList.ToList<GongDan>();
return r.ElementAt(0);
}
}
catch (Exception )
{ return null; }
}
//适用流程A6.2
//获取超期未换油信息
//public List<OilInfo> getOilInfo_Overdue(string curDate)
//{
// try
// {
// using (var db = new EquipWebContext())
// {
// var oilInfoList = db.Database.SqlQuery<OilInfo>("select * from oilInfo where oil_NextDate <'" + curDate + "'");
// List<OilInfo> r = oilInfoList.ToList<OilInfo>();
// return r;
// }
// }
// catch (Exception)
// { return null; }
//}
//适用于KPI计算
public List<Notice> getNoticeInfos_ByNoticeType(string Pq_code,string Notice_type,string Notice_state,string Notice_OverCondition="")
{
try
{
using (var db = new EquipWebContext())
{
string lastDate = DateTime.Now.AddMonths(-1).ToString("yyyyMM") + "16";
string nextDate = DateTime.Now.ToString("yyyyMM") + "15";
List<Notice> r ;
//string sql = "select * from Notice where Notice_Type='" + Notice_type + "' and Notice_state!='" + Notice_state + "' and Notice_CR_Date>='" + lastDate + "' and Notice_CR_Date<='" + nextDate + "' and Notice_PlanGroup in(select rtrim(ltrim(cName)) collate Chinese_PRC_CI_AS from Pq_Zz_map where Pq_Name = '" + Pq_code + "')";
if (Notice_OverCondition=="")
r = db.Database.SqlQuery<Notice>("select * from Notice where Notice_Type='" + Notice_type + "' and Notice_state!='" + Notice_state + "' and Notice_CR_Date>='" + lastDate + "' and Notice_CR_Date<='" + nextDate + "' and Notice_PlanGroup in (select rtrim(ltrim(Zz_Code)) collate Chinese_PRC_CI_AS from Pq_Zz_map where Pq_Name = '" + Pq_code + "')").ToList<Notice>();
else
r = db.Database.SqlQuery<Notice>("select * from Notice where Notice_Type='" + Notice_type + "' and Notice_state!='" + Notice_state + "' and Notice_OverConditon='" + Notice_OverCondition + "' and Notice_CR_Date>='" + lastDate + "' and Notice_CR_Date<='" + nextDate + "' and Notice_PlanGroup in (select rtrim(ltrim(Zz_Code)) collate Chinese_PRC_CI_AS from Pq_Zz_map where Pq_Name='" + Pq_code + "' )").ToList<Notice>();
return r;
}
}
catch (Exception)
{ return null; }
}
//不需要Notice_Type
public List<Notice> getNoticeInfos_ByNoticeTypes(string Pq_code, string Notice_state, string Notice_OverCondition = "")
{
try
{
using (var db = new EquipWebContext())
{
string lastDate = DateTime.Now.AddMonths(-1).ToString("yyyyMM") + "16";
string nextDate = DateTime.Now.ToString("yyyyMM") + "15";
List<Notice> r;
//string sql = "select * from Notice where Notice_Type='" + Notice_type + "' and Notice_state!='" + Notice_state + "' and Notice_CR_Date>='" + lastDate + "' and Notice_CR_Date<='" + nextDate + "' and Notice_PlanGroup in(select rtrim(ltrim(cName)) collate Chinese_PRC_CI_AS from Pq_Zz_map where Pq_Name = '" + Pq_code + "')";
if (Notice_OverCondition == "")
r = db.Database.SqlQuery<Notice>("select * from Notice where Notice_state!='" + Notice_state + "' and Notice_CR_Date>='" + lastDate + "' and Notice_CR_Date<='" + nextDate + "' and Notice_PlanGroup in (select rtrim(ltrim(Zz_Code)) collate Chinese_PRC_CI_AS from Pq_Zz_map where Pq_Name = '" + Pq_code + "')").ToList<Notice>();
else
r = db.Database.SqlQuery<Notice>("select * from Notice where Notice_state!='" + Notice_state + "' and Notice_OverConditon='" + Notice_OverCondition + "' and Notice_CR_Date>='" + lastDate + "' and Notice_CR_Date<='" + nextDate + "' and Notice_PlanGroup in (select rtrim(ltrim(Zz_Code)) collate Chinese_PRC_CI_AS from Pq_Zz_map where Pq_Name='" + Pq_code + "' )").ToList<Notice>();
return r;
}
}
catch (Exception)
{ return null; }
}
public List<Notice> getNoticeInfos(string Pq_code,string Notice_state)
{
try
{
using (var db = new EquipWebContext())
{
string lastDate = DateTime.Now.AddMonths(-1).ToString("yyyyMM") + "16";
string nextDate = DateTime.Now.ToString("yyyyMM") + "15";
List<Notice> r;
r = db.Database.SqlQuery<Notice>("select * from Notice where Notice_state !='" + Notice_state + "' and Notice_CR_Date>='" + lastDate + "' and Notice_CR_Date<='" + nextDate + "' and Notice_PlanGroup in (select rtrim(ltrim(Zz_Code)) collate Chinese_PRC_CI_AS from Pq_Zz_map where Pq_Name='" + Pq_code + "')").ToList<Notice>();
return r;
}
}
catch (Exception)
{ return null; }
}
//全厂统计 Pq_Code=ALL
public List<Notice> getNoticeInfos_BigEquip(string Pq_code, string Notice_type, string Notice_state, string Notice_OverCondition)
{
try
{
using (var db = new EquipWebContext())
{
string lastDate = DateTime.Now.AddMonths(-1).ToString("yyyyMM") + "16000000";
string nextDate = DateTime.Now.ToString("yyyyMM") + "15235959";
List<Notice> r;
//string asd = "select * from Notice where Notice_Type +'" + Notice_type + "' and Notice_State!='" + Notice_state + "' and Notice_FaultStart+Notice_FaultStartTime>='" + lastDate + "' and Notice_FaultEnd+Notice_FaultEndTime<='" + nextDate + "' and Notice_OverConditon='" + Notice_OverCondition + "' and Notice_EquipCode in (select rtrim(ltrim(Equip_Code)) collate Chinese_PRC_CI_AS from Pq_EC_map where Pq_Name='" + Pq_code + "')";
if (Pq_code == "ALL")
r = db.Database.SqlQuery<Notice>("select * from Notice where Notice_Type ='" + Notice_type + "' and Notice_State!='" + Notice_state + "' and Notice_FaultStart+Notice_FaultStartTime>='" + lastDate + "' and Notice_FaultEnd+Notice_FaultEndTime<='" + nextDate + "' and Notice_OverConditon='" + Notice_OverCondition + "' and Notice_EquipCode in (select rtrim(ltrim(Equip_Code)) collate Chinese_PRC_CI_AS from Pq_EC_map)").ToList<Notice>();
else
r = db.Database.SqlQuery<Notice>("select * from Notice where Notice_Type ='" + Notice_type + "' and Notice_State!='" + Notice_state + "' and Notice_FaultStart+Notice_FaultStartTime>='" + lastDate + "' and Notice_FaultEnd+Notice_FaultEndTime<='" + nextDate + "' and Notice_OverConditon='" + Notice_OverCondition + "' and Notice_EquipCode in (select rtrim(ltrim(Equip_Code)) collate Chinese_PRC_CI_AS from Pq_EC_map where Pq_Name='" + Pq_code + "')").ToList<Notice>();
return r;
}
}
catch (Exception)
{ return null; }
}
public int geBigEquip_Num(string Pq_code)
{
try
{
using (var db = new EquipWebContext())
{
int r = 0;
if (Pq_code == "ALL")
r = db.Database.SqlQuery<Notice>("select * from Pq_EC_map").Count();
else
r = db.Database.SqlQuery<Notice>("select * from Pq_EC_map where Pq_Name='" + Pq_code + "'").Count();
return r;
}
}
catch (Exception)
{ return -1; }
}
}
}
<file_sep>using FlowEngine;
using FlowEngine.DAL;
using FlowEngine.Flow;
using FlowEngine.Modals;
using FlowEngine.Param;
using FlowEngine.TimerManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace EXPRESS_TEST
{
class Program
{
static void Main(string[] args)
{
CTimerManage.InitTimerManager();
CTimerManage.Start();
var wfe = CWFEngine.CreateAWFEntityByName("test1");
wfe.Start(null);
CWFEngine.SubmitSignal(wfe.EntityID, new Dictionary<string, string>());
Thread.Sleep(10 * 60 * 1000);
}
}
}
<file_sep>using FlowEngine.DAL;
using FlowEngine.Modals;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.TimerManage
{
/// <summary>
/// 超时处理任务
/// </summary>
public class CTimerTimeout : CTimerMission
{
#region 构造函数
public CTimerTimeout()
{
//运行参数
//SUSPEND: 将对应工作流实体设置为 WE_SUSPEND
//DELETE: 将对应工作流实体设置为 WE_DELETED
//其他: 不做处理
m_run_params = "";
type = "TimeOut";
}
#endregion
#region 属性
/// <summary>
/// 与任务关联的工作流实体ID号
/// </summary>
private int m_wfentityID = -1;
public int AttachWFEntityID
{
get { return m_wfentityID; }
set { m_wfentityID = value; }
}
/// <summary>
/// 该任务对应的event名称
/// </summary>
private string m_eventName = "";
public string EventName
{
get
{
return m_eventName;
}
set
{
m_eventName = value;
}
}
/// <summary>
/// 超时用户的Callback, 可用于后期的绩效处理
/// </summary>
//private string m_callBackURL = "";
#endregion
#region 公共方法
/// <summary>
/// 设置该任务对关联工作流实体的操作
/// </summary>
/// <param name="action"></param>
public void SetActionForWF(string action)
{
string act = action.ToUpper();
m_run_params = act;
}
/// <summary>
/// 解析数据库参数到运行参数
/// </summary>
/// <param name="strPars"></param>
public override void ParseRunParam(string strPars)
{
JObject jpar = JObject.Parse(strPars);
m_run_params = jpar["target_status"];
}
/// <summary>
/// 解析运行参数到数据库
/// </summary>
/// <returns></returns>
public override object ParseRunParamsToJObject()
{
JObject jpar = new JObject();
jpar["target_status"] = m_run_params.ToString();
return jpar;
}
/// <summary>
/// 解析运行结果
/// </summary>
/// <returns></returns>
public override object ParseRunResultToJobject()
{
//throw new NotImplementedException();
return null;
}
/// <summary>
/// 解析运行结果
/// </summary>
/// <param name="strResult"></param>
public override void ParseRunResult(string strResult)
{
//throw new NotImplementedException();
return;
}
/// <summary>
/// 保存该定时性任务
/// </summary>
/// <param name="job"></param>
public override void Save(Timer_Jobs job = null)
{
Timer_Jobs self_Job = new Timer_Jobs();
self_Job.workflow_ID = m_wfentityID;
self_Job.Job_Type = TIMER_JOB_TYPE.TIME_OUT;
//保留字段STR_RES_1保存callback URL地址
self_Job.STR_RES_1 = m_eventName;
base.Save(self_Job);
}
public override void Load(Timer_Jobs job)
{
base.Load(job);
m_wfentityID = job.workflow_ID;
m_eventName = job.STR_RES_1;
}
#endregion
#region 私有方法
/// <summary>
/// 用户定义的Callback调用
/// </summary>
protected void _CustomCallBack()
{
string custom_param = "{";
custom_param += "\"entity_id\":" + m_wfentityID.ToString() + ",";
custom_param += "\"event_name\":\"" + m_eventName + "\"";
custom_param += "}";
base.CallCustomAction(custom_param);
}
/// <summary>
/// 该事件的处理函数
/// </summary>
protected override void __processing()
{
WE_STATUS status = WE_STATUS.SUSPEND;
WorkFlows wfs = new WorkFlows();
try
{
switch ((string)m_run_params)
{
case "SUSPEND":
status = WE_STATUS.SUSPEND;
wfs.UpdateWorkFlowEntity(m_wfentityID, "WE_Status", status);
break;
case "DELETE":
status = WE_STATUS.DELETED;
wfs.UpdateWorkFlowEntity(m_wfentityID, "WE_Status", status);
break;
default:
break;
}
//调用用户定义的回调URL
_CustomCallBack();
this.status = TM_STATUS.TM_FINISH;
}
catch
{
Trace.WriteLine("Timeout processing exception!");
}
}
#endregion
}
}
<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class TablesManagment
{
public List<A5dot1Tab1> get_Allbytime(DateTime time)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
var e = wft.get_Allbytime(time);
return e;
}
catch
{
return null;
}
}
public bool Zzsubmit(A5dot1Tab1 a5dot1Tab1)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.Zzsubmit(a5dot1Tab1);
return true;
}
catch
{
return false;
}
}
public bool savefivesb(A5dot1Tab2 a5dot1Tab2)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.savefivesb(a5dot1Tab2);
return true;
}
catch
{
return false;
}
}
public bool setstate_byid(int id, int state, string name)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.setstate_byid(id, state, name);
return true;
}
catch
{
return false;
}
}
public bool setisworst10_byid(int id, int isworst10)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.setisworst10_byid(id, isworst10);
return true;
}
catch
{
return false;
}
}
public List<A5dot1Tab1> Getdcl_listbyisZG(int isRectified, List<string> cjname)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab1> E = wft.Getdcl_listbyisZG(isRectified, cjname);
return E;
}
catch
{
return null;
}
}
public List<A5dot1Tab1> GetLS_listbywfe_id(List<int> wfe_id)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab1> E = wft.GetLS_listbywfe_id(wfe_id);
return E;
}
catch
{
return null;
}
}
public List<A5dot1Tab1> GetAll1_byym(string ym, List<string> cjname)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab1> E = wft.GetAll1_byym(ym, cjname);
return E;
}
catch
{
return null;
}
}
/// <summary>
/// code:1代表车间,2代表片区,3代表全厂
/// 获取对应不完好数目
/// </summary>
/// <param name="name"></param>
/// <param name="code"></param>
/// <returns></returns>
public List<A5dot1Tab1> Getbwh_byname(string name, int code)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab1> E = wft.Getbwh_byname(name, code);
return E;
}
catch
{
return null;
}
}
public List<A5dot1Tab2> GetAll2_byymandstate(string ym, int state)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab2> E = wft.GetAll2_byymandstate(ym, state);
return E;
}
catch
{
return null;
}
}
public List<A5dot1Tab2> GetAll_byymandcode(string ym, string sbcode)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab2> E = wft.GetAll_byymandcode(ym, sbcode);
return E;
}
catch
{
return null;
}
}
public List<A5dot1Tab1> GetAll1_byymandcode(string ym, string sbcode)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab1> E = wft.GetAll1_byymandcode(ym, sbcode);
return E;
}
catch
{
return null;
}
}
public List<A5dot1Tab1> GetAll1_bycode(string sbcode)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
List<A5dot1Tab1> E = wft.GetAll1_bycode(sbcode);
return E;
}
catch
{
return null;
}
}
public A5dot1Tab1 GetA_byid(int a_id)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
A5dot1Tab1 E = wft.GetA_byid(a_id);
return E;
}
catch
{
return null;
}
}
public bool Pqcheck_byid(int a_id, string pqname, DateTime time)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.Pqcheck_byid(a_id, pqname, time);
return true;
}
catch
{
return false;
}
}
public bool modifytNG_byid(int a_id, int tNG)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.modifytNG_byid(a_id, tNG);
return true;
}
catch
{
return false;
}
}
public bool modifytemp1_byid(int a_id, string temp1)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.modifytemp1_byid(a_id, temp1);
return true;
}
catch
{
return false;
}
}
public bool delete_byid(int id)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
wft.delete_byid(id);
return true;
}
catch
{
return false;
}
}
public List<A5dot1Tab1> get_cj_bwh(string cj_name, int quip_num)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
var e = wft.get_cj_bwh(cj_name, quip_num);
return e;
}
catch
{
return null;
}
}
public List<A5dot1Tab1> get_pq_bwh(string pq_name, int equip_num)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
var e = wft.get_pq_bwh(pq_name, equip_num);
return e;
}
catch
{
return null;
}
}
public List<A5dot1Tab2> get_worst10byym(string ym)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
var e = wft.get_worst10byym(ym);
return e;
}
catch
{
return null;
}
}
public List<A5dot1Tab1> get_All()
{
WorkFlowTables wft = new WorkFlowTables();
try
{
var e = wft.get_All();
return e;
}
catch
{
return null;
}
}
public List<A5dot1Tab1> get_recordbyentity(string entity_id)
{
WorkFlowTables wft = new WorkFlowTables();
try
{
var e = wft.getrecordbyentity(entity_id);
return e;
}
catch
{
return null;
}
}
}
}
<file_sep>using EquipBLL.AdminManagment;
using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp.Controllers
{
public class QueryController : CommonController
{
//
// GET: /Query/
public class QueryModal
{
public List<UI_WF_Define> wf;
public List<Equip_Archi> UserHasEquips;
}
public ActionResult Index()
{
QueryModal qm=new QueryModal();
qm.wf = CWFEngine.ListAllWFDefine();
PersonManagment pm = new PersonManagment();
qm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(qm);
}
public ActionResult Gxq_Query()
{
QueryModal qm = new QueryModal();
qm.wf = CWFEngine.ListAllWFDefine();
PersonManagment pm = new PersonManagment();
qm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(qm);
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string Query_HistoryFlow(string time, string flow_id, string equip_gycode)//string json1)//,)
{
// JObject item = (JObject)JsonConvert.DeserializeObject(json1);
List<object> r = new List<object>();
if (time != "" || flow_id != "" || equip_gycode != "")
{
string Equip_GyCode = equip_gycode;
string record_filter;
if (time == "")
record_filter = "1<>1";
else
{
string[] strtime = time.Split(new char[] { '-' });
record_filter = "time >= '" + strtime[0] + "00:00:00'" + "and time <= '" + strtime[1] + " 00:00:00'";
}
string Query_list = "distinct E.WE_Ser ,E.WE_Id,R.time ";
string Query_condition;
if ((flow_id == "" && Equip_GyCode == ""))
Query_condition = "";
else
{
if (flow_id != "")
{
Query_condition = "E.W_Name like '%" + flow_id + "%'";
if (equip_gycode != "")
Query_condition = Query_condition + " and P.Equip_Code like '%" + Equip_GyCode + "%'";
}
else
Query_condition = "P.Equip_Code like'%" + Equip_GyCode + "%'";
}
System.Data.DataTable dt = CWFEngine.QueryAllInformation(Query_list, Query_condition, record_filter);
for (var i = 0; i < dt.Rows.Count; i++)
{
UI_MISSION lastMi = CWFEngine.GetHistoryMissions(Convert.ToInt32(dt.Rows[i].ItemArray[1])).Last();
int Miss_Id = lastMi.Miss_Id;
IDictionary<string, string> rr = CWFEngine.GetMissionRecordInfo(Miss_Id);
string userName = "";
string missTime = "";
if (r.Count > 0)
{
userName = rr["username"];
missTime = rr["time"];
}
object o = new
{
index = i,
Flow_Name = "<a onclick=\"DispalsySide('" + dt.Rows[i].ItemArray[0].ToString() + "')\"> " + dt.Rows[i].ItemArray[0].ToString() + "</a>",
Mission_Name = CWFEngine.GetWorkFlowEntiy(Convert.ToInt32(dt.Rows[i].ItemArray[1]), true).description,
Mission_Time = userName,
Mission_User = missTime
};
r.Add(o);
}
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class A15dot1TabJing //静
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public int gzqdkf { get; set; }
//设备腐蚀泄漏次数
public int sbfsxlcs { get; set; }
//千台冷换设备管束
public double qtlhsbgs { get; set; }
//工业炉平均热效效率
public double gylpjrxl { get; set; }
//换热器检修率
public double hrqjxl { get; set; }
//压力容器定检率
public double ylrqdjl { get; set; }
//压力管道年度检验计划完成率
public double ylgdndjxjhwcl { get; set; }
//安全阀年度校验计划完成率
public double aqfndjyjhwcl { get; set; }
//设备腐蚀检测计划完成率
public double sbfsjcjhwcl { get; set; }
//静设备检维修一次合格率
public double jsbjwxychgl { get; set; }
//隐患排查情况
public string hiddenDangerInvestigation { get; set; }
//负荷率
public string rateLoad { get; set; }
//工艺变更
public string gyChange { get; set; }
//设备变更
public string equipChange { get; set; }
//其他说明
public string otherDescription { get; set; }
//装置设备运行情况基本评估
public string evaluateEquipRunStaeDesc { get; set; }
//装置设备运行情况基本评估附图
public string evaluateEquipRunStaeImgPath { get; set; }
//可靠性结论
public string reliabilityConclusion { get; set; }
//机动处建议及改进措施
public string jdcAdviseImproveMeasures { get; set; }
//提交单位: XX片区或检修单位
public string submitDepartment { get; set; }
//单位提交人
public string submitUser { get; set; }
//单位提交时间
public DateTime? submitTime { get; set; }
//机动处操作人
public string jdcOperator { get; set; }
//机动处操作时间
public DateTime? jdcOperateTime { get; set; }
//进度状态: 0-单位保存,1-单位提交完成,2-机动处保存,3-机动处提交
public int state { get; set; }
//报告类型: 月报或年报
public string reportType { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A15dot1TabDian //电
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public int gzqdkf { get; set; }
//电气误操作次数
public int dqwczcs { get; set; }
//继电保护正确动作率
public double jdbhzqdzl { get; set; }
//设备故障率
public double sbgzl { get; set; }
// 电机MTBF
public double djMTBF { get; set; }
//电力电子设备MTBF
public double dzdlsbMTBF { get; set; }
//主变功率因素
public double zbglys { get; set; }
//电能计量平衡率
public double dnjlphl { get; set; }
//隐患排查情况
public string hiddenDangerInvestigation { get; set; }
//负荷率
public string rateLoad { get; set; }
//工艺变更
public string gyChange { get; set; }
//设备变更
public string equipChange { get; set; }
//其他说明
public string otherDescription { get; set; }
//装置设备运行情况基本评估
public string evaluateEquipRunStaeDesc { get; set; }
//装置设备运行情况基本评估附图
public string evaluateEquipRunStaeImgPath { get; set; }
//可靠性结论
public string reliabilityConclusion { get; set; }
//机动处建议及改进措施
public string jdcAdviseImproveMeasures { get; set; }
//提交单位: XX片区或检修单位
public string submitDepartment { get; set; }
//单位提交人
public string submitUser { get; set; }
//单位提交时间
public DateTime? submitTime { get; set; }
//机动处操作人
public string jdcOperator { get; set; }
//机动处操作时间
public DateTime? jdcOperateTime { get; set; }
//进度状态: 0-单位保存,1-单位提交完成,2-机动处保存,3-机动处提交
public int state { get; set; }
//报告类型: 月报或年报
public string reportType { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A15dot1TabYi //仪
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public int gzqdkf { get; set; }
//联锁系统正确动作率
public double lsxtzqdzl { get; set; }
// 控制系统故障次数
public int kzxtgzcs { get; set; }
//仪表控制率
public double ybkzl { get; set; }
//仪表实际控制率
public double ybsjkzl { get; set; }
//联锁系统投用率
public double lsxttyl { get; set; }
//关键控制阀门故障次数
public int gjkzfmgzcs { get; set; }
//控制系统故障报警次数
public int kzxtgzbjcs { get; set; }
// 常规仪表故障率
public double cgybgzl { get; set; }
//调节阀门MTBF
public double tjfMDBF { get; set; }
//隐患排查情况
public string hiddenDangerInvestigation { get; set; }
//负荷率
public string rateLoad { get; set; }
//工艺变更
public string gyChange { get; set; }
//设备变更
public string equipChange { get; set; }
//其他说明
public string otherDescription { get; set; }
//装置设备运行情况基本评估
public string evaluateEquipRunStaeDesc { get; set; }
//装置设备运行情况基本评估附图
public string evaluateEquipRunStaeImgPath { get; set; }
//可靠性结论
public string reliabilityConclusion { get; set; }
//机动处建议及改进措施
public string jdcAdviseImproveMeasures { get; set; }
//提交单位: XX片区或检修单位
public string submitDepartment { get; set; }
//单位提交人
public string submitUser { get; set; }
//单位提交时间
public DateTime? submitTime { get; set; }
//机动处操作人
public string jdcOperator { get; set; }
//机动处操作时间
public DateTime? jdcOperateTime { get; set; }
//进度状态: 0-单位保存,1-单位提交完成,2-机动处保存,3-机动处提交
public int state { get; set; }
//报告类型: 月报或年报
public string reportType { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A15dot1TabQiYe //企业级KPI
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//装置可靠性指数
public double zzkkxzs { get; set; }
//维修费用指数
public double wxfyzs { get; set; }
//千台离心泵(机泵)密封消耗率
public double qtlxbmfxhl { get; set; }
//千台冷换设备管束(含整台)更换率
public double qtlhsbgsghl { get; set; }
//仪表实际控制率
public double ybsjkzl { get; set; }
//事件数
public int sjs { get; set; }
//故障强度扣分
public int gzqdkf { get; set; }
//项目逾期率
public double xmyql { get; set; }
//培训及能力
public double pxjnl { get; set; }
//隐患排查情况
public string hiddenDangerInvestigation { get; set; }
//负荷率
public string rateLoad { get; set; }
//工艺变更
public string gyChange { get; set; }
//设备变更
public string equipChange { get; set; }
//其他说明
public string otherDescription { get; set; }
//装置设备运行情况基本评估
public string evaluateEquipRunStaeDesc { get; set; }
//装置设备运行情况基本评估附图
public string evaluateEquipRunStaeImgPath { get; set; }
//可靠性结论
public string reliabilityConclusion { get; set; }
//机动处建议及改进措施
public string jdcAdviseImproveMeasures { get; set; }
//提交单位: XX片区或检修单位
public string submitDepartment { get; set; }
//单位提交人
public string submitUser { get; set; }
//单位提交时间
public DateTime? submitTime { get; set; }
//机动处操作人
public string jdcOperator { get; set; }
//机动处操作时间
public DateTime? jdcOperateTime { get; set; }
//进度状态: 0-单位保存,1-单位提交完成,2-机动处保存,3-机动处提交
public int state { get; set; }
//报告类型: 月报或年报
public string reportType { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A15dot1TabDong //动
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public int gzqdkf { get; set; }
//大机组故障率
public double djzgzl { get; set; }
//故障维修率
public double gzwxl { get; set; }
//千台离心泵密封消耗率
public double qtlxbmfxhl { get; set; }
//紧急抢修工时率
public double jjqxgsl { get; set; }
//工单平均完成时间
public double gdpjwcsj { get; set; }
//机械密封检修率
public double jxmfpjsm { get; set; }
//轴承平均寿命
public double zcpjsm { get; set; }
//设备完好率
public double sbwhl { get; set; }
//检修一次合格率
public double jxychgl { get; set; }
//主要机泵平均效率
public double zyjbpjxl { get; set; }
//机组平均效率
public double jzpjxl { get; set; }
//往复机组故障率
public double wfjzgzl { get; set; }
//年度百台机泵重复维修率
public double ndbtjbcfjxtc { get; set; }
//机泵平均无故障间隔时间MTBF
public double jbpjwgzjgsjMTBF { get; set; }
//隐患排查情况
public string hiddenDangerInvestigation { get; set; }
//负荷率
public string rateLoad { get; set; }
//工艺变更
public string gyChange { get; set; }
//设备变更
public string equipChange { get; set; }
//其他说明
public string otherDescription { get; set; }
//装置设备运行情况基本评估
public string evaluateEquipRunStaeDesc { get; set; }
//装置设备运行情况基本评估附图
public string evaluateEquipRunStaeImgPath { get; set; }
//可靠性结论
public string reliabilityConclusion { get; set; }
//机动处建议及改进措施
public string jdcAdviseImproveMeasures { get; set; }
//提交单位: XX片区或检修单位
public string submitDepartment { get; set; }
//单位提交人
public string submitUser { get; set; }
//单位提交时间
public DateTime? submitTime { get; set; }
//机动处操作人
public string jdcOperator { get; set; }
//机动处操作时间
public DateTime? jdcOperateTime { get; set; }
//进度状态: 0-单位保存,1-单位提交完成,2-机动处保存,3-机动处提交
public int state { get; set; }
//报告类型: 月报或年报
public string reportType { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
}
<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EquipModel.Context;
namespace EquipDAL.Implement
{
public class NoticeView : BaseDAO
{
/// <summary>
/// 获取待处理通知单
/// </summary>
/// <returns></returns>
public List<Notice_A13dot1> GetNotice_A13dot1()
{
using (var db = base.NewDB())
{
List<Notice_A13dot1> e ;
e = db.Database.SqlQuery<Notice_A13dot1>("select * from NoticeView where Notice_A13dot1State='0'").ToList<Notice_A13dot1>();
return e;
}
}
/// <summary>
/// 获取通知单状态为1的通知单(现场工程师提交的)
/// </summary>
/// <returns></returns>
public List<Notice_A13dot1> GetNotice_A13dot1Uncomp()
{
using (var db = base.NewDB())
{
List<Notice_A13dot1> e;
e = db.Database.SqlQuery<Notice_A13dot1>("select * from NoticeView where Notice_A13dot1State='1'").ToList<Notice_A13dot1>();
return e;
}
}
/// <summary>
/// 修改表中状态由0-->1,同时传入操作人姓名和时间
/// </summary>
/// <param name="nVal"></param>
/// <returns></returns>
public string ModifyNoticeState(string username,string opertime,string Notice_Id)
{
using (var db = base.NewDB())
{
try
{
var modifynotice = db.Notice_Infos.SqlQuery("select * from Notice_Info where Notice_ID='" + Notice_Id + "'").First();
modifynotice.Notice_A13dot1State = 1;
modifynotice.Notice_A13dot1_DoUserName = username;
modifynotice.Notice_A13dot1_DoDateTime = opertime;
db.SaveChanges();
return "成功";
}
catch
{
return "出错!";
}
}
}
/// <summary>
/// 删除功能,只需修改状态为2,2表示改行数据舍弃
/// </summary>
/// <param name="Notice_Id"></param>
/// <returns></returns>
public string RemoveNoticeState(string Notice_Id)
{
using (var db = new EquipWebContext())
{
try
{
var modifynotice = db.Notice_Infos.SqlQuery("select * from Notice_Info where Notice_ID='" + Notice_Id + "'").First();
modifynotice.Notice_A13dot1State = 2;
db.SaveChanges();
return "成功";
}
catch
{
return "出错!";
}
}
}
public Notice_A13dot1 getNoticeByNI(string Notice_Id)
{
using (var db = base.NewDB())
{
Notice_A13dot1 e ;
e = db.Database.SqlQuery<Notice_A13dot1>("select * from NoticeView where Notice_Id='"+Notice_Id+"'").First<Notice_A13dot1>();
return e;
}
}
}
}
<file_sep>using EquipModel.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL
{
public class BaseDAO
{
protected EquipWebContext NewDB()
{
return new EquipWebContext();
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using FlowEngine.DAL;
using FlowEngine.Modals;
using FlowEngine.Param;
using WebApp.Models.DateTables;
using System.Collections.Specialized;
using EquipBLL.AdminManagment.MenuConfig;
namespace WebApp.Controllers
{
public class LSA11dot2Controller : CommonController
{
EquipManagment Em = new EquipManagment();
// GET: /LSA11dot2/
public ActionResult Index(int job_id,string job_title)
{
ViewBag.job_id = job_id;
ViewBag.jobtitle = job_title;
return View();
}
public ActionResult ZzSubmit(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult LSA11dot2()
{
return View();
}
public class EquipListModel
{
public int Equip_Id;
public string Equip_GyCode;
public string Equip_Code;
public string Equip_Type;
public string Equip_Specialty;
public string Equip_ABCMark;
}
public string get_equip_info(string wfe_id)
{
WorkFlows wfsd = new WorkFlows();
Mission db_miss = wfsd.GetWFEntityMissions(Convert.ToInt16(wfe_id)).Last();//获取该实体最后一个任务
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(Convert.ToInt16(wfe_id));
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui = new UI_MISSION();
ui.WE_Entity_Ser = wfe.WE_Ser;
ui.WE_Event_Desc = db_miss.Miss_Desc;
ui.WE_Event_Name = db_miss.Event_Name;
ui.WE_Name = db_miss.Miss_Name;
ui.Mission_Url = ""; //历史任务的页面至空
ui.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui.Miss_Params[cp.name] = cp.value;
ui.Miss_ParamsDesc[cp.name] = cp.description;
}
List<EquipListModel> EquipList = Zz_Equips(ui.Miss_Params["Zz_Name"].ToString());
List<object> miss_obj = new List<object>();
int i = 1;
foreach (var item in EquipList)
{
object m = new
{
index = i,
Equip_Id = item.Equip_Id,
Equip_GyCode = item.Equip_GyCode,
Equip_Code = item.Equip_Code,
Equip_Type = item.Equip_Type,
Equip_Specialty = item.Equip_Specialty,
Equip_ABCMark = item.Equip_ABCMark
};
miss_obj.Add(m);
i++;
}
string str = JsonConvert.SerializeObject(miss_obj);
return ("{" + "\"data\": " + str + "}");
}
public List<EquipListModel> Zz_Equips(string Zz_name)
{
EquipManagment pm = new EquipManagment();
EquipArchiManagment em = new EquipArchiManagment();
List<Equip_Info> Equips_of_Zz = new List<Equip_Info>();
List<EquipListModel> Equip_obj = new List<EquipListModel>();
Equips_of_Zz = pm.getEquips_OfZz(em.getEa_idbyname(Zz_name.ToString()));
foreach (var item in Equips_of_Zz)
{
EquipListModel io = new EquipListModel();
io.Equip_Id = item.Equip_Id;
io.Equip_GyCode = item.Equip_GyCode;
io.Equip_Code = item.Equip_Code;
io.Equip_Type = item.Equip_Type;
io.Equip_Specialty = item.Equip_Specialty;
io.Equip_ABCMark = item.Equip_ABCmark;
Equip_obj.Add(io);
}
return Equip_obj;
}
//提报页面的保存按钮,根据选择的设备个数创建相应11.2的工作流
public string CreateA11dot2_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
EquipManagment tm = new EquipManagment();
string temp = item["sample"].ToString();
JArray jsonVal = JArray.Parse(temp) as JArray;
dynamic table2 = jsonVal;
foreach (dynamic T in table2)
{
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName("A11dot2");
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
string returl = wfe.Start(record);
Dictionary<string, string> signal = new Dictionary<string, string>();
string Equip_Code = T.Equip_Code;
int Equip_location_EA_Id = tm.getEA_id_byCode(Equip_Code);
signal["Zz_Name"] = tm.getZzName(Equip_location_EA_Id);
signal["Equip_GyCode"] = T.Equip_GyCode;
signal["Equip_Code"] = T.Equip_Code;
signal["Equip_ABCMark"] = T.Equip_ABCMark;
signal["currentuser"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
signal["start_done"] = "true";
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(wfe.EntityID), signal, record1);
}
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
//A11dot2临时任务在线编辑部分
private DtResponse ProcessRequest(List<KeyValuePair<string, string>> data)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
var Data = http["data"] as Dictionary<string, object>;
int wfe_id = -1;
foreach (var d in Data)
{
wfe_id = Convert.ToInt32(d.Key);
}
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
foreach (var dd in d.Value as Dictionary<string, object>)
{
Dictionary<string, string> signal = new Dictionary<string, string>();
if (dd.Key == "problem_desc")
{
signal["Problem_Desc"] = dd.Value.ToString();
signal["ZzSubmit_done"] = "true";//提报标志
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
}
}
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
paras["Equip_GyCode"] = null;
paras["Equip_Code"] = null;
paras["Problem_Desc"] = null;//隐患问题描述
paras["RiskMatrix_Color"] = null;//隐患评估结果
paras["Supervise_done"] = null;//片区监督实施是否完成
paras["ImplementPlan_done"] = null;//黄色、措施实施是否完成
if (wfe_id != -1)
{
WorkFlows wfsd = new WorkFlows();
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(wfe_id, paras);
Dictionary<string, object> m_kv = new Dictionary<string, object>();
Mission db_miss = wfsd.GetWFEntityMissions(wfe_id).Last();//获取该实体最后一个任务
m_kv["index_Id"] = wfe_id;
m_kv["zz_name"] = paras["Zz_Name"].ToString();
m_kv["sb_gycode"] = paras["Equip_GyCode"].ToString();
m_kv["sb_code"] = paras["Equip_Code"].ToString();
m_kv["problem_desc"] = paras["Problem_Desc"].ToString();
m_kv["riskMatrix_color"] = paras["RiskMatrix_Color"].ToString();
m_kv["missionname"] = db_miss.Miss_Desc;
dt.data.Add(m_kv);
}
return dt;
}
public JsonResult PostChanges()
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = ProcessRequest(list);
return Json(dtRes);
}
private List<KeyValuePair<string, string>> ParsePostForm(NameValueCollection Form)
{
var list = new List<KeyValuePair<string, string>>();
if (Form != null)
{
foreach (var f in Form.AllKeys)
{
list.Add(new KeyValuePair<string, string>(f, Form[f]));
}
}
return list;
}
//public ActionResult LSA11dot2(string run_result ,string job_title)
//{
// string s = run_result;
// // ViewBag.flows = CWFEngine.ListAllWFDefine();
// ViewBag.run_result = run_result;
// ViewBag.jobtitle = job_title;
// return View();
//}
}
}<file_sep>using FlowEngine.DAL;
using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FlowEngine.Event
{
/// <summary>
/// 子流程事件
/// </summary>
public class CSubProcessEvent : CEvent
{
/// <summary>
/// m_wfName 子流程工作流名称
/// </summary>
public string WfName { get; set; }
/// <summary>
/// 子流程的ID
/// </summary>
public int WfEntityId { get; set; }
/// <summary>
/// 子工作流的工作方式:
/// serial——串行
/// parallel——并行
/// </summary>
public string WorkingMode { get; set; }
/// <summary>
/// 传递到子流程的参数对应关系
/// </summary>
public Dictionary<string, string> m_paramsTo = new Dictionary<string, string>();
/// <summary>
/// 接受子流程的返回值对应关系
/// </summary>
public Dictionary<string, string> m_paramsFrom = new Dictionary<string, string>();
public CSubProcessEvent(CWorkFlow parent) : base(parent)
{
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public override void InstFromXmlNode(XmlNode xmlNode)
{
if (xmlNode.Attributes["type"].Value != "subprocess")
return;
//1. 解析基类CEvent的成员
base.InstFromXmlNode(xmlNode);
currentaction = ""; //无论XML是否指定currentaction, 它都为空
//2. 解析SubProcessEvent的成员
//3. 反解析子工作流
XmlNode linwf = xmlNode.SelectSingleNode("linkworkflow");
WfName = linwf.Attributes["name"].Value;
if (linwf.Attributes["workingmodel"] == null || linwf.Attributes["workingmodel"].Value.Trim() == "")
WorkingMode = "serial";
else
WorkingMode = linwf.Attributes["workingmodel"].Value;
if (linwf.Attributes["id"] == null || linwf.Attributes["id"].Value.Trim() == "")
WfEntityId = -1;
else
WfEntityId = Convert.ToInt32(linwf.Attributes["id"].Value);
//3.1 反解析参数传递
XmlNode pars_transfer = linwf.SelectSingleNode("paramtransfer");
// 变量对应关系
foreach(XmlNode item in pars_transfer.SelectNodes("item"))
{
if (item.Attributes["direction"].Value == "to") // to
m_paramsTo[item.Attributes["parent"].Value] = item.Attributes["child"].Value;
else if (item.Attributes["direction"].Value == "from") // from
m_paramsFrom[item.Attributes["parent"].Value] = item.Attributes["child"].Value;
else
return;
}
}
/// <summary>
/// 反解析到XML元素
/// </summary>
public override XmlNode WriteToXmlNode()
{
//1. 反解析基类部分成员
XmlNode xn = base.WriteToXmlNode();
//2. 反解析SubProcessEvent的成员
XmlElement xe = (XmlElement)xn;
xe.SetAttribute("type", "subprocess");
//3. 反解析相关的工作流
XmlElement linkwf = xn.OwnerDocument.CreateElement("linkworkflow");
linkwf.SetAttribute("name", WfName);
linkwf.SetAttribute("workingmodel", WorkingMode);
linkwf.SetAttribute("id", WfEntityId.ToString());
//3.1 添加参数传递
XmlElement pars_transfer = linkwf.OwnerDocument.CreateElement("paramtransfer");
//a. 添加To变量对应关系
foreach(var par in m_paramsTo)
{
XmlElement parTo = linkwf.OwnerDocument.CreateElement("item");
parTo.SetAttribute("direction", "to");
parTo.SetAttribute("parent", par.Key);
parTo.SetAttribute("child", par.Value);
pars_transfer.AppendChild(parTo);
}
//b. 添加From变量对应关系
foreach(var par in m_paramsFrom)
{
XmlElement parFrom = linkwf.OwnerDocument.CreateElement("item");
parFrom.SetAttribute("direction", "from");
parFrom.SetAttribute("parent", par.Key);
parFrom.SetAttribute("child", par.Value);
pars_transfer.AppendChild(parFrom);
}
linkwf.AppendChild(pars_transfer);
xe.AppendChild(linkwf);
return xn;
}
/// <summary>
/// 进入该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void EnterEvent(string strjson)
{
if (beforeaction != "")
{
string strjson1 = "{param:'{";
foreach (var par in m_beforeActionParams)
{
string tmp = string.Format("{0}:\"{1}\",", par.Key, parselEventActionParams(par.Value));
strjson1 += tmp;
}
strjson1.TrimEnd(new char[] { ',' });
strjson1 += "}'}";
try
{
byte[] bytes = Encoding.UTF8.GetBytes(strjson1);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(beforeaction);
request.ContentType = @"application/json";
request.Accept = "application/xml";
request.Method = "POST";
request.ContentLength = bytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Dispose();
//结束动作函数返回值
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//对返回结果进行处理
OpResutsfromAction(sr.ReadToEnd());
}
catch (Exception e)
{
Trace.WriteLine("EnterEvent error:" + e.Message);
//return;
}
}
CWorkFlow wf = new CWorkFlow();
//2016/2/12--保证子工作流串号与父工作流相同
if (!wf.CreateEntity(WfName, this.m_parentWF.EntitySerial))
{
Trace.WriteLine("Create {0} SubProcess error!", WfName);
return;
}
WfEntityId = wf.EntityID;
wf.ParentEntityID = m_parentWF.EntityID;
//设置子流程初始参数
foreach(var parTo in m_paramsTo)
{
wf.paramstable[parTo.Value].value = m_params[parTo.Key].value;
}
//2016/2/12--将自己的Record传给子流程
//2016/2/14--发现WFEngine中已通过Post_processSubprocess将record传给了子流程,故而取消修改
//至于为何没有起作用,待调试
//WorkFlows wfs = new WorkFlows();
//Mission ms = wfs.GetWFEntityLastMission(wf.EntityID);
//List<Process_Record> parent_res = wfs.GetMissionRecordInfo(ms.Miss_Id);
//Dictionary<string, string> res = new Dictionary<string, string>();
//foreach (var re in parent_res)
//{
//如果record中包含事件定义的需要记录的record item则记录到数据库中
// if (m_parentWF.GetRecordItems().ContainsKey(re.Re_Name))
// {
// res[re.Re_Name] = re.Re_Value;
// }
//}
wf.Start(null); //原始版本 wf.Start(null);
string sub_status = "";
do
{
sub_status = wf.GetCurrentState();
wf.SubmitSignal("[]");
} while (wf.GetCurrentState() != sub_status); //给子流程激励,直至其状态不再发生变化,即需要人员介入
//如果以并行方式工作, 发送激励信号
//if (WorkingMode == "parallel")
// m_parentWF.SubmitSignal("[]");
base.UpdateCurrentEvent();
}
/// <summary>
/// 离开该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void LeaveEvent(string strjson)
{
if (beforeaction != "")
{
string strjson1 = "{param:'{";
foreach (var par in m_afterActionParams)
{
string tmp = string.Format("{0}:\"{1}\",", par.Key, parselEventActionParams(par.Value));
strjson1 += tmp;
}
strjson1.TrimEnd(new char[] { ',' });
strjson1 += "}'}";
try
{
byte[] bytes = Encoding.UTF8.GetBytes(strjson1);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(afteraction);
request.ContentType = @"application/json";
request.Accept = "application/xml";
request.Method = "POST";
request.ContentLength = bytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Dispose();
//结束动作函数返回值
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//对返回结果进行处理
OpResutsfromAction(sr.ReadToEnd());
}
catch (Exception e)
{
Trace.WriteLine("EnterEvent error:" + e.Message);
//return;
}
}
//保存信息到数据库
base.InsertMissionToDB();
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using FlowEngine.Modals;
using FlowEngine.DAL;
using System.Xml;
using FlowEngine.Event;
using EquipBLL.FileManagment;
//add
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using EquipBLL.guidelinesmanagment;
namespace WebApp.Controllers
{
public class CommonController : Controller
{
//Page Models
public class MainMissionsModel
{
public string jobname;
public string WF_Name;
public string MISS_Url;
public string wfe_serial;
public string MISS_Name;
public string time;
public string Equip_GyCode;
}
public class MainModel
{
public string userName;
public string missTime;
public int missIndex;
public string miss_desc;
public string miss_url;
public string wfe_serial;
public string sbGycode;
public string workFlowName;
}
public class ZzRunhuaSubmitModel
{
public string UserName;
public string UserDepartment;
public List<Runhua_Info> UserHasEquips;
}
public class HistroyModel
{
public int miss_wfe_Id;
public string missStartName;
public string missStartTime;
public int missIndex;
public string miss_LastStatusdesc;
public string wfe_serial;
public string sbGycode;
public string workFlowName;
}
public class Index_Model
{
public List<MainModel> Am;
public List<HistroyModel> Hm;
}
public class MissInfoModel
{
public UI_MISSION miModel;
public List<string> MissTime;
public List<string> MissUser;
}
public class WFDetail_Model
{
public List<UI_MISSION> ALLHistoryMiss;
public List<string> MissTime;
public List<string> MissUser;
}
public class ZzSubmitModel
{
public string UserName;
public string UserDepartment;
public List<Equip_Archi> UserHasEquips;
}
//A5_ModelInfo
public class A5_ModelInfo
{
public string Pq_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public int nTimesInMonth;
public int nTimesInYear;
public int nFlagTheWorstTen;//是否列入最差或最脏10台? 0-否,1-是
}
//A5_Model
public class A5_Model
{
public List<A5_ModelInfo> A5_ModelInfoList;
}
//Risk Matrix
public class RiskMatrixElement
{
public int danger_intensity;
public int time_level;
public string color;
public string DangerType_isgreen;
}
public class MissHisLinkModal
{
public int Miss_Id;
public string Miss_Name;
public string Miss_Time;
public int Miss_Type; //0:历史的一般任务 1:子流程任务 2:活动的一般任务
public string Miss_LinkFlowType;//"Normal" ,"paradel","Serial"
public int Miss_LinkFlowId;//跳转的工作流Id
public string Miss_LinkFlowName;//跳转的工作流名称
}
public class MissionTemp
{
public UI_MISSION miss_info;
public int miss_status;//0:Histroy 1:active
}
public class ListMissHisLInkModal
{
public int Flow_Id;
public string Flow_Name;
public string FLow_DescPath;
public string FLow_EquipGyCode;
public List<MissHisLinkModal> Miss;
}
public class A11dot2Model
{
public int index_Id;
public string zz_name;
public string sb_gycode;
public string sb_code;
public string problem_desc;
public string riskMatrix_color;
public string supervise_done;
public string implementplan_done;
public string missionname;
}
public class A14dot3Model
{
public int index_Id;
public string zz_name;
public string sb_gycode;
public string sb_code;
public string sb_type;
public string sb_ABCMark;
public string plan_name;
public string jxreason;
public string xcconfirm;
public string kkconfirm;
public string zytdconfirm;
public string job_order;
public string notice_order;
public string missionname;
public string role;
}
public class A14dot3dot3Model
{
public int index_Id;
public string zz_name;
public string sb_gycode;
public string sb_code;
public string sb_type;
public string sb_ABCMark;
public string plan_name;
public string jxreason;
public string xcconfirm;
public string kkconfirm1;
public string zytdconfirm1;
public string job_order1;
public string notice_order1;
public string missionname;
public string role;
}
public class A14dot3dot4Model
{
public int index_Id;
public string zz_name;
public string sb_gycode;
public string sb_code;
public string sb_type;
public string sb_ABCMark;
public string plan_name;
public string jxreason;
public string xcconfirm;
public string kkconfirm2;
public string zytdconfirm2;
public string job_order2;
public string notice_order2;
public string missionname;
public string role;
}
public class A8Model
{
public int index_Id;
public string zz_name;
public string sb_gycode;
public string plan_name;
public string job_order;
public string notice_order;
public string Data_Src;
public string gd_state;
public string detail;
}
public MainMissionsModel GetMainMissionsInfo(int entity_id)
{
MainMissionsModel mm = new MainMissionsModel();
UI_WFEntity_Info wfe = new UI_WFEntity_Info();
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe1 = wfs.GetWorkFlowEntity(entity_id);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe1.WE_Binary));
XmlNode xml = doc.DocumentElement;
wf.InstFromXmlNode(xml);
IEvent e = wf.GetCurrentEvent();
if (wfe1.Last_Trans_Time != null)
mm.time = wfe1.Last_Trans_Time.ToString();
else
mm.time = "";
mm.wfe_serial = wfe1.WE_Ser;
mm.WF_Name = wf.description;
mm.MISS_Name = e.description;
mm.jobname = wf.name + ":" + e.name;
mm.MISS_Url = e.currentaction;
mm.Equip_GyCode = wf.paramstable["Equip_GyCode"].value.ToString();
return mm;
}
public JsonResult get_zhidubymenu(int menu_id)
{
ZhiduManagment Zm = new ZhiduManagment();
List<ZhiduFile> E = Zm.get_zhidu(menu_id);
List<object> e_obj = new List<object>();
foreach (var item in E)
{
object o = new
{
pdf_name = item.pdf_name
};
e_obj.Add(o);
}
return Json(e_obj.ToArray());
}
public ListMissHisLInkModal List_subFLow(UI_WFEntity_Info wfe, int condition)
{
List<MissionTemp> miss_temp = new List<MissionTemp>();
ListMissHisLInkModal missModals = new ListMissHisLInkModal();
missModals.Miss = new List<MissHisLinkModal>();
missModals.Flow_Id = wfe.EntityID;
missModals.Flow_Name = wfe.description;
missModals.FLow_DescPath = Path.Combine(("/files"), wfe.name + ".pdf");
List<UI_MISSION> miss = CWFEngine.GetHistoryMissions(wfe.EntityID);
if (condition == 1) missModals.FLow_EquipGyCode = miss[1].Miss_Params["Equip_GyCode"].ToString();
foreach (var item in miss)
{
MissionTemp temp = new MissionTemp();
temp.miss_info = item;
temp.miss_status = 0;
miss_temp.Add(temp);
}
if (wfe.Status == WE_STATUS.ACTIVE)
{
MissionTemp temp = new MissionTemp();
temp.miss_info = CWFEngine.GetActiveMission<Person_Info>(wfe.EntityID, null, false);
temp.miss_status = 1;
miss_temp.Add(temp);
}
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe2 = wfs.GetWorkFlowEntity(wfe.EntityID);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe2.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wf.EntityID = wfe.EntityID;
IDictionary<string, IEvent> allEvents = wf.events;
foreach (var tt in miss_temp)
{
var item = tt.miss_info;
if (item.WE_Event_Name == "Start") continue;
MissHisLinkModal m = new MissHisLinkModal();
m.Miss_Id = item.Miss_Id;
m.Miss_Name = item.WE_Event_Desc;
if (item.Miss_Id > 0)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
m.Miss_Time = r["time"];
}
else
{
m.Miss_Time = "";
}
}
else
{
m.Miss_Time = "";
}
if (allEvents[item.WE_Event_Name].GetType().Name == "CSubProcessEvent")
{
m.Miss_Type = 1;
m.Miss_LinkFlowType = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WorkingMode;
m.Miss_LinkFlowId = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WfEntityId;
m.Miss_LinkFlowName = Path.Combine(("/files"), ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WfName + ".pdf");
}
else
{
if (tt.miss_status == 1)
{
m.Miss_Type = 2;
m.Miss_LinkFlowType = "Normal";
m.Miss_LinkFlowId = -1;
m.Miss_LinkFlowName = "";
}
else
{
m.Miss_Type = 0;
m.Miss_LinkFlowType = "Normal";
m.Miss_LinkFlowId = -1;
m.Miss_LinkFlowName = "";
}
}
missModals.Miss.Add(m);
}
return missModals;
}
public JsonResult WorkFlow_MainProcess(string Entity_Ser)
{
UI_WFEntity_Info wfe = CWFEngine.GetMainWorkFlowEntity(Entity_Ser);
return Json(List_subFLow(wfe, 1));
}
public JsonResult WorkFlow_ListParam(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
int Flow_Id = Convert.ToInt32(item["Entity_Id"].ToString());
int Mission_Id = Convert.ToInt32(item["Mission_Id"].ToString());
List<UI_MissParam> MissParams = CWFEngine.GetMissionParams(Flow_Id, Mission_Id);
return Json(MissParams.ToArray());
}
public JsonResult WorkFlow_SubProcess(int FlowId)
{
UI_WFEntity_Info wfe = CWFEngine.GetWorkFlowEntiy(FlowId, true);
return Json(List_subFLow(wfe, 0));
}
public JsonResult WorkFlow_EquipInfo(String Equip_GyCode)
{
EquipManagment EM = new EquipManagment();
Equip_Info Einfo = EM.getEquip_ByGyCode(Equip_GyCode);
List<Equip_Archi> Equip_ZzBelong = EM.getEquip_ZzBelong(Einfo.Equip_Id);
List<Object> listE = new List<object>();
listE.Add(new { Param_Name = "设备所在车间", Param_value = Equip_ZzBelong[1].EA_Name });
listE.Add(new { Param_Name = "设备所属装置", Param_value = Equip_ZzBelong[0].EA_Name });
listE.Add(new { Param_Name = "设备工艺编号", Param_value = Einfo.Equip_GyCode });
listE.Add(new { Param_Name = "设备B相分类", Param_value = Einfo.Equip_PhaseB });
listE.Add(new { Param_Name = "设备专业分类", Param_value = Einfo.Equip_Specialty });
listE.Add(new { Param_Name = "设备型号", Param_value = Einfo.Equip_Type });
listE.Add(new { Param_Name = "设备生产厂家", Param_value = Einfo.Equip_Manufacturer });
if (string.IsNullOrEmpty(Einfo.Equip_ManufactureDate))
listE.Add(new { Param_Name = "设备生产日期", Param_value = "" });
else
listE.Add(new { Param_Name = "设备生产日期", Param_value = Einfo.Equip_ManufactureDate });
return Json(listE.ToArray());
}
//Page BLL Codes
/// <summary>
/// 获取工作流Index页面的列表记录
/// </summary>
/// <param name="WorkFlow_Name">工作流名称,如A8dot2</param>
/// <param name="username">用户名</param>
/// <returns></returns>
///
//A6dot2用查询开始
public string getdclA6dot2_list(string WorkFlow_Name)
{
List<MainModel> Am = new List<MainModel>();
List<UI_MISSION> miss;
List<object> or = new List<object>();
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
foreach (var item in miss)
{
MainModel o = new MainModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Pq_Name"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Entity_Id, paras);
UI_MISSION lastMi = CWFEngine.GetHistoryMissions(item.WE_Entity_Id).Last();
int Miss_Id = lastMi.Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
o.userName = r["username"];
o.missTime = r["time"];
}
else
{
o.userName = "";
o.missTime = "";
}
o.miss_desc = item.WE_Event_Desc;
if (item.Mission_Url.Contains("dot"))
o.miss_url = item.Mission_Url;
else
o.miss_url = "";
o.wfe_serial = wfei.serial;
o.workFlowName = wfei.description;
o.sbGycode = paras["Pq_Name"].ToString();
Am.Add(o);
}
for (int i = 0; i < Am.Count; i++)
{
object o = new
{
wfe_serial = Am[i].wfe_serial,
equip_gycode = Am[i].sbGycode,
workflow_name = Am[i].workFlowName,
miss_desc = Am[i].miss_desc,
missTime = Am[i].missTime,
userName = Am[i].userName,
miss_url = Am[i].miss_url
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public string gethistoryA6dot2_list(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
List<HistroyModel> Hm = new List<HistroyModel>();
List<UI_WFEntity_Info> start_entities;
List<object> or = new List<object>();
start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == WorkFlow_Name);
foreach (var item in start_entities)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Pq_Name"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.EntityID, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.serial;
h.miss_wfe_Id = item.EntityID;
h.workFlowName = wfei.description;
h.sbGycode = paras["Pq_Name"].ToString();
Hm.Add(h);
}
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = "已完成",
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public string getactiveA6dot2_list(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string query_list = "distinct E.WE_Id,R.username";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='0' and M.Miss_Name <> 'Start' and R.username is not null";
string record_filter = "username='" + username + "'";
List<int> wfe_id = new List<int>();
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
for (int i = 0; i < dt.Rows.Count; i++)
{
wfe_id.Add(Convert.ToInt16(dt.Rows[i]["WE_Id"]));
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in wfe_id)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Pq_Name"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = wfei.serial;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item;
h.workFlowName = wfei.description;
h.sbGycode = paras["Pq_Name"].ToString();
Hm.Add(h);
}
List<object> or = new List<object>();
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
//A6dot2用查询结束
public Index_Model getIndexListRecords(string WorkFlow_Name, string username)
{
List<UI_MISSION> miss;
//miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
Index_Model listRecord = new Index_Model();
listRecord.Am = new List<MainModel>();
foreach (var item in miss)
{
MainModel o = new MainModel();
UI_MISSION lastMi = CWFEngine.GetHistoryMissions(item.WE_Entity_Id).Last();
int Miss_Id = lastMi.Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
o.userName = r["username"];
o.missTime = r["time"];
}
else
{
o.userName = "";
o.missTime = "";
}
o.missIndex = miss.IndexOf(item) + 1;
o.miss_desc = item.WE_Event_Desc;
//if(!string.IsNullOrEmpty(item.Mission_Url))
if (item.Mission_Url.Contains("dot"))
//o.miss_url = item.Mission_Url + @"wfe_id=" + item.WE_Entity_Id;
o.miss_url = item.Mission_Url;
else
o.miss_url = "";
//
//List<UI_WFEntity_Info> current_entitie = CWFEngine.GetWFEntityByHistoryStatus(t => t.Miss_WFentity.WE_Id== item.WE_Entity_Id);
//o.wfe_serial = current_entitie[0].serial;
o.wfe_serial = lastMi.WE_Entity_Ser;
listRecord.Am.Add(o);
}
listRecord.Hm = new List<HistroyModel>();
HistroyModel h;
List<UI_WFEntity_Info> start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == WorkFlow_Name);
foreach (var item in start_entities)
{
h = new HistroyModel();
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.missIndex = start_entities.IndexOf(item) + 1;
h.wfe_serial = item.serial;
UI_MISSION miss_last = AllHistoryMiss[AllHistoryMiss.Count() - 1];
h.miss_LastStatusdesc = miss_last.WE_Event_Desc;
h.miss_wfe_Id = item.EntityID;
listRecord.Hm.Add(h);
}
return listRecord;
}
/// <summary>
/// 获取index页面待处理列表内容
/// </summary>
/// <param name="WorkFlow_Name"></param>
/// <returns>json格式字符串给前台</returns>
public string getdcl_list(string WorkFlow_Name)
{
List<MainModel> Am = new List<MainModel>();
List<UI_MISSION> miss;
List<object> or = new List<object>();
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
foreach (var item in miss)
{
MainMissionsModel mm = GetMainMissionsInfo(item.WE_Entity_Id);
MainModel o = new MainModel();
//Dictionary<string, object> paras = new Dictionary<string, object>();
//paras["Equip_GyCode"] = null;
//UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Entity_Id, paras);
UI_MISSION lastMi = CWFEngine.GetHistoryMissions(item.WE_Entity_Id).Last();
int Miss_Id = lastMi.Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
o.userName = r["username"];
o.missTime = mm.time;
}
else
{
o.userName = "";
o.missTime = "";
}
o.miss_desc = item.WE_Event_Desc;
if (item.Mission_Url.Contains("dot"))
o.miss_url = item.Mission_Url;
else
o.miss_url = "";
o.wfe_serial = mm.wfe_serial;
o.workFlowName = mm.WF_Name;
o.sbGycode = mm.Equip_GyCode;
Am.Add(o);
}
for (int i = 0; i < Am.Count; i++)
{
object o = new
{
wfe_serial = Am[i].wfe_serial,
equip_gycode = Am[i].sbGycode,
workflow_name = Am[i].workFlowName,
miss_desc = Am[i].miss_desc,
missTime = Am[i].missTime,
userName = Am[i].userName,
miss_url = Am[i].miss_url
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
/// <summary>
/// 获取index页面历史操作列表
/// </summary>
/// <param name="WorkFlow_Name"></param>
/// <returns>json格式字符串给前台</returns>
public string gethistory_list(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
List<HistroyModel> Hm = new List<HistroyModel>();
List<UI_WFEntity_Info> start_entities;
List<object> or = new List<object>();
if (WorkFlow_Name != "A7dot1dot1")
{
start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == WorkFlow_Name);
foreach (var item in start_entities)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.EntityID, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.serial;
h.miss_wfe_Id = item.EntityID;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
}
else
{
start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == "A7dot1dot1");
foreach (var item in start_entities)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.EntityID, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.serial;
h.miss_wfe_Id = item.EntityID;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == "A7dot1");
foreach (var item in start_entities)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.EntityID, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.serial;
h.miss_wfe_Id = item.EntityID;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
}
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = "已完成",
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public string gethistory_listforA7dot1dot1(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
List<HistroyModel> Hm = new List<HistroyModel>();
List<UI_WFEntity_Info> start_entities;
List<object> or = new List<object>();
if (WorkFlow_Name != "A7dot1dot1")
{
start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == WorkFlow_Name);
foreach (var item in start_entities)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.EntityID, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.serial;
h.miss_wfe_Id = item.EntityID;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
}
else
{
start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == "A7dot1dot1");
foreach (var item in start_entities)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.EntityID, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.serial;
h.miss_wfe_Id = item.EntityID;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Record_Info.Count(q => q.Re_Name == "username" && q.Re_Value == username) > 0 && t.Miss_WFentity.WE_Wref.W_Name == "A7dot1");
foreach (var item in start_entities)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.EntityID, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.serial;
h.miss_wfe_Id = item.EntityID;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
}
for (int i = 0; i < Hm.Count; i++)
{
WorkFlows wfs = new WorkFlows();
List<WorkFlow_Entity> getentity = wfs.GetWorkFlowEntitiesbySer(Hm[i].wfe_serial);
int uncompletecount=0;//未完成的任务数
string miss_LastStatusdesc="已完成";
foreach(var vtim in getentity)
{
if (vtim.WE_Status == WE_STATUS.ACTIVE)
{
uncompletecount++;
miss_LastStatusdesc="未封闭";
}
}
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = miss_LastStatusdesc,
miss_result = "有" + uncompletecount + "个未封闭任务",
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public string getactive_list(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string query_list = "distinct E.WE_Id,R.username";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='0' and M.Miss_Name <> 'Start' and R.username is not null";
string record_filter = "username='" + username + "'";
List<int> wfe_id = new List<int>();
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
for (int i = 0; i < dt.Rows.Count; i++)
{
wfe_id.Add(Convert.ToInt16(dt.Rows[i]["WE_Id"]));
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in wfe_id)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = wfei.serial;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
List<object> or = new List<object>();
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public JsonResult Cj_ZzsForA16(string cj_id)
{
EquipManagment pm = new EquipManagment();
List<Equip_Archi> Zz = new List<Equip_Archi>();
List<object> Zz_obj = new List<object>();
string[] chejian_id = cj_id.Split(',');
for (int i = 0; i < chejian_id.Length; i++)
{
Zz = pm.getZzs_ofCj(Convert.ToInt32(chejian_id[i]));
foreach (var item in Zz)
{
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name
};
Zz_obj.Add(o);
}
}
return Json(Zz_obj.ToArray());
}
public JsonResult Cj_Zzs(int cj_id)
{
PersonManagment pm = new PersonManagment();
// EquipManagment em = new EquipManagment();
int p_id = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
List<Equip_Archi> Zz = pm.Get_Person_Zz_ofCj(p_id, cj_id);
List<object> Zz_obj = new List<object>();
foreach (var item in Zz)
{
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name
};
Zz_obj.Add(o);
}
return Json(Zz_obj.ToArray());
}
public JsonResult Zz_Equips(int Zz_id)
{
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
string speciaty = pv.Speciaty_Names;
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
EquipManagment em = new EquipManagment();
List<Equip_Info> Equips_of_Zz = em.getEquips_OfZz(Zz_id, username);
List<object> Equip_obj = new List<object>();
foreach (var item in Equips_of_Zz)
{
object o = new
{
Equip_Id = item.Equip_Id,
Equip_GyCode = item.Equip_GyCode,
// Equip_Code=item.Equip_Code,
// Equip_Type=item.Equip_Type,
// Equip_Specialty=item.Equip_Specialty
};
Equip_obj.Add(o);
}
return Json(Equip_obj.ToArray());
}
public JsonResult ListEquip_Info(int Equip_Id)
{
EquipManagment pm = new EquipManagment();
Equip_Info EquipInfo_selected = pm.getEquip_Info(Equip_Id);
List<object> Equip_obj = new List<object>();
object o = new
{
Equip_Code = EquipInfo_selected.Equip_Code,
Equip_Type = EquipInfo_selected.Equip_Type,
Equip_Specialty = EquipInfo_selected.Equip_Specialty,
Equip_PhaseB = EquipInfo_selected.Equip_PhaseB
};
Equip_obj.Add(o);
return Json(Equip_obj.ToArray());
}
/// <summary>
///
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public ZzSubmitModel getSubmitModel(string wfe_id)
{
PersonManagment pm = new PersonManagment();
ZzSubmitModel mm = new ZzSubmitModel();
ViewBag.WF_NAME = wfe_id;
mm.UserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
mm.UserDepartment = pm.Get_Person_DepartOfParent((Session["User"] as EquipModel.Entities.Person_Info).Person_Id).Depart_Name;
mm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = mm.UserName;
ViewBag.equip_id = "";
//邹晶修改161110
try
{
if (wfe_id != null && wfe_id != "")
{
EquipManagment Em = new EquipManagment();
ViewBag.cj_name = "";
ViewBag.zz_id = 0;
ViewBag.zz_name = "";
ViewBag.sb_gycode = "";
ViewBag.sb_code = "";
ViewBag.cj_id = 0;
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
paras["Equip_GyCode"] = null;
paras["Equip_Code"] = null;
WorkFlows wfsd = new WorkFlows();
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(Convert.ToInt32(wfe_id), paras);
Dictionary<string, object> m_kv = new Dictionary<string, object>();
Mission db_miss = wfsd.GetWFEntityMissions(Convert.ToInt32(wfe_id)).Last();//获取该实体最后一个任务
if (paras["Zz_Name"].ToString() != null && paras["Zz_Name"].ToString() != "")
{
ViewBag.zz_name = paras["Zz_Name"].ToString();
ViewBag.zz_id = Em.getEa_idbyname(paras["Zz_Name"].ToString());
ViewBag.cj_name = Em.getEquip(paras["Zz_Name"].ToString()).ToString();
ViewBag.cj_id = Em.getEA_parentid(ViewBag.zz_id);
}
if (paras["Equip_GyCode"].ToString() != null && paras["Equip_GyCode"].ToString() != "")
{
ViewBag.sb_gycode = paras["Equip_GyCode"].ToString();
ViewBag.sb_code = Em.getEquip_ByGyCode(paras["Equip_GyCode"].ToString()).Equip_Code;
ViewBag.equip_id = Em.getEquip_ByGyCode(paras["Equip_GyCode"].ToString()).Equip_Id.ToString();
ViewBag.zz_id = Em.getEA_id_byCode(ViewBag.sb_code);
ViewBag.zz_name = Em.getEquip_ZzBelong(Convert.ToInt32(ViewBag.equip_id))[0].EA_Name;
// ViewBag.zz_id = Em.getEa_idbyname(ViewBag.zz_name);
ViewBag.cj_name = Em.getEquip(ViewBag.zz_name).ToString();
ViewBag.cj_id = Em.getEA_parentid(ViewBag.zz_id);
}
}
}
catch(Exception e)
{
return mm;
}
return mm;
}
/// <summary>
/// 为润滑间管理创建的model,目的是提报时获取润滑间列表
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public ZzRunhuaSubmitModel getRunhuaSubmitModel(string wfe_id)
{
PersonManagment pm = new PersonManagment();
ZzRunhuaSubmitModel mm = new ZzRunhuaSubmitModel();
ViewBag.WF_NAME = wfe_id;
mm.UserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
mm.UserDepartment = pm.Get_Person_DepartOfParent((Session["User"] as EquipModel.Entities.Person_Info).Person_Id).Depart_Name;
mm.UserHasEquips = pm.Get_Runhua_Cj();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = mm.UserName;
return mm;
}
/// <summary>
///
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public MissInfoModel getMissInfoModel(string wfe_id)
{
MissInfoModel cm = new MissInfoModel();
ViewBag.WF_NAME = wfe_id;
cm.miModel = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
cm.MissTime = new List<string>();
cm.MissUser = new List<string>();
string t;
foreach (var item in CWFEngine.GetHistoryMissions(cm.miModel.WE_Entity_Id))
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
t = r["username"];
cm.MissUser.Add(t);
t = r["time"];
cm.MissTime.Add(t);
}
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
return cm;
}
/// <summary>
///
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public WFDetail_Model getWFDetail_Model(string wfe_id)
{
WFDetail_Model cm = new WFDetail_Model();
ViewBag.WF_NAME = wfe_id;
cm.ALLHistoryMiss = CWFEngine.GetHistoryMissions(int.Parse(wfe_id));
ViewBag.WF_Ser = cm.ALLHistoryMiss[0].WE_Entity_Ser;
cm.MissTime = new List<string>();
cm.MissUser = new List<string>();
string t;
foreach (var item in cm.ALLHistoryMiss)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
t = r["username"];
cm.MissUser.Add(t);
t = r["time"];
cm.MissTime.Add(t);
}
else
{
cm.MissUser.Add("");
cm.MissTime.Add("");
}
}
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
return cm;
}
public class Gxqmodel
{
public int WE_Id;
public string WE_Ser;
}
public class A5dot1Gxqmodel
{
public string wfe_serial;
public string sbGycode;
public string workFlowName;
public string missStartName;
public string missStartTime;
public string miss_LastStatusdesc;
public string miss_wfe_Id;
}
/// <summary>
/// 获取用户可能感兴趣的列表,邹晶0726
/// </summary>
/// <returns></returns>
public string Getgxq_list(string WE_Status, string WorkFlow_Name, string Cjname, string time)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string record_filter = "";
string query_list = "";
if (time == "")
{
record_filter = "username is not null";
query_list = "distinct E.WE_Ser, E.WE_Id, R.username,R.time";
}
else
{
string[] strtime = time.Split(new char[] { '-' });
record_filter = "time >= '" + strtime[0] + "00:00:00'" + "and time <= '" + strtime[1] + " 00:00:00' and username is not null";
query_list = "distinct E.WE_Ser, E.WE_Id, R.username,R.time";
}
//string WorkFlow_Name = "A11dot1";
//string Cjname = "联合一车间";
//string WE_Status = "0";
string query_condition = "";
if (WorkFlow_Name != "" && Cjname != "")
query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "'and P.Cj_Name='" + Cjname + "' and R.username is not null";
else if (WorkFlow_Name != "" && Cjname == "")
query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "' and R.username is not null";
else if (WorkFlow_Name == "" && Cjname != "")
query_condition = "E.WE_Status='" + WE_Status + "'and P.Cj_Name='" + Cjname + "' and R.username is not null";
else
query_condition = "WE_Status='0' and R.username is not null";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
var tmp = from t in dt.AsEnumerable()
group t by t.Field<int>("WE_Id") into g
select new { WE_Id = g.First().Field<int>("WE_Id"), time = g.Max(item => item.Field<string>("time")) };
//var a = tmp.ToList();
var res = from d1 in dt.AsEnumerable()
from d2 in tmp
where d1.Field<int>("WE_Id") == d2.WE_Id && d1.Field<string>("time") == d2.time
select d1;
//var b = res.ToList();
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < res.ToList().Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(res.ToList()[i]["WE_Id"]);
Gm.WE_Ser = res.ToList()[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in Gmlist)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.WE_Id);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.WE_Ser;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item.WE_Id;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
List<A5dot1Tab1> qc_list = new List<A5dot1Tab1>();
TablesManagment tm = new TablesManagment();
if (WorkFlow_Name == "" || WorkFlow_Name == "A5dot1")
{
if (Cjname == "")
{
qc_list = tm.get_All();
}
else
{
qc_list = tm.get_cj_bwh(Cjname, 0);
}
}
List<A5dot1Gxqmodel> A5model = new List<A5dot1Gxqmodel>();
//A5dot1Gxqmodel A5dot1Gxqmodeltemp = new A5dot1Gxqmodel();
//double qc_bxhcount = 0;
int wzgcount = 0;
if (qc_list.Count > 0)
{
string s = "";
string isZG = "";
string problemDescription = "";
//qc_bxhcount = 0;
wzgcount = 0;
string sbcode_temp = qc_list[0].sbCode;
for (int j = 0; j < qc_list.Count; j++)
{
if (WorkFlow_Name == "" || WorkFlow_Name == "A5dot1")
{
if (Cjname == "")
{
qc_list = tm.get_All();
}
else
{
qc_list = tm.get_cj_bwh(Cjname, 0);
}
}
if (qc_list[j].temp1 == null)
{
A5dot1Gxqmodel A5dot1Gxqmodeltemp = new A5dot1Gxqmodel();
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(qc_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzgcount++;
isZG = "未整改";
}
else
isZG = "已整改";
s += cj_bycode[k].notGoodContent + " (" + isZG + ") ";
problemDescription += cj_bycode[k].notGoodContent;
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzgcount > 0)
{
// qc_bxhcount++;
A5dot1Gxqmodeltemp.miss_LastStatusdesc = "等待未整改项整改";
}
else
{
A5dot1Gxqmodeltemp.miss_LastStatusdesc = "可靠性工程师整改结束";
}
wzgcount = 0;
A5dot1Gxqmodeltemp.miss_wfe_Id = s;
A5dot1Gxqmodeltemp.sbGycode = qc_list[j].sbCode;
A5dot1Gxqmodeltemp.wfe_serial = "";
A5dot1Gxqmodeltemp.missStartName = qc_list[j].zzUserName;
A5dot1Gxqmodeltemp.missStartTime = qc_list[j].zzSubmitTime.ToString();
A5dot1Gxqmodeltemp.workFlowName = "设备完好";
A5model.Add(A5dot1Gxqmodeltemp);
s = "";
}
}
}
for (int n = 0; n < qc_list.Count; n++)
{
tm.modifytemp1_byid(qc_list[n].Id, null);
}
List<object> or = new List<object>();
for (int i = 0; i < A5model.Count; i++)
{
object o = new
{
wfe_serial = A5model[i].wfe_serial,
equip_gycode = A5model[i].sbGycode,
workflow_name = A5model[i].workFlowName,
missStartName = A5model[i].missStartName,
missStartTime = A5model[i].missStartTime,
miss_LastStatusdesc = A5model[i].miss_LastStatusdesc,
miss_wfe_Id = A5model[i].miss_wfe_Id
};
or.Add(o);
}
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
/// <summary>
/// 获取用户默认全部可能感兴趣的列表,邹晶0726
/// </summary>
/// <returns></returns>
public string MrGetgxq_list()
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
//string WorkFlow_Name = "A11dot1";
//string Cjname = "联合一车间";
//string WE_Status = "0";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username, R.time";
string query_condition = "WE_Status='0' and R.username is not null";
string record_filter = "username is not null";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
var tmp = from t in dt.AsEnumerable()
group t by t.Field<int>("WE_Id") into g
select new { WE_Id = g.First().Field<int>("WE_Id"), time = g.Max(item => item.Field<string>("time")) };
//var a = tmp.ToList();
var res = from d1 in dt.AsEnumerable()
from d2 in tmp
where d1.Field<int>("WE_Id") == d2.WE_Id && d1.Field<string>("time") == d2.time
select d1;
//var b = res.ToList();
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < res.ToList().Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(res.ToList()[i]["WE_Id"]);
Gm.WE_Ser = res.ToList()[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in Gmlist)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.WE_Id);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss.Last().WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.WE_Ser;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item.WE_Id;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
TablesManagment tm = new TablesManagment();
List<A5dot1Tab1> qc_list = tm.get_All();
List<A5dot1Gxqmodel> A5model = new List<A5dot1Gxqmodel>();
//A5dot1Gxqmodel A5dot1Gxqmodeltemp = new A5dot1Gxqmodel();
//double qc_bxhcount = 0;
int wzgcount = 0;
if (qc_list.Count > 0)
{
string s = "";
string isZG = "";
string problemDescription = "";
//qc_bxhcount = 0;
wzgcount = 0;
string sbcode_temp = qc_list[0].sbCode;
for (int j = 0; j < qc_list.Count; j++)
{
qc_list = tm.get_All();
if (qc_list[j].temp1 == null)
{
A5dot1Gxqmodel A5dot1Gxqmodeltemp = new A5dot1Gxqmodel();
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(qc_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzgcount++;
isZG = "未整改";
}
else
isZG = "已整改";
s += cj_bycode[k].notGoodContent + " (" + isZG + ") ";
problemDescription += cj_bycode[k].notGoodContent;
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzgcount > 0)
{
// qc_bxhcount++;
A5dot1Gxqmodeltemp.miss_LastStatusdesc = "等待未整改项整改";
}
else
{
A5dot1Gxqmodeltemp.miss_LastStatusdesc = "可靠性工程师整改结束";
}
wzgcount = 0;
A5dot1Gxqmodeltemp.miss_wfe_Id = s;
A5dot1Gxqmodeltemp.sbGycode = qc_list[j].sbCode;
A5dot1Gxqmodeltemp.wfe_serial = "";
A5dot1Gxqmodeltemp.missStartName = qc_list[j].zzUserName;
A5dot1Gxqmodeltemp.missStartTime = qc_list[j].zzSubmitTime.ToString();
A5dot1Gxqmodeltemp.workFlowName = "设备完好";
A5model.Add(A5dot1Gxqmodeltemp);
s = "";
}
}
}
for (int n = 0; n < qc_list.Count; n++)
{
tm.modifytemp1_byid(qc_list[n].Id, null);
}
List<object> or = new List<object>();
for (int i = 0; i < A5model.Count; i++)
{
object o = new
{
wfe_serial = A5model[i].wfe_serial,
equip_gycode = A5model[i].sbGycode,
workflow_name = A5model[i].workFlowName,
missStartName = A5model[i].missStartName,
missStartTime = A5model[i].missStartTime,
miss_LastStatusdesc = A5model[i].miss_LastStatusdesc,
miss_wfe_Id = A5model[i].miss_wfe_Id
};
or.Add(o);
}
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
/// <summary>
/// zoujing1012存定时事件详细信息
/// </summary>
/// <param name="work_name"></param>
/// <param name="event_name"></param>
/// <returns></returns>
//public bool SubmitDSEventDetails(string work_name, string event_name)
//{
// DsWorkManagment dm = new DsWorkManagment();
// DateTime now = DateTime.Now;
// string year = now.Year.ToString();
// string month = now.Month.ToString();
// if (dm.IsAlreadySave(work_name, event_name, year, month))
// return true;
// else
// {
// DSEventDetail ds = new DSEventDetail();
// ds.work_name = work_name;
// ds.event_name = event_name;
// ds.done_time = now;
// ds.year = year;
// ds.month = month;
// string time = dm.getDstime(work_name, event_name).Trim();
// if (time.Contains("-"))
// {
// string[] s = time.Split(new char[] { '-' });
// if (now.Month < Convert.ToInt16(s[0]))
// ds.state = "1";
// else if (now.Month == Convert.ToInt16(s[0]) & now.Day < Convert.ToInt16(s[1]))
// ds.state = "1";
// else
// ds.state = "0";
// }
// else if (time.Contains("*"))
// {
// string[] s = time.Split(new char[] { '*' });
// if ((int)now.DayOfWeek < Convert.ToInt16(s[0]))
// ds.state = "1";
// else
// ds.state = "0";
// }
// else if (time.Contains(","))
// {
// string[] s = time.Split(new char[] { ',' });
// if ((int)now.Day < Convert.ToInt16(s[s.Count() - 1]))
// ds.state = "1";
// else
// ds.state = "0";
// }
// else
// {
// if ((int)now.Day < Convert.ToInt16(time))
// ds.state = "1";
// else
// ds.state = "0";
// }
// dm.AddDsEvent(ds);
// return true;
// }
//}
/// <summary>
///
/// </summary>
/// <param name="typeA5">A5dot1或A5dot2</param>
/// <returns></returns>
public A5_Model getA5_Model(string WorkFlow_Name_Of_A5)
{
A5_Model A5model = new A5_Model();
A5model.A5_ModelInfoList = new List<A5_ModelInfo>();
A5_ModelInfo h;
List<UI_WFEntity_Info> start_entities = CWFEngine.GetWFEntityByHistoryDone(t => t.Miss_WFentity.WE_Wref.W_Name == WorkFlow_Name_Of_A5);
foreach (var item in start_entities)
{
h = new A5_ModelInfo();
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.EntityID);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
if (AllHistoryMiss.Count > 2)
{
h.Pq_Name = AllHistoryMiss[1].Miss_Params["Cj_Name"].ToString();
h.Zz_Name = AllHistoryMiss[1].Miss_Params["Zz_Name"].ToString();
h.Equip_Code = AllHistoryMiss[1].Miss_Params["Equip_Code"].ToString();
h.Equip_GyCode = AllHistoryMiss[1].Miss_Params["Equip_GyCode"].ToString();
h.nTimesInMonth = 2;
h.nTimesInYear = 3;
h.nFlagTheWorstTen = 0;
A5model.A5_ModelInfoList.Add(h);
}
else
{
}
}
return A5model;
}
//[HttpPost]
//public JsonResult Upload(HttpPostedFileBase file)
//{
// if (file.ContentLength == 0)
// {
// return Json(new { message = "没有文件" });
// }
// var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
// try
// {
// file.SaveAs(fileName);
// var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
// Dictionary<string, string> r = new Dictionary<string, string>();
// r.Add("message", "上传成功");
// r.Add("fileName", file.FileName);
// r.Add("fileSize", FileSize);
// return Json(r);
// }
// catch
// {
// return Json(new { message = "上传失败" });
// }
//}
//public JsonResult DelAttachment(string file)
//{
// try
// {
// string filePath = Path.Combine(Request.MapPath("~/Upload"), file);
// if (System.IO.File.Exists(filePath))
// {
// System.IO.File.Delete(filePath);
// return Json(new { status = "success" });
// }
// return Json(new { status = "false", message = "附件删除失败!" });
// }
// catch (Exception ex)
// {
// return Json(new { status = "false", message = "附件删除失败!" });
// }
//}
private string getGUID()
{
System.Guid guid = new Guid();
guid = Guid.NewGuid();
string str = guid.ToString();
return str;
}
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
if (file == null)
{
return Json(new { message = "没有选择上传文件!" });
}
if (file.ContentLength == 0)
{
return Json(new { message = "没有文件" });
}
string savedFileName = getGUID() + Path.GetExtension(file.FileName);
string uploadFileName = Path.GetFileName(file.FileName);
string allFileNames = uploadFileName + "$" + savedFileName;
var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(savedFileName));
try
{
file.SaveAs(fileName);
var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("message", "上传成功");
r.Add("fileName", Path.GetFileName(file.FileName));
r.Add("fileSize", FileSize);
r.Add("allFileNames", allFileNames);
return Json(r);
}
catch
{
return Json(new { message = "上传失败" });
}
}
[HttpPost]
public JsonResult UploadforA6dot1(HttpPostedFileBase file)
{
if (file == null)
{
return Json(new { message = "没有选择上传文件!" });
}
if (file.ContentLength == 0)
{
return Json(new { message = "没有文件" });
}
string savedFileName = getGUID() + Path.GetExtension(file.FileName);
string uploadFileName = Path.GetFileName(file.FileName);
string allFileNames = uploadFileName + "$" + savedFileName;
var fileName = Path.Combine(Request.MapPath("~/Upload/A3dot3"), Path.GetFileName(savedFileName));
try
{
file.SaveAs(fileName);
var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("message", "上传成功");
r.Add("fileName", Path.GetFileName(file.FileName));
r.Add("fileSize", FileSize);
r.Add("allFileNames", allFileNames);
return Json(r);
}
catch
{
return Json(new { message = "上传失败" });
}
}
[HttpPost]
public JsonResult UploadXlxs(HttpPostedFileBase file)
{
if (file == null)
{
return Json(new { message = "没有选择上传文件!" });
}
if (file.ContentLength == 0)
{
return Json(new { message = "没有文件" });
}
if (Path.GetExtension(file.FileName) != ".xlsx")
{
return Json(new { message = "上传文件不是.xlsx文件!" });
}
string savedFileName = getGUID() + Path.GetExtension(file.FileName);
string uploadFileName = Path.GetFileName(file.FileName);
string allFileNames = uploadFileName + "$" + savedFileName;
var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(savedFileName));
try
{
file.SaveAs(fileName);
var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("message", "上传成功");
r.Add("fileName", Path.GetFileName(file.FileName));
r.Add("fileSize", FileSize);
r.Add("allFileNames", allFileNames);
return Json(r);
}
catch
{
return Json(new { message = "上传失败" });
}
}
[HttpPost]
public JsonResult UploadForFileManage(FormCollection fromdata)
{
int pCatalogID = Convert.ToInt32(fromdata["pCataID"]);
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength == 0)
{
return Json(new { message = "没有文件" });
}
string savedFileName = getGUID() + Path.GetExtension(file.FileName);
string uploadFileName = Path.GetFileName(file.FileName);
string allFileNames = uploadFileName + "$" + savedFileName;
var fileName = Path.Combine(Request.MapPath("~/Upload/A3dot3"), Path.GetFileName(savedFileName));
try
{
file.SaveAs(fileName);
var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
FileItem fi = new FileItem();
fi.fileName = uploadFileName;
fi.fileNamePresent = savedFileName;
fi.updateTime = DateTime.Now.ToString();
fi.path = @"/Upload/A3dot3";
fi.ext = Path.GetExtension(file.FileName);
if (!(new File_Cat_Manager()).AddNewFile(pCatalogID, fi, (Session["User"] as EquipModel.Entities.Person_Info).Person_Id))
{
throw new Exception();
}
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("message", "上传成功");
r.Add("fileName", Path.GetFileName(file.FileName));
r.Add("fileSize", FileSize);
r.Add("allFileNames", allFileNames);
return Json(r);
}
catch
{
return Json(new { message = "上传失败" });
}
}
//2016-5-11 修改的方法如下
[HttpPost]
public void UploadForFileManage1(FormCollection fromdata)
{
try
{
int i;
for (i = 0; i < Request.Files.Count; i++)
{
int pCatalogID = Convert.ToInt32(fromdata["pCataID"]);
HttpPostedFileBase file = Request.Files[i];
if (file.ContentLength == 0)
{
//return Json(new { message = "没有文件" });
}
string savedFileName = getGUID() + Path.GetExtension(file.FileName);
string uploadFileName = Path.GetFileName(file.FileName);
string allFileNames = uploadFileName + "$" + savedFileName;
var fileName = Path.Combine(Request.MapPath("~/Upload/A3dot3"), Path.GetFileName(savedFileName));
file.SaveAs(fileName);
var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
FileItem fi = new FileItem();
fi.fileName = uploadFileName;
fi.fileNamePresent = savedFileName;
fi.updateTime = DateTime.Now.ToString();
fi.path = @"/Upload/A3dot3";
fi.ext = Path.GetExtension(file.FileName);
if (!(new File_Cat_Manager()).AddNewFile(pCatalogID, fi, (Session["User"] as EquipModel.Entities.Person_Info).Person_Id))
{
throw new Exception();
}
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("message", "上传成功");
r.Add("fileName", Path.GetFileName(file.FileName));
r.Add("fileSize", FileSize);
r.Add("allFileNames", allFileNames);
// return Json(r);
}
}
catch
{
// return Json(new { message = "上传失败" });
}
}
public void UploadForFileManage2(FormCollection fromdata)
{
try
{
int i;
for (i = 0; i < Request.Files.Count; i++)
{
int pCatalogID = Convert.ToInt32(fromdata["pCataID"]);
HttpPostedFileBase file = Request.Files[i];
if (file.ContentLength == 0)
{
//return Json(new { message = "没有文件" });
}
string savedFileName = getGUID() + Path.GetExtension(file.FileName);
string uploadFileName = Path.GetFileName(file.FileName);
string allFileNames = uploadFileName + "$" + savedFileName;
var fileName = Path.Combine(Request.MapPath("~/Upload/A2dot2"), Path.GetFileName(savedFileName));
file.SaveAs(fileName);
var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
FileItem fi = new FileItem();
fi.fileName = uploadFileName;
fi.fileNamePresent = savedFileName;
fi.updateTime = DateTime.Now.ToString();
fi.path = @"/Upload/A2dot2";
fi.ext = Path.GetExtension(file.FileName);
if (!(new File_Cat_Manager()).AddNewFile(pCatalogID, fi, (Session["User"] as EquipModel.Entities.Person_Info).Person_Id))
{
throw new Exception();
}
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("message", "上传成功");
r.Add("fileName", Path.GetFileName(file.FileName));
r.Add("fileSize", FileSize);
r.Add("allFileNames", allFileNames);
// return Json(r);
}
}
catch
{
// return Json(new { message = "上传失败" });
}
}
/// <summary>
/// 17/1/13修改用于A1dot1方针政策上传文件
///
/// </summary>
/// <param name="fromdata"></param>
/// <returns></returns>
public JsonResult UploadForguidelinesManage(FormCollection fromdata)
{
int pCatalogID = Convert.ToInt32(fromdata["pCataID"]);
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength == 0)
{
return Json(new { message = "没有文件" });
}
string savedFileName = getGUID() + Path.GetExtension(file.FileName);
string uploadFileName = Path.GetFileName(file.FileName);
string allFileNames = uploadFileName + "$" + savedFileName;
var fileName = Path.Combine(Request.MapPath("~/Upload/A1dot1"), Path.GetFileName(savedFileName));
try
{
file.SaveAs(fileName);
var FileSize = (file.ContentLength * 1.0 / 1024).ToString("0.00");
guiditem fi = new guiditem();
fi.fileName = uploadFileName;
fi.fileNamePresent = savedFileName;
fi.updateTime = DateTime.Now.ToString();
fi.path = @"/Upload/A1dot1";
fi.ext = Path.GetExtension(file.FileName);
if (!(new guide_Cat_manager()).AddNewFile(pCatalogID, fi, (Session["User"] as EquipModel.Entities.Person_Info).Person_Id))
{
throw new Exception();
}
Dictionary<string, string> r = new Dictionary<string, string>();
r.Add("message", "上传成功");
r.Add("fileName", Path.GetFileName(file.FileName));
r.Add("fileSize", FileSize);
r.Add("allFileNames", allFileNames);
return Json(r);
}
catch
{
return Json(new { message = "上传失败" });
}
}
public JsonResult DelAttachment(string file)
{
try
{
string[] savedFileName = file.Split(new char[] { '$' });
string filePath = Path.Combine(Request.MapPath("~/Upload"), savedFileName[1]);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
return Json(new { status = "success" });
}
return Json(new { status = "false", message = "附件删除失败!" });
}
catch (Exception ex)
{
return Json(new { status = "false", message = "附件删除失败!" });
}
}
//取消提交,从数据库中删除刚建立的一个工作流实体
public string CancelSubmit(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string wfe_id = item["wef_id"].ToString();
string return_url = item["return_url"].ToString();
CWFEngine.RemoveWFEntity(int.Parse(wfe_id));
return return_url;
}
catch (Exception e)
{
return "";
}
}
//获取待处理任务:帽子工作流
public string getLsA11dot2dcl_list(string WorkFlow_Name, string jobname)
{
List<MainModel> Am = new List<MainModel>();
List<UI_MISSION> miss;
List<object> or = new List<object>();
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
foreach (var item in miss)
{
MainModel o = new MainModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Entity_Id, paras);
UI_MISSION lastMi = CWFEngine.GetHistoryMissions(item.WE_Entity_Id).Last();
int Miss_Id = lastMi.Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
o.userName = r["username"];
o.missTime = r["time"];
}
else
{
o.userName = "";
o.missTime = "";
}
o.miss_desc = item.WE_Event_Desc;
if (item.Mission_Url.Contains("dot"))
o.miss_url = item.Mission_Url;
else
o.miss_url = "";
o.wfe_serial = wfei.serial;
o.workFlowName = wfei.description;
o.sbGycode = jobname;
Am.Add(o);
}
for (int i = 0; i < Am.Count; i++)
{
object o = new
{
wfe_serial = Am[i].wfe_serial,
equip_gycode = jobname,
workflow_name = Am[i].workFlowName,
miss_desc = Am[i].miss_desc,
missTime = Am[i].missTime,
userName = Am[i].userName,
miss_url = Am[i].miss_url
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public string getA11dot2dcl_list(string WorkFlow_Name)
{
List<A11dot2Model> Am = new List<A11dot2Model>();
List<UI_MISSION> miss;
List<object> or = new List<object>();
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
int i = 1;
foreach (var item in miss)
{
A11dot2Model o = new A11dot2Model();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
paras["Equip_GyCode"] = null;
paras["Equip_Code"] = null;
paras["Problem_Desc"] = null;//隐患问题描述
paras["RiskMatrix_Color"] = null;//隐患评估结果
paras["Supervise_done"] = null;//片区监督实施是否完成
paras["ImplementPlan_done"] = null;//黄色、措施实施是否完成
WorkFlows wfsd = new WorkFlows();
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Entity_Id, paras);
Mission db_miss = wfsd.GetWFEntityMissions(item.WE_Entity_Id).Last();//获取该实体最后一个任务
o.index_Id = item.WE_Entity_Id;
o.zz_name = paras["Zz_Name"].ToString();
o.sb_gycode = paras["Equip_GyCode"].ToString();
o.sb_code = paras["Equip_Code"].ToString();
o.problem_desc = paras["Problem_Desc"].ToString();
o.riskMatrix_color = paras["RiskMatrix_Color"].ToString();
o.supervise_done = paras["Supervise_done"].ToString();
o.implementplan_done = paras["ImplementPlan_done"].ToString();
o.missionname = db_miss.Miss_Desc;
Am.Add(o);
i++;
}
string str = JsonConvert.SerializeObject(Am);
return ("{" + "\"data\": " + str + "}");
}
/// <summary>
/// 获取A14dot3index页面待处理列表内容(在线表单)
/// </summary>
/// <param name="WorkFlow_Name"></param>
/// <returns>json格式字符串给前台</returns>
public string getA14dot3dcl_list(string WorkFlow_Name)
{
List<A14dot3Model> Am = new List<A14dot3Model>();
List<UI_MISSION> miss;
List<object> or = new List<object>();
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
int i = 1;
foreach (var item in miss)
{
A14dot3Model o = new A14dot3Model();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
paras["Equip_GyCode"] = null;
paras["Equip_Code"] = null;
paras["Equip_Type"] = null;
paras["Equip_ABCMark"] = null;
paras["Plan_Name"] = null;
paras["JxCauseDesc"] = null;
paras["XcConfirm_Result"] = null;
paras["KkConfirm_Result"] = null;
paras["ZytdConfirm_Result"] = null;
paras["JobOrder"] = null;
paras["NoticeOrder"] = null;
WorkFlows wfsd = new WorkFlows();
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Entity_Id, paras);
Mission db_miss = wfsd.GetWFEntityMissions(item.WE_Entity_Id).Last();//获取该实体最后一个任务
o.index_Id = item.WE_Entity_Id;
o.zz_name = paras["Zz_Name"].ToString();
o.sb_gycode = paras["Equip_GyCode"].ToString();
o.sb_code = paras["Equip_Code"].ToString();
o.sb_type = paras["Equip_Type"].ToString();
o.sb_ABCMark = paras["Equip_ABCMark"].ToString();
o.plan_name = paras["Plan_Name"].ToString();
o.jxreason = paras["JxCauseDesc"].ToString();
o.xcconfirm = paras["XcConfirm_Result"].ToString();
o.kkconfirm = paras["KkConfirm_Result"].ToString();
o.zytdconfirm = paras["ZytdConfirm_Result"].ToString();
o.job_order = paras["JobOrder"].ToString();
o.notice_order = paras["NoticeOrder"].ToString();
o.missionname = db_miss.Miss_Desc;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
o.role = pv.Role_Names;
Am.Add(o);
i++;
}
string str = JsonConvert.SerializeObject(Am);
return ("{" + "\"data\": " + str + "}");
}
public string getA14dot3dot3dcl_list(string WorkFlow_Name)
{
List<A14dot3dot3Model> Am = new List<A14dot3dot3Model>();
List<UI_MISSION> miss;
List<object> or = new List<object>();
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
int i = 1;
foreach (var item in miss)
{
A14dot3dot3Model o = new A14dot3dot3Model();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
paras["Equip_GyCode"] = null;
paras["Equip_Code"] = null;
paras["Equip_Type"] = null;
paras["Equip_ABCMark"] = null;
paras["Plan_Name"] = null;
paras["JxCauseDesc"] = null;
paras["KkConfirm_Result"] = null;
paras["ZytdConfirm_Result"] = null;
paras["JobOrder"] = null;
paras["NoticeOrder"] = null;
WorkFlows wfsd = new WorkFlows();
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Entity_Id, paras);
Mission db_miss = wfsd.GetWFEntityMissions(item.WE_Entity_Id).Last();//获取该实体最后一个任务
o.index_Id = item.WE_Entity_Id;
o.zz_name = paras["Zz_Name"].ToString();
o.sb_gycode = paras["Equip_GyCode"].ToString();
o.sb_code = paras["Equip_Code"].ToString();
o.sb_type = paras["Equip_Type"].ToString();
o.sb_ABCMark = paras["Equip_ABCMark"].ToString();
o.plan_name = paras["Plan_Name"].ToString();
o.jxreason = paras["JxCauseDesc"].ToString();
o.xcconfirm = "同意";
o.kkconfirm1 = paras["KkConfirm_Result"].ToString();
o.zytdconfirm1 = paras["ZytdConfirm_Result"].ToString();
o.job_order1 = paras["JobOrder"].ToString();
o.notice_order1 = paras["NoticeOrder"].ToString();
o.missionname = db_miss.Miss_Desc;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
o.role = pv.Role_Names;
Am.Add(o);
i++;
}
string str = JsonConvert.SerializeObject(Am);
return ("{" + "\"data\": " + str + "}");
}
#region DRBPM系统接口 -公共
//数据库连接
public static SqlConnection getDRBPMSqlConnection()
{
return new SqlConnection("Password=<PASSWORD>;Persist Security Info=True;User ID=sa;Initial Catalog=DRBPMNew;Data Source=10.128.189.203");
//投用时替换:Password=<PASSWORD>;Persist Security Info=True;User ID=sa;Initial Catalog=DRBPMNew;Data Source=10.128.189.203
//本地测试:Data Source=127.0.0.1;Initial Catalog=DRBPMNew;User ID=sa;Password=<PASSWORD>
}
//计划检修原因解析
public static string GetReason(string code)
{
string str = string.Empty;
switch (code)
{
case "PM1":
str = "[PM1] 超期在役未修;正常运行";
break;
case "PM2":
str = "[PM2] 故障强度等级较高设备,一级报警,运行趋势差,达到检修时间";
break;
case "PM3":
str = "[PM3] 故障强度等级较高设备,二级报警";
break;
case "PM4":
str = "[PM4] 二级报警,达到检修时间";
break;
case "PM5":
str = "[PM5] 故障强度等级较高设备,运行趋势差,达到检修时间";
break;
case "PM21":
str = "[PM2-1] 故障强度等级较高设备,一级报警,运行趋势差,达到检修时间;超期在役未修";
break;
case "PM31":
str = "[PM3-1] 故障强度等级较高设备,二级报警;超期在役未修";
break;
case "PM41":
str = "[PM4-1] 二级报警,达到检修时间;超期在役未修";
break;
case "PM51":
str = "[PM5-1] 故障强度等级较高设备,运行趋势差,达到检修时间;超期在役未修";
break;
case "PMx":
str = "[PMx] 人工筛选,预防性维修";
break;
case "OP":
str = "[OP] 一般性关注";
break;
case "OPx":
str = "[OPx] 人工筛选,一般性关注";
break;
case "PS":
str = "[PS] 正常运行";
break;
//2015.5.22
case "PM6":
str = "[PM6] 密封泄漏级别达到检修要求";
break;
case "PM6-U":
str = "[PM6-U] 不允许泄漏机泵渗漏、轻微泄漏或泄漏;或易燃易爆、烃类、轻质油、高温机泵泄漏";
break;
case "PM6-1":
str = "[PM6-1] 易燃易爆、烃类、轻质油、高温机泵轻微泄漏";
break;
case "PM6-2":
str = "[PM6-2] 一般性机泵泄漏";
break;
case "PDM":
str = "[PDM] 预知性检修";
break;
case "PMG":
str = "[PMG] 所监测的工艺量状态达到检修要求";
break;
//default:
// str = code;
// break;
}
return str;
}
public static string GetReasonAll(string SbStateBak, string Temp6, string Temp3, int IsUrgentPM)
{
//2015.6.2 add +GetReasonPM6(sb.Temp6)
string desc = string.Empty;
if (!string.IsNullOrEmpty(SbStateBak))
{
if (SbStateBak == "PM6")
{
desc = GetReasonPM6(Temp6, false);
if (IsUrgentPM >= 1) //
desc = desc + " --[紧急!] " + Temp3;
}
else
{
//2015.6.5 修改显示规则
if (IsUrgentPM >= 1 && !Temp6.Contains("PM6-U")) //加上干预理由
desc = GetReason(SbStateBak) + " --[紧急!] " + Temp3;
else if (SbStateBak == "PMx" || SbStateBak == "OPx" || SbStateBak == "PDM")
desc = GetReason(SbStateBak) + " --[干预理由] " + Temp3;
else
desc = GetReason(SbStateBak);
desc = desc + GetReasonPM6(Temp6, false);
if (IsUrgentPM >= 1 && Temp6.Contains("PM6-U")) //加上干预理由
desc = desc + " --[紧急!] " + Temp3;
}
}
return desc;
}
//密封-PM6-说明
public static string GetReasonPM6(string PM6Type, bool bAddBr = false)
{
string desc = string.Empty;
if (!string.IsNullOrEmpty(PM6Type) && PM6Type.Contains("PM6"))
{
if (bAddBr)
desc = "\r\n" + GetReason(PM6Type);
else
desc = GetReason(PM6Type);
}
return desc;
}
//工艺异常指标及说明(综合描述,分行显示)
public static string GetGyStateDescription(string GyStatePMGList, bool bAddBr = false)
{
string desc = string.Empty;
//顺序:FQmin, FQavg, TGavg, LGmin, DA, EnergyEfficiency
//if(sb.IsAddCorrectTabstrList.Substring(0,1)=="1")
//依次判断PMG1-4,同时存在要分行显示 (相关量为FQavg, EnergyEfficiency, LGmin)
if (GyStatePMGList.Contains("PMG1"))
desc = "[PMG1] 流量低于设计允许范围,为额定流量的50%~70%,且工艺无法修正;";
if (GyStatePMGList.Contains("PMG2"))
{
if (!string.IsNullOrEmpty(desc))
desc += "\r\n"; //Web显示时的换行符
//出于兼容性和面向对象化的考虑,推荐使用System.Environment.NewLine作为换行符(???试过,不行)
desc += "[PMG2] 流量低于设计允许范围,低于额定流量的50%,且工艺无法修正;";
}
if (GyStatePMGList.Contains("PMG3"))
{
if (!string.IsNullOrEmpty(desc))
desc += "\r\n";
desc += "[PMG3] 设备能效低于设计效率75%;";
}
if (GyStatePMGList.Contains("PMG4"))
{
if (!string.IsNullOrEmpty(desc))
desc += "\r\n";
desc += "[PMG4] 液位低于设计允许范围,工艺无法修正,且气蚀余量不满足要求;";
}
if (bAddBr && !string.IsNullOrEmpty(desc))
desc = "\r\n" + desc; //加一个换行
return desc;
//其它3个警示信息FQmin, TGavg, LGmin
//最低流量在允许范围外,由sb.IsFQminAlarm判定;
//介质温度高于176℃(超工艺温度,核对设计条件),由sb.IsTGavgAlarm判定;
//液位低,请核对汽蚀余量,是否抽空?由sb.IsNPSHokLG判定;
}
//短时趋势分析-shortTermTrend-说明
public static string GetShortTermTrendDescription(string shortTermTrend, bool bAddBr = false)
{
string desc = string.Empty;
if (string.IsNullOrEmpty(shortTermTrend))
return desc;
if (shortTermTrend.Length >= 2)
{
if (bAddBr)
desc = "\r\n" + "[PMT] 设备短时趋势明显恶化" + "[" + shortTermTrend + "值]";
else
desc = "[PMT] 设备短时趋势明显恶化" + "[" + shortTermTrend + "值]";
}
else if (shortTermTrend.Length == 1)
{
if (bAddBr)
desc = "\r\n" + "[OPT] 设备短时趋势恶化" + "[" + shortTermTrend + "值],需及时关注并排查原因";
else
desc = "[OPT] 设备短时趋势恶化" + "[" + shortTermTrend + "值],需及时关注并排查原因";
}
return desc;
}
/// <summary>
/// 写DRBMP数据库,生成检修计划(相当于装置自动提报),后续在DRBPM系统由检修单位、机动处确认
/// </summary>
/// <param name="sbcode">设备编号</param>
/// <param name="reason">理由,如:"一级缺陷" 或 "二级缺陷" 等</param>
/// <param name="isUrgent">是否生成紧急计划,true-是,false-否</param>
/// <param name="Ser">从完整性继承的流水号</param>
public static void writeDRBPM(string sbcode, string reason, bool isUrgent,string Ser="")
{
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
//机动处同意在本月执行的检修计划(非紧急计划,A14dot1中用)
//string strWhere = String.Format(" GybhId='{0}' and SUBSTRING(JxPlanDate,0,8)='{1}' ", sbcode, System.DateTime.Now.ToString("yyyy-MM"));
string strWhere = String.Format(" GybhId='{0}' ", sbcode);
string sqlcmd = String.Format("select * from SbStateFullAnalysis where {0} order by id asc ", strWhere);
//"select id,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,IsUrgentPM,jdcOpinion from SbStateFullAnalysisx"
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
if (dt.Rows.Count == 1)
{
string vals = "";
for (int i = 0; i <= 3; i++)
{
vals += string.Format("'{0}',", dt.Rows[0][i].ToString().Trim());
}
if (isUrgent)
vals += string.Format("'{0}',", System.DateTime.Now.ToString("yyyy-MM-dd")); //JxPlanDate
else
vals += string.Format("'{0}',", System.DateTime.Now.AddMonths(1).ToString("yyyy-MM-01")); //JxPlanDate
vals += string.Format("'{0}',", dt.Rows[0]["sbStateAuto"].ToString());//sbStateAuto
vals += string.Format("'{0}',", "PMx");//sbStateBak
for (int i = 7; i <= 15; i++)
{
vals += string.Format("'{0}',", dt.Rows[0][i].ToString());
}
if (isUrgent)
vals += string.Format("'{0}',", 2); //IsUrgentPM 2-人工干预的紧急计划
else
vals += string.Format("'{0}',", dt.Rows[0]["IsUrgentPM"].ToString()); //IsUrgentPM
vals += string.Format("'{0}',", dt.Rows[0]["LatestDate"].ToString());//LatestDate
vals += string.Format("'{0}',", "同意");//zzOpinion
vals += string.Format("'{0}',", "完整性管理系统生成"+Ser);//zzReason
for (int i = 20; i <= 23; i++)
{
vals += string.Format("'{0}',", dt.Rows[0][i].ToString());
}
vals += string.Format("'{0}',", 1);//State
vals += string.Format("'{0}',", System.DateTime.Now.ToString("yyyy-MM-dd"));//temp2 存放装置操作的日期
vals += string.Format("'完整性管理系统{0}',", reason);//temp3 存放人工干预的理由
for (int i = 27; i <= dt.Columns.Count - 2; i++)
{
vals += string.Format("'{0}',", dt.Rows[0][i].ToString());
}
vals += string.Format("'{0}'", dt.Rows[0][dt.Columns.Count - 1].ToString());
string insertSql = String.Format(" insert into SbStateFullAnalysisx (OrgId,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,SbType,service_interval,FaultIntensity,AlarmState,AvgInterval,RunTrend_L,RunTrend_T,RunTrend_V,RunTrend,IsUrgentPM,LatestDate,zzOpinion,zzReason,jxOpinion,jxReason,jxKeyContent,jdcOpinion,State,temp2,temp3,temp4,temp5,temp6,temp7,temp8,temp9,temp10) values({0})", vals);
SqlCommand cmd = new SqlCommand(insertSql, con); //定义一个sql操作命令对象
cmd.ExecuteNonQuery(); //执行语句
}
con.Close();
con.Dispose();
}
#endregion
#region DRBPM系统接口 for A14dot1
//A14dot1_ModelInfo
public class A14dot1_ModelInfo
{
public string Cj_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public string Equip_Type;
public string Zy_Type;
public string Zy_SubType;
public string Equip_ABCMark;
//from DRBPM
public string drbpmRecordId;//唯一标志ID-在DRBPM表中
public string Jx_Reason;//检修原因
public string jxPlanDate;//计划检修时间
public string faultIntensity; //故障强度
public string alarmState;//报警状态
public string runTrend;//运行趋势
public string latestDate; //上次检修时间
//from A8.2
public string Job_Order = ""; //工单号
public string Job_OrderState = ""; //工单号(当前计划)状态
public string Plan_DescFilePath = ""; //检修方案
public string ZzConfirmPlan_Result = ""; //计划是否可实施,现场工程师确认是否可实施计划
public string JxdwConfirmEnd_done = ""; //计划实施情况-是否完成
public string PlanFinishDate = ""; //完工时间
public string JxSubmit_done = ""; //检修单位-是否提报(A8.2是否生成?)
}
//A14dot1_Model
public class A14dot1_Model
{
public List<A14dot1_ModelInfo> A14dot1_ModelInfoList;
public string isJx;//0712,zoujing
}
public A14dot1_Model getA14dot1_Model()
{
string equip_codes = "";
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
//string zzcode = "A03"; //
//机动处同意在本月执行的检修计划(非紧急计划,A14dot1中用)
//string strWhere = " sbStateBak like 'PM%' and IsUrgentPM=0 and JdcOpinion = '同意' and SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' " + " and ZzId='" + zzcode + "' ";
string strWhere = " sbStateBak like 'PM%' and JdcOpinion = '同意' and SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' "; //and IsUrgentPM=0
string sqlcmd = String.Format("select * from SbStateFullAnalysisx where {0} order by id asc ", strWhere);
//"select id,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,IsUrgentPM,jdcOpinion from SbStateFullAnalysisx"
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
A14dot1_Model A14dot1model = new A14dot1_Model();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("检维修人员"))
A14dot1model.isJx = "true";
A14dot1model.A14dot1_ModelInfoList = new List<A14dot1_ModelInfo>();
int j = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
A14dot1_ModelInfo h = new A14dot1_ModelInfo();
h.Equip_Code = dt.Rows[i]["GybhId"].ToString(); //sbid
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(h.Equip_Code);
if (eqinfo == null)
continue;
if (j > 0)
equip_codes += ",";
equip_codes += h.Equip_Code;
j += 1;
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
h.Equip_GyCode = eqinfo.Equip_GyCode;
h.Equip_Type = eqinfo.Equip_Type;
h.Zy_Type = eqinfo.Equip_Specialty;
h.Zy_SubType = eqinfo.Equip_PhaseB;
h.Equip_ABCMark = eqinfo.Equip_ABCmark;
h.drbpmRecordId = dt.Rows[i]["Id"].ToString();//唯一标志ID-在DRBPM表中
string SbStateBak = dt.Rows[i]["sbStateBak"].ToString();
string Temp6 = dt.Rows[i]["Temp6"].ToString();
string Temp3 = dt.Rows[i]["Temp3"].ToString();
int IsUrgentPM = int.Parse(dt.Rows[i]["IsUrgentPM"].ToString());
string Temp5 = dt.Rows[i]["Temp5"].ToString();
string Temp9 = dt.Rows[i]["Temp9"].ToString();
h.Jx_Reason = GetReasonAll(SbStateBak, Temp6, Temp3, IsUrgentPM) + GetShortTermTrendDescription(Temp9, false);
//h.Jx_Reason = GetReasonAll(SbStateBak, Temp6, Temp3, IsUrgentPM) + GetGyStateDescription(Temp5, true) + GetShortTermTrendDescription(Temp9, true);
//h.Jx_Reason = getDRBPMJxReason(dt.Rows[i]["sbStateBak"].ToString()); // "一级缺陷"? //计划检修原因 PM?
h.jxPlanDate = DateTime.Now.ToString("yyyy-MM");
h.faultIntensity = dt.Rows[i]["faultIntensity"].ToString(); //故障强度
h.alarmState = dt.Rows[i]["alarmState"].ToString();//报警状态
h.runTrend = dt.Rows[i]["runTrend"].ToString(); //运行趋势
h.latestDate = dt.Rows[i]["latestDate"].ToString(); //上次检修时间
A14dot1model.A14dot1_ModelInfoList.Add(h);
}
string query_list = " E.W_Name,M.Event_Name, P.Equip_Code, P.Job_Order, P.Job_OrderState, P.Plan_DescFilePath, P.ZzConfirmPlan_Result,P.JxdwConfirmEnd_done, R.time,P.JxSubmit_done";
string query_condition = string.Format("P.Equip_Code in ({0}) and E.W_Name = 'A8dot2'", equip_codes);
DateTime dtime = DateTime.Now;
dtime = dtime.AddDays(-dtime.Day + 1);
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
string record_filter = string.Format("time >= '{0}' ", dtime.ToString()); //"1 <> 1";
System.Data.DataTable dtA8dot2 = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
if (dtA8dot2 != null && dtA8dot2.Rows.Count > 0)
{
for (int i = 0; i < A14dot1model.A14dot1_ModelInfoList.Count; i++)
{
string current_code = A14dot1model.A14dot1_ModelInfoList[i].Equip_Code;
//Job_Order
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Job_Order is not null";
dtA8dot2.DefaultView.Sort = "time";
DataTable dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot1model.A14dot1_ModelInfoList[i].Job_Order = dtTmp.Rows[dtTmp.Rows.Count - 1]["Job_Order"].ToString();
dtTmp.Clear();
//Job_OrderState
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Job_OrderState is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot1model.A14dot1_ModelInfoList[i].Job_OrderState = dtTmp.Rows[dtTmp.Rows.Count - 1]["Job_OrderState"].ToString();
dtTmp.Clear();
//Plan_DescFilePath
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Plan_DescFilePath is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot1model.A14dot1_ModelInfoList[i].Plan_DescFilePath = dtTmp.Rows[dtTmp.Rows.Count - 1]["Plan_DescFilePath"].ToString();
dtTmp.Clear();
//ZzConfirmPlan_Result
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and ZzConfirmPlan_Result is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot1model.A14dot1_ModelInfoList[i].ZzConfirmPlan_Result = dtTmp.Rows[dtTmp.Rows.Count - 1]["ZzConfirmPlan_Result"].ToString();
dtTmp.Clear();
//JxdwConfirmEnd_done
dtA8dot2.DefaultView.RowFilter = "JxdwConfirmEnd_done is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot1model.A14dot1_ModelInfoList[i].JxdwConfirmEnd_done = dtTmp.Rows[dtTmp.Rows.Count - 1]["JxdwConfirmEnd_done"].ToString();
dtTmp.Clear();
//PlanFinishDate
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and JxdwConfirmEnd_done =true and time is not null";//?
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot1model.A14dot1_ModelInfoList[i].PlanFinishDate = dtTmp.Rows[dtTmp.Rows.Count - 1]["time"].ToString();
dtTmp.Clear();
//JxSubmit_done
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and JxSubmit_done =true and time is not null";//?
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot1model.A14dot1_ModelInfoList[i].JxSubmit_done = dtTmp.Rows[dtTmp.Rows.Count - 1]["JxSubmit_done"].ToString().ToLower();
dtTmp.Clear();
}
}
con.Close();
con.Dispose();
return A14dot1model;
}
#endregion
#region DRBPM系统接口 for A13dot2
//A13dot2_ModelInfo
public class A13dot2_ModelInfo
{
public string Cj_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public string Equip_Type;
public string Zy_Type;
public string Zy_SubType;
public string Equip_ABCMark;
//from DRBPM
public string drbpmRecordId;//唯一标志ID-在DRBPM表中
public string Jx_Reason;//检修原因
public string jxPlanDate;//计划检修时间
public string faultIntensity; //故障强度
public string alarmState;//报警状态
public string runTrend;//运行趋势
public string latestDate; //上次检修时间
//from A8.2
public string Job_Order = ""; //工单号
public string Job_OrderState = ""; //工单号(当前计划)状态
public string Plan_DescFilePath = ""; //检修方案
public string ZzConfirmPlan_Result = ""; //计划是否可实施,现场工程师确认是否可实施计划
public string JxdwConfirmEnd_done = ""; //计划实施情况-是否完成
public string PlanFinishDate = ""; //完工时间
public string JxSubmit_done = ""; //检修单位-是否提报(A8.2是否生成?)
}
//A13dot2_Model
public class A13dot2_Model
{
public List<A13dot2_ModelInfo> A13dot2_ModelInfoList;
public string isJx;//0712,邹晶,添加index页面按钮权限
}
public A13dot2_Model getA13dot2_Model()
{
string equip_codes = "";
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
//string zzcode = "A03"; //
//机动处同意在本月执行的紧急检修计划(A13dot2中用)
//string strWhere = " IsUrgentPM>0 AND JdcOpinion = '同意' AND SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' " + " and ZzId='" + zzcode + "' ";
string strWhere = " IsUrgentPM>0 AND JdcOpinion = '同意' AND SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' ";
string sqlcmd = String.Format("select * from SbStateFullAnalysisx where {0} order by id asc ", strWhere);
//"select id,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,IsUrgentPM,jdcOpinion from SbStateFullAnalysisx"
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
A13dot2_Model A13dot2model = new A13dot2_Model();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("检维修人员"))
A13dot2model.isJx = "true";
A13dot2model.A13dot2_ModelInfoList = new List<A13dot2_ModelInfo>();
int j = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
//if (i > 0)
// equip_codes += ",";
A13dot2_ModelInfo h = new A13dot2_ModelInfo();
h.Equip_Code = dt.Rows[i]["GybhId"].ToString(); //sbid
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(h.Equip_Code);
if (eqinfo == null)
continue;
if (j > 0)
equip_codes += ",";
equip_codes += h.Equip_Code;
j += 1;
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
h.Equip_GyCode = eqinfo.Equip_GyCode;
h.Equip_Type = eqinfo.Equip_Type;
h.Zy_Type = eqinfo.Equip_Specialty;
h.Zy_SubType = eqinfo.Equip_PhaseB;
h.Equip_ABCMark = eqinfo.Equip_ABCmark;
h.drbpmRecordId = dt.Rows[i]["Id"].ToString();//唯一标志ID-在DRBPM表中
string SbStateBak = dt.Rows[i]["sbStateBak"].ToString();
string Temp6 = dt.Rows[i]["Temp6"].ToString();
string Temp3 = dt.Rows[i]["Temp3"].ToString();
int IsUrgentPM = int.Parse(dt.Rows[i]["IsUrgentPM"].ToString());
string Temp5 = dt.Rows[i]["Temp5"].ToString();
string Temp9 = dt.Rows[i]["Temp9"].ToString();
h.Jx_Reason = GetReasonAll(SbStateBak, Temp6, Temp3, IsUrgentPM) + GetShortTermTrendDescription(Temp9, false);
//h.Jx_Reason = GetReasonAll(SbStateBak, Temp6, Temp3, IsUrgentPM) + GetGyStateDescription(Temp5, true) + GetShortTermTrendDescription(Temp9, true);
//h.Jx_Reason = getDRBPMJxReason(dt.Rows[i]["sbStateBak"].ToString()); // "一级缺陷"? //计划检修原因 PM?
h.jxPlanDate = DateTime.Now.ToString("yyyy-MM");
h.faultIntensity = dt.Rows[i]["faultIntensity"].ToString(); //故障强度
h.alarmState = dt.Rows[i]["alarmState"].ToString();//报警状态
h.runTrend = dt.Rows[i]["runTrend"].ToString(); //运行趋势
h.latestDate = dt.Rows[i]["latestDate"].ToString(); //上次检修时间
A13dot2model.A13dot2_ModelInfoList.Add(h);
}
string query_list = " E.W_Name,M.Event_Name, P.Equip_Code, P.Job_Order, P.Job_OrderState, P.Plan_DescFilePath, P.ZzConfirmPlan_Result,P.JxdwConfirmEnd_done, R.time,P.JxSubmit_done";
string query_condition = string.Format("P.Equip_Code in ({0}) and E.W_Name = 'A8dot2'", equip_codes);
DateTime dtime = DateTime.Now;
dtime = dtime.AddDays(-dtime.Day + 1);
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
string record_filter = string.Format("time >= '{0}' ", dtime.ToString()); //"1 <> 1";
System.Data.DataTable dtA8dot2 = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
if (dtA8dot2 != null && dtA8dot2.Rows.Count > 0)
{
for (int i = 0; i < A13dot2model.A13dot2_ModelInfoList.Count; i++)
{
string current_code = A13dot2model.A13dot2_ModelInfoList[i].Equip_Code;
//Job_Order
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Job_Order is not null";
dtA8dot2.DefaultView.Sort = "time";
DataTable dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A13dot2model.A13dot2_ModelInfoList[i].Job_Order = dtTmp.Rows[dtTmp.Rows.Count - 1]["Job_Order"].ToString();
dtTmp.Clear();
//Job_OrderState
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Job_OrderState is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A13dot2model.A13dot2_ModelInfoList[i].Job_OrderState = dtTmp.Rows[dtTmp.Rows.Count - 1]["Job_OrderState"].ToString();
dtTmp.Clear();
//Plan_DescFilePath
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Plan_DescFilePath is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A13dot2model.A13dot2_ModelInfoList[i].Plan_DescFilePath = dtTmp.Rows[dtTmp.Rows.Count - 1]["Plan_DescFilePath"].ToString();
dtTmp.Clear();
//ZzConfirmPlan_Result
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and ZzConfirmPlan_Result is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A13dot2model.A13dot2_ModelInfoList[i].ZzConfirmPlan_Result = dtTmp.Rows[dtTmp.Rows.Count - 1]["ZzConfirmPlan_Result"].ToString();
dtTmp.Clear();
//JxdwConfirmEnd_done
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and JxdwConfirmEnd_done is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A13dot2model.A13dot2_ModelInfoList[i].JxdwConfirmEnd_done = dtTmp.Rows[dtTmp.Rows.Count - 1]["JxdwConfirmEnd_done"].ToString();
dtTmp.Clear();
//PlanFinishDate
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and JxdwConfirmEnd_done =true and time is not null";//?
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A13dot2model.A13dot2_ModelInfoList[i].PlanFinishDate = dtTmp.Rows[dtTmp.Rows.Count - 1]["time"].ToString();
dtTmp.Clear();
//JxSubmit_done
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and JxSubmit_done =true and time is not null";//?
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A13dot2model.A13dot2_ModelInfoList[i].JxSubmit_done = dtTmp.Rows[dtTmp.Rows.Count - 1]["JxSubmit_done"].ToString().ToLower();
dtTmp.Clear();
}
}
con.Close();
con.Dispose();
return A13dot2model;
}
#endregion
#region DRBPM系统接口 for A7dot1MxAlarm (美迅一二级报警)
//A7dot1MxAlarm_ModelInfo
public class A7dot1MxAlarm_ModelInfo
{
public string Cj_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public string Equip_Type;
public string Zy_Type;
public string Zy_SubType;
public string Equip_ABCMark;
public string AlarmState;
public string AlarmDate;
}
//A7dot1MxAlarm_Model
public class A7dot1MxAlarm_Model
{
public List<A7dot1MxAlarm_ModelInfo> A7dot1MxAlarm_ModelInfoList;
}
public A7dot1MxAlarm_Model getA7dot1MxAlarm_Model()
{
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
//string zzcode = "A03"; //投用时,改为操作者所能管辖的装置的代码,如果是多个,需要处理一下
//一二级报警数据,DRBPM平台已处理
//string strWhere = " (AlarmState = '1' or AlarmState = '2') and sbStateBak not like 'PM%' " + " and ZzId='" + zzcode + "' ";
string strWhere = " (AlarmState = '1' or AlarmState = '2') and sbStateBak not like 'PM%' ";
string sqlcmd = String.Format("select * from SbStateFullAnalysis where {0} order by id asc ", strWhere);
//"select id,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,IsUrgentPM,jdcOpinion from SbStateFullAnalysisx"
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
A7dot1MxAlarm_Model A7dot1MxAlarmmodel = new A7dot1MxAlarm_Model();
A7dot1MxAlarmmodel.A7dot1MxAlarm_ModelInfoList = new List<A7dot1MxAlarm_ModelInfo>();
for (int i = 0; i < dt.Rows.Count; i++)
{
A7dot1MxAlarm_ModelInfo h = new A7dot1MxAlarm_ModelInfo();
h.Equip_Code = dt.Rows[i]["GybhId"].ToString(); //sbid
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(h.Equip_Code);
if (eqinfo == null)
continue;
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
h.Equip_GyCode = eqinfo.Equip_GyCode;
h.Equip_Type = eqinfo.Equip_Type;
h.Zy_Type = eqinfo.Equip_Specialty;
h.Zy_SubType = eqinfo.Equip_PhaseB;
h.Equip_ABCMark = eqinfo.Equip_ABCmark;
h.AlarmState = dt.Rows[i]["AlarmState"].ToString(); //AlarmState
h.AlarmDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); //AlarmState
A7dot1MxAlarmmodel.A7dot1MxAlarm_ModelInfoList.Add(h);
}
con.Close();
con.Dispose();
//for test:
//h = new A7dot1MxAlarm_ModelInfo();
//h.Equip_Code = "210002277";
//eqinfo = em.getEquip_Info(h.Equip_Code);
//Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
//h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
//h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
//h.Equip_GyCode = eqinfo.Equip_GyCode;
//h.Equip_Type = eqinfo.Equip_Type;
//h.Zy_Type = eqinfo.Equip_Specialty;
//h.Zy_SubType = eqinfo.Equip_PhaseB;
//h.Equip_ABCMark = eqinfo.Equip_ABCmark;
//h.AlarmState = "2"; //AlarmState
//A7dot1MxAlarmmodel.A7dot1MxAlarm_ModelInfoList.Add(h);
return A7dot1MxAlarmmodel;
}
#endregion
#region DRBPM系统接口 for A7dot2 (工艺效能监察,能效低设备)
//A7dot2_ModelInfo
public class A7dot2_ModelInfo
{
public string Cj_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public string Equip_Type;
public string Zy_Type;
public string Zy_SubType;
public string Equip_ABCMark;
public string gyState_PMGList;
public string gyAnalysis_Date;
public string gyAnalysis_EnValue;
}
//A7dot2_Model
public class A7dot2_Model
{
public List<A7dot2_ModelInfo> A7dot2_ModelInfoList;
}
public A7dot2_Model getA7dot2_Model()
{
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
//string zzcode = "A03"; //投用时,改为操作者所能管辖的装置的代码,如果是多个,需要处理一下
//能效低PMG3,DRBPM平台已处理
//string strWhere = " temp5 like '%PMG3%' and sbStateBak not like 'PM%' " + " and ZzId='" + zzcode + "' ";
string strWhere = " temp5 like '%PMG3%' and sbStateBak not like 'PM%' ";
string sqlcmd = String.Format("select * from SbStateFullAnalysisx where {0} order by id asc ", strWhere);
//"select id,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,IsUrgentPM,jdcOpinion from SbStateFullAnalysisx"
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
A7dot2_Model A7dot2model = new A7dot2_Model();
A7dot2model.A7dot2_ModelInfoList = new List<A7dot2_ModelInfo>();
for (int i = 0; i < dt.Rows.Count; i++)
{
A7dot2_ModelInfo h = new A7dot2_ModelInfo();
h.Equip_Code = dt.Rows[i]["GybhId"].ToString(); //sbid
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(h.Equip_Code);
if (eqinfo == null)
continue;
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
h.Equip_GyCode = eqinfo.Equip_GyCode;
h.Equip_Type = eqinfo.Equip_Type;
h.Zy_Type = eqinfo.Equip_Specialty;
h.Zy_SubType = eqinfo.Equip_PhaseB;
h.Equip_ABCMark = eqinfo.Equip_ABCmark;
h.gyState_PMGList = GetGyStateDescription(dt.Rows[i]["gyState_PMGList"].ToString(),true); //gyState_PMGList
h.gyAnalysis_Date = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
//h.gyAnalysis_EnValue=;
A7dot2model.A7dot2_ModelInfoList.Add(h);
}
con.Close();
con.Dispose();
//for test:
//h = new A7dot2_ModelInfo();
//h.Equip_Code = "210394641";
//eqinfo = em.getEquip_Info(h.Equip_Code);
//Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
//h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
//h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
//h.Equip_GyCode = eqinfo.Equip_GyCode;
//h.Equip_Type = eqinfo.Equip_Type;
//h.Zy_Type = eqinfo.Equip_Specialty;
//h.Zy_SubType = eqinfo.Equip_PhaseB;
//h.Equip_ABCMark = eqinfo.Equip_ABCmark;
//h.gyState_PMGList = "PMG3"; //gyState_PMGList
//A7dot2model.A7dot2_ModelInfoList.Add(h);
return A7dot2model;
}
#endregion
#region DRBPM系统接口 for Query Table SbStateFullAnalysis(x) - 设备PM状态分析
//DRBPM_SbStateFullAnalysisInfo
public class DRBPM_SbStateFullAnalysisInfo
{
//equip basic info
public string Pq_Name;
public string Cj_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public string Equip_Type;
public string Zy_Type;
public string Zy_SubType;
public string Equip_ABCMark;
//drbmp result
public string jxPlanDate;
public string sbStateAuto;
public string sbStateBak;
public string serviceinterval;
public string faultIntensity; //故障强度
public string alarmState;//报警状态
public string avgInterval;
public string runTrendL;
public string runTrendT;
public string runTrendV;
public string runTrend;//运行趋势
public int? isUrgentPM;
public DateTime? latestDate;
public string zzOpinion;
public string zzReason;
public string jxOpinion;
public string jxReason;
public string jxKeyContent;
public string jdcOpinion;
public int? state;
public string temp2;
public string temp3;
public string temp4;
public string temp5;
public string temp6;
public string temp7;
public string temp8;
public string temp9;
public string temp10;
}
//DRBPM_SbStateFullAnalysisList
public class DRBPM_SbStateFullAnalysisList
{
public List<DRBPM_SbStateFullAnalysisInfo> DRBPM_SbStateFullAnalysisInfoList;
}
/// <summary>
/// 获取DRBPM设备状态分析结果列表
/// </summary>
/// <param name="strTableName">要查询的表名,如:SbStateFullAnalysis(每天自动分析结果) 或 SbStateFullAnalysisx(审批结束后的结果)</param>
/// <param name="strWhere">查询条件,使用是要根据需要构造合适的条件语句</param>
/// <returns></returns>
public DRBPM_SbStateFullAnalysisList getDRBPM_SbStateFullAnalysisList(string strTableName, string strWhere)
{
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
//string zzcode = "A03"; //投用时,改为操作者所能管辖的装置的代码,如果是多个,需要处理一下
//机动处同意在本月执行的检修计划(非紧急计划,A14dot1中用)
//string strWhere = " sbStateBak like 'PM%' and IsUrgentPM=0 and JdcOpinion = '同意' and SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' " + " and ZzId='" + zzcode + "' ";
//string strWhere = " sbStateBak like 'PM%' and IsUrgentPM=0 and JdcOpinion = '同意' and SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' ";
string sqlcmd = String.Format("select * from {0} where {1} order by id asc ", strTableName, strWhere);
//"select id,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,IsUrgentPM,jdcOpinion from SbStateFullAnalysisx"
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
DRBPM_SbStateFullAnalysisList drbmpSFAlist = new DRBPM_SbStateFullAnalysisList();
//drbmpSFAlist.DRBPM_SbStateFullAnalysisInfoList = new List<DRBPM_SbStateFullAnalysisInfo>();
for (int i = 0; i < dt.Rows.Count; i++)
{
DRBPM_SbStateFullAnalysisInfo h = new DRBPM_SbStateFullAnalysisInfo();
h.Equip_Code = dt.Rows[i]["GybhId"].ToString(); //sbid
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(h.Equip_Code);
if (eqinfo == null)
continue;
//Equip info
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
h.Equip_GyCode = eqinfo.Equip_GyCode;
h.Equip_Type = eqinfo.Equip_Type;
h.Zy_Type = eqinfo.Equip_Specialty;
h.Zy_SubType = eqinfo.Equip_PhaseB;
h.Equip_ABCMark = eqinfo.Equip_ABCmark;
//DRBPM result
h.jxPlanDate = dt.Rows[i]["jxPlanDate"].ToString();
h.sbStateAuto = dt.Rows[i]["sbStateAuto"].ToString();
h.sbStateBak = dt.Rows[i]["sbStateBak"].ToString();
h.serviceinterval = dt.Rows[i]["serviceinterval"].ToString();
h.faultIntensity = dt.Rows[i]["faultIntensity"].ToString(); //故障强度
h.alarmState = dt.Rows[i]["alarmState"].ToString(); //报警状态
h.avgInterval = dt.Rows[i]["avgInterval"].ToString();
h.runTrendL = dt.Rows[i]["runTrendL"].ToString();
h.runTrendT = dt.Rows[i]["runTrendT"].ToString();
h.runTrendV = dt.Rows[i]["runTrendV"].ToString();
h.runTrend = dt.Rows[i]["runTrend"].ToString(); //运行趋势
h.isUrgentPM = int.Parse(dt.Rows[i]["isUrgentPM"].ToString());
h.latestDate = DateTime.Parse(dt.Rows[i]["latestDate"].ToString());
h.zzOpinion = dt.Rows[i]["zzOpinion"].ToString();
h.zzReason = dt.Rows[i]["zzReason"].ToString();
h.jxOpinion = dt.Rows[i]["jxOpinion"].ToString();
h.jxReason = dt.Rows[i]["jxReason"].ToString();
h.jxKeyContent = dt.Rows[i]["jxKeyContent"].ToString();
h.jdcOpinion = dt.Rows[i]["jdcOpinion"].ToString();
h.state = int.Parse(dt.Rows[i]["state"].ToString());
h.temp2 = dt.Rows[i]["temp2"].ToString();
h.temp3 = dt.Rows[i]["temp3"].ToString();
h.temp4 = dt.Rows[i]["temp4"].ToString();
h.temp5 = dt.Rows[i]["temp5"].ToString();
h.temp6 = dt.Rows[i]["temp6"].ToString();
h.temp7 = dt.Rows[i]["temp7"].ToString();
h.temp8 = dt.Rows[i]["temp8"].ToString();
h.temp9 = dt.Rows[i]["temp9"].ToString();
h.temp10 = dt.Rows[i]["temp10"].ToString();
//add to List
drbmpSFAlist.DRBPM_SbStateFullAnalysisInfoList.Add(h);
}
con.Close();
con.Dispose();
return drbmpSFAlist;
}
#endregion
#region DRBPM系统接口 for Query Table SbGyAnalysis -工艺能效分析
//DRBPM_SbGyAnalysisInfo
public class DRBPM_SbGyAnalysisInfo
{
//equip basic info
public string Pq_Name;
public string Cj_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public string Equip_Type;
public string Zy_Type;
public string Zy_SubType;
public string Equip_ABCMark;
public string sbWh;
//drbmp result
public Single? energyEfficiency;
public string gyState_PMGList;
public string gyState_PMGList_Desc;
public string pState;
public string currentDate;
}
//DRBPM_SbGyAnalysisList
public class DRBPM_SbGyAnalysisList
{
public List<DRBPM_SbGyAnalysisInfo> DRBPM_SbGyAnalysisInfoList;
}
/// <summary>
/// 获取DRBPM设备工艺能效分析结果列表
/// </summary>
/// <param name="strTableName">要查询的表名,如:SbGyAnalysis(每天自动分析结果)</param>
/// <param name="strWhere">查询条件,使用是要根据需要构造合适的条件语句</param>
/// <returns></returns>
public DRBPM_SbGyAnalysisList getDRBPM_SbGyAnalysisList(string strTableName = "SbGyAnalysis", string strWhere = "1=1")
{
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
DateTime dtime = DateTime.Now;
//dtime = dtime.AddDays(-1);
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
string record_filter = string.Format("currentDate >= '{0}' ", dtime.ToString()); //"1 <> 1";
strWhere = strWhere + " and " + record_filter;
string sqlcmd = String.Format("select * from {0} where {1} order by id asc ", strTableName, strWhere);
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
DRBPM_SbGyAnalysisList drbmpGyAlist = new DRBPM_SbGyAnalysisList();
drbmpGyAlist.DRBPM_SbGyAnalysisInfoList = new List<DRBPM_SbGyAnalysisInfo>();
for (int i = 0; i < dt.Rows.Count; i++)
{
DRBPM_SbGyAnalysisInfo h = new DRBPM_SbGyAnalysisInfo();
h.Equip_Code = dt.Rows[i]["sbId"].ToString(); //sbId
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(h.Equip_Code);
if (eqinfo == null)
continue;
//Equip info
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
h.Equip_GyCode = eqinfo.Equip_GyCode;
h.Equip_Type = eqinfo.Equip_Type;
h.Zy_Type = eqinfo.Equip_Specialty;
h.Zy_SubType = eqinfo.Equip_PhaseB;
h.Equip_ABCMark = eqinfo.Equip_ABCmark;
h.sbWh = dt.Rows[i]["sbWh"].ToString();
//drbmp result
h.energyEfficiency = Single.Parse(dt.Rows[i]["energyEfficiency"].ToString());
h.gyState_PMGList=dt.Rows[i]["gyState_PMGList"].ToString();
h.gyState_PMGList_Desc = GetGyStateDescription(dt.Rows[i]["gyState_PMGList"].ToString(), true);
h.pState = dt.Rows[i]["pState"].ToString();
h.currentDate = DateTime.Parse(dt.Rows[i]["currentDate"].ToString()).ToString("yyyy-MM-dd");
//add to List
drbmpGyAlist.DRBPM_SbGyAnalysisInfoList.Add(h);
}
con.Close();
con.Dispose();
return drbmpGyAlist;
}
#endregion
#region DRBPM系统接口 for A14dot3dot4
//A14dot3dot4_ModelInfo
public class A14dot3dot4_ModelInfo
{
public string Cj_Name;
public string Zz_Name;
public string Equip_Code;
public string Equip_GyCode;
public string Equip_Type;
public string Zy_Type;
public string Zy_SubType;
public string Equip_ABCMark;
//from DRBPM
public string drbpmRecordId;//唯一标志ID-在DRBPM表中
public string Jx_Reason;//检修原因
public string jxPlanDate;//计划检修时间
public string faultIntensity; //故障强度
public string alarmState;//报警状态
public string runTrend;//运行趋势
public string latestDate; //上次检修时间
//from A8.2
public string Job_Order = ""; //工单号
public string Job_OrderState = ""; //工单号(当前计划)状态
public string Plan_DescFilePath = ""; //检修方案
public string ZzConfirmPlan_Result = ""; //计划是否可实施,现场工程师确认是否可实施计划
public string JxdwConfirmEnd_done = ""; //计划实施情况-是否完成
public string PlanFinishDate = ""; //完工时间
public string JxSubmit_done = ""; //检修单位-是否提报(A8.2是否生成?)
}
//A14dot3dot4_Model
public class A14dot3dot4_Model
{
public List<A14dot3dot4_ModelInfo> A14dot3dot4_ModelInfoList;
public string isJx;//0712,zoujing
}
public A14dot3dot4_Model getA14dot3dot4_Model()
{
string equip_codes = "";
SqlConnection con = getDRBPMSqlConnection();//连接DRBPM数据库
if (con.State == ConnectionState.Closed)
con.Open();
//string zzcode = "A03"; //
//机动处同意在本月执行的检修计划(非紧急计划,A14dot3dot4中用)
//string strWhere = " sbStateBak like 'PM%' and IsUrgentPM=0 and JdcOpinion = '同意' and SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' " + " and ZzId='" + zzcode + "' ";
string strWhere = " sbStateBak like 'PM%' and JdcOpinion = '同意' and SUBSTRING(JxPlanDate,0,8)='" + System.DateTime.Now.ToString("yyyy-MM") + "' "; //and IsUrgentPM=0
string sqlcmd = String.Format("select * from SbStateFullAnalysisx where {0} order by id asc ", strWhere);
//"select id,ZzId,GybhId,SbName,JxPlanDate,sbStateAuto,sbStateBak,IsUrgentPM,jdcOpinion from SbStateFullAnalysisx"
SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
DataTable dt = new DataTable();
da.Fill(dt); //准备好查询到的数据到dt,供访问
A14dot3dot4_Model A14dot3dot4model = new A14dot3dot4_Model();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("检维修人员"))
A14dot3dot4model.isJx = "true";
A14dot3dot4model.A14dot3dot4_ModelInfoList = new List<A14dot3dot4_ModelInfo>();
int j = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
A14dot3dot4_ModelInfo h = new A14dot3dot4_ModelInfo();
h.Equip_Code = dt.Rows[i]["GybhId"].ToString(); //sbid
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(h.Equip_Code);
if (eqinfo == null)
continue;
if (j > 0)
equip_codes += ",";
equip_codes += h.Equip_Code;
j += 1;
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
h.Cj_Name = Equip_ZzBelong[1].EA_Name; //Cj_Name
h.Zz_Name = Equip_ZzBelong[0].EA_Name; //Zz_Name
h.Equip_GyCode = eqinfo.Equip_GyCode;
h.Equip_Type = eqinfo.Equip_Type;
h.Zy_Type = eqinfo.Equip_Specialty;
h.Zy_SubType = eqinfo.Equip_PhaseB;
h.Equip_ABCMark = eqinfo.Equip_ABCmark;
h.drbpmRecordId = dt.Rows[i]["Id"].ToString();//唯一标志ID-在DRBPM表中
string SbStateBak = dt.Rows[i]["sbStateBak"].ToString();
string Temp6 = dt.Rows[i]["Temp6"].ToString();
string Temp3 = dt.Rows[i]["Temp3"].ToString();
int IsUrgentPM = int.Parse(dt.Rows[i]["IsUrgentPM"].ToString());
string Temp5 = dt.Rows[i]["Temp5"].ToString();
string Temp9 = dt.Rows[i]["Temp9"].ToString();
h.Jx_Reason = GetReasonAll(SbStateBak, Temp6, Temp3, IsUrgentPM) + GetShortTermTrendDescription(Temp9, false);
//h.Jx_Reason = GetReasonAll(SbStateBak, Temp6, Temp3, IsUrgentPM) + GetGyStateDescription(Temp5, true) + GetShortTermTrendDescription(Temp9, true);
//h.Jx_Reason = getDRBPMJxReason(dt.Rows[i]["sbStateBak"].ToString()); // "一级缺陷"? //计划检修原因 PM?
h.jxPlanDate = DateTime.Now.ToString("yyyy-MM");
h.faultIntensity = dt.Rows[i]["faultIntensity"].ToString(); //故障强度
h.alarmState = dt.Rows[i]["alarmState"].ToString();//报警状态
h.runTrend = dt.Rows[i]["runTrend"].ToString(); //运行趋势
h.latestDate = dt.Rows[i]["latestDate"].ToString(); //上次检修时间
A14dot3dot4model.A14dot3dot4_ModelInfoList.Add(h);
}
string query_list = " E.W_Name,M.Event_Name, P.Equip_Code, P.Job_Order, P.Job_OrderState, P.Plan_DescFilePath, P.ZzConfirmPlan_Result,P.JxdwConfirmEnd_done, R.time,P.JxSubmit_done";
string query_condition = string.Format("P.Equip_Code in ({0}) and E.W_Name = 'A8dot2'", equip_codes);
DateTime dtime = DateTime.Now;
dtime = dtime.AddDays(-dtime.Day + 1);
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
string record_filter = string.Format("time >= '{0}' ", dtime.ToString()); //"1 <> 1";
System.Data.DataTable dtA8dot2 = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
if (dtA8dot2 != null && dtA8dot2.Rows.Count > 0)
{
for (int i = 0; i < A14dot3dot4model.A14dot3dot4_ModelInfoList.Count; i++)
{
string current_code = A14dot3dot4model.A14dot3dot4_ModelInfoList[i].Equip_Code;
//Job_Order
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Job_Order is not null";
dtA8dot2.DefaultView.Sort = "time";
DataTable dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot3dot4model.A14dot3dot4_ModelInfoList[i].Job_Order = dtTmp.Rows[dtTmp.Rows.Count - 1]["Job_Order"].ToString();
dtTmp.Clear();
//Job_OrderState
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Job_OrderState is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot3dot4model.A14dot3dot4_ModelInfoList[i].Job_OrderState = dtTmp.Rows[dtTmp.Rows.Count - 1]["Job_OrderState"].ToString();
dtTmp.Clear();
//Plan_DescFilePath
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and Plan_DescFilePath is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot3dot4model.A14dot3dot4_ModelInfoList[i].Plan_DescFilePath = dtTmp.Rows[dtTmp.Rows.Count - 1]["Plan_DescFilePath"].ToString();
dtTmp.Clear();
//ZzConfirmPlan_Result
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and ZzConfirmPlan_Result is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot3dot4model.A14dot3dot4_ModelInfoList[i].ZzConfirmPlan_Result = dtTmp.Rows[dtTmp.Rows.Count - 1]["ZzConfirmPlan_Result"].ToString();
dtTmp.Clear();
//JxdwConfirmEnd_done
dtA8dot2.DefaultView.RowFilter = "JxdwConfirmEnd_done is not null";
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot3dot4model.A14dot3dot4_ModelInfoList[i].JxdwConfirmEnd_done = dtTmp.Rows[dtTmp.Rows.Count - 1]["JxdwConfirmEnd_done"].ToString();
dtTmp.Clear();
//PlanFinishDate
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and JxdwConfirmEnd_done =true and time is not null";//?
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot3dot4model.A14dot3dot4_ModelInfoList[i].PlanFinishDate = dtTmp.Rows[dtTmp.Rows.Count - 1]["time"].ToString();
dtTmp.Clear();
//JxSubmit_done
dtA8dot2.DefaultView.RowFilter = "Equip_Code = '" + current_code + "' and JxSubmit_done =true and time is not null";//?
dtA8dot2.DefaultView.Sort = "time";
dtTmp = dtA8dot2.DefaultView.ToTable();
if (dtTmp.Rows.Count > 0)
A14dot3dot4model.A14dot3dot4_ModelInfoList[i].JxSubmit_done = dtTmp.Rows[dtTmp.Rows.Count - 1]["JxSubmit_done"].ToString().ToLower();
dtTmp.Clear();
}
}
con.Close();
con.Dispose();
return A14dot3dot4model;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Speciaty_Info
{ /// <summary>
/// 主键
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Specialty_Id { get; set; }
/// <summary>
/// 专业名称
/// </summary>
public string Specialty_Name { get; set; }
/// <summary>
/// 父节点
/// </summary>
public virtual Speciaty_Info Speciaty_Parent { get; set; }
/// <summary>
/// 子节点
/// </summary>
public virtual ICollection<Speciaty_Info> Speciaty_Childs { get; set; }
/// <summary>
/// 和Person_Info的关系
/// </summary>
public virtual ICollection<Person_Info> Speciaty_Persons { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
/// <summary>
/// 对表File_Catalog的访问接口
/// </summary>
public class guidelinescatalogs : BaseDAO
{
//根据分类号查找分类
public guidelines_catalog GetCatalog(int cat_ID)
{
using (var db = base.NewDB())
{
var fc = db.gcatalogs.Where(s => s.Catalog_Id == cat_ID).First();
return fc;
}
}
//根据分类名称查找分类
public List<guidelines_catalog> GetCatalog(string cat_name)
{
using (var db = base.NewDB())
{
return db.gcatalogs.Where(s => s.Catalog_Name == cat_name).ToList();
}
}
//查找分类的子分类
public List<guidelines_catalog> GetChildCatalogs(int cat_ID)
{
using (var db = base.NewDB())
{
var fc = db.gcatalogs.Where(s => s.Catalog_Id == cat_ID).First();
if (fc == null)
return null;
return fc.Child_Catalogs.ToList();
}
}
//查找分类的父类
public guidelines_catalog GetParentCatalog(int cat_ID)
{
using (var db = base.NewDB())
{
var fc = db.gcatalogs.Where(s => s.Catalog_Id == cat_ID).First();
if (fc == null)
return null;
return fc.parent_Catalog;
}
}
public DbSet<guidelines_catalog> GetCatalogsSet()
{
return base.NewDB().gcatalogs;
}
/// <summary>
/// 添加一个新分类
/// </summary>
/// <param name="p_ID">父节点ID</param>
/// <param name="n_Name">新节点名称</param>
/// <returns></returns>
public bool AddNewCatalog(int p_ID, string n_Name)
{
using (var db = base.NewDB())
{
guidelines_catalog nfc = new guidelines_catalog();
nfc.Catalog_Name = n_Name;
if (p_ID != -1)
{
var fc = db.gcatalogs.Where(s => s.Catalog_Id == p_ID).First();
if (fc == null)
return false;
fc.Child_Catalogs.Add(nfc);
}
else
{
db.gcatalogs.Add(nfc);
}
db.SaveChanges();
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="ID"></param>
/// <returns></returns>
public bool DeleteCatalog(int ID)
{
bool bResult = false;
try
{
using (var db = base.NewDB())
{
db.gcatalogs.Remove(db.gcatalogs.Where(s => s.Catalog_Id == ID).First());
db.SaveChanges();
}
bResult = true;
}
catch
{
bResult = false;
}
return bResult;
}
public bool ModifyCatalog(int ID, string name)
{
bool bResult = false;
try
{
using (var db = base.NewDB())
{
db.gcatalogs.Where(s => s.Catalog_Id == ID).First().Catalog_Name = name;
db.SaveChanges();
}
}
catch
{
bResult = false;
}
return bResult;
}
public List<guidelines_info> GetFiles(int ID)
{
List<guidelines_info> files = null;
try
{
using (var db = base.NewDB())
{
files = db.gcatalogs.Where(s => s.Catalog_Id == ID).First().Files_Included.ToList();
}
}
catch
{
files = null;
}
return files;
}
public bool AddFiletoCatalog(int pID, guidelines_info nf)
{
try
{
using (var db = base.NewDB())
{
db.gcatalogs.Where(s => s.Catalog_Id == pID).First().Files_Included.Add(nf);
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EquipModel.Entities;
using EquipDAL.Implement;
namespace EquipBLL.AdminManagment
{
public class NoticeManagement
{ //适用于流程A13.1 获取状态为0即待处理的通知单
public List<Notice_A13dot1> getNoticeForA13dot1()
{
NoticeView Notice = new NoticeView();
return Notice.GetNotice_A13dot1();
}
/// <summary>
/// 适用于流程A13.1 获取状态为1即待处理的通知单(现场工程师提交的)
/// </summary>
/// <returns></returns>
public List<Notice_A13dot1> getNoticeForA13dot1Uncomp()
{
NoticeView Notice = new NoticeView();
return Notice.GetNotice_A13dot1Uncomp();
}
/// <summary>
/// 生成13.1的工作流,同时修改状态为1,传入操作人和操作时间
/// </summary>
/// <param name="username"></param>
/// <param name="opertime"></param>
/// <param name="Notice_Id"></param>
/// <returns></returns>
public string modifyNoticeForA13dot1(string username, string opertime, string Notice_Id)
{
NoticeView Notice = new NoticeView();
return Notice.ModifyNoticeState(username,opertime,Notice_Id);
}
/// <summary>
/// 删除功能,即该库中状态为2
/// </summary>
/// <param name="Notice_Id"></param>
/// <returns></returns>
public string removeNoticeForA13dot1(string Notice_Id)
{
NoticeView Notice = new NoticeView();
return Notice.RemoveNoticeState(Notice_Id);
}
/// <summary>
/// 通过通知单号来获取对应通知单数据
/// </summary>
/// <param name="Notice_Id"></param>
/// <returns></returns>
public Notice_A13dot1 getNoticeForA13dot1ByNI(string Notice_Id)
{
NoticeView Notice = new NoticeView();
return Notice.getNoticeByNI(Notice_Id);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowDesigner.PropertyEditor
{
/// <summary>
/// ActionValueSelector.xaml 的交互逻辑
/// </summary>
public partial class ActionValueSelector : Window
{
private List<string> _linkParams = new List<string>();
public List<string> LinkParams
{
get
{
return _linkParams;
}
set
{
_linkParams = value;
foreach (var lp in _linkParams)
{
TreeViewItem ti = new TreeViewItem();
ti.Header = lp;
(LinkValue.Items.GetItemAt(1) as TreeViewItem).Items.Add(ti);
}
}
}
public string ret_value = "";
public ActionValueSelector()
{
InitializeComponent();
}
private void Ok_Click(object sender, RoutedEventArgs e)
{
string selHeader = (LinkValue.SelectedItem as TreeViewItem).Header.ToString();
if (selHeader == "当前事件关联变量" || selHeader == "工作流属性")
return;
else
{
if (((LinkValue.SelectedItem as TreeViewItem).Parent as TreeViewItem).Header.ToString() == "工作流属性")
{
ret_value = @"@ATT_" + (LinkValue.SelectedItem as TreeViewItem).Header.ToString();
}
else if (((LinkValue.SelectedItem as TreeViewItem).Parent as TreeViewItem).Header.ToString() == "当前事件关联变量")
{
ret_value = @"@PAR_" + (LinkValue.SelectedItem as TreeViewItem).Header.ToString();
}
else
{
this.DialogResult = false;
this.Close();
return;
}
this.DialogResult = true;
this.Close();
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Context
{
public class EquipWebContext : DbContext
{
public EquipWebContext() : base("EquipWebContext") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Depart_Archi>().HasMany(s => s.Depart_child).WithOptional(s => s.Depart_Parent);
modelBuilder.Entity<Person_Info>().HasMany(s => s.Person_roles).WithMany(s => s.Role_Persons).Map( s =>
{
s.ToTable("Person_to_Role");
s.MapLeftKey("Person_Id");
s.MapRightKey("Role_Id");
}
);
modelBuilder.Entity<Person_Info>().HasMany(s => s.Person_EquipEAs).WithMany(s =>s.EA_Persons).Map(s =>
{
s.ToTable("Person_to_EquipArchi");
s.MapLeftKey("Person_Id");
s.MapRightKey("EA_Id");
}
);
modelBuilder.Entity<Person_Info>().HasMany(s => s.Person_Equips).WithMany(s => s.Equip_Manager).Map(s =>
{
s.ToTable("Person_to_Equip");
s.MapLeftKey("Person_Id");
s.MapRightKey("Equip_Id");
}
);
modelBuilder.Entity<Equip_Archi>().HasMany(s => s.EA_Childs).WithOptional(s => s.EA_Parent);
modelBuilder.Entity<Speciaty_Info>().HasMany(s => s.Speciaty_Childs).WithOptional(s => s.Speciaty_Parent);
modelBuilder.Entity<Person_Info>().HasMany(s => s.Person_specialties).WithMany(s => s.Speciaty_Persons).Map(s =>
{
s.ToTable("Person_to_Speciaty");
s.MapLeftKey("Person_Id");
s.MapRightKey("Speciaty_Id");
}
);
modelBuilder.Entity<Person_Info>().HasMany(s => s.Person_Menus).WithMany(s => s.Menu_Persons).Map(s =>
{
s.ToTable("Person_to_Menu");
s.MapLeftKey("Person_Id");
s.MapRightKey("Menu_Id");
}
);
modelBuilder.Entity<Role_Info>().HasMany(s => s.Role_Menus).WithMany(s => s.Menu_Roles).Map(s =>
{
s.ToTable("Role_to_Menu");
s.MapLeftKey("Role_Id");
s.MapRightKey("Menu_Id");
}
);
modelBuilder.Entity<File_Info>().HasMany(s => s.File_Equips).WithMany(s => s.Equip_Files).Map(s =>
{
s.ToTable("File_to_Equip");
s.MapLeftKey("File_Id");
s.MapRightKey("Equip_Id");
}
);
modelBuilder.Entity<Person_Info>().HasMany(s => s.Person_WorkFlows).WithMany(s => s.WorkFlow_Persons).Map(s =>
{
s.ToTable("Person_to_WorkFlow");
s.MapLeftKey("Person_Id");
s.MapRightKey("Menu_Id");
}
);
modelBuilder.Entity<guidelines_catalog>().HasMany(s => s.Child_Catalogs).WithOptional(s => s.parent_Catalog);
modelBuilder.Entity<guidelines_info>().HasRequired(s => s.Self_Catalog).WithMany(s => s.Files_Included).WillCascadeOnDelete(true);
modelBuilder.Entity<File_Catalog>().HasMany(s => s.Child_Catalogs).WithOptional(s => s.parent_Catalog);
modelBuilder.Entity<File_Info>().HasRequired(s => s.Self_Catalog).WithMany(s => s.Files_Included).WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
//系统菜单表
public DbSet<Menu> Sys_Menus { get; set; }
public DbSet<NWorkFlowSer> NWorkFlowSer { get; set; }
//组织结构
public DbSet<Depart_Archi> Department { get; set; }
//职员信息
public DbSet<Person_Info> Persons { get; set; }
//角色信息
public DbSet<Role_Info> Roles { get; set; }
//设备组织结构
public DbSet<Equip_Archi> EArchis { get; set; }
//设备信息
public DbSet<Equip_Info> Equips { get; set; }
//专业表
public DbSet<Speciaty_Info> Specialties { get; set; }
//文件类别表
public DbSet<File_Catalog> FCatalogs { get; set; }
public DbSet<File_Info> Files { get; set; }
//方针政策表
public DbSet<guidelines_catalog> gcatalogs { get; set; }
public DbSet<guidelines_info> guidelines { get; set; }
public DbSet<Quick_Entrance> Quick_Entrance { get; set; }
public DbSet<A15dot1Tab> A15dot1Tab { get; set; }
public DbSet<A5dot1Tab1> A5dot1Tab1 { get; set; }
public DbSet<A5dot1Tab2> A5dot1Tab2 { get; set; }
public DbSet<A5dot2Tab1> A5dot2Tab1 { get; set; }
public DbSet<A5dot2Tab2> A5dot2Tab2 { get; set; }
public DbSet<ZhiduFile> ZhiduFile { get; set; }
public DbSet<A6dot2Tab1> A6dot2Tab1 { get; set; }
public DbSet<A6dot2Tab2> A6dot2Tab2 { get; set; }
public DbSet<A6dot2LsTaskTab> A6dot2LsTaskTab { get; set; }
public DbSet<Runhua_Info> Runhua { get; set; }
public DbSet<DSEventDetail> DSEventDetail { get; set; }
public DbSet<DsTimeOfWork> DsTimeOfWork { get; set; }
public DbSet<WorkSumCatalog> WCatalogs { get; set; }
public DbSet<WorkSummary> WorkSumFiles { get; set; }
public DbSet<Pq_Zz_map> Pq_Zz_maps { get; set; }
public DbSet<Pq_EC_map> Pq_EC_maps { get; set; }
public DbSet<A15dot1TabDian> A15dot1TabDian { get; set; }
public DbSet<A15dot1TabJing> A15dot1TabJing { get; set; }
public DbSet<A15dot1TabYi> A15dot1TabYi { get; set; }
public DbSet<A15dot1TabQiYe> A15dot1TabQiYe { get; set; }
public DbSet<A15dot1TabDong> A15dot1TabDong { get; set; }
public DbSet<A15dot1TabDian_Weight> A15dot1TabDian_Weight { get; set; }
public DbSet<A15dot1TabJing_Weight> A15dot1TabJing_Weight { get; set; }
public DbSet<A15dot1TabYi_Weight> A15dot1TabYi_Weight { get; set; }
public DbSet<A15dot1TabQiYe_Weight> A15dot1TabQiYe_Weight { get; set; }
public DbSet<A15dot1TabDong_Weight> A15dot1TabDong_Weight { get; set; }
public DbSet<Pq_A15dot1TabDian_Weight> Pq_A15dot1TabDian_Weight { get; set; }
public DbSet<Pq_A15dot1TabJing_Weight> Pq_A15dot1TabJing_Weight { get; set; }
public DbSet<Pq_A15dot1TabYi_Weight> Pq_A15dot1TabYi_Weight { get; set; }
public DbSet<Pq_A15dot1TabQiYe_Weight> Pq_A15dot1TabQiYe_Weight { get; set; }
public DbSet<Pq_A15dot1TabDong_Weight> Pq_A15dot1TabDong_Weight { get; set; }
public DbSet<Notice_Info> Notice_Infos { get; set; }
////基础数据表
//public DbSet<PqInfo> Sys_PqInfos { get; set; }
//public DbSet<CjInfo> Sys_CjInfos { get; set; }
//public DbSet<ZzInfo> Sys_ZzInfos { get; set; }
//public DbSet<SbInfo> Sys_SbInfos { get; set; }
//public DbSet<RoleInfo> Sys_RoleInfos { get; set; }
//public DbSet<UserInfo> Sys_UserInfos { get; set; }
//public DbSet<User2Sb> Sys_User2Sbs { get; set; }
//public DbSet<User2Zz> Sys_User2Zzs { get; set; }
//public DbSet<Role2Authority> Sys_Role2Authoritys { get; set; }
//public DbSet<User2Authority> Sys_User2Authoritys { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class PersonAndWorkflow : BaseDAO
{
public int GetPersonIdByName(string Person_Name)
{
using (var db = base.NewDB())
{
int PersonId = db.Persons.Where(a => a.Person_Name == Person_Name).First().Person_Id;
return PersonId;
}
}
public int GetMenuIdByName(string Menu_Name)
{
using (var db = base.NewDB())
{
int MenuId = db.Sys_Menus.Where(a => a.Menu_Name == Menu_Name).First().Menu_Id;
return MenuId;
}
}
public bool AttachtoMenu(int personid, int menuid)
{
try
{
using (var db = base.NewDB())
{
Person_Info person = db.Persons.Where(s => s.Person_Id == personid).First();
Menu menu = db.Sys_Menus.Where(s => s.Menu_Id == menuid).First();
person.Person_Menus.Add(menu);
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
}
}
<file_sep>
function DispalsySide(Entity_Ser) {
//显示右边的导航条
var inhtml;
$.ajax({
url: '/Common/WorkFlow_MainProcess',
dataType: 'json',
type: 'post',
data: { "Entity_Ser": Entity_Ser },
success: function (backdata) {
inhtml = "<h5 >设备工艺编号:<a role=\"button\" data-toggle=\"modal\" data-target=\"#EquipInfoModal\" onclick=\"displayEquipInfo('" + backdata.FLow_EquipGyCode + "')\"> " + backdata.FLow_EquipGyCode + "</a></h5>";
inhtml = inhtml + "<ul class=\"timeline\"> <li class=\"time-label\"> <span class=\"bg-red\">" + backdata.Flow_Name + "</span>";
//inhtml = inhtml + "<div class=\"timeline-item\">";
inhtml = inhtml + "<a href=\"" + backdata.FLow_DescPath + "\" target=_blank>" + "流程说明</a></span>";
inhtml = inhtml + "</li>";
for (var i = 0; i < backdata.Miss.length; i++) {
if ((backdata.Miss[i]).Miss_Type == 0) {
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">"
inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i>" + (backdata.Miss[i]).Miss_Time + "</span>";
//inhtml = inhtml + "<h1 class=\"timeline-header no-border\"><a data-toggle=\"modal\" data-target=\"#ParamModal\" onclick=\"displayParams('" + backdata.Flow_Id + "','" + (backdata.Miss[i]).Miss_Id + "')\"> " + (backdata.Miss[i]).Miss_Name + "</a></h1>";
inhtml = inhtml + "<h5 class=\"timeline-header no-border\" role=\"button\" data-toggle=\"modal\" data-target=\"#ParamModal\" onclick=\"displayParams('" + backdata.Flow_Id + "','" + (backdata.Miss[i]).Miss_Id + "')\"> " + (backdata.Miss[i]).Miss_Name + "</h5>";
inhtml = inhtml + " </div> </li>"
}
else if ((backdata.Miss[i]).Miss_Type == 2) {
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">"
inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i>待处理任务</span>";
//inhtml = inhtml + "<h1 class=\"timeline-header no-border\"><a data-toggle=\"modal\" data-target=\"#ParamModal\" onclick=\"displayParams('" + backdata.Flow_Id + "','" + (backdata.Miss[i]).Miss_Id + "')\"> " + (backdata.Miss[i]).Miss_Name + "</a></h1>";
inhtml = inhtml + "<h5 class=\"timeline-header no-border\" > " + (backdata.Miss[i]).Miss_Name + "</h5>";
inhtml = inhtml + " </div> </li>"
}
else {
if (backdata.Miss[i].Miss_LinkFlowType == "parallel") {
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">";
//inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i> " + (backdata.Miss[i]).Miss_Time + "</span>";
inhtml = inhtml + "<span class=\"time\"><a href=\"" + (backdata.Miss[i]).Miss_LinkFlowName + "\" target=_blank>" + "流程说明</a></span>";
if ((backdata.Miss[i]).Miss_LinkFlowId > -1)
inhtml = inhtml + "<a class=\"btn btn-primary btn-warning\" role=\"button\" data-toggle=\"collapse\" href=\"#FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + "\" aria-expanded=true aria-controls=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + " onclick=\"subFlow(" + (backdata.Miss[i]).Miss_LinkFlowId + ")\">" + (backdata.Miss[i]).Miss_Name + "</a>";
else
inhtml = inhtml + "<a class=\"btn btn-primary btn-warning\" role=\"button\" data-toggle=\"collapse\" >" + (backdata.Miss[i]).Miss_Name + "</a>";
inhtml = inhtml + " <div class=\"collapse\" id=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + ">";
inhtml = inhtml + "</div> </li>";
}
if (backdata.Miss[i].Miss_LinkFlowType == "serial") {
// inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
// inhtml = inhtml + "<div class=\"timeline-item\">"
// inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i>" + (backdata.Miss[i]).Miss_Time + "</span>";
// inhtml = inhtml + "<h1 class=\"timeline-header no-border\"><a href=\"/A13dot1/WorkFlow_HisDetailParallel?Entity_Id=" + (backdata.Miss[i]).Miss_LinkFlowId + "\" target=\"_blank\">" + backdata.Miss[i].Miss_Name + "</a> </h1>";
// inhtml = inhtml + " </div> </li>"
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">";
// inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i> " + (backdata.Miss[i]).Miss_Time + "</span>";
inhtml = inhtml + "<span class=\"time\"><a href=\"" + (backdata.Miss[i]).Miss_LinkFlowName + "\" target=_blank>" + "流程说明</a></span>";
if ((backdata.Miss[i]).Miss_LinkFlowId > -1)
inhtml = inhtml + "<a class=\"btn btn-primary btn-success \" role=\"button\" data-toggle=\"collapse\" href=\"#FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + "\" aria-expanded=true aria-controls=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + " onclick=\"subFlow(" + (backdata.Miss[i]).Miss_LinkFlowId + ")\">" + (backdata.Miss[i]).Miss_Name + "</a>";
else
inhtml = inhtml + "<a class=\"btn btn-primary btn-success\" role=\"button\" data-toggle=\"collapse\" >" + (backdata.Miss[i]).Miss_Name + "</a>";
inhtml = inhtml + " <div class=\"collapse\" id=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + ">";
inhtml = inhtml + "</div> </li>";
}
}
}
inhtml = inhtml + "</ul>";
$("#sidebar").empty().append(inhtml);
}
});
}
function displayParams(Entity_Id, Mission_Id) {
var inhtml;
$.ajax({
url: '/Common/WorkFlow_ListParam',
dataType: 'json',
type: 'post',
data: {
json1: '{Entity_Id: "' + Entity_Id
+ '", Mission_Id: "' + Mission_Id
+ '"}'
},
success: function (backdata) {
inhtml = "<table class=\"table table-hover table-bordered\"> <tbody><tr>";
for (var i = 0; i < backdata.length; i++) {
if (backdata[i].Param_Value == "green") {
backdata[i].Param_Value = "绿色";
}
if (backdata[i].Param_Value == "red") {
backdata[i].Param_Value = "红色";
}
if (backdata[i].Param_Value == "yellow") {
backdata[i].Param_Value = "黄色";
}
if (backdata[i].Param_Value == "True") {
backdata[i].Param_Value = "是";
}
if (backdata[i].Param_Value == "False") {
backdata[i].Param_Value = "否";
}
inhtml = inhtml + " <tr class=\"info\">";
inhtml = inhtml + "<th>" + backdata[i].Param_Desc + "</th>";
if (backdata[i].Param_isFile == 1 && backdata[i].Param_Value != "") {
inhtml = inhtml + "<td><a href=" + backdata[i].Param_UploadFilePath + " target=_blank>" + backdata[i].Param_SavedFilePath + "</a></td> ";
}
else
inhtml = inhtml + "<td>" + backdata[i].Param_Value + "</td>";
inhtml = inhtml + " </tr>";
}
inhtml = inhtml + " </tbody></table>";
$('#ParamDiv').empty().append(inhtml);
}
}
);
}
function displayEquipInfo(Equip_GyCode) {
var inhtml;
$.ajax({
url: '/Common/WorkFlow_EquipInfo',
dataType: 'json',
type: 'post',
data: {
"Equip_GyCode": Equip_GyCode
},
success: function (backdata) {
inhtml = "<table class=\"table table-hover table-bordered\"> <tbody><tr>";
for (var i = 0; i < backdata.length; i++) {
inhtml = inhtml + " <tr class=\"info\">";
inhtml = inhtml + "<th>" + backdata[i].Param_Name + "</th>";
inhtml = inhtml + "<td>" + backdata[i].Param_value + "</td>";
inhtml = inhtml + " </tr>";
}
inhtml = inhtml + " </tbody></table>";
$('#EquipInfoDiv').empty().append(inhtml);
}
}
);
}
function subFlow(FlowId) {
var divname = "#FLow_" + FlowId;
var inhtml;
$.ajax({
url: '/Common/WorkFlow_SubProcess',
dataType: 'json',
type: 'post',
data: { "FlowId": FlowId },
success: function (backdata) {
inhtml = "<ul class=\"timeline\">";
for (var i = 0; i < backdata.Miss.length; i++) {
if ((backdata.Miss[i]).Miss_Type == 0) {
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">"
inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i>" + (backdata.Miss[i]).Miss_Time + "</span>";
//inhtml = inhtml + "<h1 class=\"timeline-header no-border\"><a data-toggle=\"modal\" data-target=\"#ParamModal\" onclick=\"displayParams('" + backdata.Flow_Id + "','" + (backdata.Miss[i]).Miss_Id + "')\"> " + (backdata.Miss[i]).Miss_Name + "</a></h1>";
inhtml = inhtml + "<h6 class=\"timeline-header no-border\" role=\"button\" data-toggle=\"modal\" data-target=\"#ParamModal\" onclick=\"displayParams('" + backdata.Flow_Id + "','" + (backdata.Miss[i]).Miss_Id + "')\"> " + (backdata.Miss[i]).Miss_Name + "</h6>";
inhtml = inhtml + " </div> </li>"
}
else if ((backdata.Miss[i]).Miss_Type == 2) {
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">"
inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i>待处理任务</span>";
//inhtml = inhtml + "<h1 class=\"timeline-header no-border\"><a data-toggle=\"modal\" data-target=\"#ParamModal\" onclick=\"displayParams('" + backdata.Flow_Id + "','" + (backdata.Miss[i]).Miss_Id + "')\"> " + (backdata.Miss[i]).Miss_Name + "</a></h1>";
inhtml = inhtml + "<h6 class=\"timeline-header no-border\"> " + (backdata.Miss[i]).Miss_Name + "</h6>";
inhtml = inhtml + " </div> </li>"
}
else {
if (backdata.Miss[i].Miss_LinkFlowType == "parallel") {
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">";
//inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i> " + (backdata.Miss[i]).Miss_Time + "</span>";
inhtml = inhtml + "<span class=\"time\"><a href=\"" + (backdata.Miss[i]).Miss_LinkFlowName + "\" target=_blank>" + "流程说明</a></span>";
if ((backdata.Miss[i]).Miss_LinkFlowId > -1)
inhtml = inhtml + "<a class=\"btn btn-primary btn-warning\" role=\"button\" data-toggle=\"collapse\" href=\"#FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + "\" aria-expanded=true aria-controls=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + " onclick=\"subFlow(" + (backdata.Miss[i]).Miss_LinkFlowId + ")\">" + (backdata.Miss[i]).Miss_Name + "</a>";
else
inhtml = inhtml + "<a class=\"btn btn-primary btn-warning\" role=\"button\" data-toggle=\"collapse\" >" + (backdata.Miss[i]).Miss_Name + "</a>";
inhtml = inhtml + " <div class=\"collapse\" id=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + ">";
inhtml = inhtml + "</div> </li>";
}
if (backdata.Miss[i].Miss_LinkFlowType == "serial") {
// inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
// inhtml = inhtml + "<div class=\"timeline-item\">"
// inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i>" + (backdata.Miss[i]).Miss_Time + "</span>";
// inhtml = inhtml + "<h1 class=\"timeline-header no-border\"><a href=\"/A13dot1/WorkFlow_HisDetailParallel?Entity_Id=" + (backdata.Miss[i]).Miss_LinkFlowId + "\" target=\"_blank\">" + backdata.Miss[i].Miss_Name + "</a> </h1>";
// inhtml = inhtml + " </div> </li>"
inhtml = inhtml + "<li> <i class=\"fa fa-user bg-aqua\"></i>";
inhtml = inhtml + "<div class=\"timeline-item\">";
// inhtml = inhtml + "<span class=\"time\"><i class=\"fa fa-clock-o\"></i> " + (backdata.Miss[i]).Miss_Time + "</span>";
inhtml = inhtml + "<span class=\"time\"><a href=\"" + (backdata.Miss[i]).Miss_LinkFlowName + "\" target=_blank>" + "流程说明</a></span>";
if ((backdata.Miss[i]).Miss_LinkFlowId > -1)
inhtml = inhtml + "<a class=\"btn btn-primary btn-success \" role=\"button\" data-toggle=\"collapse\" href=\"#FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + "\" aria-expanded=true aria-controls=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + " onclick=\"subFlow(" + (backdata.Miss[i]).Miss_LinkFlowId + ")\">" + (backdata.Miss[i]).Miss_Name + "</a>";
else
inhtml = inhtml + "<a class=\"btn btn-primary btn-success\" role=\"button\" data-toggle=\"collapse\" >" + (backdata.Miss[i]).Miss_Name + "</a>";
inhtml = inhtml + " <div class=\"collapse\" id=FLow_" + (backdata.Miss[i]).Miss_LinkFlowId + ">";
inhtml = inhtml + "</div> </li>";
}
}
}
inhtml = inhtml + "</ul>";
$(divname).empty().append(inhtml);
}
}
);
}<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Kpi : BaseDAO
{
public List<A15dot1TabQiYe> GetJxRecord(string roles, string dep, string name,List<string> cjname)
{
List<A15dot1TabQiYe> e = new List<A15dot1TabQiYe>();
List<A15dot1TabQiYe> temp = new List<A15dot1TabQiYe>();
using (var db = base.NewDB())
{
if (dep.Contains("机动处"))
{
if (roles.Contains("可靠性工程师") )
{
return db.A15dot1TabQiYe.Where(a => (a.state == 1 || a.state == 2 || a.state == 0) && a.submitUser == name).ToList();
}
else
return db.A15dot1TabQiYe.Where(a => a.state == 1 || a.state == 2).ToList();
}
else if (roles.Contains("可靠性工程师"))
{
foreach (var cj in cjname)
{
List<A15dot1TabQiYe> t = db.A15dot1TabQiYe.Where(a => a.state == 0 && a.temp3 == cj).ToList();
foreach(var tt in t)
{
temp.Add(tt);
}
}
return temp;
}
else
return e;
}
}
public List<A15dot1TabQiYe> GetJxRecord_detail(int id)
{
using (var db = base.NewDB())
{
return db.A15dot1TabQiYe.Where(a => a.Id == id).ToList();
}
}
public List<A15dot1TabQiYe> GetHisJxRecord(string roles, string dep, string name)
{
List<A15dot1TabQiYe> e = new List<A15dot1TabQiYe>();
List<A15dot1TabQiYe>temp=new List<A15dot1TabQiYe>();
using (var db = base.NewDB())
{
if (dep.Contains("机动处"))
{
return db.A15dot1TabQiYe.Where(a => a.state == 3).ToList();
}
else if (roles.Contains("可靠性工程师") )
{
return db.A15dot1TabQiYe.Where(a => a.state == 3 && a.submitUser == name).ToList();
}
else
return e;
}
}
public List<A15dot1TabQiYe> GetHisJxRecord_detail(int id)
{
using (var db = base.NewDB())
{
return db.A15dot1TabQiYe.Where(a => a.Id == id).ToList();
}
}
public List<A15dot1TabDian> GetJxRecord_detailDian(int id)
{
using (var db = base.NewDB())
{
return db.A15dot1TabDian.Where(a => a.Id == id).ToList();
}
}
public List<object> qstdata(string grahpic_name, string zz)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabQiYe>("select * from A15dot1TabQiYe where submitDepartment='" + zz + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("jdcOperateTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}
/// <summary>
/// 趋势图的方法
/// </summary>
/// <param name="grahpic_name">字段名</param>
/// <param name="zz">装置</param>
/// <param name="zy">专业</param>
/// <returns></returns>
public List<object> qstdataQiYe(string grahpic_name, string zzId,string zy)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabQiYe>("select * from A15dot1TabQiYe where temp2='"+zy+"'and submitDepartment='" + zzId + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitDepartment");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}
public List<object> qstdataqc(string grahpic_name, string graphic_zdm, string graphic_zy, string graphic_subdipartment)//全厂的趋势图
{
using (var db = base.NewDB())
{
List<object> a = new List<object>();
object cut = new object();
cut = "$$";
if (graphic_zy == "企业级")//查询企业级的qst
{
var i = db.Database.SqlQuery<A15dot1TabQiYe>("select * from A15dot1TabQiYe where submitDepartment='" + graphic_subdipartment + "'").ToList();
foreach (var item in i)
{
var t = item.GetType().GetProperty(graphic_zdm);
var result = t.GetValue(item, null);
a.Add(result);
}
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
else if (graphic_zy == "动设备专业")//查询企业级的qst
{
var i = db.Database.SqlQuery<A15dot1TabDong>("select * from A15dot1TabDong where submitDepartment='" + graphic_subdipartment + "'").ToList();
foreach (var item in i)
{
var t = item.GetType().GetProperty(graphic_zdm);
var result = t.GetValue(item, null);
a.Add(result);
}
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
else if (graphic_zy == "静设备专业")//查询企业级的qst
{
var i = db.Database.SqlQuery<A15dot1TabJing>("select * from A15dot1TabJing where submitDepartment='" + graphic_subdipartment + "'").ToList();
foreach (var item in i)
{
var t = item.GetType().GetProperty(graphic_zdm);
var result = t.GetValue(item, null);
a.Add(result);
}
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
else if (graphic_zy == "电气专业")//查询企业级的qst
{
var i = db.Database.SqlQuery<A15dot1TabDian>("select * from A15dot1TabDian where submitDepartment='" + graphic_subdipartment + "'").ToList();
foreach (var item in i)
{
var t = item.GetType().GetProperty(graphic_zdm);
var result = t.GetValue(item, null);
a.Add(result);
}
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
else if (graphic_zy == "仪表专业")//查询企业级的qst
{
var i = db.Database.SqlQuery<A15dot1TabYi>("select * from A15dot1TabYi where submitDepartment='" + graphic_subdipartment + "'").ToList();
foreach (var item in i)
{
var t = item.GetType().GetProperty(graphic_zdm);
var result = t.GetValue(item, null);
a.Add(result);
}
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
else
{
return a;
}
}
}
public bool ModifyJxRecord(A15dot1TabQiYe nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA15QiYe = db.A15dot1TabQiYe.Where(a => a.Id == nVal.Id).First();
modifyA15QiYe.zzkkxzs = nVal.zzkkxzs;
modifyA15QiYe.wxfyzs = nVal.wxfyzs;
modifyA15QiYe.qtlxbmfxhl = nVal.qtlxbmfxhl;
modifyA15QiYe.qtlhsbgsghl = nVal.qtlhsbgsghl;
modifyA15QiYe.ybsjkzl = nVal.ybsjkzl;
modifyA15QiYe.sjs = nVal.sjs;
modifyA15QiYe.gzqdkf = nVal.gzqdkf;
modifyA15QiYe.xmyql = nVal.xmyql;
modifyA15QiYe.pxjnl = nVal.pxjnl;
modifyA15QiYe.submitDepartment = nVal.submitDepartment;
modifyA15QiYe.temp2 = nVal.temp2;
modifyA15QiYe.Id = nVal.Id;
modifyA15QiYe.reliabilityConclusion = nVal.reliabilityConclusion;
modifyA15QiYe.state = nVal.state;
//modifyA15QiYe.submitTime = nVal.submitTime;
//modifyA15QiYe.submitUser = nVal.submitUser;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}//更新企业级表装置的内容
public bool ModifyQcQyJxItem(A15dot1TabQiYe nVal,DateTime stime,DateTime etime)
{
using (var db = base.NewDB())
{
try
{
var modifyA15QiYeList = db.A15dot1TabQiYe.Where(a => a.submitDepartment == nVal.submitDepartment&&a.submitTime>stime&&a.submitTime<etime).ToList();
if (modifyA15QiYeList.Count>0)
{
int id = modifyA15QiYeList.First().Id;
var modifyA15QiYe = db.A15dot1TabQiYe.Where(a => a.Id == id).First();
modifyA15QiYe.zzkkxzs = nVal.zzkkxzs;
modifyA15QiYe.wxfyzs = nVal.wxfyzs;
modifyA15QiYe.qtlxbmfxhl = nVal.qtlxbmfxhl;
modifyA15QiYe.qtlhsbgsghl = nVal.qtlhsbgsghl;
modifyA15QiYe.ybsjkzl = nVal.ybsjkzl;
modifyA15QiYe.sjs = nVal.sjs;
modifyA15QiYe.gzqdkf = nVal.gzqdkf;
modifyA15QiYe.xmyql = nVal.xmyql;
modifyA15QiYe.pxjnl = nVal.pxjnl;
//modifyA15QiYe.submitUser = nVal.submitUser;
db.SaveChanges();
return true;
}
else
{
db.A15dot1TabQiYe.Add(nVal);
db.SaveChanges();
return true;
}
}
catch(Exception e)
{
return false;
}
}
}
public bool ModifyQcDongJxItem(A15dot1TabDong nVal, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
try
{
var modifyA15DongList = db.A15dot1TabDong.Where(a => a.submitDepartment == nVal.submitDepartment && a.submitTime > stime && a.submitTime < etime).ToList();
if (modifyA15DongList.Count > 0)
{
int id = modifyA15DongList.First().Id;
var modifyA15Dong = db.A15dot1TabDong.Where(a => a.Id == id).First();
modifyA15Dong.gzqdkf = nVal.gzqdkf;
modifyA15Dong.djzgzl = nVal.djzgzl;
modifyA15Dong.gzwxl = nVal.gzwxl;
modifyA15Dong.qtlxbmfxhl = nVal.qtlxbmfxhl;
modifyA15Dong.jjqxgsl = nVal.jjqxgsl;
modifyA15Dong.gdpjwcsj = nVal.gdpjwcsj;
modifyA15Dong.jxmfpjsm = nVal.jxmfpjsm;
modifyA15Dong.zcpjsm = nVal.zcpjsm;
modifyA15Dong.sbwhl = nVal.sbwhl;
modifyA15Dong.jxychgl = nVal.jxychgl;
modifyA15Dong.zyjbpjxl = nVal.zyjbpjxl;
modifyA15Dong.jzpjxl = nVal.jzpjxl;
modifyA15Dong.wfjzgzl = nVal.wfjzgzl;
modifyA15Dong.ndbtjbcfjxtc = nVal.ndbtjbcfjxtc;
modifyA15Dong.jbpjwgzjgsjMTBF = nVal.jbpjwgzjgsjMTBF;
db.SaveChanges();
return true;
}
else
{
db.A15dot1TabDong.Add(nVal);
db.SaveChanges();
return true;
}
}
catch (Exception e)
{
return false;
}
}
}
public bool ModifyQcJingJxItem(A15dot1TabJing nVal, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
try
{
var modifyA15JingList = db.A15dot1TabJing.Where(a => a.submitDepartment == nVal.submitDepartment && a.submitTime > stime && a.submitTime < etime).ToList();
if (modifyA15JingList.Count > 0)
{
int id = modifyA15JingList.First().Id;
var modifyA15Jing = db.A15dot1TabJing.Where(a => a.Id == id).First();
modifyA15Jing.gzqdkf = nVal.gzqdkf;
modifyA15Jing.sbfsxlcs = nVal.sbfsxlcs;
modifyA15Jing.qtlhsbgs = nVal.qtlhsbgs;
modifyA15Jing.gylpjrxl = nVal.gylpjrxl;
modifyA15Jing.hrqjxl = nVal.hrqjxl;
modifyA15Jing.ylrqdjl = nVal.ylrqdjl;
modifyA15Jing.ylgdndjxjhwcl = nVal.ylgdndjxjhwcl;
modifyA15Jing.aqfndjyjhwcl = nVal.aqfndjyjhwcl;
modifyA15Jing.sbfsjcjhwcl = nVal.sbfsjcjhwcl;
modifyA15Jing.jsbjwxychgl = nVal.jsbjwxychgl;
db.SaveChanges();
return true;
}
else
{
db.A15dot1TabJing.Add(nVal);
db.SaveChanges();
return true;
}
}
catch (Exception e)
{
return false;
}
}
}
public bool ModifyQcDianJxItem(A15dot1TabDian nVal, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
try
{
var modifyA15DianList = db.A15dot1TabDian.Where(a => a.submitDepartment == nVal.submitDepartment && a.submitTime > stime && a.submitTime < etime).ToList();
if (modifyA15DianList.Count > 0)
{
int id = modifyA15DianList.First().Id;
var modifyA15Dian = db.A15dot1TabDian.Where(a => a.Id == id).First();
modifyA15Dian.gzqdkf = nVal.gzqdkf;
modifyA15Dian.dqwczcs = nVal.dqwczcs;
modifyA15Dian.jdbhzqdzl = nVal.jdbhzqdzl;
modifyA15Dian.sbgzl = nVal.sbgzl;
modifyA15Dian.djMTBF = nVal.djMTBF;
modifyA15Dian.dzdlsbMTBF = nVal.dzdlsbMTBF;
modifyA15Dian.zbglys = nVal.zbglys;
modifyA15Dian.dnjlphl = nVal.dnjlphl;
db.SaveChanges();
return true;
}
else
{
db.A15dot1TabDian.Add(nVal);
db.SaveChanges();
return true;
}
}
catch (Exception e)
{
return false;
}
}
}
public bool ModifyQcYiJxItem(A15dot1TabYi nVal, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
try
{
var modifyA15YiList = db.A15dot1TabYi.Where(a => a.submitDepartment == nVal.submitDepartment && a.submitTime > stime && a.submitTime < etime).ToList();
if (modifyA15YiList.Count > 0)
{
int id = modifyA15YiList.First().Id;
var modifyA15Yi = db.A15dot1TabYi.Where(a => a.Id == id).First();
modifyA15Yi.gzqdkf = nVal.gzqdkf;
modifyA15Yi.lsxtzqdzl = nVal.lsxtzqdzl;
modifyA15Yi.kzxtgzcs = nVal.kzxtgzcs;
modifyA15Yi.ybkzl = nVal.ybkzl;
modifyA15Yi.ybsjkzl = nVal.ybsjkzl;
modifyA15Yi.lsxttyl = nVal.lsxttyl;
modifyA15Yi.gjkzfmgzcs = nVal.gjkzfmgzcs;
modifyA15Yi.kzxtgzbjcs = nVal.kzxtgzbjcs;
modifyA15Yi.cgybgzl = nVal.cgybgzl;
modifyA15Yi.tjfMDBF = nVal.tjfMDBF;
db.SaveChanges();
return true;
}
else
{
db.A15dot1TabYi.Add(nVal);
db.SaveChanges();
return true;
}
}
catch (Exception e)
{
return false;
}
}
}
public bool ModifyJxRecordDong(A15dot1TabDong nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA15Dong = db.A15dot1TabDong.Where(a => a.Id == nVal.Id).First();
modifyA15Dong.gzqdkf = nVal.gzqdkf;
modifyA15Dong.djzgzl = nVal.djzgzl;
modifyA15Dong.gzwxl = nVal.gzwxl;
modifyA15Dong.qtlxbmfxhl = nVal.qtlxbmfxhl;
modifyA15Dong.jjqxgsl = nVal.jjqxgsl;
modifyA15Dong.gdpjwcsj = nVal.gdpjwcsj;
modifyA15Dong.jxmfpjsm = nVal.jxmfpjsm;
modifyA15Dong.zcpjsm = nVal.zcpjsm;
modifyA15Dong.sbwhl = nVal.sbwhl;
modifyA15Dong.jxychgl = nVal.jxychgl;
modifyA15Dong.zyjbpjxl = nVal.zyjbpjxl;
modifyA15Dong.jzpjxl = nVal.jzpjxl;
modifyA15Dong.wfjzgzl = nVal.wfjzgzl;
modifyA15Dong.ndbtjbcfjxtc = nVal.ndbtjbcfjxtc;
modifyA15Dong.jbpjwgzjgsjMTBF = nVal.jbpjwgzjgsjMTBF;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}//更新企业级表装置的内容
public bool ModifyJxRecordDian(A15dot1TabDian nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA15Dian = db.A15dot1TabDian.Where(a => a.Id == nVal.Id).First();
modifyA15Dian.gzqdkf = nVal.gzqdkf;
modifyA15Dian.dqwczcs = nVal.dqwczcs;
modifyA15Dian.jdbhzqdzl = nVal.jdbhzqdzl;
modifyA15Dian.sbgzl = nVal.sbgzl;
modifyA15Dian.djMTBF = nVal.djMTBF;
modifyA15Dian.zbglys = nVal.zbglys;
modifyA15Dian.dnjlphl = nVal.dnjlphl;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool ModifyJxRecordJing(A15dot1TabJing nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA15Jing = db.A15dot1TabJing.Where(a => a.Id == nVal.Id).First();
modifyA15Jing.gzqdkf = nVal.gzqdkf;
modifyA15Jing.sbfsxlcs = nVal.sbfsxlcs;
modifyA15Jing.qtlhsbgs = nVal.qtlhsbgs;
modifyA15Jing.gylpjrxl = nVal.gylpjrxl;
modifyA15Jing.hrqjxl = nVal.hrqjxl;
modifyA15Jing.ylrqdjl = nVal.ylrqdjl;
modifyA15Jing.ylgdndjxjhwcl = nVal.ylgdndjxjhwcl;
modifyA15Jing.aqfndjyjhwcl = nVal.aqfndjyjhwcl;
modifyA15Jing.sbfsjcjhwcl = nVal.sbfsjcjhwcl;
modifyA15Jing.jsbjwxychgl = nVal.jsbjwxychgl;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool ModifyJxRecordYi(A15dot1TabYi nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA15Yi = db.A15dot1TabYi.Where(a => a.Id == nVal.Id).First();
modifyA15Yi.gzqdkf = nVal.gzqdkf;
modifyA15Yi.lsxtzqdzl = nVal.lsxtzqdzl;
modifyA15Yi.kzxtgzcs = nVal.kzxtgzcs;
modifyA15Yi.ybkzl = nVal.ybkzl;
modifyA15Yi.ybsjkzl = nVal.ybsjkzl;
modifyA15Yi.lsxttyl = nVal.lsxttyl;
modifyA15Yi.gjkzfmgzcs = nVal.gjkzfmgzcs;
modifyA15Yi.kzxtgzbjcs = nVal.kzxtgzbjcs;
modifyA15Yi.cgybgzl = nVal.cgybgzl;
modifyA15Yi.tjfMDBF = nVal.tjfMDBF;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool AddJxRecord(A15dot1TabQiYe nVal)
{
using (var db = base.NewDB())
{
try
{
db.A15dot1TabQiYe.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool AddDianRecord(A15dot1TabDian nVal)
{
using (var db = base.NewDB())
{
try
{
db.A15dot1TabDian.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool AddJingRecord(A15dot1TabJing nVal)
{
using (var db = base.NewDB())
{
try
{
db.A15dot1TabJing.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool AddYiRecord(A15dot1TabYi nVal)
{
using (var db = base.NewDB())
{
try
{
db.A15dot1TabYi.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public List<A15dot1TabQiYe> GetQiYeJxByA2(DateTime astime,DateTime aetime, string zzname, string zy)
{
DateTime Cxtime = DateTime.Now;
//string stime;
//string etime;
using (var db = base.NewDB())
{
//查出全厂的数据,超级用户修改计算出的全厂的数据后就在这里查询
return db.A15dot1TabQiYe.Where(a => a.submitDepartment == zzname && a.submitTime >= astime && a.submitTime <= aetime).ToList();
//&& a.submitTime <= Convert.ToDateTime(etime)
}
}//取企业级表中的数据
public List<A15dot1TabDong> GetDongJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
DateTime Cxtime = DateTime.Now;
//string stime;
//string etime;
using (var db = base.NewDB())
{
//查出全厂的数据,超级用户修改计算出的全厂的数据后就在这里查询
return db.A15dot1TabDong.Where(a => a.submitDepartment == zzname&& a.submitTime >= astime && a.submitTime <= aetime).ToList();
//&& a.submitTime <= Convert.ToDateTime(etime)
}
}
public List<A15dot1TabJing> GetJingJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
DateTime Cxtime = DateTime.Now;
//string stime;
//string etime;
using (var db = base.NewDB())
{
//查出全厂的数据,超级用户修改计算出的全厂的数据后就在这里查询
return db.A15dot1TabJing.Where(a => a.submitDepartment == zzname && a.submitTime >= astime && a.submitTime <= aetime).ToList();
//&& a.submitTime <= Convert.ToDateTime(etime)
}
}//取静设备专业表中的数据
public List<A15dot1TabDian> GetDianJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
DateTime Cxtime = DateTime.Now;
//string stime;
//string etime;
using (var db = base.NewDB())
{
//查出全厂的数据,超级用户修改计算出的全厂的数据后就在这里查询
return db.A15dot1TabDian.Where(a => a.submitDepartment == zzname && a.submitTime >= astime && a.submitTime <= aetime).ToList();
//&& a.submitTime <= Convert.ToDateTime(etime)
}
}//取电气专业表中的数据
public List<A15dot1TabYi> GetYiJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
DateTime Cxtime = DateTime.Now;
//string stime;
//string etime;
using (var db = base.NewDB())
{
//查出全厂的数据,超级用户修改计算出的全厂的数据后就在这里查询
return db.A15dot1TabYi.Where(a => a.submitDepartment == zzname && a.submitTime >= astime && a.submitTime <= aetime).ToList();
//&& a.submitTime <= Convert.ToDateTime(etime)
}
}//取仪表专业表中的数据
public List<object> qstdata2(string grahpic_name, string zzname, string zy)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabDian>("select * from A15dot1TabDian where submitDepartment='" + zzname + "'and temp2='" + zy + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("jdcOperateTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}//取电气专业表的数据生成趋势图
public List<object> qstdata3(string grahpic_name, string zzname, string zy)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabYi>("select * from A15dot1TabYi where submitDepartment='" + zzname + "'and temp2='" + zy + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("jdcOperateTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}//取仪表专业表的数据生成趋势图
public bool GetifQiYeQc(string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabQiYe.Where(a => a.submitDepartment == "全厂" && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifDongQc(string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabDong.Where(a => a.submitDepartment == "全厂" && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifJingQc(string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabJing.Where(a => a.submitDepartment == "全厂" && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifDianQc(string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabDian.Where(a => a.submitDepartment == "全厂" && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifYiQc(string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabYi.Where(a => a.submitDepartment == "全厂" && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifQiYeCj(string cjname,string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabQiYe.Where(a => a.submitDepartment == cjname && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifDongCj(string cjname, string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabDong.Where(a => a.submitDepartment == cjname && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifJingCj(string cjname, string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabJing.Where(a => a.submitDepartment == cjname && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifDianCj(string cjname, string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabDian.Where(a => a.submitDepartment == cjname && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
public bool GetifYiCj(string cjname, string zy, DateTime stime, DateTime etime)
{
using (var db = base.NewDB())
{
var A15Tabxiugai = db.A15dot1TabYi.Where(a => a.submitDepartment == cjname && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabxiugai.Count() == 0)//超级用户没有修改数据,
return false;
else
{
return true;
}
}
}
//获取全厂的动静电仪专业
public List<object> GetQiYeQc(string zy, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.zzkkxzs*b.zzkkxzs_weight) zzkkxzs,sum(a.wxfyzs*b.wxfyzs_weight) wxfyzs,sum(a.qtlxbmfxhl*b.qtlxbmfxhl_weight) qtlxbmfxhl,sum(a.qtlhsbgsghl*b.qtlhsbgsghl_weight) qtlhsbgsghl,sum(a.ybsjkzl*b.ybsjkzl_weight) ybsjkzl,sum(a.sjs*b.sjs_weight) sjs,sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.xmyql*b.xmyql_weight) xmyql,sum(a.pxjnl*b.pxjnl_weight) pxjnl from [EquipWeb].[dbo].[A15dot1TabQiYe] a,[EquipWeb].[dbo].[A15dot1TabQiYe_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'";
var i = db.Database.SqlQuery<qiyemodel>(r).First();
a.Add(i.GetType().GetProperty("zzkkxzs").GetValue(i, null));
a.Add(i.GetType().GetProperty("wxfyzs").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlxbmfxhl").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlhsbgsghl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ybsjkzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sjs").GetValue(i, null));
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("xmyql").GetValue(i, null));
a.Add(i.GetType().GetProperty("pxjnl").GetValue(i, null));
return a;
}
}
public List<object> GetDongQc(string zy, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
if (zy == "动设备专业")
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.djzgzl*b.djzgzl_weight) djzgzl,sum(a.gzwxl*b.gzwxl_weight) gzwxl,sum(a.qtlxbmfxhl*b.qtlxbmfxhl_weight) qtlxbmfxhl,sum(a.jjqxgsl*b.jjqxgsl_weight) jjqxgsl,sum(a.gdpjwcsj*b.gdpjwcsj_weight) gdpjwcsj,sum(a.jxmfpjsm*b.jxmfpjsm_weight) jxmfpjsm,sum(a.zcpjsm*b.zcpjsm_weight) zcpjsm,sum(a.sbwhl*b.sbwhl_weight) sbwhl,sum(a.jxychgl*b.jxychgl_weight) jxychgl,sum(a.zyjbpjxl*b.zyjbpjxl_weight) zyjbpjxl,sum(a.jzpjxl*b.jzpjxl_weight) jzpjxl,sum(a.wfjzgzl*b.wfjzgzl_weight) wfjzgzl,sum(a.ndbtjbcfjxtc*b.ndbtjbcfjxtc_weight) ndbtjbcfjxtc,sum(a.jbpjwgzjgsjMTBF*b.jbpjwgzjgsjMTBF_weight) jbpjwgzjgsjMTBF from [EquipWeb].[dbo].[A15dot1TabDong] a,[EquipWeb].[dbo].[A15dot1TabDong_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'";
var i = db.Database.SqlQuery<dongmodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("djzgzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("gzwxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlxbmfxhl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jjqxgsl").GetValue(i, null));
a.Add(i.GetType().GetProperty("gdpjwcsj").GetValue(i, null));
a.Add(i.GetType().GetProperty("jxmfpjsm").GetValue(i, null));
a.Add(i.GetType().GetProperty("zcpjsm").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbwhl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jxychgl").GetValue(i, null));
a.Add(i.GetType().GetProperty("zyjbpjxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jzpjxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("wfjzgzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ndbtjbcfjxtc").GetValue(i, null));
a.Add(i.GetType().GetProperty("jbpjwgzjgsjMTBF").GetValue(i, null));
}
return a;
}
}
public List<object> GetJingQc(string zy, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
if (zy == "静设备专业")
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.sbfsxlcs*b.sbfsxlcs_weight) sbfsxlcs,sum(a.qtlhsbgs*b.qtlhsbgs_weight) qtlhsbgs,sum(a.gylpjrxl*b.gylpjrxl_weight)gylpjrxl,sum(a.hrqjxl*b.hrqjxl_weight) hrqjxl,sum(a.ylrqdjl*b.ylrqdjl_weight) ylrqdjl,sum(a.ylgdndjxjhwcl*b.ylgdndjxjhwcl_weight) ylgdndjxjhwcl,sum(a.aqfndjyjhwcl*b.aqfndjyjhwcl_weight) aqfndjyjhwcl,sum(a.sbfsjcjhwcl*b.sbfsjcjhwcl_weight) sbfsjcjhwcl,sum(a.jsbjwxychgl*b.jsbjwxychgl_weight) jsbjwxychgl from [EquipWeb].[dbo].[A15dot1TabJing] a,[EquipWeb].[dbo].[A15dot1TabJing_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'";
var i = db.Database.SqlQuery<jingmodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbfsxlcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlhsbgs").GetValue(i, null));
a.Add(i.GetType().GetProperty("gylpjrxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("hrqjxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ylrqdjl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ylgdndjxjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("aqfndjyjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbfsjcjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jsbjwxychgl").GetValue(i, null));
}
return a;
}
}
public List<object> GetDianQc(string zy, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.dqwczcs*b.dqwczcs_weight) dqwczcs,sum(a.jdbhzqdzl*b.jdbhzqdzl_weight) jdbhzqdzl,sum(a.sbgzl*b.sbgzl_weight) sbgzl,sum(a.djMTBF*b.djMTBF_weight) djMTBF from [EquipWeb].[dbo].[A15dot1TabDian] a,[EquipWeb].[dbo].[A15dot1TabDian_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'";
var i = db.Database.SqlQuery<Dianmodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("dqwczcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("jdbhzqdzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbgzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("djMTBF").GetValue(i, null));
return a;
}
}
public List<object> GetYiQc(string zy, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.lsxtzqdzl*b.lsxtzqdzl_weight) lsxtzqdzl,sum(a.kzxtgzcs*b.kzxtgzcs_weight) kzxtgzcs,sum(a.ybkzl*b.ybkzl_weight) ybkzl,sum(a.ybsjkzl*b.ybsjkzl_weight) ybsjkzl,sum(a.lsxttyl*b.lsxttyl_weight) lsxttyl,sum(a.gjkzfmgzcs*b.gjkzfmgzcs_weight) gjkzfmgzcs,sum(a.kzxtgzbjcs*b.kzxtgzbjcs_weight) kzxtgzbjcs,sum(a.cgybgzl*b.cgybgzl_weight) cgybgzl,sum(a.tjfMDBF*b.tjfMDBF_weight) tjfMDBF from [EquipWeb].[dbo].[A15dot1TabYi] a,[EquipWeb].[dbo].[A15dot1TabYi_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'";
var i = db.Database.SqlQuery<yimodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("lsxtzqdzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("kzxtgzcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("ybkzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ybsjkzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("lsxttyl").GetValue(i, null));
a.Add(i.GetType().GetProperty("gjkzfmgzcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("kzxtgzbjcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("cgybgzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("tjfMDBF").GetValue(i, null));
return a;
}
}
public List<object> GetCjQiYe(string zy, string cjname, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.zzkkxzs*b.zzkkxzs_weight) zzkkxzs,sum(a.wxfyzs*b.wxfyzs_weight) wxfyzs,sum(a.qtlxbmfxhl*b.qtlxbmfxhl_weight) qtlxbmfxhl,sum(a.qtlhsbgsghl*b.qtlhsbgsghl_weight) qtlhsbgsghl,sum(a.ybsjkzl*b.ybsjkzl_weight) ybsjkzl,sum(a.sjs*b.sjs_weight) sjs,sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.xmyql*b.xmyql_weight) xmyql,sum(a.pxjnl*b.pxjnl_weight) pxjnl from [EquipWeb].[dbo].[A15dot1TabQiYe] a,[EquipWeb].[dbo].[Pq_A15dot1TabQiYe_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'and b.Pq_Name='" + cjname + "'";
var i = db.Database.SqlQuery<qiyemodel>(r).First();
a.Add(i.GetType().GetProperty("zzkkxzs").GetValue(i, null));
a.Add(i.GetType().GetProperty("wxfyzs").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlxbmfxhl").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlhsbgsghl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ybsjkzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sjs").GetValue(i, null));
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("xmyql").GetValue(i, null));
a.Add(i.GetType().GetProperty("pxjnl").GetValue(i, null));
return a;
}
}
public List<object> GetCjDong(string zy, string cjname, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.djzgzl*b.djzgzl_weight) djzgzl,sum(a.gzwxl*b.gzwxl_weight) gzwxl,sum(a.qtlxbmfxhl*b.qtlxbmfxhl_weight) qtlxbmfxhl,sum(a.jjqxgsl*b.jjqxgsl_weight) jjqxgsl,sum(a.gdpjwcsj*b.gdpjwcsj_weight) gdpjwcsj,sum(a.jxmfpjsm*b.jxmfpjsm_weight) gzqdkf,sum(a.zcpjsm*b.zcpjsm_weight) zcpjsm,sum(a.zyjbpjxl*b.zyjbpjxl_weight) zyjbpjxl,sum(a.jzpjxl*b.jzpjxl_weight) jzpjxl,sum(a.wfjzgzl*b.wfjzgzl_weight) wfjzgzl,sum(a.zcpjsm*b.zcpjsm_weight) zcpjsm,sum(a.ndbtjbcfjxtc*b.ndbtjbcfjxtc_weight) ndbtjbcfjxtc,sum(a.ndbtjbcfjxtc*b.ndbtjbcfjxtc_weight) ndbtjbcfjxtc from [EquipWeb].[dbo].[A15dot1TabDong] a,[EquipWeb].[dbo].[Pq_A15dot1TabDong_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'and b.Pq_Name='" + cjname + "'";
var i = db.Database.SqlQuery<dongmodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("djzgzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("gzwxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlxbmfxhl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jjqxgsl").GetValue(i, null));
a.Add(i.GetType().GetProperty("gdpjwcsj").GetValue(i, null));
a.Add(i.GetType().GetProperty("jxmfpjsm").GetValue(i, null));
a.Add(i.GetType().GetProperty("zcpjsm").GetValue(i, null));
a.Add(i.GetType().GetProperty("jxychgl").GetValue(i, null));
a.Add(i.GetType().GetProperty("zyjbpjxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbwhl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jzpjxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("wfjzgzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ndbtjbcfjxtc").GetValue(i, null));
a.Add(i.GetType().GetProperty("jbpjwgzjgsjMTBF").GetValue(i, null));
return a;
}
}
public List<object> GetCjJing(string zy, string cjname, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.sbfsxlcs*b.sbfsxlcs_weight) sbfsxlcs,sum(a.qtlhsbgs*b.qtlhsbgs_weight) qtlhsbgs,sum(a.gylpjrxl*b.gylpjrxl_weight) gylpjrxl,sum(a.hrqjxl*b.hrqjxl_weight) hrqjxl,sum(a.ylrqdjl*b.ylrqdjl_weight) ylrqdjl,sum(a.ylgdndjxjhwcl*b.ylgdndjxjhwcl_weight) ylgdndjxjhwcl,sum(a.aqfndjyjhwcl*b.aqfndjyjhwcl_weight) aqfndjyjhwcl,sum(a.sbfsjcjhwcl*b.sbfsjcjhwcl_weight) sbfsjcjhwcl,sum(a.jsbjwxychgl*b.jsbjwxychgl_weight) jsbjwxychgl from [EquipWeb].[dbo].[A15dot1TabJing] a,[EquipWeb].[dbo].[Pq_A15dot1TabJing_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'and b.Pq_Name='" + cjname + "'";
var i = db.Database.SqlQuery<jingmodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbfsxlcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlhsbgs").GetValue(i, null));
a.Add(i.GetType().GetProperty("gylpjrxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("hrqjxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ylrqdjl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ylgdndjxjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("aqfndjyjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbfsjcjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jsbjwxychgl").GetValue(i, null));
return a;
}
}
public List<object> GetCjDian(string zy, string cjname, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.dqwczcs*b.dqwczcs_weight) dqwczcs,sum(a.jdbhzqdzl*b.jdbhzqdzl_weight) jdbhzqdzl,sum(a.sbgzl*b.sbgzl_weight) sbgzl,sum(a.djMTBF*b.djMTBF_weight) djMTBF from [EquipWeb].[dbo].[A15dot1TabDian] a,[EquipWeb].[dbo].[Pq_A15dot1TabDian_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'and b.Pq_Name='" + cjname + "'";
var i = db.Database.SqlQuery<Dianmodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("dqwczcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("jdbhzqdzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbgzl").GetValue(i, null));
a.Add(i.GetType().GetProperty("djMTBF").GetValue(i, null));
return a;
}
}
public List<object> GetCjYi(string zy, string cjname, DateTime stime, DateTime etime)
{
string r = "";
List<object> a = new List<object>();
using (var db = base.NewDB())
{
r = "select sum(a.gzqdkf*b.gzqdkf_weight) gzqdkf,sum(a.lsxtzqdzl*b.lsxtzqdzl_weight) lsxtzqdzl,sum(a.kzxtgzcs*b.kzxtgzcs_weight) kzxtgzcs,sum(a.ybkzl*b.ybkzl_weight) ybkzl,sum(a.ybsjkzl*b.ybsjkzl_weight) ybsjkzl,sum(a.lsxttyl*b.lsxttyl_weight) lsxttyl,sum(a.gjkzfmgzcs*b.gjkzfmgzcs_weight) gjkzfmgzcs,sum(a.kzxtgzbjcs*b.kzxtgzbjcs_weight) kzxtgzbjcs,sum(a.cgybgzl*b.cgybgzl_weight) cgybgzl,sum(a.tjfMDBF*b.tjfMDBF_weight) tjfMDBF from [EquipWeb].[dbo].[A15dot1TabYi] a,[EquipWeb].[dbo].[Pq_A15dot1TabYi_Weight] b where b.Zz_Name=a.submitDepartment and a.submitTime>'" + stime + "' and a.submitTime<'" + etime + "'and b.Pq_Name='" + cjname + "'";
var i = db.Database.SqlQuery<yimodel>(r).First();
a.Add(i.GetType().GetProperty("gzqdkf").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbfsxlcs").GetValue(i, null));
a.Add(i.GetType().GetProperty("qtlhsbgs").GetValue(i, null));
a.Add(i.GetType().GetProperty("gylpjrxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("hrqjxl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ylrqdjl").GetValue(i, null));
a.Add(i.GetType().GetProperty("ylgdndjxjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("aqfndjyjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("sbfsjcjhwcl").GetValue(i, null));
a.Add(i.GetType().GetProperty("jsbjwxychgl").GetValue(i, null));
return a;
}
}
public bool AddDongJxRecord(A15dot1TabDong nVal)
{
using (var db = base.NewDB())
{
try
{
db.A15dot1TabDong.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
//public List<object> Dongqstdata(string grahpic_name, string pianqu)
//{
// using (var db = base.NewDB())
// {
// var i = db.Database.SqlQuery<A15dot1TabDong>("select * from A15dot1TabDong where submitDepartment='" + pianqu + "'").ToList();
// List<object> a = new List<object>();
// foreach (var item in i)
// {
// var t = item.GetType().GetProperty(grahpic_name);
// var result = t.GetValue(item, null);
// a.Add(result);
// }
// object cut = new object();
// cut = "$$";
// a.Add(cut);
// foreach (var ex in i)
// {
// var t = ex.GetType().GetProperty("jdcOperateTime");
// var result = t.GetValue(ex, null);
// a.Add(result);
// }
// return a;
// }
//}
public List<object> qstdataQiYe(string grahpic_name, string zzname)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabQiYe>("select * from A15dot1TabQiYe where submitDepartment='" + zzname + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}
public List<object> qstdataDong(string grahpic_name, string zzname)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabDong>("select * from A15dot1TabDong where submitDepartment='" + zzname + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}
public List<object> qstdataYi(string grahpic_name, string zzname)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabYi>("select * from A15dot1TabYi where submitDepartment='" + zzname + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}//取仪表专业表的数据生成趋势图
public List<object> qstdataJing(string grahpic_name, string zzname)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabJing>("select * from A15dot1TabJing where submitDepartment='" + zzname + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}
public List<object> qstdataDian(string grahpic_name, string zzname)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1TabDian>("select * from A15dot1TabDian where submitDepartment='" + zzname + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("submitTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}
public bool GetifzztibaoQiYe( DateTime stime, DateTime etime, string Zz_Name)
{
using (var db = base.NewDB())
{
var A15Tabtibao = db.A15dot1TabQiYe.Where(a => a.submitDepartment == Zz_Name && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabtibao.Count() == 0)//没有提报数据,
return false;
else
{
return true;
}
}
}
public bool GetifzztibaoDong(DateTime stime, DateTime etime, string Zz_Name)
{
using (var db = base.NewDB())
{
var A15Tabtibao = db.A15dot1TabDong.Where(a => a.submitDepartment == Zz_Name && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabtibao.Count() == 0)//没有提报数据,
return false;
else
{
return true;
}
}
}
public bool GetifzztibaoJing(DateTime stime, DateTime etime, string Zz_Name)
{
using (var db = base.NewDB())
{
var A15Tabtibao = db.A15dot1TabJing.Where(a => a.submitDepartment == Zz_Name && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabtibao.Count() == 0)//没有提报数据,
return false;
else
{
return true;
}
}
}
public bool GetifzztibaoDian(DateTime stime, DateTime etime, string Zz_Name)
{
using (var db = base.NewDB())
{
var A15Tabtibao = db.A15dot1TabDian.Where(a => a.submitDepartment == Zz_Name && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabtibao.Count() == 0)//没有提报数据,
return false;
else
{
return true;
}
}
}
public bool GetifzztibaoYi(DateTime stime, DateTime etime, string Zz_Name)
{
using (var db = base.NewDB())
{
var A15Tabtibao = db.A15dot1TabYi.Where(a => a.submitDepartment == Zz_Name && a.submitTime >= stime && a.submitTime <= etime).ToList();
if (A15Tabtibao.Count() == 0)//没有提报数据,
return false;
else
{
return true;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
/// <summary>
/// 职工信息
/// </summary>
public class Person_Info
{
/// <summary>
/// 主键
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Person_Id { get; set; }
/// <summary>
/// 用户名称
/// </summary>
[Required()]
public string Person_Name { get; set; }
/// <summary>
/// 用户密码 MD5
/// </summary>
public Byte[] Person_Pwd { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public string Person_mail { get; set; }
/// <summary>
/// 电话
/// </summary>
public string Person_tel { get; set; }
/// <summary>
/// 所属部门
/// </summary>
public virtual Depart_Archi Dept_Belong { get; set; }
/// <summary>
///所属专业种类
/// </summary>
public virtual ICollection<Speciaty_Info> Person_specialties { get; set; }
/// <summary>
/// 用户对应的角色
/// </summary>
public virtual ICollection<Role_Info> Person_roles { get; set; }
/// <summary>
/// 该人员管理的设备列表
/// </summary>
public virtual ICollection<Equip_Info> Person_Equips { get; set; }
public virtual ICollection<Equip_Archi> Person_EquipEAs { get; set; }
/// <summary>
/// 该人员所能操作的功能菜单
/// </summary>
public virtual ICollection<Menu> Person_Menus { get; set; }
/// <summary>
///
/// 用户与工作流对应关系
/// </summary>
public virtual ICollection<Menu> Person_WorkFlows { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment.ZyConfig
{
public class SpecialtyTree
{
public SpecialtyTree()
{
childs = new List<SpecialtyTree>();
}
public int Specialty_Id { get; set; }
//专业名称
public string Specialty_Name { get; set; }
public List<SpecialtyTree> childs { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EquipModel.Entities;
using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using System.Collections;
using EquipBLL.FileManagment;
namespace EquipBLL.AdminManagment
{
public class A6dot2Managment
{
public class WDTTJ_CellModal
{
public string cellName;
public string cellId;
public int cellNum;
public int cellSpanNum;
}
public class WDTTJ_RowModal
{
public string starttime;
public string endtime;
public int Id;
public WDTTJ_CellModal row_PqInfo=new WDTTJ_CellModal();
public List<WDTTJ_CellModal> row_CjInfo=new List<WDTTJ_CellModal>();
public List<WDTTJ_CellModal> row_ZzInfo=new List<WDTTJ_CellModal>();
}
public class WDTHistoy_ListModal
{
public int ID;
public string uploadTime;
public string userName;
public string wdtName;
public string pqName;
public string url;
}
public class WDT_detailModal
{
public int Id;
public string uploadDesc;
public string uploadTime;
public string userName;
public string uploadName;
public List<WDTTJ_RowModal> TjContent=new List<WDTTJ_RowModal>();
}
public class CQDetailModal
{
public string equipCode;
public string equipDesc;
public string lastOilTime;
public string NextOilTime;
public string oilCode_desc;
public string equip_PqName;
public string equip_CjName;
public string equip_ZzName;
public string CQ_demo;
}
//临时任务添加
public List<A6dot2LsTaskTab> getLsTask(string wfe_id)
{
A6dot2LsTaskTabs t = new A6dot2LsTaskTabs();
return t.getAllLsTaskTabs(wfe_id);
}
public A6dot2LsTaskTab UpdateA6dot2LsTask(int id, List<string> propertis, List<object> vals)
{
A6dot2LsTaskTabs t = new A6dot2LsTaskTabs();
return t.UpdateA6dot2LsTask(id, propertis, vals);
}
public A6dot2LsTaskTab AddA6dot2LsTask(A6dot2LsTaskTab new_A6dot2LsTask)
{
A6dot2LsTaskTabs t = new A6dot2LsTaskTabs();
return t.AddA6dot2LsTask(new_A6dot2LsTask);
}
public bool RemoveA6dot2LsTask(int id)
{
A6dot2LsTaskTabs t = new A6dot2LsTaskTabs();
return t.remove(id);
}
//end
private A6dot2Tabs WTDs = new A6dot2Tabs();
private Files XM = new Files();
public List<CQDetailModal> getCQdetail(string pqName,string starttime,string endtime)
{
Depart_Archis DA = new Depart_Archis();
//string pqName;
//pqName = DA.getDepart_info(pqId).Depart_Name;
List<A6dot2Tab2> tab2 = WTDs.getCQList(pqName,starttime, endtime);
List<CQDetailModal> r = new List<CQDetailModal>();
foreach(var item in tab2)
{
CQDetailModal cq = new CQDetailModal();
cq.equip_PqName = item.equip_PqName;
cq.equip_CjName = item.equip_CjName;
cq.equip_ZzName = item.equip_ZzName;
cq.equipCode = item.equipCode;
cq.equipDesc = item.equipDesc;
cq.lastOilTime = item.lastOilTime;
cq.NextOilTime = item.NextOilTime;
cq.CQ_demo = "超期未换油";
cq.oilCode_desc = item.oilCode_desc;
r.Add(cq);
}
return r;
}
public List<CQDetailModal> getCQdetailId (int Id,string pqName)
{
//string pqName;
List<A6dot2Tab2> tab2 = WTDs.getCQListId(Id,pqName);
List<CQDetailModal> r = new List<CQDetailModal>();
foreach (var item in tab2)
{
CQDetailModal cq = new CQDetailModal();
cq.equip_PqName = item.equip_PqName;
cq.equip_CjName = item.equip_CjName;
cq.equip_ZzName = item.equip_ZzName;
cq.equipCode = item.equipCode;
cq.equipDesc = item.equipDesc;
cq.lastOilTime = item.lastOilTime;
cq.NextOilTime = item.NextOilTime;
cq.CQ_demo = "超期未换油";
cq.oilCode_desc = item.oilCode_desc;
r.Add(cq);
}
return r;
}
public WDT_detailModal getWDT_detail(int WDT_Id)
{
WDT_detailModal r=new WDT_detailModal();
A6dot2Tab1 t1 = WTDs.get_WDTInfo(WDT_Id);
r.Id = t1.Id;
r.uploadDesc = t1.uploadDesc;
r.uploadTime = t1.uploadtime;
r.userName = t1.userName;
r.uploadName = t1.uuploadFileName;
r.TjContent = WDTTJ(r.Id);
return r;
}
public List<WDTTJ_RowModal> WDTTJ(int Id)
{
Depart_Archis DA = new Depart_Archis();
List<WDTTJ_RowModal> r = new List<WDTTJ_RowModal>();
String[] pqNameList=new String[7]{"联合一片区","联合二片区","联合三片区","联合四片区","化工片区","综合片区","其他"};
List<EquipDAL.Implement.A6dot2Tabs.WDT_PqTj> pqGroup_1 = new List<EquipDAL.Implement.A6dot2Tabs.WDT_PqTj>();
List<EquipDAL.Implement.A6dot2Tabs.WDT_PqTj> pqGroup= WTDs.PqGroup(Id);
List<EquipDAL.Implement.A6dot2Tabs.WDT_CjTj> cjGroup = WTDs.CjGroup(Id);
List<EquipDAL.Implement.A6dot2Tabs.WDT_ZzTj> zzGroup = WTDs.ZzGroup(Id);
int i=0;
while(i<7)
{
if (pqGroup.Where(x => x.pqName == pqNameList[i]).Count() > 0)
pqGroup_1.Add(pqGroup.Where(x => x.pqName == pqNameList[i]).ToList().First());
i = i + 1;
}
foreach(var p in pqGroup_1)
{
WDTTJ_RowModal tmp = new WDTTJ_RowModal();
tmp.Id = Id;
tmp.row_PqInfo.cellName = p.pqName;
tmp.row_PqInfo.cellId = p.pqName;//DA.getDepart_Id(p.pqName);
tmp.row_PqInfo.cellNum = p.tjNum;
tmp.row_PqInfo.cellSpanNum = zzGroup.Where(x => x.pqName == p.pqName).Count();
List<EquipDAL.Implement.A6dot2Tabs.WDT_CjTj> cjGroup_1 = cjGroup.Where(x => x.pqName == p.pqName).ToList();
foreach(var c in cjGroup_1)
{
WDTTJ_CellModal cj1 = new WDTTJ_CellModal();
cj1.cellName = c.cjName;
cj1.cellNum = c.tjNum;
cj1.cellSpanNum = zzGroup.Where(x=>x.cjName==c.cjName).Count();
tmp.row_CjInfo.Add(cj1);
List<EquipDAL.Implement.A6dot2Tabs.WDT_ZzTj> zzGroup_1 = zzGroup.Where(x => x.pqName == p.pqName && x.cjName == c.cjName).ToList();
foreach(var z in zzGroup_1)
{
WDTTJ_CellModal Zz1 = new WDTTJ_CellModal();
Zz1.cellName =z.zzName;
Zz1.cellNum = z.tjNum;
Zz1.cellSpanNum = 1;
tmp.row_ZzInfo.Add(Zz1);
}
}
r.Add(tmp);
}
return r;
}
public List<WDTTJ_RowModal> WDTTJ(string starttime,string endtime)
{
Depart_Archis DA = new Depart_Archis();
List<WDTTJ_RowModal> r = new List<WDTTJ_RowModal>();
String[] pqNameList = new String[7] { "联合一片区", "联合二片区", "联合三片区", "联合四片区", "化工片区", "综合片区", "其他" };
List<EquipDAL.Implement.A6dot2Tabs.WDT_PqTj> pqGroup_1 = new List<EquipDAL.Implement.A6dot2Tabs.WDT_PqTj>();
List<EquipDAL.Implement.A6dot2Tabs.WDT_PqTj> pqGroup = WTDs.PqGroup(starttime, endtime);
List<EquipDAL.Implement.A6dot2Tabs.WDT_CjTj> cjGroup = WTDs.CjGroup(starttime,endtime);
List<EquipDAL.Implement.A6dot2Tabs.WDT_ZzTj> zzGroup = WTDs.ZzGroup(starttime,endtime);
int i = 0;
while (i < 7)
{
if (pqGroup.Where(x => x.pqName == pqNameList[i]).Count() > 0)
pqGroup_1.Add(pqGroup.Where(x => x.pqName == pqNameList[i]).ToList().First());
i = i + 1;
}
foreach (var p in pqGroup_1)
{
WDTTJ_RowModal tmp = new WDTTJ_RowModal();
tmp.starttime = starttime.Substring(0,10);
tmp.endtime = endtime.Substring(0,10);
tmp.row_PqInfo.cellName = p.pqName;
tmp.row_PqInfo.cellId = p.pqName;//DA.getDepart_Id(p.pqName);
tmp.row_PqInfo.cellNum = p.tjNum;
tmp.row_PqInfo.cellSpanNum = zzGroup.Where(x=>x.pqName==p.pqName).Count();
List<EquipDAL.Implement.A6dot2Tabs.WDT_CjTj> cjGroup_1 = cjGroup.Where(x => x.pqName == p.pqName).ToList();
foreach (var c in cjGroup_1)
{
WDTTJ_CellModal cj1 = new WDTTJ_CellModal();
cj1.cellName = c.cjName;
cj1.cellNum = c.tjNum;
cj1.cellSpanNum = zzGroup.Where(x => x.cjName == c.cjName).Count();
tmp.row_CjInfo.Add(cj1);
List<EquipDAL.Implement.A6dot2Tabs.WDT_ZzTj> zzGroup_1 = zzGroup.Where(x => x.pqName == p.pqName && x.cjName == c.cjName).ToList();
foreach (var z in zzGroup_1)
{
WDTTJ_CellModal Zz1 = new WDTTJ_CellModal();
Zz1.cellName = z.zzName;
Zz1.cellNum = z.tjNum;
Zz1.cellSpanNum = 1;
tmp.row_ZzInfo.Add(Zz1);
}
}
r.Add(tmp);
}
return r;
}
public List<WDTHistoy_ListModal> getHistoryList()
{ int i=0;
List<WDTHistoy_ListModal> r = new List<WDTHistoy_ListModal>();
List<A6dot2Tab1> mt=WTDs.getWDTList();
foreach(var item in mt)
{
WDTHistoy_ListModal ritem = new WDTHistoy_ListModal();
ritem.ID = ++i;
ritem.uploadTime = item.uploadtime;
ritem.userName = item.userName;
string[] savedFileName = item.uuploadFileName.Split(new char[] { '$' });
ritem.wdtName = savedFileName[0]; ;
ritem.pqName = item.pqName;
ritem.url = "/A6dot2/WDT_detail?WDT_Id="+ Convert.ToString(item.Id);
r.Add(ritem);
}
return r;
}
public int add_WDT_list(A6dot2Tab1 WDT_List)
{
return WTDs.Add_A6dot2Tab1(WDT_List).Id;
}
public int add_WDT_content(int WDT_Id,List<A6dot2Tab2> WDT_content)
{
return WTDs.Add_A6dot2Tab2(WDT_Id,WDT_content);
}
//2016.8.11以下为6dot1归档上传文件信息至File_Info
public bool AddNewFile(int pID, FileItem fi)
{
File_Info nf = new File_Info();
nf.File_NewName = fi.fileNamePresent;
nf.File_OldName = fi.fileName;
nf.File_UploadTime = Convert.ToDateTime(fi.updateTime);
nf.Mission_Id = fi.Mission_Id;
nf.WfEntity_Id = fi.WfEntity_Id;
nf.File_SavePath = fi.path;
nf.File_ExtType = fi.ext;
return (new A6dot2Tabs()).AddFiletoCatalog(pID, nf);
}
//2016.8.11以下为6dot1通过上传文件的时间来获取File_Id,为下一个函数设备与文件的勾连做准备
public int GetFileIdByUpdateTime(DateTime time)
{
return WTDs.getfileid(time);
}
public int GetEquipIdBySbCode(string sbcode)
{
return WTDs.getequipid(sbcode);
}
//勾连设备与文件
public bool AttachtoEuipAndFile(int File_Id, int EquipID)
{
return XM.AttachtoEuip(File_Id, EquipID);
}
public List<EQ> caozuoguicheng()
{
return WTDs.getguicheng();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class EANummodel
{
public int EA_Id;
public int Equip_Num;
}
}
<file_sep>namespace EquipModel.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class _0215 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.guidelines_catalog",
c => new
{
Catalog_Id = c.Int(nullable: false, identity: true),
Catalog_Name = c.String(nullable: false),
parent_Catalog_Catalog_Id = c.Int(),
})
.PrimaryKey(t => t.Catalog_Id)
.ForeignKey("dbo.guidelines_catalog", t => t.parent_Catalog_Catalog_Id)
.Index(t => t.parent_Catalog_Catalog_Id);
CreateTable(
"dbo.guidelines_info",
c => new
{
File_Id = c.Int(nullable: false, identity: true),
File_NewName = c.String(),
File_OldName = c.String(),
File_SavePath = c.String(),
File_ExtType = c.String(),
File_UploadTime = c.DateTime(nullable: false),
WfEntity_Id = c.Int(nullable: false),
Mission_Id = c.Int(nullable: false),
File_Submiter_Person_Id = c.Int(),
Self_Catalog_Catalog_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.File_Id)
.ForeignKey("dbo.Person_Info", t => t.File_Submiter_Person_Id)
.ForeignKey("dbo.guidelines_catalog", t => t.Self_Catalog_Catalog_Id, cascadeDelete: true)
.Index(t => t.File_Submiter_Person_Id)
.Index(t => t.Self_Catalog_Catalog_Id);
CreateTable(
"dbo.Notice_Info",
c => new
{
id = c.Int(nullable: false, identity: true),
Notice_ID = c.String(),
Notice_Type = c.String(),
Notice_Desc = c.String(),
Notice_Yx = c.String(),
Notice_EquipCode = c.String(),
Notice_Equip_ABCmark = c.String(),
Notice_OverCondition = c.String(),
Notice_State = c.String(),
Notice_Order_ID = c.String(),
Notice_FaultStart = c.String(),
Notice_FaultEnd = c.String(),
Notice_FaultStartTime = c.String(),
Notice_FaultEndTime = c.String(),
Notice_PlanGroup = c.String(),
Notice_CR_Person = c.String(),
Notice_CR_Date = c.String(),
Notice_Stop = c.String(),
Notice_Commit_Time = c.String(),
Notice_FunLoc = c.String(),
Notice_Catalog = c.String(),
Notice_Priority = c.String(),
Notice_Commit_Date = c.String(),
Notice_QMcode = c.String(),
Notice_FaultYx = c.String(),
Notice_LongTxt = c.String(),
Notice_EquipSpeciality = c.String(),
Notice_A13dot1State = c.Int(nullable: false),
Notice_A13dot1_DoDateTime = c.String(),
Notice_A13dot1_DoUserName = c.String(),
Notice_LoadinDateTime = c.String(),
Notice_Speciality = c.String(),
Notice_UpdateDate = c.String(),
})
.PrimaryKey(t => t.id);
}
public override void Down()
{
DropForeignKey("dbo.guidelines_info", "Self_Catalog_Catalog_Id", "dbo.guidelines_catalog");
DropForeignKey("dbo.guidelines_info", "File_Submiter_Person_Id", "dbo.Person_Info");
DropForeignKey("dbo.guidelines_catalog", "parent_Catalog_Catalog_Id", "dbo.guidelines_catalog");
DropIndex("dbo.guidelines_info", new[] { "Self_Catalog_Catalog_Id" });
DropIndex("dbo.guidelines_info", new[] { "File_Submiter_Person_Id" });
DropIndex("dbo.guidelines_catalog", new[] { "parent_Catalog_Catalog_Id" });
DropTable("dbo.Notice_Info");
DropTable("dbo.guidelines_info");
DropTable("dbo.guidelines_catalog");
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A14dot2Controller : CommonController
{
//
// GET: /A14dot2/
public ActionResult Index()
{
return View(getIndexListRecords("A14dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A14dot2/维修单位填写维保内容
public ActionResult JxdwSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A14dot2/装置确认
public ActionResult ZzConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A14dot2/可靠性工程师检查确认
public ActionResult PqConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A14dot2/机动处检查确认
public ActionResult JdcConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A14dot2/跳转到A3.3
public ActionResult JumpToA3dot3(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//GET: /A14dot2/工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string JxdwSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxdwSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["EquipMaintain_Time"] = item["EquipMaintain_Time"].ToString();
signal["Content_Desc"] = item["Content_Desc"].ToString();
//string filename = Path.Combine(Request.MapPath("~/Upload"),item["Plan_DescFilePath"].ToString());
signal["Content_File"] = item["Content_File"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot2/Index");
}
public string ZzConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzConfirm_done"] = item["ZzConfirm_done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot2/Index");
}
public string PqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirm_done"] = item["PqConfirm_done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot2/Index");
}
public string JdcConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JdcConfirm_done"] = item["JdcConfirm_done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot2/Index");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quartz;
namespace FlowEngine.TimerManage
{
/// <summary>
/// 触发事件
/// </summary>
public class TriggerTiming
{
#region 属性
/// <summary>
/// cron表达式对象
/// </summary>
private CronExpression m_cronExpression = null;
/// <summary>
/// 下一次触发事件
/// </summary>
private DateTime? m_nextTiming = null;
public DateTime? NextTiming
{
get
{
return m_nextTiming;
}
set
{
m_nextTiming = value;
}
}
#endregion
#region 公有方法
/// <summary>
/// 从字符串解析
/// </summary>
/// <param name="str">时间字符串</param>
/// <returns>解析成功返回True, 否则返回False</returns>
public bool FromString(string str)
{
//如果不是正确的cron表达式
if (CronExpression.IsValidExpression(str) == false)
return false;
//构建新的CronExpression
if (m_cronExpression != null)
m_cronExpression = null;
m_cronExpression = new CronExpression(str);
return true;
}
/// <summary>
/// 反解析到字符串
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (m_cronExpression == null)
return "";
return m_cronExpression.ToString();
}
/// <summary>
/// 获得下次触发事件, 以dt_source为基础
/// </summary>
/// <returns></returns>
public void RefreshNextTiming(DateTime dt_source)
{
if (m_cronExpression != null)
{
DateTimeOffset? dto = m_cronExpression.GetNextValidTimeAfter(dt_source);
if (dto != null)
NextTiming = dto.Value.LocalDateTime;
else
NextTiming = null;
}
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Role_Info
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Role_Id { get; set; }
/// <summary>
/// 角色名称
/// </summary>
public string Role_Name { get; set; }
/// <summary>
/// 角色描述
/// </summary>
public string Role_Desc { get; set; }
/// <summary>
/// 角色对应的用户
/// </summary>
public virtual ICollection<Person_Info> Role_Persons { get; set; }
/// <summary>
/// 角色对应的系统功能菜单
/// </summary>
public virtual ICollection<Menu> Role_Menus { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowDesigner.PropertyEditor
{
public class E_Param
{
public string p_name { get; set; }
public string p_value { get; set; }
}
/// <summary>
/// EventActionWin.xaml 的交互逻辑
/// </summary>
public partial class EventActionWin : Window
{
/// <summary>
/// action的url地址
/// </summary>
public string action_url
{
get
{
return Action_Url.Text;
}
set
{
Action_Url.Text = value;
}
}
public Dictionary<string, string> event_linkParams;
private Dictionary<string, string> _params = new Dictionary<string, string>();
public Dictionary<string , string> action_params
{
get
{
return _params;
}
set{
_params = value;
Params_List.Items.Clear();
foreach(var p in _params)
{
Params_List.Items.Add(new E_Param() { p_name = p.Key, p_value = p.Value });
}
}
}
public EventActionWin()
{
InitializeComponent();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
this.Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
private void Add_Param(object sender, RoutedEventArgs e)
{
EventActionParamAdd pa = new EventActionParamAdd();
pa._linkParams.Clear();
foreach (var lp in event_linkParams)
{
pa._linkParams.Add(lp.Key);
}
if (pa.ShowDialog().Equals(true))
{
Dictionary<string, string> oldValue = action_params;
if (!oldValue.ContainsKey(pa._NewParam.p_name))
{
oldValue[pa._NewParam.p_name] = pa._NewParam.p_value;
}
action_params = oldValue;
}
}
private void Del_Param(object sender, RoutedEventArgs e)
{
E_Param ep = Params_List.SelectedItem as E_Param;
if (ep == null)
return;
Dictionary<string, string> pas = action_params;
pas.Remove(ep.p_name);
action_params = pas;
}
}
}
<file_sep>using EquipBLL.AdminManagment;
using EquipBLL.AdminManagment.ZyConfig;
using EquipBLL.AdminManagment.MenuConfig;
using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp.Controllers
{
public class QuickEntranceController : Controller
{
//
// GET: /QuickEntrance/
public ActionResult Index()
{
ViewBag.userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
ViewBag.userId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
return View(ViewBag);
}
public string Add(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
int person_id = Convert.ToInt16(item["user_Id"].ToString());
int menu_id = Convert.ToInt16(item["menu_Id"].ToString());
int q_id = Convert.ToInt16(item["q_Id"].ToString());
string datastring;
QEntranceManagment qem = new QEntranceManagment();
bool flag = qem.AddQ_Entrance(person_id, menu_id, q_id);
if(flag)
datastring ="添加成功";
else
datastring = "添加失败";
object r = new
{
backdata = datastring
};
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
catch
{
object r = new
{
backdata = "添加失败"
};
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
}
public JsonResult GetQE_InfobyPerson()
{
int p_id = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
List<object> r = new List<object>();
QEntranceManagment qem = new QEntranceManagment();
Quick_Entrance[] qe = new Quick_Entrance[8]{null,null,null,null,null,null,null,null};
List<Quick_Entrance> QE = new List<Quick_Entrance>();
QE = qem.GetQ_EbyP_Id(p_id);
foreach (var q in QE)
{
qe[q.xuhao - 1] = q;
}
for (int i = 0; i < 8;i++)
{
if (qe[i] == null)
{
object o = new
{
menuname = "",
menulink = "",
qe_id = i+1
};
r.Add(o);
}
else
{
object o = new
{
menuname = qe[i].Menu.Menu_Name,
menulink = qe[i].Menu.Link_Url,
qe_id = qe[i].xuhao
};
r.Add(o);
}
}
return Json(r.ToArray());
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using iTextSharp.text.pdf;
using iTextSharp.text;
using EquipBLL.AdminManagment.MenuConfig;
namespace WebApp.Controllers
{
public class A15dot1YiController : CommonController
{
private KpiManagement Jx = new KpiManagement();
public class submitmodel
{
public string timesNonPlanStop;//非计划停工次数
public string scoreDeductFaultIntensity;//四类以上故障强度扣分
public string rateBigUnitFault;//大机组故障率K
public string rateFaultMaintenance;//故障维修率F
public string MTBF;//一般机泵设备平均无故障间隔期MTBF
public string rateEquipUse; // 设备投用率R
public string avgLifeSpanSeal;//密封平均寿命S
public string avgLifeSpanAxle;//轴承平均寿命B
public string percentEquipAvailability;//设备完好率W
public string percentPassOnetimeRepair;//检修一次合格率
public List<Equip_Archi> UserHasEquips;
public int kkxgcs;
public int jwxry;
}
public ActionResult Index()
{
return View();
}
public ActionResult Submit()
{
submitmodel sm = new submitmodel();
ViewBag.curtime = DateTime.Now;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
sm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(sm);
}
public bool Submit_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabYi new_15dot1Yi = new A15dot1TabYi();
new_15dot1Yi.gzqdkf = Convert.ToInt32(item["gzqdkf"].ToString());
new_15dot1Yi.lsxtzqdzl = Convert.ToDouble(item["lsxtzqdzl"].ToString());
new_15dot1Yi.kzxtgzcs = Convert.ToInt32(item["kzxtgzcs"].ToString());
new_15dot1Yi.ybkzl = Convert.ToDouble(item["ybkzl"].ToString());
new_15dot1Yi.ybsjkzl = Convert.ToDouble(item["ybsjkzl"].ToString());
new_15dot1Yi.lsxttyl = Convert.ToDouble(item["lsxttyl"].ToString());
new_15dot1Yi.gjkzfmgzcs = Convert.ToInt32(item["gjkzfmgzcs"].ToString());
new_15dot1Yi.kzxtgzbjcs = Convert.ToInt32(item["kzxtgzbjcs"].ToString());
new_15dot1Yi.cgybgzl = Convert.ToDouble(item["cgybgzl"].ToString());
new_15dot1Yi.tjfMDBF = Convert.ToDouble(item["tjfMDBF"].ToString());
new_15dot1Yi.temp3 = item["cjname"].ToString();
new_15dot1Yi.submitDepartment = item["submitDepartment"].ToString();
new_15dot1Yi.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1Yi.submitTime = DateTime.Now;
new_15dot1Yi.state = 0;
//new_15dot1.state = Convert.ToInt32(item["state"].ToString());
new_15dot1Yi.reportType = item["reportType"].ToString();
new_15dot1Yi.temp2 = "仪表专业";
bool res = Jx.AddYiItem(new_15dot1Yi);
return res;
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.FileManagment
{
public class CatalogTreeNode
{
//名称
public string text;
//
public Boolean selectable;
//子节点
public List<CatalogTreeNode> nodes = new List<CatalogTreeNode>();
//标识
public List<string> tags = new List<string>();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
/// <summary>
/// 文件分类的树形结构
/// </summary>
public class File_Catalog
{
/// <summary>
/// 文件分类ID
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Catalog_Id { get; set; }
/// <summary>
/// 文件分类的名称
/// </summary>
[Required()]
public string Catalog_Name { get; set; }
/// <summary>
/// 该文件类包含的子类
/// </summary>
virtual public ICollection<File_Catalog> Child_Catalogs { get; set; }
/// <summary>
/// 该文件类的父类
/// </summary>
virtual public File_Catalog parent_Catalog { get; set; }
/// <summary>
/// 属于该类文件
/// </summary>
virtual public ICollection<File_Info> Files_Included { get; set; }
}
}
<file_sep>namespace FlowEngine.Modals.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class modify1207 : DbMigration
{
public override void Up()
{
AddColumn("dbo.WorkFlow_Entity", "Last_Trans_Time", c => c.DateTime());
}
public override void Down()
{
DropColumn("dbo.WorkFlow_Entity", "Last_Trans_Time");
}
}
}
<file_sep>using FlowEngine.Flow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FlowEngine.Event
{
/// <summary>
/// 定时性任务
/// </summary>
public class CTimerEvent : CEvent
{
public CTimerEvent(CWorkFlow parent)
: base(parent)
{
}
/// <summary>
/// 定时任务的执行间隔, 单位:天
/// </summary>
public int Interval
{
get; set;
}
/// <summary>
/// Waiting Action: 等待事件(Event)执行的动作
/// Action(动作):对应于MVC的Controller
/// 当定时器定时事件未到时,返回
/// 与之对应,currentaction 在定时器事件到达时返回
/// </summary>
private string m_WaitingAction = "";
/// <summary>
/// 定时事件下次触发的时间
/// </summary>
private DateTime m_nextTiming = new DateTime();
/// <summary>
/// Event的状态
/// processing: 处理定时任务中
/// waiting: 等待下次任务到来
/// 初始状态为waiting
/// </summary>
private string m_WorkStatus = "waiting";
public string workstatus
{
get
{
return m_WorkStatus;
}
set
{
m_WorkStatus = value;
}
}
public string waitingaction
{
get
{
return m_WaitingAction;
}
set
{
m_WaitingAction = value;
}
}
/// <summary>
/// 重载currentaction
/// 如果当前状态为 processing, 则返回currentaction
/// 如果当前状态为 waiting, 则返回waitingaction
/// </summary>
public override string currentaction
{
get
{
if (m_WorkStatus == "processing")
{
return base.currentaction;
}
else if (m_WorkStatus == "waiting")
{
return m_WaitingAction;
}
else
return "";
}
set
{
base.currentaction = value;
}
}
/// <summary>
/// 重载Event的UpdatParams, 该函数仅在workflow的submitsignal函数内调用,
/// 因此可任务该函数是用户处理的时刻
/// </summary>
/// <param name="strjson"></param>
/// <returns></returns>
public override bool UpdateParams(string strjson)
{
DateTime dt = DateTime.Now;
//当前状态为processing
if (m_WorkStatus == "processing")
{
//如果提交时间未超时
if (dt <= m_nextTiming)
{
//更新变量的值
if (!base.UpdateParams(strjson))
throw new Exception("UpdateParams error");
LeaveEvent("");
EnterEvent("");
//即本次触发已处理,状态转为等待下次触发
m_WorkStatus = "waiting";
}
//如果提交时间超时,即认为上一次或若干次任务未处理,因此将未处理任务存储到数据
//而将本次提交的数据作为最近一次任务提交的数据
else
{
m_WorkStatus = "waiting";
while(dt > m_nextTiming)
{
LeaveEvent("");
EnterEvent("");
m_nextTiming.AddDays(this.Interval);
}
//将本次提交的数据作为最近一次任务数据,进行处理
m_WorkStatus = "processing";
//更新变量的值
if (!base.UpdateParams(strjson))
throw new Exception("UpdateParams error");
LeaveEvent("");
EnterEvent("");
m_WorkStatus = "waiting";
}
}
//当前状态为等待
else if (m_WorkStatus == "waiting")
{
//如果等待到触发时间,但有之前的任务未处理(即当前时间大于触发事件+Interval,则将前面未处理的任务更新到数据库)
while ((dt - m_nextTiming).Days > this.Interval)
{
LeaveEvent("");
EnterEvent("");
m_nextTiming.AddDays(this.Interval);
}
//更新变量的值
if (!base.UpdateParams(strjson))
throw new Exception("UpdateParams error");
LeaveEvent("");
EnterEvent("");
}
return true;
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public override void InstFromXmlNode(XmlNode xmlNode)
{
if (xmlNode.Attributes["type"].Value != "timerevent")
return;
//1. 解析基类CEvent的成员
base.InstFromXmlNode(xmlNode);
//2. 解析TimerEvent的成员
//解析 waitingaction
XmlNode actions = xmlNode.SelectSingleNode("actions");
XmlNode m_WaitingAction = actions.SelectSingleNode("waitingaction");
//解析Interval
this.Interval = Convert.ToInt32(xmlNode.Attributes["Interval"].Value);
//解析状态
this.m_WorkStatus = xmlNode.SelectSingleNode("status").InnerText;
//3. 解析下次触发时间
m_nextTiming = DateTime.Parse(xmlNode.SelectSingleNode("Timing").InnerText);
}
/// <summary>
/// 进入事件Action
/// </summary>
/// <param name="strjson"></param>
public override void EnterEvent(string strjson)
{
}
/// <summary>
/// 离开事件Action
/// </summary>
/// <param name="strjson"></param>
public override void LeaveEvent(string strjson)
{
}
}
}
<file_sep>///////////////////////////////////////////////////////////
// WorkFlow_Entities.cs
// Implementation of the Class WorkFlow_Entities
// Generated by Enterprise Architect
// Created on: 13-11月-2015 14:05:13
// Original author: Chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FlowEngine.Modals {
public enum WE_STATUS : int {ACTIVE, SUSPEND, CREATED, DONE, DELETED, INVALID}
public class WorkFlow_Entity {
public WorkFlow_Entity(){
}
~WorkFlow_Entity(){
}
/// <summary>
/// 工作流实体ID 主键
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int WE_Id{
get;
set;
}
/// <summary>
/// 工作流编号 YYYYMMXXXX
/// </summary>
public string WE_Ser { get; set; }
/// <summary>
/// 与之联系的WorkFlow
/// </summary>
public virtual WorkFlow_Define WE_Wref{
get;
set;
}
/// <summary>
/// 工作流实体的状态
/// </summary>
public WE_STATUS WE_Status{
get;
set;
}
/// <summary>
/// 工作流实体的二进制动态信息
/// </summary>
public byte[] WE_Binary
{
get;
set;
}
/// <summary>
/// 该实体的运行相关信息
/// </summary>
public virtual ICollection<Mission> Process_Info{
get;
set;
}
/// <summary>
/// 实体的当前事件 2016/5/16
/// </summary>
public virtual ICollection<CURR_Mission> Curr_Mission
{
get;
set;
}
/// <summary>
/// 实体状态迁移的最后时间
/// </summary>
public DateTime? Last_Trans_Time
{
get;
set;
}
}//end WorkFlow_Entity//end WorkFlow_Entities
}//end namespace FlowEngine.Modals<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class WorkFlowTables : BaseDAO
{
public List<A5dot1Tab1> get_Allbytime(DateTime time)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.zzSubmitTime < time).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> GetLS_listbywfe_id(List<int> wfe_id)
{
using (var db = base.NewDB())
{
List<A5dot1Tab1> E = new List<A5dot1Tab1>();
try
{
foreach (var w in wfe_id)
{
var e = db.A5dot1Tab1.Where(a => a.dataSource == w.ToString()).ToList();
E.AddRange(e);
}
return E;
}
catch (Exception e)
{
return null;
}
}
}
public bool Zzsubmit(A5dot1Tab1 a5dot1Tab1)
{
using (var db = base.NewDB())
{
try
{
//Quick_Entrance QE = new Quick_Entrance();
//db.Quick_Entrance.Add(QE);
//QE.Menu = db.Sys_Menus.Where(a => a.Menu_Id == m_id).First();
//QE.Person_Info = db.Persons.Where(a => a.Person_Id == p_id).First();
//QE.Quick_Entrance_id = p_id;
//db.SaveChanges();
db.A5dot1Tab1.Add(a5dot1Tab1);
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
}
public bool savefivesb(A5dot1Tab2 a5dot1Tab2)
{
//A5dot1Tab2 temp = new A5dot1Tab2();
using (var db = base.NewDB())
{
try
{
//var E = db.A5dot1Tab2.Where(a => a.sbCode == a5dot1Tab2.sbCode).First();
//if (E!=null)
//{
// a5dot1Tab2.notGoodContents += E.notGoodContents;
// a5dot1Tab2.timesNotGood += 1;
// db.SaveChanges();
//}
//else
//{
db.A5dot1Tab2.Add(a5dot1Tab2);
db.SaveChanges();
//}
return true;
}
catch (Exception e)
{
return false;
}
}
}
public bool setstate_byid(int id, int state, string name)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab2.Where(a => a.Id == id).First();
E.state = state;
if (state == 2)
E.jxdwUserName = name;
else
E.jdcUserName = name;
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
}
public bool setisworst10_byid(int id, int isworst10)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab2.Where(a => a.Id == id).First();
E.isSetAsTop10Worst = isworst10;
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
}
public List<A5dot1Tab1> Getdcl_listbyisZG(int isRectified, List<string> cjname)
{
using (var db = base.NewDB())
{
List<A5dot1Tab1> E = new List<A5dot1Tab1>();
try
{
foreach (var cn in cjname)
{
var e = db.A5dot1Tab1.Where(a => a.isRectified == isRectified && a.cjName == cn).ToList();
E.AddRange(e);
}
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> GetAll1_byym(string ym, List<string> cjname)
{
using (var db = base.NewDB())
{
List<A5dot1Tab1> E = new List<A5dot1Tab1>();
try
{
foreach (var cn in cjname)
{
var e = db.A5dot1Tab1.Where(a => a.yearMonthForStatistic == ym && a.cjName == cn).ToList();
E.AddRange(e);
}
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> Getbwh_byname(string name, int code)
{
using (var db = base.NewDB())
{
try
{
var E = new List<A5dot1Tab1>();
if (code == 1)
{
E = db.A5dot1Tab1.Where(a => a.cjName == name).ToList();
}
else if (code == 2)
{
E = db.A5dot1Tab1.Where(a => a.pqName == name).ToList();
}
else if (code == 3)
{
E = db.A5dot1Tab1.ToList();
}
else
E = db.A5dot1Tab1.Where(a => a.cjName == name).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab2> GetAll2_byymandstate(string ym, int state)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab2.Where(a => a.yearMonthForStatistic == ym && a.state == state).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab2> GetAll_byymandcode(string ym, string sbCode)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab2.Where(a => a.yearMonthForStatistic == ym && a.sbCode == sbCode).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> GetAll1_byymandcode(string ym, string sbCode)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.yearMonthForStatistic == ym && a.sbCode == sbCode).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> GetAll1_bycode(string sbCode)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.sbCode == sbCode).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public A5dot1Tab1 GetA_byid(int a_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.Id == a_id).First();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public bool Pqcheck_byid(int a_id, string pqname, DateTime time)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.Id == a_id).First();
E.isRectified = 1;
E.pqUserName = pqname;
E.pqCheckTime = time;
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
}
public bool modifytNG_byid(int a_id, int tNG)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab2.Where(a => a.Id == a_id).First();
E.timesNotGood = tNG;
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
}
public bool modifytemp1_byid(int a_id, string temp1)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.Id == a_id).First();
E.temp1 = temp1;
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
}
public bool delete_byid(int id)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab2.Where(a => a.Id == id).First();
db.A5dot1Tab2.Remove(E);
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
}
public List<A5dot1Tab1> get_cj_bwh(string cj_name, int equip_num)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.cjName == cj_name).ToList();
//var bwh = Math.Round(((double)E.Count/equip_num),6);
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> get_pq_bwh(string pq_name, int equip_num)
{
using (var db = base.NewDB())
{
try
{
if (pq_name != "其他")
{
var E = db.A5dot1Tab1.Where(a => a.pqName == pq_name).ToList();
//var bwh = Math.Round(((double)E.Count / equip_num), 6);
return E;
}
else
{
var E = db.A5dot1Tab1.Where(a => a.pqName == "消防队" || a.pqName == "计量站").ToList();
// var bwh = Math.Round(((double)E.Count / equip_num), 6);
return E;
}
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab2> get_worst10byym(string ym)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab2.Where(a => a.yearMonthForStatistic == ym && a.state == 3).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> get_All()
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
public List<A5dot1Tab1> getrecordbyentity(string entity_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.A5dot1Tab1.Where(a => a.temp2 == entity_id).ToList();
return E;
}
catch (Exception e)
{
return null;
}
}
}
}
}
<file_sep>using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.UserInterface
{
public class UI_WFEntity_Info
{
public string name { get; set; }
public int EntityID { get; set; }
public string description { get; set; }
public string serial { get; set; }
public string Binary { get; set; }
public WE_STATUS Status
{
get;
set;
}
public DateTime? Last_TransTime
{
get;
set;
}
}
}
<file_sep>///////////////////////////////////////////////////////////
// IEvent.cs
// Implementation of the Interface IEvent
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine.Param;
using System.Data.Entity.Core.Objects;
namespace FlowEngine.Event {
/// <summary>
/// 事件(Event)类对外提供的接口
/// </summary>
public interface IEvent {
/// <summary>
/// 获取事件(Event)的名称
/// </summary>
string name
{
get;
set;
}
/// <summary>
/// 获取事件(Event)的描述
/// </summary>
string description
{
get;
set;
}
/// <summary>
/// After Action
/// </summary>
string afteraction{
get;
set;
}
/// <summary>
/// Before Action
/// </summary>
string beforeaction{
get;
set;
}
/// <summary>
/// 事件的主事件
/// </summary>
string currentaction{
get;
set;
}
/// <summary>
/// 进入该事件(Event)
/// </summary>
/// <param name="strjson"></param>
void EnterEvent(string strjson);
/// <summary>
/// 离开该事件(Event)
/// </summary>
/// <param name="strjson"></param>
void LeaveEvent(string strjson);
/// <summary>
/// 跟新与之相关的变量的值
/// </summary>
/// <param name="strjson"></param>
/// <returns></returns>
bool UpdateParams(string strjson);
/// <summary>
/// 获取相关联的参数
/// </summary>
Dictionary<string, CParam> paramlist
{
get;
}
/// <summary>
/// 获取相关联参数的App_res
/// </summary>
Dictionary<string, string> paramsApp_res
{
get;
}
/// <summary>
/// 权限检查
/// </summary>
bool CheckAuthority<T>(Dictionary<string, object> outer_paras, ObjectContext oc);
/// <summary>
/// 注册Timeout
/// </summary>
/// <param name="bCreated"></param>
void RegTimeOut(bool bCreated);
CTimeOutProperty TimeOutProperty
{
get;
}
/// <summary>
/// 获得权限字符串
/// </summary>
/// <returns></returns>
string GetAuthorityString();
/// <summary>
/// 获得Timeout属性
/// </summary>
/// <returns></returns>
CTimeOutProperty GetTimeOutProperty();
}//end IEvent
}//end namespace Event<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.FileManagment
{
public class WSFileItem
{
public string fileName = "";
public string updateTime = "";
public string fileNamePresent = "";
public string uploader = "";
public string path = "";
public string ext = "";
public string id = "";
public int Mission_Id;
public int WfEntity_Id;
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using EquipBLL;
namespace WebApp.Controllers
{
public class A2Controller : CommonController
{
private JxpgManagment Jx = new JxpgManagment();
private KpiManagement Jx1 = new KpiManagement();//kpi的bll层代码调用
public ActionResult Index(string time)
{
return View(getRecord(time));
}
//public ActionResult Index1()
//{
// return View();
//}
public ActionResult Index2()
{
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_specis = pv.Speciaty_Names;
string rolename=pv.Role_Names;
DateTime Cxtime = DateTime.Now;
if (Cxtime.Day > 15)
ViewBag.Month = Cxtime.AddMonths(1).Month;
else
ViewBag.Month = Cxtime.Month;
ViewBag.adminqx="";
if (rolename.Contains("管理员"))//管理员权限
{
ViewBag.adminqx = "true";//有管理员权限
}
else
{
ViewBag.adminqx = "false";//没有管理员权限
}
ViewBag.pianquzhangqx = "";
if(rolename.Contains("片区长"))//片区长权限
{
ViewBag.pianquzhangqx = "true";//有片区长权限
}
else
{
ViewBag.pianquzhangqx = "false";//没有片区长权限
}
index2model index2model = new index2model();
//ViewBag.curtime = DateTime.Now.ToString();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name.ToString();//获得当前用户的名字
index2model.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
if (pv.Role_Names.Contains("可靠性工程师") || pv.Role_Names.Contains("检维修人员"))
index2model.isSubmit = 1;
else
index2model.isSubmit = 0;
if (ViewBag.Month == 1)
ViewBag.Monthname = "一月(12月15日至1月14日)";
if (ViewBag.Month == 2)
ViewBag.Monthname = "二月(1月15日至2月14日)";
if (ViewBag.Month == 3)
ViewBag.Monthname = "三月(2月15日至3月14日)";
if (ViewBag.Month == 4)
ViewBag.Monthname = "四月(3月15日至4月14日)";
if (ViewBag.Month == 5)
ViewBag.Monthname = "五月(4月15日至5月14日)";
if (ViewBag.Month == 6)
ViewBag.Monthname = "六月(5月15日至6月14日)";
if (ViewBag.Month == 7)
ViewBag.Monthname = "七月(6月15日至7月14日)";
if (ViewBag.Month == 8)
ViewBag.Monthname = "八月(7月15日至8月14日)";
if (ViewBag.Month == 9)
ViewBag.Monthname = "九月(8月15日至9月14日)";
if (ViewBag.Month == 10)
ViewBag.Monthname = "十月(9月15日至10月14日)";
if (ViewBag.Month == 11)
ViewBag.Monthname = "十一月(10月15日至11月14日)";
if (ViewBag.Month == 12)
ViewBag.Monthname = "十二月(11月15日至12月14日)";
return View(index2model);
}
public ActionResult yearreport(string time)
{
return View(getRecordforyear(time));
}
public class index2model
{
public int isSubmit;
// public string title;
public List<Equip_Archi> UserHasEquips;
}
public class Index_ModelforA2
{
public List<A15dot1Tab> Am;
public List<A15dot1Tab> Bm;
public List<A15dot1Tab> Cm;
public List<A15dot1Tab> Dm;
public List<A15dot1Tab> Em;
public List<A15dot1Tab> Fm;
public List<A15dot1Tab> Gm;
public List<A15dot1Tab> Hm;
public List<A15dot1Tab> Qc;//全厂指标
}
public class submitmodel
{
public string equipReliableExponent;//装置可靠性指数
public string maintainChargeExponent;//维修费用指数
public string thousandLXBrate;//千台离心泵(机泵)密封消耗率
public string thousandColdChangeRate;//千台冷换设备管束(含整台)更换率
public string instrumentControlRate;//仪表实际控制率
public string eventNumber;//事件数
public string troubleKoufen;//故障强度扣分
public string projectLateRate;//项目逾期率
public string trainAndAbility;//培训及能力
//public int kkxgcs;
//public int jwxry;
public List<Equip_Archi> UserHasEquips;
}
public Index_ModelforA2 getRecord(string time)
{
Index_ModelforA2 RecordforA2 = new Index_ModelforA2();
//ViewBag.curtime = DateTime.Now.ToString();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
DateTime Cxtime = DateTime.Now;
List<A15dot1Tab> miss = new List<A15dot1Tab>();
RecordforA2.Am = new List<A15dot1Tab>();
RecordforA2.Bm = new List<A15dot1Tab>();
RecordforA2.Cm = new List<A15dot1Tab>();
RecordforA2.Dm = new List<A15dot1Tab>();
RecordforA2.Em = new List<A15dot1Tab>();
RecordforA2.Fm = new List<A15dot1Tab>();
RecordforA2.Gm = new List<A15dot1Tab>();
RecordforA2.Qc = new List<A15dot1Tab>();
if (time == null)
{
miss = Jx.GetJxItemforA2(Cxtime, Cxtime.AddMonths(-1));
}
else
{
string[] strtime = time.Split(new char[] { '-', ' ' });
string[] starttime = strtime[0].Split(new char[] { '/' });
string[] endtime = strtime[3].Split(new char[] { '/' });
string stime = starttime[2] + '/' + starttime[0] + '/' + starttime[1];
string etime = endtime[2] + '/' + endtime[0] + '/' + endtime[1];
miss = Jx.GetJxItemforA2(Convert.ToDateTime(etime), Convert.ToDateTime(stime));
}
foreach (var item in miss)
{
A15dot1Tab a = new A15dot1Tab();
if (item.submitDepartment == "联合一片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA2.Am.Add(a);
}
if (item.submitDepartment == "联合二片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
//参与统计的台数
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA2.Bm.Add(a);
}
if (item.submitDepartment == "联合三片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA2.Cm.Add(a);
}
if (item.submitDepartment == "联合四片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA2.Dm.Add(a);
}
if (item.submitDepartment == "化工片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA2.Em.Add(a);
}
if (item.submitDepartment == "综合片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA2.Fm.Add(a);
}
if (item.submitDepartment == "系统片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA2.Gm.Add(a);
}
}
/***************************计算全厂KPI值****************************************************/
A15dot1Tab QcKPI = new A15dot1Tab();
if (RecordforA2.Am.Count != 0 && RecordforA2.Bm.Count != 0 && RecordforA2.Cm.Count != 0 && RecordforA2.Dm.Count != 0 && RecordforA2.Em.Count != 0 && RecordforA2.Fm.Count != 0 && RecordforA2.Gm.Count != 0)
{//一个月一个片区只存一次因此为Am[0]
QcKPI.timesNonPlanStop = RecordforA2.Am[0].timesNonPlanStop
+ RecordforA2.Bm[0].timesNonPlanStop
+ RecordforA2.Cm[0].timesNonPlanStop
+ RecordforA2.Dm[0].timesNonPlanStop
+ RecordforA2.Em[0].timesNonPlanStop
+ RecordforA2.Fm[0].timesNonPlanStop
+ RecordforA2.Gm[0].timesNonPlanStop;
QcKPI.scoreDeductFaultIntensity = RecordforA2.Am[0].scoreDeductFaultIntensity
+ RecordforA2.Bm[0].scoreDeductFaultIntensity
+ RecordforA2.Cm[0].scoreDeductFaultIntensity
+ RecordforA2.Dm[0].scoreDeductFaultIntensity
+ RecordforA2.Em[0].scoreDeductFaultIntensity
+ RecordforA2.Fm[0].scoreDeductFaultIntensity
+ RecordforA2.Gm[0].scoreDeductFaultIntensity;
QcKPI.rateBigUnitFault = RecordforA2.Am[0].rateBigUnitFault
+ RecordforA2.Bm[0].rateBigUnitFault
+ RecordforA2.Cm[0].rateBigUnitFault
+ RecordforA2.Dm[0].rateBigUnitFault
+ RecordforA2.Em[0].rateBigUnitFault
+ RecordforA2.Fm[0].rateBigUnitFault
+ RecordforA2.Gm[0].rateBigUnitFault;
QcKPI.rateFaultMaintenance = (RecordforA2.Am[0].rateFaultMaintenance
+ RecordforA2.Bm[0].rateFaultMaintenance
+ RecordforA2.Cm[0].rateFaultMaintenance
+ RecordforA2.Dm[0].rateFaultMaintenance
+ RecordforA2.Em[0].rateFaultMaintenance
+ RecordforA2.Fm[0].rateFaultMaintenance
+ RecordforA2.Gm[0].rateFaultMaintenance)
/ (RecordforA2.Am[0].Count_rateFaultMaintenance
+ RecordforA2.Bm[0].Count_rateFaultMaintenance
+ RecordforA2.Cm[0].Count_rateFaultMaintenance
+ RecordforA2.Dm[0].Count_rateFaultMaintenance
+ RecordforA2.Em[0].Count_rateFaultMaintenance
+ RecordforA2.Fm[0].Count_rateFaultMaintenance
+ RecordforA2.Gm[0].Count_rateFaultMaintenance);
QcKPI.MTBF = (RecordforA2.Am[0].Count_MTBF
+ RecordforA2.Bm[0].Count_MTBF
+ RecordforA2.Cm[0].Count_MTBF
+ RecordforA2.Dm[0].Count_MTBF
+ RecordforA2.Em[0].Count_MTBF
+ RecordforA2.Fm[0].Count_MTBF
+ RecordforA2.Gm[0].Count_MTBF) * 12 /
(RecordforA2.Am[0].MTBF
+ RecordforA2.Bm[0].MTBF
+ RecordforA2.Cm[0].MTBF
+ RecordforA2.Dm[0].MTBF
+ RecordforA2.Em[0].MTBF
+ RecordforA2.Fm[0].MTBF
+ RecordforA2.Gm[0].MTBF);
QcKPI.rateEquipUse = (RecordforA2.Am[0].rateEquipUse
+ RecordforA2.Bm[0].rateEquipUse
+ RecordforA2.Cm[0].rateEquipUse
+ RecordforA2.Dm[0].rateEquipUse
+ RecordforA2.Em[0].rateEquipUse
+ RecordforA2.Fm[0].rateEquipUse
+ RecordforA2.Gm[0].rateEquipUse)
/ (RecordforA2.Am[0].rateEquipUse
+ RecordforA2.Bm[0].Count_rateEquipUse
+ RecordforA2.Cm[0].Count_rateEquipUse
+ RecordforA2.Dm[0].Count_rateEquipUse
+ RecordforA2.Em[0].Count_rateEquipUse
+ RecordforA2.Fm[0].Count_rateEquipUse
+ RecordforA2.Gm[0].Count_rateEquipUse);
QcKPI.avgLifeSpanSeal = (RecordforA2.Am[0].avgLifeSpanSeal
+ RecordforA2.Bm[0].avgLifeSpanSeal
+ RecordforA2.Cm[0].avgLifeSpanSeal
+ RecordforA2.Dm[0].avgLifeSpanSeal
+ RecordforA2.Em[0].avgLifeSpanSeal
+ RecordforA2.Fm[0].avgLifeSpanSeal
+ RecordforA2.Gm[0].avgLifeSpanSeal)
/ (RecordforA2.Am[0].Count_avgLifeSpanSeal
+ RecordforA2.Bm[0].Count_avgLifeSpanSeal
+ RecordforA2.Cm[0].Count_avgLifeSpanSeal
+ RecordforA2.Dm[0].Count_avgLifeSpanSeal
+ RecordforA2.Em[0].Count_avgLifeSpanSeal
+ RecordforA2.Fm[0].Count_avgLifeSpanSeal
+ RecordforA2.Gm[0].Count_avgLifeSpanSeal);
QcKPI.avgLifeSpanAxle = (RecordforA2.Am[0].avgLifeSpanAxle
+ RecordforA2.Bm[0].avgLifeSpanAxle
+ RecordforA2.Cm[0].avgLifeSpanAxle
+ RecordforA2.Dm[0].avgLifeSpanAxle
+ RecordforA2.Em[0].avgLifeSpanAxle
+ RecordforA2.Fm[0].avgLifeSpanAxle
+ RecordforA2.Gm[0].avgLifeSpanAxle)
/ (RecordforA2.Am[0].Count_avgLifeSpanAxle
+ RecordforA2.Bm[0].Count_avgLifeSpanAxle
+ RecordforA2.Cm[0].Count_avgLifeSpanAxle
+ RecordforA2.Dm[0].Count_avgLifeSpanAxle
+ RecordforA2.Em[0].Count_avgLifeSpanAxle
+ RecordforA2.Fm[0].Count_avgLifeSpanAxle
+ RecordforA2.Gm[0].Count_avgLifeSpanAxle);
QcKPI.percentEquipAvailability = (RecordforA2.Am[0].percentEquipAvailability
+ RecordforA2.Bm[0].percentEquipAvailability
+ RecordforA2.Cm[0].percentEquipAvailability
+ RecordforA2.Dm[0].percentEquipAvailability
+ RecordforA2.Em[0].percentEquipAvailability
+ RecordforA2.Fm[0].percentEquipAvailability
+ RecordforA2.Gm[0].percentEquipAvailability)
/ (RecordforA2.Am[0].Count_percentEquipAvailability
+ RecordforA2.Bm[0].Count_percentEquipAvailability
+ RecordforA2.Cm[0].Count_percentEquipAvailability
+ RecordforA2.Dm[0].Count_percentEquipAvailability
+ RecordforA2.Em[0].Count_percentEquipAvailability
+ RecordforA2.Fm[0].Count_percentEquipAvailability
+ RecordforA2.Gm[0].Count_percentEquipAvailability);
QcKPI.percentPassOnetimeRepair = (RecordforA2.Am[0].percentPassOnetimeRepair
+ RecordforA2.Bm[0].percentPassOnetimeRepair
+ RecordforA2.Cm[0].percentPassOnetimeRepair
+ RecordforA2.Dm[0].percentPassOnetimeRepair
+ RecordforA2.Em[0].percentPassOnetimeRepair
+ RecordforA2.Fm[0].percentPassOnetimeRepair
+ RecordforA2.Gm[0].percentPassOnetimeRepair)
/ (RecordforA2.Am[0].Count_percentPassOnetimeRepair
+ RecordforA2.Bm[0].Count_percentPassOnetimeRepair
+ RecordforA2.Cm[0].Count_percentPassOnetimeRepair
+ RecordforA2.Dm[0].Count_percentPassOnetimeRepair
+ RecordforA2.Em[0].Count_percentPassOnetimeRepair
+ RecordforA2.Fm[0].Count_percentPassOnetimeRepair
+ RecordforA2.Gm[0].Count_percentPassOnetimeRepair);
RecordforA2.Qc.Add(QcKPI);
}
return RecordforA2;
}
public Index_ModelforA2 getRecordforyear(string time)
{
Index_ModelforA2 RecordforA2 = new Index_ModelforA2();
Index_ModelforA2 Record = new Index_ModelforA2();
//ViewBag.curtime = DateTime.Now.ToString();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
string Cxtime = Convert.ToString(DateTime.Now.Year) + "/01/01 00:00:00";
string CxEndtime = Convert.ToString(DateTime.Now.Year + 1) + "/01/01 00:00:00";
List<A15dot1Tab> miss = new List<A15dot1Tab>();
RecordforA2.Am = new List<A15dot1Tab>();
RecordforA2.Bm = new List<A15dot1Tab>();
RecordforA2.Cm = new List<A15dot1Tab>();
RecordforA2.Dm = new List<A15dot1Tab>();
RecordforA2.Em = new List<A15dot1Tab>();
RecordforA2.Fm = new List<A15dot1Tab>();
RecordforA2.Gm = new List<A15dot1Tab>();
RecordforA2.Hm = new List<A15dot1Tab>();
Record.Am = new List<A15dot1Tab>();
Record.Bm = new List<A15dot1Tab>();
Record.Cm = new List<A15dot1Tab>();
Record.Dm = new List<A15dot1Tab>();
Record.Em = new List<A15dot1Tab>();
Record.Fm = new List<A15dot1Tab>();
Record.Gm = new List<A15dot1Tab>();
Record.Hm = new List<A15dot1Tab>();
if (time == null)
{
miss = Jx.GetJxItemforA2(Convert.ToDateTime(CxEndtime), Convert.ToDateTime(Cxtime));
}
else
{
string stime = time + "/01/01 00:00:00";
string etime = Convert.ToInt32(time) + 1 + "/01/01 00:00:00";
miss = Jx.GetJxItemforA2(Convert.ToDateTime(etime), Convert.ToDateTime(stime));
}
foreach (var item in miss)
{
A15dot1Tab a = new A15dot1Tab();
if (item.submitDepartment == "联合一片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Am.Add(a);
}
if (item.submitDepartment == "联合二片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Bm.Add(a);
}
if (item.submitDepartment == "联合三片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Cm.Add(a);
}
if (item.submitDepartment == "焦化片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Dm.Add(a);
}
if (item.submitDepartment == "化工片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Em.Add(a);
}
if (item.submitDepartment == "综合片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Fm.Add(a);
}
if (item.submitDepartment == "系统片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Gm.Add(a);
}
if (item.submitDepartment == "检修单位")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.rateUrgentRepairWorkHour = item.rateUrgentRepairWorkHour;
a.hourWorkOrderFinish = item.hourWorkOrderFinish;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.avgEfficiencyPump = item.avgEfficiencyPump;
a.avgEfficiencyUnit = item.avgEfficiencyUnit;
RecordforA2.Hm.Add(a);
}
}
A15dot1Tab aa = new A15dot1Tab();
foreach (var ruo in RecordforA2.Am)//联合一
{
aa.timesNonPlanStop += ruo.timesNonPlanStop;
aa.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
aa.rateBigUnitFault += ruo.rateBigUnitFault;
aa.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
aa.MTBF += ruo.MTBF;//jun
aa.rateEquipUse += ruo.rateEquipUse;//jun
aa.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
aa.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
aa.percentEquipAvailability += ruo.percentEquipAvailability;//jun
aa.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
}
aa.rateFaultMaintenance = aa.rateFaultMaintenance / 12;
aa.MTBF = aa.MTBF / 12;
aa.rateEquipUse = aa.rateEquipUse / 12;
aa.percentEquipAvailability = aa.percentEquipAvailability / 12;
aa.percentPassOnetimeRepair = aa.percentPassOnetimeRepair / 12;
Record.Am.Add(aa);
A15dot1Tab bb = new A15dot1Tab();
foreach (var ruo in RecordforA2.Bm)//联合二
{
bb.timesNonPlanStop += ruo.timesNonPlanStop;
bb.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
bb.rateBigUnitFault += ruo.rateBigUnitFault;
bb.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
bb.MTBF += ruo.MTBF;//jun
bb.rateEquipUse += ruo.rateEquipUse;//jun
bb.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
bb.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
bb.percentEquipAvailability += ruo.percentEquipAvailability;//jun
bb.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
}
bb.rateFaultMaintenance = bb.rateFaultMaintenance / 12;
bb.MTBF = bb.MTBF / 12;
bb.rateEquipUse = bb.rateEquipUse / 12;
bb.percentEquipAvailability = bb.percentEquipAvailability / 12;
bb.percentPassOnetimeRepair = bb.percentPassOnetimeRepair / 12;
Record.Bm.Add(bb);
A15dot1Tab cc = new A15dot1Tab();
foreach (var ruo in RecordforA2.Cm)//联合三
{
cc.timesNonPlanStop += ruo.timesNonPlanStop;
cc.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
cc.rateBigUnitFault += ruo.rateBigUnitFault;
cc.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
cc.MTBF += ruo.MTBF;//jun
cc.rateEquipUse += ruo.rateEquipUse;//jun
cc.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
cc.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
cc.percentEquipAvailability += ruo.percentEquipAvailability;//jun
cc.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
}
cc.rateFaultMaintenance = cc.rateFaultMaintenance / 12;
cc.MTBF = cc.MTBF / 12;
cc.rateEquipUse = cc.rateEquipUse / 12;
cc.percentEquipAvailability = cc.percentEquipAvailability / 12;
cc.percentPassOnetimeRepair = cc.percentPassOnetimeRepair / 12;
Record.Cm.Add(cc);
A15dot1Tab dd = new A15dot1Tab();
foreach (var ruo in RecordforA2.Dm)//焦化
{
dd.timesNonPlanStop += ruo.timesNonPlanStop;
dd.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
dd.rateBigUnitFault += ruo.rateBigUnitFault;
dd.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
dd.MTBF += ruo.MTBF;//jun
dd.rateEquipUse += ruo.rateEquipUse;//jun
dd.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
dd.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
dd.percentEquipAvailability += ruo.percentEquipAvailability;//jun
dd.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
}
dd.rateFaultMaintenance = dd.rateFaultMaintenance / 12;
dd.MTBF = dd.MTBF / 12;
dd.rateEquipUse = dd.rateEquipUse / 12;
dd.percentEquipAvailability = dd.percentEquipAvailability / 12;
dd.percentPassOnetimeRepair = dd.percentPassOnetimeRepair / 12;
Record.Dm.Add(dd);
A15dot1Tab ee = new A15dot1Tab();
foreach (var ruo in RecordforA2.Em)//化工
{
ee.timesNonPlanStop += ruo.timesNonPlanStop;
ee.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
ee.rateBigUnitFault += ruo.rateBigUnitFault;
ee.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
ee.MTBF += ruo.MTBF;//jun
ee.rateEquipUse += ruo.rateEquipUse;//jun
ee.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
ee.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
ee.percentEquipAvailability += ruo.percentEquipAvailability;//jun
ee.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
}
ee.rateFaultMaintenance = ee.rateFaultMaintenance / 12;
ee.MTBF = ee.MTBF / 12;
ee.rateEquipUse = ee.rateEquipUse / 12;
ee.percentEquipAvailability = ee.percentEquipAvailability / 12;
ee.percentPassOnetimeRepair = ee.percentPassOnetimeRepair / 12;
Record.Em.Add(ee);
A15dot1Tab ff = new A15dot1Tab();
foreach (var ruo in RecordforA2.Fm)//综合
{
ff.timesNonPlanStop += ruo.timesNonPlanStop;
ff.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
ff.rateBigUnitFault += ruo.rateBigUnitFault;
ff.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
ff.MTBF += ruo.MTBF;//jun
ff.rateEquipUse += ruo.rateEquipUse;//jun
ff.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
ff.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
ff.percentEquipAvailability += ruo.percentEquipAvailability;//jun
ff.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
}
ff.rateFaultMaintenance = ff.rateFaultMaintenance / 12;
ff.MTBF = ff.MTBF / 12;
ff.rateEquipUse = ff.rateEquipUse / 12;
ff.percentEquipAvailability = ff.percentEquipAvailability / 12;
ff.percentPassOnetimeRepair = ff.percentPassOnetimeRepair / 12;
Record.Fm.Add(ff);
A15dot1Tab gg = new A15dot1Tab();
foreach (var ruo in RecordforA2.Gm)//系统
{
gg.timesNonPlanStop += ruo.timesNonPlanStop;
gg.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
gg.rateBigUnitFault += ruo.rateBigUnitFault;
gg.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
gg.MTBF += ruo.MTBF;//jun
gg.rateEquipUse += ruo.rateEquipUse;//jun
gg.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
gg.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
gg.percentEquipAvailability += ruo.percentEquipAvailability;//jun
gg.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
}
gg.rateFaultMaintenance = gg.rateFaultMaintenance / 12;
gg.MTBF = gg.MTBF / 12;
gg.rateEquipUse = gg.rateEquipUse / 12;
gg.percentEquipAvailability = gg.percentEquipAvailability / 12;
gg.percentPassOnetimeRepair = gg.percentPassOnetimeRepair / 12;
Record.Gm.Add(gg);
A15dot1Tab hh = new A15dot1Tab();
foreach (var ruo in RecordforA2.Hm)//检修单位
{
hh.timesNonPlanStop += ruo.timesNonPlanStop;
hh.scoreDeductFaultIntensity += ruo.scoreDeductFaultIntensity;
hh.rateBigUnitFault += ruo.rateBigUnitFault;
hh.rateFaultMaintenance += ruo.rateFaultMaintenance;//jun
hh.MTBF += ruo.MTBF;//jun
hh.rateEquipUse += ruo.rateEquipUse;//jun
hh.rateUrgentRepairWorkHour += ruo.rateUrgentRepairWorkHour;
hh.hourWorkOrderFinish += hh.hourWorkOrderFinish;//jun
hh.avgLifeSpanSeal = ruo.avgLifeSpanSeal;
hh.avgLifeSpanAxle = ruo.avgLifeSpanAxle;
hh.percentEquipAvailability += ruo.percentEquipAvailability;//jun
hh.percentPassOnetimeRepair += ruo.percentPassOnetimeRepair;//jun
hh.avgEfficiencyPump = ruo.avgEfficiencyPump;
hh.avgEfficiencyUnit = ruo.avgEfficiencyUnit;
}
hh.rateFaultMaintenance = hh.rateFaultMaintenance / 12;
hh.MTBF = hh.MTBF / 12;
hh.rateEquipUse = hh.rateEquipUse / 12;
hh.hourWorkOrderFinish = hh.hourWorkOrderFinish / 12;
hh.percentEquipAvailability = hh.percentEquipAvailability / 12;
hh.percentPassOnetimeRepair = hh.percentPassOnetimeRepair / 12;
Record.Hm.Add(hh);
return Record;
}
public string OutputExcel(string time)
{
DateTime Cxtime = DateTime.Now;
List<A15dot1Tab> miss = new List<A15dot1Tab>();
Index_ModelforA2 RecordforA2 = new Index_ModelforA2();
RecordforA2.Am = new List<A15dot1Tab>();
RecordforA2.Bm = new List<A15dot1Tab>();
RecordforA2.Cm = new List<A15dot1Tab>();
RecordforA2.Dm = new List<A15dot1Tab>();
RecordforA2.Em = new List<A15dot1Tab>();
RecordforA2.Fm = new List<A15dot1Tab>();
RecordforA2.Gm = new List<A15dot1Tab>();
if (time == "")
{
miss = Jx.GetJxItemforA2(Cxtime, Cxtime.AddMonths(-1));
}
else
{
string[] strtime = time.Split(new char[] { '-', ' ' });
string[] starttime = strtime[0].Split(new char[] { '/' });
string[] endtime = strtime[3].Split(new char[] { '/' });
string stime = starttime[2] + '/' + starttime[0] + '/' + starttime[1];
string etime = endtime[2] + '/' + endtime[0] + '/' + endtime[1];
miss = Jx.GetJxItemforA2(Convert.ToDateTime(etime), Convert.ToDateTime(stime));
}
foreach (var item in miss)
{
A15dot1Tab a = new A15dot1Tab();
if (item.submitDepartment == "联合一片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Am.Add(a);
}
if (item.submitDepartment == "联合二片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Bm.Add(a);
}
if (item.submitDepartment == "联合三片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Cm.Add(a);
}
if (item.submitDepartment == "焦化片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Dm.Add(a);
}
if (item.submitDepartment == "化工片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Em.Add(a);
}
if (item.submitDepartment == "综合片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Fm.Add(a);
}
if (item.submitDepartment == "系统片区")
{
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
RecordforA2.Gm.Add(a);
}
}
try
{
// 创建Excel 文档
HSSFWorkbook wk = new HSSFWorkbook();
ISheet tb = wk.CreateSheet("sheet1");
//设置单元的宽度
tb.SetColumnWidth(0, 15 * 256);
tb.SetColumnWidth(1, 25 * 256);
tb.SetColumnWidth(2, 25 * 256);
tb.SetColumnWidth(3, 11 * 256);
tb.SetColumnWidth(4, 15 * 256);
tb.SetColumnWidth(5, 15 * 256);
tb.SetColumnWidth(6, 15 * 256);
tb.SetColumnWidth(7, 15 * 256);
tb.SetColumnWidth(8, 15 * 256);
tb.SetColumnWidth(9, 15 * 256);
tb.SetColumnWidth(10, 15 * 256);
//合并标题头,该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 10));
IRow head = tb.CreateRow(0);
head.Height = 20 * 30;
ICell head_first_cell = head.CreateCell(0);
ICellStyle cellStyle_head = wk.CreateCellStyle();
//对齐
cellStyle_head.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
// 边框
/*
cellStyle_head.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
* */
// 字体
IFont font = wk.CreateFont();
font.FontName = "微软雅黑";
font.Boldweight = 8;
font.FontHeightInPoints = 16;
cellStyle_head.SetFont(font);
head_first_cell.CellStyle = head.CreateCell(1).CellStyle
= head.CreateCell(2).CellStyle
= head.CreateCell(3).CellStyle
= cellStyle_head;
head_first_cell.SetCellValue("各片区KPI指标统计表");
IRow table_head = tb.CreateRow(1);
ICellStyle cellStyle_normal = wk.CreateCellStyle();
cellStyle_normal.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
ICell table_head_zhibiaoleixing = table_head.CreateCell(0);
table_head_zhibiaoleixing.CellStyle = cellStyle_normal;
table_head_zhibiaoleixing.SetCellValue("指标类型");
ICell table_head_KPIzhibiao = table_head.CreateCell(1);
table_head_KPIzhibiao.CellStyle = cellStyle_normal;
table_head_KPIzhibiao.SetCellValue("KPI指标");
ICell table_head_zhibiaoshuoming = table_head.CreateCell(2);
table_head_zhibiaoshuoming.CellStyle = cellStyle_normal;
table_head_zhibiaoshuoming.SetCellValue("指标说明");
ICell table_head_mubiaozhi = table_head.CreateCell(3);
table_head_mubiaozhi.CellStyle = cellStyle_normal;
table_head_mubiaozhi.SetCellValue("目标值");
ICell table_head_lianheyi = table_head.CreateCell(4);
table_head_lianheyi.CellStyle = cellStyle_normal;
table_head_lianheyi.SetCellValue("联合一片区");
ICell table_head_lianheer = table_head.CreateCell(5);
table_head_lianheer.CellStyle = cellStyle_normal;
table_head_lianheer.SetCellValue("联合二片区");
ICell table_head_lianhesan = table_head.CreateCell(6);
table_head_lianhesan.CellStyle = cellStyle_normal;
table_head_lianhesan.SetCellValue("联合三片区");
ICell table_head_jiaohua = table_head.CreateCell(7);
table_head_jiaohua.CellStyle = cellStyle_normal;
table_head_jiaohua.SetCellValue("焦化片区");
ICell table_head_huagong = table_head.CreateCell(8);
table_head_huagong.CellStyle = cellStyle_normal;
table_head_huagong.SetCellValue("化工片区");
ICell table_head_zonghe = table_head.CreateCell(9);
table_head_zonghe.CellStyle = cellStyle_normal;
table_head_zonghe.SetCellValue("综合片区");
ICell table_head_xitong = table_head.CreateCell(10);
table_head_xitong.CellStyle = cellStyle_normal;
table_head_xitong.SetCellValue("系统片区");
ICellStyle thjl_record_cellStyle = wk.CreateCellStyle();
thjl_record_cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
//水平对齐
thjl_record_cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
//垂直对齐
thjl_record_cellStyle.VerticalAlignment = VerticalAlignment.Top;
//自动换行
thjl_record_cellStyle.WrapText = true;
IRow table_row1 = tb.CreateRow(2);
ICell table_row1_zhibiaoleixing = table_row1.CreateCell(0);
table_row1_zhibiaoleixing.CellStyle = thjl_record_cellStyle;
table_row1_zhibiaoleixing.SetCellValue("可靠性指标");
ICell table_row1_KPIzhibiao = table_row1.CreateCell(1);
table_row1_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row1_KPIzhibiao.SetCellValue("非计划停工次数");
ICell table_row1_zhibiaoshuoming = table_row1.CreateCell(2);
table_row1_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row1_zhibiaoshuoming.SetCellValue("由设备机械原因导致生产装置非计划停工");
ICell table_row1_KPImubiaozhi = table_row1.CreateCell(3);
table_row1_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row1_KPImubiaozhi.SetCellValue("0次");
ICell table_row1_KPIlianheyi = table_row1.CreateCell(4);
table_row1_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row1_KPIlianheyi.SetCellValue(RecordforA2.Am[0].timesNonPlanStop);
}
ICell table_row1_KPIlianheer = table_row1.CreateCell(5);
table_row1_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row1_KPIlianheer.SetCellValue(RecordforA2.Bm[0].timesNonPlanStop);
}
ICell table_row1_KPIlianhesan = table_row1.CreateCell(6);
table_row1_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row1_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].timesNonPlanStop);
}
ICell table_row1_KPIjiaohua = table_row1.CreateCell(7);
table_row1_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row1_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].timesNonPlanStop);
}
ICell table_row1_KPIhuagong = table_row1.CreateCell(8);
table_row1_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row1_KPIhuagong.SetCellValue(RecordforA2.Em[0].timesNonPlanStop);
}
ICell table_row1_KPIzonghe = table_row1.CreateCell(9);
table_row1_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row1_KPIzonghe.SetCellValue(RecordforA2.Fm[0].timesNonPlanStop);
}
ICell table_row1_KPIxitong = table_row1.CreateCell(10);
table_row1_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row1_KPIxitong.SetCellValue(RecordforA2.Gm[0].timesNonPlanStop);
}
IRow table_row2 = tb.CreateRow(3);
ICell table_row2_zhibiaoleixing = table_row2.CreateCell(0);
table_row2_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row2_zhibiaoleixing.SetCellValue("");
ICell table_row2_KPIzhibiao = table_row2.CreateCell(1);
table_row2_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row2_KPIzhibiao.SetCellValue("四类以上故障强度扣分");
ICell table_row2_zhibiaoshuoming = table_row2.CreateCell(2);
table_row2_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row2_zhibiaoshuoming.SetCellValue("由设备机械原因导致发生四类以上强度故障扣分");
ICell table_row2_KPImubiaozhi = table_row2.CreateCell(3);
table_row2_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row2_KPImubiaozhi.SetCellValue("≤60分/年");
ICell table_row2_KPIlianheyi = table_row2.CreateCell(4);
table_row2_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row2_KPIlianheyi.SetCellValue(RecordforA2.Am[0].scoreDeductFaultIntensity);
}
ICell table_row2_KPIlianheer = table_row2.CreateCell(5);
table_row2_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row2_KPIlianheer.SetCellValue(RecordforA2.Bm[0].scoreDeductFaultIntensity);
}
ICell table_row2_KPIlianhesan = table_row2.CreateCell(6);
table_row2_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row2_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].scoreDeductFaultIntensity);
}
ICell table_row2_KPIjiaohua = table_row2.CreateCell(7);
table_row2_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row2_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].scoreDeductFaultIntensity);
}
ICell table_row2_KPIhuagong = table_row2.CreateCell(8);
table_row2_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row2_KPIhuagong.SetCellValue(RecordforA2.Em[0].scoreDeductFaultIntensity);
}
ICell table_row2_KPIzonghe = table_row2.CreateCell(9);
table_row2_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row2_KPIzonghe.SetCellValue(RecordforA2.Fm[0].scoreDeductFaultIntensity);
}
ICell table_row2_KPIxitong = table_row2.CreateCell(10);
table_row2_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row2_KPIxitong.SetCellValue(RecordforA2.Gm[0].scoreDeductFaultIntensity);
}
IRow table_row3 = tb.CreateRow(4);
ICell table_row3_zhibiaoleixing = table_row3.CreateCell(0);
table_row3_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row3_zhibiaoleixing.SetCellValue("");
ICell table_row3_KPIzhibiao = table_row3.CreateCell(1);
table_row3_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row3_KPIzhibiao.SetCellValue("大机组故障率K");
ICell table_row3_zhibiaoshuoming = table_row3.CreateCell(2);
table_row3_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row3_zhibiaoshuoming.SetCellValue("K=∑(所有考核大机组故障时间)/∑(所有考核大机组计划投用时间)");
ICell table_row3_KPImubiaozhi = table_row3.CreateCell(3);
table_row3_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row3_KPImubiaozhi.SetCellValue("<1‰");
ICell table_row3_KPIlianheyi = table_row3.CreateCell(4);
table_row3_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row3_KPIlianheyi.SetCellValue(RecordforA2.Am[0].rateBigUnitFault);
}
ICell table_row3_KPIlianheer = table_row3.CreateCell(5);
table_row3_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row3_KPIlianheer.SetCellValue(RecordforA2.Bm[0].rateBigUnitFault);
}
ICell table_row3_KPIlianhesan = table_row3.CreateCell(6);
table_row3_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row3_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].rateBigUnitFault);
}
ICell table_row3_KPIjiaohua = table_row3.CreateCell(7);
table_row3_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row3_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].rateBigUnitFault);
}
ICell table_row3_KPIhuagong = table_row3.CreateCell(8);
table_row3_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row3_KPIhuagong.SetCellValue(RecordforA2.Em[0].rateBigUnitFault);
}
ICell table_row3_KPIzonghe = table_row3.CreateCell(9);
table_row3_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row3_KPIzonghe.SetCellValue(RecordforA2.Fm[0].rateBigUnitFault);
}
ICell table_row3_KPIxitong = table_row3.CreateCell(10);
table_row3_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row3_KPIxitong.SetCellValue(RecordforA2.Gm[0].rateBigUnitFault);
}
IRow table_row4 = tb.CreateRow(5);
ICell table_row4_zhibiaoleixing = table_row4.CreateCell(0);
table_row4_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row4_zhibiaoleixing.SetCellValue("");
ICell table_row4_KPIzhibiao = table_row4.CreateCell(1);
table_row4_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row4_KPIzhibiao.SetCellValue("故障维修率F");
ICell table_row4_zhibiaoshuoming = table_row4.CreateCell(2);
table_row4_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row4_zhibiaoshuoming.SetCellValue("F=故障维修次数/维修总次数");
ICell table_row4_KPImubiaozhi = table_row4.CreateCell(3);
table_row4_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row4_KPImubiaozhi.SetCellValue("<7.5%");
ICell table_row4_KPIlianheyi = table_row4.CreateCell(4);
table_row4_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row4_KPIlianheyi.SetCellValue(RecordforA2.Am[0].rateFaultMaintenance);
}
ICell table_row4_KPIlianheer = table_row4.CreateCell(5);
table_row4_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row4_KPIlianheer.SetCellValue(RecordforA2.Bm[0].rateFaultMaintenance);
}
ICell table_row4_KPIlianhesan = table_row4.CreateCell(6);
table_row4_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row4_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].rateFaultMaintenance);
}
ICell table_row4_KPIjiaohua = table_row4.CreateCell(7);
table_row4_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row4_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].rateFaultMaintenance);
}
ICell table_row4_KPIhuagong = table_row4.CreateCell(8);
table_row4_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row4_KPIhuagong.SetCellValue(RecordforA2.Em[0].rateFaultMaintenance);
}
ICell table_row4_KPIzonghe = table_row4.CreateCell(9);
table_row4_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row4_KPIzonghe.SetCellValue(RecordforA2.Fm[0].rateFaultMaintenance);
}
ICell table_row4_KPIxitong = table_row4.CreateCell(10);
table_row4_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row4_KPIxitong.SetCellValue(RecordforA2.Gm[0].rateFaultMaintenance);
}
IRow table_row5 = tb.CreateRow(6);
ICell table_row5_zhibiaoleixing = table_row5.CreateCell(0);
table_row5_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row5_zhibiaoleixing.SetCellValue("");
ICell table_row5_KPIzhibiao = table_row5.CreateCell(1);
table_row5_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row5_KPIzhibiao.SetCellValue("一般机泵设备平均无故障间隔期MTBF");
ICell table_row5_zhibiaoshuoming = table_row5.CreateCell(2);
table_row5_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row5_zhibiaoshuoming.SetCellValue("MTBF=考核期内机泵设备总数×12/设备故障维修总数");
ICell table_row5_KPImubiaozhi = table_row5.CreateCell(3);
table_row5_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row5_KPImubiaozhi.SetCellValue(">68月");
ICell table_row5_KPIlianheyi = table_row5.CreateCell(4);
table_row5_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row5_KPIlianheyi.SetCellValue(RecordforA2.Am[0].MTBF);
}
ICell table_row5_KPIlianheer = table_row5.CreateCell(5);
table_row5_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row5_KPIlianheer.SetCellValue(RecordforA2.Bm[0].MTBF);
}
ICell table_row5_KPIlianhesan = table_row5.CreateCell(6);
table_row5_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row5_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].MTBF);
}
ICell table_row5_KPIjiaohua = table_row5.CreateCell(7);
table_row5_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row5_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].MTBF);
}
ICell table_row5_KPIhuagong = table_row5.CreateCell(8);
table_row5_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row5_KPIhuagong.SetCellValue(RecordforA2.Em[0].MTBF);
}
ICell table_row5_KPIzonghe = table_row5.CreateCell(9);
table_row5_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row5_KPIzonghe.SetCellValue(RecordforA2.Fm[0].MTBF);
}
ICell table_row5_KPIxitong = table_row5.CreateCell(10);
table_row5_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row5_KPIxitong.SetCellValue(RecordforA2.Gm[0].MTBF);
}
IRow table_row6 = tb.CreateRow(7);
ICell table_row6_zhibiaoleixing = table_row6.CreateCell(0);
table_row6_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row6_zhibiaoleixing.SetCellValue("");
ICell table_row6_KPIzhibiao = table_row6.CreateCell(1);
table_row6_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row6_KPIzhibiao.SetCellValue("设备投用率R(反映MTTR)");
ICell table_row6_zhibiaoshuoming = table_row6.CreateCell(2);
table_row6_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row6_zhibiaoshuoming.SetCellValue("R=1-(∑(所有设备维修时间)/∑(所有设备计划投用时间)");
ICell table_row6_KPImubiaozhi = table_row6.CreateCell(3);
table_row6_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row6_KPImubiaozhi.SetCellValue(">99.5%");
ICell table_row6_KPIlianheyi = table_row6.CreateCell(4);
table_row6_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row6_KPIlianheyi.SetCellValue(RecordforA2.Am[0].rateEquipUse);
}
ICell table_row6_KPIlianheer = table_row6.CreateCell(5);
table_row6_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row6_KPIlianheer.SetCellValue(RecordforA2.Bm[0].rateEquipUse);
}
ICell table_row6_KPIlianhesan = table_row6.CreateCell(6);
table_row6_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row6_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].rateEquipUse);
}
ICell table_row6_KPIjiaohua = table_row6.CreateCell(7);
table_row6_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row6_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].rateEquipUse);
}
ICell table_row6_KPIhuagong = table_row6.CreateCell(8);
table_row6_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row6_KPIhuagong.SetCellValue(RecordforA2.Em[0].rateEquipUse);
}
ICell table_row6_KPIzonghe = table_row6.CreateCell(9);
table_row6_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row6_KPIzonghe.SetCellValue(RecordforA2.Fm[0].rateEquipUse);
}
ICell table_row6_KPIxitong = table_row6.CreateCell(10);
table_row6_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row6_KPIxitong.SetCellValue(RecordforA2.Gm[0].rateEquipUse);
}
IRow table_row7 = tb.CreateRow(8);
ICell table_row7_zhibiaoleixing = table_row7.CreateCell(0);
table_row7_zhibiaoleixing.CellStyle = thjl_record_cellStyle;
table_row7_zhibiaoleixing.SetCellValue("专业指标");
ICell table_row7_KPIzhibiao = table_row7.CreateCell(1);
table_row7_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row7_KPIzhibiao.SetCellValue("机械密封平均寿命s");
ICell table_row7_zhibiaoshuoming = table_row7.CreateCell(2);
table_row7_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row7_zhibiaoshuoming.SetCellValue("S=∑各密封点寿命/动密封总数");
ICell table_row7_KPImubiaozhi = table_row7.CreateCell(3);
table_row7_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row7_KPImubiaozhi.SetCellValue("≥20000小时");
ICell table_row7_KPIlianheyi = table_row7.CreateCell(4);
table_row7_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row7_KPIlianheyi.SetCellValue(RecordforA2.Am[0].avgLifeSpanSeal);
}
ICell table_row7_KPIlianheer = table_row7.CreateCell(5);
table_row7_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row7_KPIlianheer.SetCellValue(RecordforA2.Bm[0].avgLifeSpanSeal);
}
ICell table_row7_KPIlianhesan = table_row7.CreateCell(6);
table_row7_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row7_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].avgLifeSpanSeal);
}
ICell table_row7_KPIjiaohua = table_row7.CreateCell(7);
table_row7_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row7_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].avgLifeSpanSeal);
}
ICell table_row7_KPIhuagong = table_row7.CreateCell(8);
table_row7_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row7_KPIhuagong.SetCellValue(RecordforA2.Em[0].avgLifeSpanSeal);
}
ICell table_row7_KPIzonghe = table_row7.CreateCell(9);
table_row7_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row7_KPIzonghe.SetCellValue(RecordforA2.Fm[0].avgLifeSpanSeal);
}
ICell table_row7_KPIxitong = table_row7.CreateCell(10);
table_row7_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row7_KPIxitong.SetCellValue(RecordforA2.Gm[0].avgLifeSpanSeal);
}
IRow table_row8 = tb.CreateRow(9);
ICell table_row8_zhibiaoleixing = table_row8.CreateCell(0);
table_row8_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row8_zhibiaoleixing.SetCellValue("");
ICell table_row8_KPIzhibiao = table_row8.CreateCell(1);
table_row8_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row8_KPIzhibiao.SetCellValue("轴承平均寿命B");
ICell table_row8_zhibiaoshuoming = table_row8.CreateCell(2);
table_row8_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row8_zhibiaoshuoming.SetCellValue("B=∑各轴承寿命/轴承总数");
ICell table_row8_KPImubiaozhi = table_row8.CreateCell(3);
table_row8_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row8_KPImubiaozhi.SetCellValue("≥280000小时");
ICell table_row8_KPIlianheyi = table_row8.CreateCell(4);
table_row8_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row8_KPIlianheyi.SetCellValue(RecordforA2.Am[0].avgLifeSpanAxle);
}
ICell table_row8_KPIlianheer = table_row8.CreateCell(5);
table_row8_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row8_KPIlianheer.SetCellValue(RecordforA2.Bm[0].avgLifeSpanAxle);
}
ICell table_row8_KPIlianhesan = table_row8.CreateCell(6);
table_row8_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row8_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].avgLifeSpanAxle);
}
ICell table_row8_KPIjiaohua = table_row8.CreateCell(7);
table_row8_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row8_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].avgLifeSpanAxle);
}
ICell table_row8_KPIhuagong = table_row8.CreateCell(8);
table_row8_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row8_KPIhuagong.SetCellValue(RecordforA2.Em[0].avgLifeSpanAxle);
}
ICell table_row8_KPIzonghe = table_row8.CreateCell(9);
table_row8_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row8_KPIzonghe.SetCellValue(RecordforA2.Fm[0].avgLifeSpanAxle);
}
ICell table_row8_KPIxitong = table_row8.CreateCell(10);
table_row8_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row8_KPIxitong.SetCellValue(RecordforA2.Gm[0].avgLifeSpanAxle);
}
IRow table_row9 = tb.CreateRow(10);
ICell table_row9_zhibiaoleixing = table_row9.CreateCell(0);
table_row9_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row9_zhibiaoleixing.SetCellValue("");
ICell table_row9_KPIzhibiao = table_row9.CreateCell(1);
table_row9_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row9_KPIzhibiao.SetCellValue("设备完好率W");
ICell table_row9_zhibiaoshuoming = table_row9.CreateCell(2);
table_row9_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row9_zhibiaoshuoming.SetCellValue("W=∑完好设备台数/总设备台数");
ICell table_row9_KPImubiaozhi = table_row9.CreateCell(3);
table_row9_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row9_KPImubiaozhi.SetCellValue("≥98%");
ICell table_row9_KPIlianheyi = table_row9.CreateCell(4);
table_row9_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row9_KPIlianheyi.SetCellValue(RecordforA2.Am[0].percentEquipAvailability);
}
ICell table_row9_KPIlianheer = table_row9.CreateCell(5);
table_row9_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row9_KPIlianheer.SetCellValue(RecordforA2.Bm[0].percentEquipAvailability);
}
ICell table_row9_KPIlianhesan = table_row9.CreateCell(6);
table_row9_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row9_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].percentEquipAvailability);
}
ICell table_row9_KPIjiaohua = table_row9.CreateCell(7);
table_row9_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row9_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].percentEquipAvailability);
}
ICell table_row9_KPIhuagong = table_row9.CreateCell(8);
table_row9_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row9_KPIhuagong.SetCellValue(RecordforA2.Em[0].percentEquipAvailability);
}
ICell table_row9_KPIzonghe = table_row9.CreateCell(9);
table_row9_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row9_KPIzonghe.SetCellValue(RecordforA2.Fm[0].percentEquipAvailability);
}
ICell table_row9_KPIxitong = table_row9.CreateCell(10);
table_row9_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row9_KPIxitong.SetCellValue(RecordforA2.Gm[0].percentEquipAvailability);
}
IRow table_row10 = tb.CreateRow(11);
ICell table_row10_zhibiaoleixing = table_row10.CreateCell(0);
table_row10_zhibiaoleixing.CellStyle = cellStyle_normal;
table_row10_zhibiaoleixing.SetCellValue("");
ICell table_row10_KPIzhibiao = table_row10.CreateCell(1);
table_row10_KPIzhibiao.CellStyle = thjl_record_cellStyle;
table_row10_KPIzhibiao.SetCellValue("检修一次合格率");
ICell table_row10_zhibiaoshuoming = table_row10.CreateCell(2);
table_row10_zhibiaoshuoming.CellStyle = thjl_record_cellStyle;
table_row10_zhibiaoshuoming.SetCellValue("∑检修一次合格台数/检修设备总台数");
ICell table_row10_KPImubiaozhi = table_row10.CreateCell(3);
table_row10_KPImubiaozhi.CellStyle = thjl_record_cellStyle;
table_row10_KPImubiaozhi.SetCellValue("≥98%");
ICell table_row10_KPIlianheyi = table_row10.CreateCell(4);
table_row10_KPIlianheyi.CellStyle = cellStyle_normal;
if (RecordforA2.Am.Count != 0)
{
table_row10_KPIlianheyi.SetCellValue(RecordforA2.Am[0].percentPassOnetimeRepair);
}
ICell table_row10_KPIlianheer = table_row10.CreateCell(5);
table_row10_KPIlianheer.CellStyle = cellStyle_normal;
if (RecordforA2.Bm.Count != 0)
{
table_row10_KPIlianheer.SetCellValue(RecordforA2.Bm[0].percentPassOnetimeRepair);
}
ICell table_row10_KPIlianhesan = table_row10.CreateCell(6);
table_row10_KPIlianhesan.CellStyle = cellStyle_normal;
if (RecordforA2.Cm.Count != 0)
{
table_row10_KPIlianhesan.SetCellValue(RecordforA2.Cm[0].percentPassOnetimeRepair);
}
ICell table_row10_KPIjiaohua = table_row10.CreateCell(7);
table_row10_KPIjiaohua.CellStyle = cellStyle_normal;
if (RecordforA2.Dm.Count != 0)
{
table_row10_KPIjiaohua.SetCellValue(RecordforA2.Dm[0].percentPassOnetimeRepair);
}
ICell table_row10_KPIhuagong = table_row10.CreateCell(8);
table_row10_KPIhuagong.CellStyle = cellStyle_normal;
if (RecordforA2.Em.Count != 0)
{
table_row10_KPIhuagong.SetCellValue(RecordforA2.Em[0].percentPassOnetimeRepair);
}
ICell table_row10_KPIzonghe = table_row10.CreateCell(9);
table_row10_KPIzonghe.CellStyle = cellStyle_normal;
if (RecordforA2.Fm.Count != 0)
{
table_row10_KPIzonghe.SetCellValue(RecordforA2.Fm[0].percentPassOnetimeRepair);
}
ICell table_row10_KPIxitong = table_row10.CreateCell(10);
table_row10_KPIxitong.CellStyle = cellStyle_normal;
if (RecordforA2.Gm.Count != 0)
{
table_row10_KPIxitong.SetCellValue(RecordforA2.Gm[0].percentPassOnetimeRepair);
}
string path = Server.MapPath("~/Upload//各片区KPI指标统计表.xls");
using (FileStream fs = System.IO.File.OpenWrite(path)) //打开一个xls文件,如果没有则自行创建,如果存在myxls.xls文件则在创建是不要打开该文件!
{
wk.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。
Console.WriteLine("提示:创建成功!");
}
return Path.Combine("/Upload", "各片区KPI指标统计表.xls");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return "";
}
}
//新月度KPI选取片区及月份
public string newgetRecord(string time, string zzid, string zy,string cjname,string chaxunmethod)
{
List<object> r = new List<object>();
if (zy == "企业级")
{
r = getObjectQiYe(time, zzid,zy,cjname,chaxunmethod);
}
else if (zy == "电气专业")
{
r = getObjectDian(time, zzid, zy, cjname, chaxunmethod);
}
else if (zy == "仪表专业")
{
r = getObjectYi(time, zzid, zy, cjname, chaxunmethod);
}
else if (zy == "动设备专业")
{
r = getObjectDong(time, zzid, zy, cjname, chaxunmethod);
}
else if (zy == "静设备专业")
{
r = getObjectJing(time, zzid, zy, cjname, chaxunmethod);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public List<object> getObjectQiYe(string time, string zzid, string zy, string cjname, string chaxunmethod)
{
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
string rolename = pv.Role_Names;//获得角色名
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;//获得用户名
List<object> r = new List<object>();
EquipManagment em = new EquipManagment();
if (chaxunmethod == "全厂")
{
zzid = "全厂";//如果查询方式是全厂
}
else if (chaxunmethod == "装置")
{
zzid = em.getEa_namebyid(Convert.ToInt32(zzid));//如果查询方式是装置将zzid转换为装置的名字
}else if(chaxunmethod=="车间")
{
zzid = cjname;
}
DateTime Cxtime = DateTime.Now;
string stime;
string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if ((chaxunmethod == "全厂" && !rolename.Contains("管理员")) || (chaxunmethod == "装置") || (chaxunmethod == "车间") && !rolename.Contains("片区长"))
{
List<A15dot1TabQiYe> res = Jx1.GetQiYeJxByA2(astime, aetime, zzid, zy);//直接在数据库中查询
if (res.Count != 0)
{
object a1 = new
{
zdm = "zzkkxzs",
zblx = "KPI",
zbname = "装置可靠性指标",
ndmbz = "",
ljz = res[0].zzkkxzs,
id = res[0].Id,
ActualValue = res[0].zzkkxzs,
};
r.Add(a1);
object a2 = new
{
zdm = "wxfyzs",
zblx = "KPI",
zbname = "维修费用指数",
id = res[0].Id,
ndmbz = "",
ljz = res[0].wxfyzs,
ActualValue = res[0].wxfyzs,
};
r.Add(a2);
object a3 = new
{
zdm = "qtlxbmfxhl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台离心泵(机泵)密封消耗率",
ndmbz = "<320",
ljz = res[0].qtlxbmfxhl,
ActualValue = res[0].qtlxbmfxhl,
};
r.Add(a3);
object a9 = new
{
zdm = "qtlhsbgsghl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = res[0].qtlhsbgsghl,
ActualValue = res[0].qtlhsbgsghl,
};
r.Add(a9);
object a4 = new
{
zdm = "ybsjkzl",
id = res[0].Id,
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = res[0].ybsjkzl,
ActualValue = res[0].ybsjkzl,
};
r.Add(a4);
object a5 = new
{
zdm = "sjs",
id = res[0].Id,
zblx = "KPI",
zbname = "事件数",
ndmbz = "",
ljz = res[0].sjs,
ActualValue = res[0].sjs,
};
r.Add(a5);
object a6 = new
{
zdm = "gzqdkf",
id = res[0].Id,
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a6);
object a7 = new
{
zdm = "xmyql",
id = res[0].Id,
zblx = "KPI",
zbname = "项目逾期率",
ndmbz = "",
ljz = res[0].xmyql,
ActualValue = res[0].xmyql,
};
r.Add(a7);
object a8 = new
{
zdm = "pxjnl",
id = res[0].Id,
zblx = "KPI",
zbname = "培训及能力",
ndmbz = "",
ljz = res[0].pxjnl,
ActualValue = res[0].pxjnl,
};
r.Add(a8);
return r;
}
else
{
return r;
}
}
else if ((chaxunmethod == "全厂" && rolename.Contains("管理员")) || (chaxunmethod == "车间" && rolename.Contains("片区长")))
{
//再次判断管理员和片区长的查询位置
//首先利用ifqc判断管理员是查询数据库还是计算查询
bool ifqc = Jx1.GetifQiYeQc(zy, astime, aetime);//如果表中存在超级用户已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (chaxunmethod == "全厂" && ifqc)
{//表中存在超级用户已经提报的全厂的数据,就在数据库中去查
List<A15dot1TabQiYe> res = Jx1.GetQiYeJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
zdm = "zzkkxzs",
zblx = "KPI",
zbname = "装置可靠性指标",
ndmbz = "",
ljz = res[0].zzkkxzs,
id = res[0].Id,
ActualValue = res[0].zzkkxzs,
};
r.Add(a1);
object a2 = new
{
zdm = "wxfyzs",
zblx = "KPI",
zbname = "维修费用指数",
id = res[0].Id,
ndmbz = "",
ljz = res[0].wxfyzs,
ActualValue = res[0].wxfyzs,
};
r.Add(a2);
object a3 = new
{
zdm = "qtlxbmfxhl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台离心泵(机泵)密封消耗率",
ndmbz = "<320",
ljz = res[0].qtlxbmfxhl,
ActualValue = res[0].qtlxbmfxhl,
};
r.Add(a3);
object a9 = new
{
zdm = "qtlhsbgsghl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = res[0].qtlhsbgsghl,
ActualValue = res[0].qtlhsbgsghl,
};
r.Add(a9);
object a4 = new
{
zdm = "ybsjkzl",
id = res[0].Id,
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = res[0].ybsjkzl,
ActualValue = res[0].ybsjkzl,
};
r.Add(a4);
object a5 = new
{
zdm = "sjs",
id = res[0].Id,
zblx = "KPI",
zbname = "事件数",
ndmbz = "",
ljz = res[0].sjs,
ActualValue = res[0].sjs,
};
r.Add(a5);
object a6 = new
{
zdm = "gzqdkf",
id = res[0].Id,
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a6);
object a7 = new
{
zdm = "xmyql",
id = res[0].Id,
zblx = "KPI",
zbname = "项目逾期率",
ndmbz = "",
ljz = res[0].xmyql,
ActualValue = res[0].xmyql,
};
r.Add(a7);
object a8 = new
{
zdm = "pxjnl",
id = res[0].Id,
zblx = "KPI",
zbname = "培训及能力",
ndmbz = "",
ljz = res[0].pxjnl,
ActualValue = res[0].pxjnl,
};
r.Add(a8);
return r;
}
else
{
return r;//数据库没有查到表
}
}
else if (chaxunmethod == "全厂")
{
var qc = Jx1.GetQiYeQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
if (qc.Count == 9)
{
object a1 = new
{
zdm = "zzkkxzs",
zblx = "KPI",
zbname = "装置可靠性指数",
ndmbz = "45",
ljz = qc_list[0].ToString(),
id = 0,//id设置为0,则获得趋势图的时候可以判断
ActualValue = qc_list[0].ToString(),
};
r.Add(a1);
object a2 = new
{
zdm = "wxfyzs",
zblx = "KPI",
zbname = "维修费用指数",
id = 0,//id设置为0,则获得趋势图的时候可以判断
ndmbz = "<0.6‰",
ljz = qc_list[1].ToString(),
//id = res[0].Id,
ActualValue = qc_list[1].ToString(),
};
r.Add(a2);
object a3 = new
{
zdm = "qtlxbmfxhl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "千台离心泵(机泵)密封消耗率",
ndmbz = "<7%",
ljz = qc_list[2].ToString(),
//id = res[0].Id,
ActualValue = qc_list[2].ToString(),
};
r.Add(a3);
object a4 = new
{
zdm = "qtlxbmfxhl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "<7%",
ljz = qc_list[2].ToString(),
//id = res[0].Id,
ActualValue = qc_list[3].ToString(),
};
r.Add(a4);
object a5 = new
{
zdm = "ybsjkzl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "",
ljz = qc_list[4].ToString(),
//id = res[0].Id,
ActualValue = qc_list[4].ToString(),
};
r.Add(a5);
object a6 = new
{
zdm = "sjs",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "事件数",
ndmbz = "",
ljz = qc_list[5].ToString(),
//id = res[0].Id,
ActualValue = qc_list[5].ToString(),
};
r.Add(a6);
object a7 = new
{
zdm = "gzqdkf",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "20000",
ljz = qc_list[6].ToString(),
//id = res[0].Id,
ActualValue = qc_list[6].ToString(),
};
r.Add(a7);
object a8 = new
{
zdm = "xmyql",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "项目逾期率",
ndmbz = "28000",
ljz = qc_list[7].ToString(),
//id = res[0].Id,
ActualValue = qc_list[7].ToString(),
};
r.Add(a8);
object a9 = new
{
zdm = "pxjnl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "培训及能力",
ndmbz = "98%",
ljz = qc_list[8].ToString(),
//id = res[0].Id,
ActualValue = qc_list[8].ToString(),
};
r.Add(a9);
return r;
}
else
{
return r;//有人没有提报装置,计算不到数据
}
}
else if (chaxunmethod == "车间")
{
bool ifcj = Jx1.GetifQiYeCj(cjname,zy, astime, aetime);//如果表中存在片区长已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (ifcj)
{
List<A15dot1TabQiYe> res = Jx1.GetQiYeJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
zdm = "zzkkxzs",
zblx = "KPI",
zbname = "装置可靠性指标",
ndmbz = "",
ljz = res[0].zzkkxzs,
id = res[0].Id,
ActualValue = res[0].zzkkxzs,
};
r.Add(a1);
object a2 = new
{
zdm = "wxfyzs",
zblx = "KPI",
zbname = "维修费用指数",
id = res[0].Id,
ndmbz = "",
ljz = res[0].wxfyzs,
ActualValue = res[0].wxfyzs,
};
r.Add(a2);
object a3 = new
{
zdm = "qtlxbmfxhl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台离心泵(机泵)密封消耗率",
ndmbz = "<320",
ljz = res[0].qtlxbmfxhl,
ActualValue = res[0].qtlxbmfxhl,
};
r.Add(a3);
object a9 = new
{
zdm = "qtlhsbgsghl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = res[0].qtlhsbgsghl,
ActualValue = res[0].qtlhsbgsghl,
};
r.Add(a9);
object a4 = new
{
zdm = "ybsjkzl",
id = res[0].Id,
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = res[0].ybsjkzl,
ActualValue = res[0].ybsjkzl,
};
r.Add(a4);
object a5 = new
{
zdm = "sjs",
id = res[0].Id,
zblx = "KPI",
zbname = "事件数",
ndmbz = "",
ljz = res[0].sjs,
ActualValue = res[0].sjs,
};
r.Add(a5);
object a6 = new
{
zdm = "gzqdkf",
id = res[0].Id,
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a6);
object a7 = new
{
zdm = "xmyql",
id = res[0].Id,
zblx = "KPI",
zbname = "项目逾期率",
ndmbz = "",
ljz = res[0].xmyql,
ActualValue = res[0].xmyql,
};
r.Add(a7);
object a8 = new
{
zdm = "pxjnl",
id = res[0].Id,
zblx = "KPI",
zbname = "培训及能力",
ndmbz = "",
ljz = res[0].pxjnl,
ActualValue = res[0].pxjnl,
};
r.Add(a8);
return r;
}
else
{
return r;//数据库没有查到表
}
}
else //表中没有数据
{
var qc = Jx1.GetCjQiYe(zy, cjname, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
object a1 = new
{
zdm = "zzkkxzs",
zblx = "KPI",
zbname = "装置可靠性指数",
ndmbz = "45",
ljz = qc_list[0].ToString(),
id = 0,//id设置为0,则获得趋势图的时候可以判断
ActualValue = qc_list[0].ToString(),
};
r.Add(a1);
object a2 = new
{
zdm = "wxfyzs",
zblx = "KPI",
zbname = "维修费用指数",
id = 0,//id设置为0,则获得趋势图的时候可以判断
ndmbz = "<0.6‰",
ljz = qc_list[1].ToString(),
//id = res[0].Id,
ActualValue = qc_list[1].ToString(),
};
r.Add(a2);
object a3 = new
{
zdm = "qtlxbmfxhl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "千台离心泵(机泵)密封消耗率",
ndmbz = "<7%",
ljz = qc_list[2].ToString(),
//id = res[0].Id,
ActualValue = qc_list[2].ToString(),
};
r.Add(a3);
object a4 = new
{
zdm = "qtlxbmfxhl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "<7%",
ljz = qc_list[2].ToString(),
//id = res[0].Id,
ActualValue = qc_list[3].ToString(),
};
r.Add(a4);
object a5 = new
{
zdm = "ybsjkzl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "",
ljz = qc_list[4].ToString(),
//id = res[0].Id,
ActualValue = qc_list[4].ToString(),
};
r.Add(a5);
object a6 = new
{
zdm = "sjs",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "事件数",
ndmbz = "",
ljz = qc_list[5].ToString(),
//id = res[0].Id,
ActualValue = qc_list[5].ToString(),
};
r.Add(a6);
object a7 = new
{
zdm = "gzqdkf",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "20000",
ljz = qc_list[6].ToString(),
//id = res[0].Id,
ActualValue = qc_list[6].ToString(),
};
r.Add(a7);
object a8 = new
{
zdm = "xmyql",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "项目逾期率",
ndmbz = "28000",
ljz = qc_list[7].ToString(),
//id = res[0].Id,
ActualValue = qc_list[7].ToString(),
};
r.Add(a8);
object a9 = new
{
zdm = "pxjnl",
id = 0,//id设置为0,则获得趋势图的时候可以判断
zblx = "KPI",
zbname = "培训及能力",
ndmbz = "98%",
ljz = qc_list[8].ToString(),
//id = res[0].Id,
ActualValue = qc_list[8].ToString(),
};
r.Add(a9);
return r;
}
}
}
return r;
}
//public string newgetRecord(string time, string zzid, string zy)
//{
// List<object> r = new List<object>();
// EquipManagment em = new EquipManagment();
// string zzname = "";
// if (zzid == "全厂")
// {
// zzname = "全厂";
// }
// else
// {
// zzname = em.getEa_namebyid(Convert.ToInt32(zzid));
// }
// if (zzname != "全厂")
// {
// List<A15dot1TabQiYe> res = Jx1.GetJxByA2(time, zzname, zy);
// if (res.Count != 0)
// {
// object a1 = new
// {
// zblx = "KPI",
// zbname = "装置可靠性指标",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].zzkkxzs,
// };
// r.Add(a1);
// object a2 = new
// {
// zblx = "KPI",
// zbname = "维修费用指数",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].wxfyzs,
// };
// r.Add(a2);
// object a3 = new
// {
// zblx = "KPI",
// zbname = "千台离心泵(机泵)密封消耗率",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].qtlxbmfxhl,
// };
// r.Add(a3);
// object a9 = new
// {
// zblx = "KPI",
// zbname = "千台冷换设备管束(含整台)更换率",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].qtlhsbgsghl,
// };
// r.Add(a9);
// object a4 = new
// {
// zblx = "KPI",
// zbname = "仪表实际控制率",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].ybsjkzl,
// };
// r.Add(a4);
// object a5 = new
// {
// zblx = "KPI",
// zbname = "事件数",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].sjs,
// };
// r.Add(a5);
// object a6 = new
// {
// zblx = "KPI",
// zbname = "故障强度扣分",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].gzqdkf,
// };
// r.Add(a6);
// object a7 = new
// {
// zblx = "KPI",
// zbname = "项目逾期率",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].xmyql,
// };
// r.Add(a7);
// object a8 = new
// {
// zblx = "KPI",
// zbname = "培训及能力",
// ndmbz = "",
// ljz = "",
// ActualValue = res[0].pxjnl,
// };
// r.Add(a8);
// string str = JsonConvert.SerializeObject(r);
// return ("{" + "\"data\": " + str + "}");
// }
// else
// {
// object a1 = new
// {
// zblx = "KPI",
// zbname = "装置可靠性指标",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a1);
// object a2 = new
// {
// zblx = "KPI",
// zbname = "维修费用指数",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a2);
// object a3 = new
// {
// zblx = "KPI",
// zbname = "千台离心泵(机泵)密封消耗率",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a3);
// object a9 = new
// {
// zblx = "KPI",
// zbname = "千台冷换设备管束(含整台)更换率",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a9);
// object a4 = new
// {
// zblx = "KPI",
// zbname = "仪表实际控制率",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a4);
// object a5 = new
// {
// zblx = "KPI",
// zbname = "事件数",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a5);
// object a6 = new
// {
// zblx = "KPI",
// zbname = "故障强度扣分",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a6);
// object a7 = new
// {
// zblx = "KPI",
// zbname = "项目逾期率",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a7);
// object a8 = new
// {
// zblx = "KPI",
// zbname = "培训及能力",
// ndmbz = "",
// ljz = "",
// ActualValue = "",
// };
// r.Add(a8);
// string str = JsonConvert.SerializeObject(r);
// return ("{" + "\"data\": " + str + "}");
// }
// }
// else
// {
// return ("{" + "\"data\": }");
// }
//}
//public List<object> getObjectQiYe(string time, string zzid, string zy,string cjname,string chaxunmethod)
//{
// PersonManagment pm = new PersonManagment();
// EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
// string rolename = pv.Role_Names;//获得角色名
// string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;//获得用户名
// List<object> r = new List<object>();
// EquipManagment em = new EquipManagment();
// if(chaxunmethod=="全厂"){
// zzid="全厂";//如果查询方式是全厂
// }else if(chaxunmethod=="装置")
// {
// zzid = em.getEa_namebyid(Convert.ToInt32(zzid));//如果查询方式是装置将zzid转换为装置的名字
// }
// DateTime Cxtime = DateTime.Now;
// string stime;
// string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
// if (Convert.ToInt32(time) > 1)
// {
// string Reducetime = (Convert.ToInt32(time) -1).ToString();
// etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
// stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
// }
// else
// {
// string Addtime = (Convert.ToInt32(time) + 1).ToString();
// stime = (Cxtime.Year-1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
// etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
// }
// DateTime astime = Convert.ToDateTime(stime);
// DateTime aetime = Convert.ToDateTime(etime);
// if ((chaxunmethod == "全厂" && !rolename.Contains("管理员")) || (chaxunmethod == "装置") || (chaxunmethod == "车间") && !rolename.Contains("片区长"))
// {
// //直接在数据库中查询
// List<A15dot1TabQiYe> res = Jx1.GetQiYeJxByA2(astime,aetime, zzid, zy);
// if (res.Count != 0)
// {
// object a1 = new
// {
// zdm = "zzkkxzs",
// zblx = "KPI",
// zbname = "装置可靠性指标",
// ndmbz = "",
// ljz = res[0].zzkkxzs,
// id = res[0].Id,
// ActualValue = res[0].zzkkxzs,
// };
// r.Add(a1);
// object a2 = new
// {
// zdm = "wxfyzs",
// zblx = "KPI",
// zbname = "维修费用指数",
// id = res[0].Id,
// ndmbz = "",
// ljz = res[0].wxfyzs,
// ActualValue = res[0].wxfyzs,
// };
// r.Add(a2);
// object a3 = new
// {
// zdm = "qtlxbmfxhl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "千台离心泵(机泵)密封消耗率",
// ndmbz = "<320",
// ljz = res[0].qtlxbmfxhl,
// ActualValue = res[0].qtlxbmfxhl,
// };
// r.Add(a3);
// object a9 = new
// {
// zdm = "qtlhsbgsghl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "千台冷换设备管束(含整台)更换率",
// ndmbz = "≤30‰",
// ljz = res[0].qtlhsbgsghl,
// ActualValue = res[0].qtlhsbgsghl,
// };
// r.Add(a9);
// object a4 = new
// {
// zdm = "ybsjkzl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "仪表实际控制率",
// ndmbz = "0.93",
// ljz = res[0].ybsjkzl,
// ActualValue = res[0].ybsjkzl,
// };
// r.Add(a4);
// object a5 = new
// {
// zdm = "sjs",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "事件数",
// ndmbz = "",
// ljz = res[0].sjs,
// ActualValue = res[0].sjs,
// };
// r.Add(a5);
// object a6 = new
// {
// zdm = "gzqdkf",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "故障强度扣分",
// ndmbz = "",
// ljz = res[0].gzqdkf,
// ActualValue = res[0].gzqdkf,
// };
// r.Add(a6);
// object a7 = new
// {
// zdm = "xmyql",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "项目逾期率",
// ndmbz = "",
// ljz = res[0].xmyql,
// ActualValue = res[0].xmyql,
// };
// r.Add(a7);
// object a8 = new
// {
// zdm = "pxjnl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "培训及能力",
// ndmbz = "",
// ljz = res[0].pxjnl,
// ActualValue = res[0].pxjnl,
// };
// r.Add(a8);
// return r;
// }
// else
// {
// return r;
// }
// }
// else if ((chaxunmethod == "全厂" && rolename.Contains("管理员")) || (chaxunmethod == "车间" && rolename.Contains("片区长")))
// {
// //再次判断管理员和片区长的查询位置
// //首先利用ifqc判断管理员是查询数据库还是计算查询
// bool ifqc = Jx1.GetifQiYeQc(zy, astime, aetime);//如果表中存在超级用户已经提报的全厂的数据,就在数据库中去查,否则计算显示.
// if (chaxunmethod == "全厂" && ifqc)
// {//表中存在超级用户已经提报的全厂的数据,就在数据库中去查
// List<A15dot1TabQiYe> res = Jx1.GetQiYeJxByA2(astime,aetime, zzid, zy);
// if (res.Count != 0)
// {
// object a1 = new
// {
// zdm = "zzkkxzs",
// zblx = "KPI",
// zbname = "装置可靠性指标",
// ndmbz = "",
// ljz = res[0].zzkkxzs,
// id = res[0].Id,
// ActualValue = res[0].zzkkxzs,
// };
// r.Add(a1);
// object a2 = new
// {
// zdm = "wxfyzs",
// zblx = "KPI",
// zbname = "维修费用指数",
// id = res[0].Id,
// ndmbz = "",
// ljz = res[0].wxfyzs,
// ActualValue = res[0].wxfyzs,
// };
// r.Add(a2);
// object a3 = new
// {
// zdm = "qtlxbmfxhl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "千台离心泵(机泵)密封消耗率",
// ndmbz = "<320",
// ljz = res[0].qtlxbmfxhl,
// ActualValue = res[0].qtlxbmfxhl,
// };
// r.Add(a3);
// object a9 = new
// {
// zdm = "qtlhsbgsghl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "千台冷换设备管束(含整台)更换率",
// ndmbz = "≤30‰",
// ljz = res[0].qtlhsbgsghl,
// ActualValue = res[0].qtlhsbgsghl,
// };
// r.Add(a9);
// object a4 = new
// {
// zdm = "ybsjkzl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "仪表实际控制率",
// ndmbz = "0.93",
// ljz = res[0].ybsjkzl,
// ActualValue = res[0].ybsjkzl,
// };
// r.Add(a4);
// object a5 = new
// {
// zdm = "sjs",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "事件数",
// ndmbz = "",
// ljz = res[0].sjs,
// ActualValue = res[0].sjs,
// };
// r.Add(a5);
// object a6 = new
// {
// zdm = "gzqdkf",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "故障强度扣分",
// ndmbz = "",
// ljz = res[0].gzqdkf,
// ActualValue = res[0].gzqdkf,
// };
// r.Add(a6);
// object a7 = new
// {
// zdm = "xmyql",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "项目逾期率",
// ndmbz = "",
// ljz = res[0].xmyql,
// ActualValue = res[0].xmyql,
// };
// r.Add(a7);
// object a8 = new
// {
// zdm = "pxjnl",
// id = res[0].Id,
// zblx = "KPI",
// zbname = "培训及能力",
// ndmbz = "",
// ljz = res[0].pxjnl,
// ActualValue = res[0].pxjnl,
// };
// r.Add(a8);
// return r;
// }
// else
// {
// return r;//数据库没有查到表
// }
// }
// else if (chaxunmethod == "全厂")
// {
// var qc = Jx1.GetQiYeQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
// List<string> qc_list = new List<string>();
// foreach (var i in qc)
// {
// if (i == null)
// qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
// else
// qc_list.Add(i.ToString());
// }
// if (qc.Count == 9)
// {
// object a1 = new
// {
// zdm = "zzkkxzs",
// zblx = "KPI",
// zbname = "装置可靠性指数",
// ndmbz = "45",
// ljz = qc_list[0].ToString(),
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// ActualValue = qc_list[0].ToString(),
// };
// r.Add(a1);
// object a2 = new
// {
// zdm = "wxfyzs",
// zblx = "KPI",
// zbname = "维修费用指数",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// ndmbz = "<0.6‰",
// ljz = qc_list[1].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[1].ToString(),
// };
// r.Add(a2);
// object a3 = new
// {
// zdm = "qtlxbmfxhl",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// zblx = "KPI",
// zbname = "千台离心泵(机泵)密封消耗率",
// ndmbz = "<7%",
// ljz = qc_list[2].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[2].ToString(),
// };
// r.Add(a3);
// object a4 = new
// {
// zdm = "qtlxbmfxhl",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// zblx = "KPI",
// zbname = "千台冷换设备管束(含整台)更换率",
// ndmbz = "<7%",
// ljz = qc_list[2].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[3].ToString(),
// };
// r.Add(a4);
// object a5 = new
// {
// zdm = "ybsjkzl",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// zblx = "KPI",
// zbname = "仪表实际控制率",
// ndmbz = "",
// ljz = qc_list[4].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[4].ToString(),
// };
// r.Add(a5);
// object a6 = new
// {
// zdm = "sjs",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// zblx = "KPI",
// zbname = "事件数",
// ndmbz = "",
// ljz = qc_list[5].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[5].ToString(),
// };
// r.Add(a6);
// object a7 = new
// {
// zdm = "gzqdkf",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// zblx = "KPI",
// zbname = "故障强度扣分",
// ndmbz = "20000",
// ljz = qc_list[6].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[6].ToString(),
// };
// r.Add(a7);
// object a8 = new
// {
// zdm = "xmyql",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// zblx = "KPI",
// zbname = "项目逾期率",
// ndmbz = "28000",
// ljz = qc_list[7].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[7].ToString(),
// };
// r.Add(a8);
// object a9 = new
// {
// zdm = "pxjnl",
// id = 0,//id设置为0,则获得趋势图的时候可以判断
// zblx = "KPI",
// zbname = "培训及能力",
// ndmbz = "98%",
// ljz = qc_list[8].ToString(),
// //id = res[0].Id,
// ActualValue = qc_list[8].ToString(),
// };
// r.Add(a9);
// return r;
// }
// else
// {
// return r;//有人没有提报装置,计算不到数据
// }
// }
// else if (chaxunmethod == "车间")
// {
// return r;
// //车间查询的写法
// }
// else
// {
// return r;
// }
// }
// return r;
//}
//public List<object> getObjectQiYeforuser(string time, string zzid, string zy)
//{
//}
public List<object> getObjectDong(string time, string zzid, string zy, string cjname, string chaxunmethod)
{
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
string rolename = pv.Role_Names;//获得角色名
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;//获得用户名
List<object> r = new List<object>();
EquipManagment em = new EquipManagment();
if (chaxunmethod == "全厂")
{
zzid = "全厂";//如果查询方式是全厂
}
else if (chaxunmethod == "装置")
{
zzid = em.getEa_namebyid(Convert.ToInt32(zzid));//如果查询方式是装置将zzid转换为装置的名字
}else if(chaxunmethod=="车间")
{
zzid = cjname;
}
DateTime Cxtime = DateTime.Now;
string stime;
string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if ((chaxunmethod == "全厂" && !rolename.Contains("管理员")) || (chaxunmethod == "装置") || (chaxunmethod == "车间") && !rolename.Contains("片区长"))
{
List<A15dot1TabDong> res = Jx1.GetDongJxByA2(astime, aetime, zzid, zy);//直接在数据库中查询
if (res.Count != 0)
{
object a1 = new
{
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "45",
ljz = res[0].gzqdkf,
id = res[0].Id,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
zdm = "djzgzl",
zblx = "KPI",
zbname = "大机组故障率",
id = res[0].Id,
ndmbz = "<0.6‰",
ljz = res[0].djzgzl,
ActualValue = res[0].djzgzl,
};
r.Add(a2);
object a3 = new
{
zdm = "gzwxl",
id = res[0].Id,
zblx = "KPI",
zbname = "故障维修率",
ndmbz = "<7%",
ljz = res[0].gzwxl,
ActualValue = res[0].gzwxl,
};
r.Add(a3);
object a9 = new
{
zdm = "qtlxbmfxhl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台离心泵密封消耗率",
ndmbz = "<320",
ljz = res[0].qtlxbmfxhl,
ActualValue = res[0].qtlxbmfxhl,
};
r.Add(a9);
object a4 = new
{
zdm = "jjqxgsl",
id = res[0].Id,
zblx = "KPI",
zbname = "紧急抢修工时率",
ndmbz = "",
ljz = res[0].jjqxgsl,
ActualValue = res[0].jjqxgsl,
};
r.Add(a4);
object a5 = new
{
zdm = "gdpjwcsj",
id = res[0].Id,
zblx = "KPI",
zbname = "工单平均完成时间",
ndmbz = "",
ljz = res[0].gdpjwcsj,
ActualValue = res[0].gdpjwcsj,
};
r.Add(a5);
object a6 = new
{
zdm = "jxmfpjsm",
id = res[0].Id,
zblx = "KPI",
zbname = "机械密封平均寿命",
ndmbz = "20000",
ljz = res[0].jxmfpjsm,
ActualValue = res[0].jxmfpjsm,
};
r.Add(a6);
object a7 = new
{
zdm = "zcpjsm",
id = res[0].Id,
zblx = "KPI",
zbname = "轴承平均寿命",
ndmbz = "28000",
ljz = res[0].zcpjsm,
ActualValue = res[0].zcpjsm,
};
r.Add(a7);
object a8 = new
{
zdm = "sbwhl",
id = res[0].Id,
zblx = "KPI",
zbname = "设备完好率",
ndmbz = "98%",
ljz = res[0].sbwhl,
ActualValue = res[0].sbwhl,
};
r.Add(a8);
object a10 = new
{
zdm = "jxychgl",
id = res[0].Id,
zblx = "KPI",
zbname = "检修一次合格率",
ndmbz = "",
ljz = res[0].jxychgl,
ActualValue = res[0].jxychgl,
};
r.Add(a10);
object a11 = new
{
zdm = "zyjbpjxl",
id = res[0].Id,
zblx = "KPI",
zbname = "主要机泵平均效率",
ndmbz = "50%",
ljz = res[0].zyjbpjxl,
ActualValue = res[0].zyjbpjxl,
};
r.Add(a11);
object a12 = new
{
zdm = "jzpjxl",
id = res[0].Id,
zblx = "KPI",
zbname = "机组平均效率",
ndmbz = "",
ljz = res[0].jzpjxl,
ActualValue = res[0].jzpjxl,
};
r.Add(a12);
object a13 = new
{
zdm = "wfjzgzl",
id = res[0].Id,
zblx = "KPI",
zbname = "往复机组故障率",
ndmbz = "<0.15%",
ljz = res[0].wfjzgzl,
ActualValue = res[0].wfjzgzl,
};
r.Add(a13);
object a14 = new
{
zdm = "ndbtjbcfjxtc",
id = res[0].Id,
zblx = "KPI",
zbname = "年度百台机泵重复检修台次",
ndmbz = "<10台次/百台·年",
ljz = res[0].ndbtjbcfjxtc,
ActualValue = res[0].ndbtjbcfjxtc,
};
r.Add(a14);
object a15 = new
{
zdm = "jbpjwgzjgsjMTBF",
id = res[0].Id,
zblx = "KPI",
zbname = "机泵平均无故障间隔时间MTBF",
ndmbz = ">72月",
ljz = res[0].jbpjwgzjgsjMTBF,
ActualValue = res[0].jbpjwgzjgsjMTBF,
};
r.Add(a15);
return r;
}
else
{
return r;
}
}
else if ((chaxunmethod == "全厂" && rolename.Contains("管理员")) || (chaxunmethod == "车间" && rolename.Contains("片区长")))
{
//再次判断管理员和片区长的查询位置
//首先利用ifqc判断管理员是查询数据库还是计算查询
bool ifqc = Jx1.GetifDongQc(zy, astime, aetime);//如果表中存在超级用户已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (chaxunmethod == "全厂" && ifqc)
{//表中存在超级用户已经提报的全厂的数据,就在数据库中去查
List<A15dot1TabDong> res = Jx1.GetDongJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "45",
ljz = res[0].gzqdkf,
id = res[0].Id,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
zdm = "djzgzl",
zblx = "KPI",
zbname = "大机组故障率",
id = res[0].Id,
ndmbz = "<0.6‰",
ljz = res[0].djzgzl,
ActualValue = res[0].djzgzl,
};
r.Add(a2);
object a3 = new
{
zdm = "gzwxl",
id = res[0].Id,
zblx = "KPI",
zbname = "故障维修率",
ndmbz = "<7%",
ljz = res[0].gzwxl,
ActualValue = res[0].gzwxl,
};
r.Add(a3);
object a9 = new
{
zdm = "qtlxbmfxhl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台离心泵密封消耗率",
ndmbz = "<320",
ljz = res[0].qtlxbmfxhl,
ActualValue = res[0].qtlxbmfxhl,
};
r.Add(a9);
object a4 = new
{
zdm = "jjqxgsl",
id = res[0].Id,
zblx = "KPI",
zbname = "紧急抢修工时率",
ndmbz = "",
ljz = res[0].jjqxgsl,
ActualValue = res[0].jjqxgsl,
};
r.Add(a4);
object a5 = new
{
zdm = "gdpjwcsj",
id = res[0].Id,
zblx = "KPI",
zbname = "工单平均完成时间",
ndmbz = "",
ljz = res[0].gdpjwcsj,
ActualValue = res[0].gdpjwcsj,
};
r.Add(a5);
object a6 = new
{
zdm = "jxmfpjsm",
id = res[0].Id,
zblx = "KPI",
zbname = "机械密封平均寿命",
ndmbz = "20000",
ljz = res[0].jxmfpjsm,
ActualValue = res[0].jxmfpjsm,
};
r.Add(a6);
object a7 = new
{
zdm = "zcpjsm",
id = res[0].Id,
zblx = "KPI",
zbname = "轴承平均寿命",
ndmbz = "28000",
ljz = res[0].zcpjsm,
ActualValue = res[0].zcpjsm,
};
r.Add(a7);
object a8 = new
{
zdm = "sbwhl",
id = res[0].Id,
zblx = "KPI",
zbname = "设备完好率",
ndmbz = "98%",
ljz = res[0].sbwhl,
ActualValue = res[0].sbwhl,
};
r.Add(a8);
object a10 = new
{
zdm = "jxychgl",
id = res[0].Id,
zblx = "KPI",
zbname = "检修一次合格率",
ndmbz = "",
ljz = res[0].jxychgl,
ActualValue = res[0].jxychgl,
};
r.Add(a10);
object a11 = new
{
zdm = "zyjbpjxl",
id = res[0].Id,
zblx = "KPI",
zbname = "主要机泵平均效率",
ndmbz = "50%",
ljz = res[0].zyjbpjxl,
ActualValue = res[0].zyjbpjxl,
};
r.Add(a11);
object a12 = new
{
zdm = "jzpjxl",
id = res[0].Id,
zblx = "KPI",
zbname = "机组平均效率",
ndmbz = "",
ljz = res[0].jzpjxl,
ActualValue = res[0].jzpjxl,
};
r.Add(a12);
object a13 = new
{
zdm = "wfjzgzl",
id = res[0].Id,
zblx = "KPI",
zbname = "往复机组故障率",
ndmbz = "<0.15%",
ljz = res[0].wfjzgzl,
ActualValue = res[0].wfjzgzl,
};
r.Add(a13);
object a14 = new
{
zdm = "ndbtjbcfjxtc",
id = res[0].Id,
zblx = "KPI",
zbname = "年度百台机泵重复检修台次",
ndmbz = "<10台次/百台·年",
ljz = res[0].ndbtjbcfjxtc,
ActualValue = res[0].ndbtjbcfjxtc,
};
r.Add(a14);
object a15 = new
{
zdm = "jbpjwgzjgsjMTBF",
id = res[0].Id,
zblx = "KPI",
zbname = "机泵平均无故障间隔时间MTBF",
ndmbz = ">72月",
ljz = res[0].jbpjwgzjgsjMTBF,
ActualValue = res[0].jbpjwgzjgsjMTBF,
};
r.Add(a15);
return r;
}
else
{
return r;
}
}
else if (chaxunmethod == "全厂")
{
var qc = Jx1.GetDongQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
if (qc.Count == 15)
{
object a1 = new
{
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "45",
ljz = qc_list[0],
id = "0",
ActualValue = qc_list[0],
};
r.Add(a1);
object a2 = new
{
id = "0",
zdm = "djzgzl",
zblx = "KPI",
zbname = "大机组故障率",
// id = res[0].Id,
ndmbz = "<0.6‰",
ljz = qc_list[1],
//id = res[0].Id,
ActualValue = qc_list[1],
};
r.Add(a2);
object a3 = new
{
id = "0",
zdm = "gzwxl",
// id = res[0].Id,
zblx = "KPI",
zbname = "故障维修率",
ndmbz = "<7%",
ljz = qc_list[2],
//id = res[0].Id,
ActualValue = qc_list[2],
};
r.Add(a3);
object a9 = new
{
id = "0",
zdm = "qtlxbmfxhl",
// id = res[3].Id,
zblx = "KPI",
zbname = "千台离心泵密封消耗率",
ndmbz = "<320",
ljz = qc_list[3],
//id = res[0].Id,
ActualValue = qc_list[3],
};
r.Add(a9);
object a4 = new
{
id = "0",
zdm = "jjqxgsl",
// id = res[0].Id,
zblx = "KPI",
zbname = "紧急抢修工时率",
ndmbz = "",
ljz = qc_list[4],
//id = res[0].Id,
ActualValue = qc_list[4],
};
r.Add(a4);
object a5 = new
{
id = "0",
zdm = "gdpjwcsj",
// id = res[0].Id,
zblx = "KPI",
zbname = "工单平均完成时间",
ndmbz = "",
ljz = qc_list[5],
//id = res[0].Id,
ActualValue = qc_list[5],
};
r.Add(a5);
object a6 = new
{
id = "0",
zdm = "jxmfpjsm",
//id = res[0].Id,
zblx = "KPI",
zbname = "机械密封平均寿命",
ndmbz = "20000",
ljz = qc_list[6],
//id = res[0].Id,
ActualValue = qc_list[6],
};
r.Add(a6);
object a7 = new
{
id = "0",
zdm = "zcpjsm",
//id = res[0].Id,
zblx = "KPI",
zbname = "轴承平均寿命",
ndmbz = "28000",
ljz = qc_list[7],
//id = res[0].Id,
ActualValue = qc_list[7],
};
r.Add(a7);
object a8 = new
{
id = "0",
zdm = "sbwhl",
// id = res[0].Id,
zblx = "KPI",
zbname = "设备完好率",
ndmbz = "98%",
ljz = qc_list[8],
//id = res[0].Id,
ActualValue = qc_list[8],
};
r.Add(a8);
object a10 = new
{
id = "0",
zdm = "jxychgl",
// id = res[0].Id,
zblx = "KPI",
zbname = "检修一次合格率",
ndmbz = "",
ljz = qc_list[9],
//id = res[0].Id,
ActualValue = qc_list[9],
};
r.Add(a10);
object a11 = new
{
id = "0",
zdm = "zyjbpjxl",
// id = res[0].Id,
zblx = "KPI",
zbname = "主要机泵平均效率",
ndmbz = "50%",
ljz = qc_list[10],
//id = res[0].Id,
ActualValue = qc_list[10],
};
r.Add(a11);
object a12 = new
{
id = "0",
zdm = "jzpjxl",
// id = res[0].Id,
zblx = "KPI",
zbname = "机组平均效率",
ndmbz = "",
ljz = qc_list[11],
//id = res[0].Id,
ActualValue = qc_list[11],
};
r.Add(a12);
object a13 = new
{
id = "0",
zdm = "wfjzgzl",
// id = res[0].Id,
zblx = "KPI",
zbname = "往复机组故障率",
ndmbz = "<0.15%",
ljz = qc_list[12],
//id = res[0].Id,
ActualValue = qc_list[12],
};
r.Add(a13);
object a14 = new
{
id = "0",
zdm = "ndbtjbcfjxtc",
// id = res[0].Id,
zblx = "KPI",
zbname = "年度百台机泵重复检修台次",
ndmbz = "<10台次/百台·年",
ljz = qc_list[13],
//id = res[0].Id,
ActualValue = qc_list[13],
};
r.Add(a14);
object a15 = new
{
id = "0",
zdm = "jbpjwgzjgsjMTBF",
// id = res[0].Id,
zblx = "KPI",
zbname = "机泵平均无故障间隔时间MTBF",
ndmbz = ">72月",
ljz = qc_list[14],
//id = res[0].Id,
ActualValue = qc_list[14],
};
r.Add(a15);
return r;
}
else
{
return r;
}
}
else if (chaxunmethod == "车间")
{
bool ifcj = Jx1.GetifDongCj(cjname,zy, astime, aetime);//如果表中存在片区长已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (ifcj)
{
List<A15dot1TabDong> res = Jx1.GetDongJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "45",
ljz = res[0].gzqdkf,
id = res[0].Id,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
zdm = "djzgzl",
zblx = "KPI",
zbname = "大机组故障率",
id = res[0].Id,
ndmbz = "<0.6‰",
ljz = res[0].djzgzl,
ActualValue = res[0].djzgzl,
};
r.Add(a2);
object a3 = new
{
zdm = "gzwxl",
id = res[0].Id,
zblx = "KPI",
zbname = "故障维修率",
ndmbz = "<7%",
ljz = res[0].gzwxl,
ActualValue = res[0].gzwxl,
};
r.Add(a3);
object a9 = new
{
zdm = "qtlxbmfxhl",
id = res[0].Id,
zblx = "KPI",
zbname = "千台离心泵密封消耗率",
ndmbz = "<320",
ljz = res[0].qtlxbmfxhl,
ActualValue = res[0].qtlxbmfxhl,
};
r.Add(a9);
object a4 = new
{
zdm = "jjqxgsl",
id = res[0].Id,
zblx = "KPI",
zbname = "紧急抢修工时率",
ndmbz = "",
ljz = res[0].jjqxgsl,
ActualValue = res[0].jjqxgsl,
};
r.Add(a4);
object a5 = new
{
zdm = "gdpjwcsj",
id = res[0].Id,
zblx = "KPI",
zbname = "工单平均完成时间",
ndmbz = "",
ljz = res[0].gdpjwcsj,
ActualValue = res[0].gdpjwcsj,
};
r.Add(a5);
object a6 = new
{
zdm = "jxmfpjsm",
id = res[0].Id,
zblx = "KPI",
zbname = "机械密封平均寿命",
ndmbz = "20000",
ljz = res[0].jxmfpjsm,
ActualValue = res[0].jxmfpjsm,
};
r.Add(a6);
object a7 = new
{
zdm = "zcpjsm",
id = res[0].Id,
zblx = "KPI",
zbname = "轴承平均寿命",
ndmbz = "28000",
ljz = res[0].zcpjsm,
ActualValue = res[0].zcpjsm,
};
r.Add(a7);
object a8 = new
{
zdm = "sbwhl",
id = res[0].Id,
zblx = "KPI",
zbname = "设备完好率",
ndmbz = "98%",
ljz = res[0].sbwhl,
ActualValue = res[0].sbwhl,
};
r.Add(a8);
object a10 = new
{
zdm = "jxychgl",
id = res[0].Id,
zblx = "KPI",
zbname = "检修一次合格率",
ndmbz = "",
ljz = res[0].jxychgl,
ActualValue = res[0].jxychgl,
};
r.Add(a10);
object a11 = new
{
zdm = "zyjbpjxl",
id = res[0].Id,
zblx = "KPI",
zbname = "主要机泵平均效率",
ndmbz = "50%",
ljz = res[0].zyjbpjxl,
ActualValue = res[0].zyjbpjxl,
};
r.Add(a11);
object a12 = new
{
zdm = "jzpjxl",
id = res[0].Id,
zblx = "KPI",
zbname = "机组平均效率",
ndmbz = "",
ljz = res[0].jzpjxl,
ActualValue = res[0].jzpjxl,
};
r.Add(a12);
object a13 = new
{
zdm = "wfjzgzl",
id = res[0].Id,
zblx = "KPI",
zbname = "往复机组故障率",
ndmbz = "<0.15%",
ljz = res[0].wfjzgzl,
ActualValue = res[0].wfjzgzl,
};
r.Add(a13);
object a14 = new
{
zdm = "ndbtjbcfjxtc",
id = res[0].Id,
zblx = "KPI",
zbname = "年度百台机泵重复检修台次",
ndmbz = "<10台次/百台·年",
ljz = res[0].ndbtjbcfjxtc,
ActualValue = res[0].ndbtjbcfjxtc,
};
r.Add(a14);
object a15 = new
{
zdm = "jbpjwgzjgsjMTBF",
id = res[0].Id,
zblx = "KPI",
zbname = "机泵平均无故障间隔时间MTBF",
ndmbz = ">72月",
ljz = res[0].jbpjwgzjgsjMTBF,
ActualValue = res[0].jbpjwgzjgsjMTBF,
};
r.Add(a15);
return r;
}
else
{
return r;
}
}
else //库中没有数据则直接算出数据
{
var qc = Jx1.GetDongQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
if (qc.Count == 15)
{
object a1 = new
{
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "45",
ljz = qc_list[0],
id = "0",
ActualValue = qc_list[0],
};
r.Add(a1);
object a2 = new
{
id = "0",
zdm = "djzgzl",
zblx = "KPI",
zbname = "大机组故障率",
// id = res[0].Id,
ndmbz = "<0.6‰",
ljz = qc_list[1],
//id = res[0].Id,
ActualValue = qc_list[1],
};
r.Add(a2);
object a3 = new
{
id = "0",
zdm = "gzwxl",
// id = res[0].Id,
zblx = "KPI",
zbname = "故障维修率",
ndmbz = "<7%",
ljz = qc_list[2],
//id = res[0].Id,
ActualValue = qc_list[2],
};
r.Add(a3);
object a9 = new
{
id = "0",
zdm = "qtlxbmfxhl",
// id = res[3].Id,
zblx = "KPI",
zbname = "千台离心泵密封消耗率",
ndmbz = "<320",
ljz = qc_list[3],
//id = res[0].Id,
ActualValue = qc_list[3],
};
r.Add(a9);
object a4 = new
{
id = "0",
zdm = "jjqxgsl",
// id = res[0].Id,
zblx = "KPI",
zbname = "紧急抢修工时率",
ndmbz = "",
ljz = qc_list[4],
//id = res[0].Id,
ActualValue = qc_list[4],
};
r.Add(a4);
object a5 = new
{
id = "0",
zdm = "gdpjwcsj",
// id = res[0].Id,
zblx = "KPI",
zbname = "工单平均完成时间",
ndmbz = "",
ljz = qc_list[5],
//id = res[0].Id,
ActualValue = qc_list[5],
};
r.Add(a5);
object a6 = new
{
id = "0",
zdm = "jxmfpjsm",
//id = res[0].Id,
zblx = "KPI",
zbname = "机械密封平均寿命",
ndmbz = "20000",
ljz = qc_list[6],
//id = res[0].Id,
ActualValue = qc_list[6],
};
r.Add(a6);
object a7 = new
{
id = "0",
zdm = "zcpjsm",
//id = res[0].Id,
zblx = "KPI",
zbname = "轴承平均寿命",
ndmbz = "28000",
ljz = qc_list[7],
//id = res[0].Id,
ActualValue = qc_list[7],
};
r.Add(a7);
object a8 = new
{
id = "0",
zdm = "sbwhl",
// id = res[0].Id,
zblx = "KPI",
zbname = "设备完好率",
ndmbz = "98%",
ljz = qc_list[8],
//id = res[0].Id,
ActualValue = qc_list[8],
};
r.Add(a8);
object a10 = new
{
id = "0",
zdm = "jxychgl",
// id = res[0].Id,
zblx = "KPI",
zbname = "检修一次合格率",
ndmbz = "",
ljz = qc_list[9],
//id = res[0].Id,
ActualValue = qc_list[9],
};
r.Add(a10);
object a11 = new
{
id = "0",
zdm = "zyjbpjxl",
// id = res[0].Id,
zblx = "KPI",
zbname = "主要机泵平均效率",
ndmbz = "50%",
ljz = qc_list[10],
//id = res[0].Id,
ActualValue = qc_list[10],
};
r.Add(a11);
object a12 = new
{
id = "0",
zdm = "jzpjxl",
// id = res[0].Id,
zblx = "KPI",
zbname = "机组平均效率",
ndmbz = "",
ljz = qc_list[11],
//id = res[0].Id,
ActualValue = qc_list[11],
};
r.Add(a12);
object a13 = new
{
id = "0",
zdm = "wfjzgzl",
// id = res[0].Id,
zblx = "KPI",
zbname = "往复机组故障率",
ndmbz = "<0.15%",
ljz = qc_list[12],
//id = res[0].Id,
ActualValue = qc_list[12],
};
r.Add(a13);
object a14 = new
{
id = "0",
zdm = "ndbtjbcfjxtc",
// id = res[0].Id,
zblx = "KPI",
zbname = "年度百台机泵重复检修台次",
ndmbz = "<10台次/百台·年",
ljz = qc_list[13],
//id = res[0].Id,
ActualValue = qc_list[13],
};
r.Add(a14);
object a15 = new
{
id = "0",
zdm = "jbpjwgzjgsjMTBF",
// id = res[0].Id,
zblx = "KPI",
zbname = "机泵平均无故障间隔时间MTBF",
ndmbz = ">72月",
ljz = qc_list[14],
//id = res[0].Id,
ActualValue = qc_list[14],
};
r.Add(a15);
return r;
}
else
{
return r;
}
}
}
}
return r;
}
public List<object> getObjectJing(string time, string zzid, string zy, string cjname, string chaxunmethod)
{
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
string rolename = pv.Role_Names;//获得角色名
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;//获得用户名
List<object> r = new List<object>();
EquipManagment em = new EquipManagment();
if (chaxunmethod == "全厂")
{
zzid = "全厂";//如果查询方式是全厂
}
else if (chaxunmethod == "装置")
{
zzid = em.getEa_namebyid(Convert.ToInt32(zzid));//如果查询方式是装置将zzid转换为装置的名字
}
else if (chaxunmethod == "车间")
{
zzid = cjname;
}
DateTime Cxtime = DateTime.Now;
string stime;
string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if ((chaxunmethod == "全厂" && !rolename.Contains("管理员")) || (chaxunmethod == "装置") || (chaxunmethod == "车间") && !rolename.Contains("片区长"))
{
List<A15dot1TabJing> res = Jx1.GetJingJxByA2(astime, aetime, zzid, zy);//直接在数据库中查询
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "sbfsxlcs",
zblx = "KPI",
zbname = "设备腐蚀泄漏次数(有毒有害易燃易爆介质)",
ndmbz = "≤28次",
ljz = res[0].sbfsxlcs,
ActualValue = res[0].sbfsxlcs,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "qtlhsbgs",
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = res[0].qtlhsbgs,
ActualValue = res[0].qtlhsbgs,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "gylpjrxl",
zblx = "KPI",
zbname = "工业炉(≥10MW)平均热效率",
ndmbz = "≥92.2%",
ljz = res[0].gylpjrxl,
ActualValue = res[0].gylpjrxl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "hrqjxl",
zblx = "KPI",
zbname = "换热器检修率",
ndmbz = "<2%",
ljz = res[0].hrqjxl,
ActualValue = res[0].hrqjxl,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "ylrqdjl",
zblx = "KPI",
zbname = "压力容器定检率",
ndmbz = "1",
ljz = res[0].ylrqdjl,
ActualValue = res[0].ylrqdjl,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "ylgdndjxjhwcl",
zblx = "KPI",
zbname = "压力管道年度检验计划完成率",
ndmbz = "1",
ljz = res[0].ylgdndjxjhwcl,
ActualValue = res[0].ylgdndjxjhwcl,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "aqfndjyjhwcl",
zblx = "KPI",
zbname = "安全阀年度校验计划完成率",
ndmbz = "1",
ljz = res[0].aqfndjyjhwcl,
ActualValue = res[0].aqfndjyjhwcl,
};
r.Add(a8);
object a9 = new
{
id = res[0].Id,
zdm = "sbfsjcjhwcl",
zblx = "KPI",
zbname = "设备腐蚀监测计划完成率",
ndmbz = "1",
ljz = res[0].sbfsjcjhwcl,
ActualValue = res[0].sbfsjcjhwcl,
};
r.Add(a9);
object a10 = new
{
id = res[0].Id,
zdm = "jsbjwxychgl",
zblx = "KPI",
zbname = "静设备检维修一次合格率",
ndmbz = ">99%",
ljz = res[0].jsbjwxychgl,
ActualValue = res[0].jsbjwxychgl,
};
r.Add(a10);
return r;
}
else
{
return r;
}
}
else if ((chaxunmethod == "全厂" && rolename.Contains("管理员")) || (chaxunmethod == "车间" && rolename.Contains("片区长")))
{
//再次判断管理员和片区长的查询位置
//首先利用ifqc判断管理员是查询数据库还是计算查询
bool ifqc = Jx1.GetifJingQc(zy, astime, aetime);//如果表中存在超级用户已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (chaxunmethod == "全厂" && ifqc)
{//表中存在超级用户已经提报的全厂的数据,就在数据库中去查
List<A15dot1TabJing> res = Jx1.GetJingJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "sbfsxlcs",
zblx = "KPI",
zbname = "设备腐蚀泄漏次数(有毒有害易燃易爆介质)",
ndmbz = "≤28次",
ljz = res[0].sbfsxlcs,
ActualValue = res[0].sbfsxlcs,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "qtlhsbgs",
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = res[0].qtlhsbgs,
ActualValue = res[0].qtlhsbgs,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "gylpjrxl",
zblx = "KPI",
zbname = "工业炉(≥10MW)平均热效率",
ndmbz = "≥92.2%",
ljz = res[0].gylpjrxl,
ActualValue = res[0].gylpjrxl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "hrqjxl",
zblx = "KPI",
zbname = "换热器检修率",
ndmbz = "<2%",
ljz = res[0].hrqjxl,
ActualValue = res[0].hrqjxl,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "ylrqdjl",
zblx = "KPI",
zbname = "压力容器定检率",
ndmbz = "1",
ljz = res[0].ylrqdjl,
ActualValue = res[0].ylrqdjl,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "ylgdndjxjhwcl",
zblx = "KPI",
zbname = "压力管道年度检验计划完成率",
ndmbz = "1",
ljz = res[0].ylgdndjxjhwcl,
ActualValue = res[0].ylgdndjxjhwcl,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "aqfndjyjhwcl",
zblx = "KPI",
zbname = "安全阀年度校验计划完成率",
ndmbz = "1",
ljz = res[0].aqfndjyjhwcl,
ActualValue = res[0].aqfndjyjhwcl,
};
r.Add(a8);
object a9 = new
{
id = res[0].Id,
zdm = "sbfsjcjhwcl",
zblx = "KPI",
zbname = "设备腐蚀监测计划完成率",
ndmbz = "1",
ljz = res[0].sbfsjcjhwcl,
ActualValue = res[0].sbfsjcjhwcl,
};
r.Add(a9);
object a10 = new
{
id = res[0].Id,
zdm = "jsbjwxychgl",
zblx = "KPI",
zbname = "静设备检维修一次合格率",
ndmbz = ">99%",
ljz = res[0].jsbjwxychgl,
ActualValue = res[0].jsbjwxychgl,
};
r.Add(a10);
return r;
}
else
{
return r;//数据库没有查到表
}
}
else if (chaxunmethod == "全厂")
{
var qc = Jx1.GetJingQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
if (qc.Count == 10)
{
object a1 = new
{
id = 0,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4",
ljz = qc_list[0].ToString(),
ActualValue = qc_list[0].ToString(),
};
r.Add(a1);
object a2 = new
{
id = 0,
zdm = "sbfsxlcs",
zblx = "KPI",
zbname = "设备腐蚀泄漏次数(有毒有害易燃易爆介质)",
ndmbz = "≤28次",
ljz = qc_list[1].ToString(),
ActualValue = qc_list[1].ToString(),
};
r.Add(a2);
object a3 = new
{
id = 0,
zdm = "qtlhsbgs",
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = qc_list[2].ToString(),
ActualValue = qc_list[2].ToString(),
};
r.Add(a3);
object a4 = new
{
id = 0,
zdm = "gylpjrxl",
zblx = "KPI",
zbname = "工业炉(≥10MW)平均热效率",
ndmbz = "≥92.2%",
ljz = qc_list[3].ToString(),
ActualValue = qc_list[3].ToString(),
};
r.Add(a4);
object a5 = new
{
id = 0,
zdm = "hrqjxl",
zblx = "KPI",
zbname = "换热器检修率",
ndmbz = "<2%",
ljz = qc_list[4].ToString(),
ActualValue = qc_list[4].ToString(),
};
r.Add(a5);
object a6 = new
{
id = 0,
zdm = "ylrqdjl",
zblx = "KPI",
zbname = "压力容器定检率",
ndmbz = "1",
ljz = qc_list[5].ToString(),
ActualValue = qc_list[5].ToString(),
};
r.Add(a6);
object a7 = new
{
id = 0,
zdm = "ylgdndjxjhwcl",
zblx = "KPI",
zbname = "压力管道年度检验计划完成率",
ndmbz = "1",
ljz = qc_list[6].ToString(),
ActualValue = qc_list[6].ToString(),
};
r.Add(a7);
object a8 = new
{
id = 0,
zdm = "aqfndjyjhwcl",
zblx = "KPI",
zbname = "安全阀年度校验计划完成率",
ndmbz = "1",
ljz = qc_list[7].ToString(),
ActualValue = qc_list[7].ToString(),
};
r.Add(a8);
object a9 = new
{
id = 0,
zdm = "sbfsjcjhwcl",
zblx = "KPI",
zbname = "设备腐蚀监测计划完成率",
ndmbz = "1",
ljz = qc_list[8].ToString(),
ActualValue = qc_list[8].ToString(),
};
r.Add(a9);
object a10 = new
{
id = 0,
zdm = "jsbjwxychgl",
zblx = "KPI",
zbname = "静设备检维修一次合格率",
ndmbz = ">99%",
ljz = qc_list[9].ToString(),
ActualValue = qc_list[9].ToString(),
};
r.Add(a10);
return r;
}
else
{
return r;//有人没有提报装置,计算不到数据
}
}
else if (chaxunmethod == "车间")
{
bool ifcj = Jx1.GetifJingCj(cjname,zy, astime, aetime);//如果表中存在片区长已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (ifcj)
{
List<A15dot1TabJing> res = Jx1.GetJingJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "sbfsxlcs",
zblx = "KPI",
zbname = "设备腐蚀泄漏次数(有毒有害易燃易爆介质)",
ndmbz = "≤28次",
ljz = res[0].sbfsxlcs,
ActualValue = res[0].sbfsxlcs,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "qtlhsbgs",
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = res[0].qtlhsbgs,
ActualValue = res[0].qtlhsbgs,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "gylpjrxl",
zblx = "KPI",
zbname = "工业炉(≥10MW)平均热效率",
ndmbz = "≥92.2%",
ljz = res[0].gylpjrxl,
ActualValue = res[0].gylpjrxl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "hrqjxl",
zblx = "KPI",
zbname = "换热器检修率",
ndmbz = "<2%",
ljz = res[0].hrqjxl,
ActualValue = res[0].hrqjxl,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "ylrqdjl",
zblx = "KPI",
zbname = "压力容器定检率",
ndmbz = "1",
ljz = res[0].ylrqdjl,
ActualValue = res[0].ylrqdjl,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "ylgdndjxjhwcl",
zblx = "KPI",
zbname = "压力管道年度检验计划完成率",
ndmbz = "1",
ljz = res[0].ylgdndjxjhwcl,
ActualValue = res[0].ylgdndjxjhwcl,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "aqfndjyjhwcl",
zblx = "KPI",
zbname = "安全阀年度校验计划完成率",
ndmbz = "1",
ljz = res[0].aqfndjyjhwcl,
ActualValue = res[0].aqfndjyjhwcl,
};
r.Add(a8);
object a9 = new
{
id = res[0].Id,
zdm = "sbfsjcjhwcl",
zblx = "KPI",
zbname = "设备腐蚀监测计划完成率",
ndmbz = "1",
ljz = res[0].sbfsjcjhwcl,
ActualValue = res[0].sbfsjcjhwcl,
};
r.Add(a9);
object a10 = new
{
id = res[0].Id,
zdm = "jsbjwxychgl",
zblx = "KPI",
zbname = "静设备检维修一次合格率",
ndmbz = ">99%",
ljz = res[0].jsbjwxychgl,
ActualValue = res[0].jsbjwxychgl,
};
r.Add(a10);
return r;
}
else
{
return r;
}
}
else //表中没有数据则直接计算权重
{
var qc = Jx1.GetCjJing(zy, cjname, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
object a1 = new
{
id = 0,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4",
ljz = qc_list[0].ToString(),
ActualValue = qc_list[0].ToString(),
};
r.Add(a1);
object a2 = new
{
id = 0,
zdm = "sbfsxlcs",
zblx = "KPI",
zbname = "设备腐蚀泄漏次数(有毒有害易燃易爆介质)",
ndmbz = "≤28次",
ljz = qc_list[1].ToString(),
ActualValue = qc_list[1].ToString(),
};
r.Add(a2);
object a3 = new
{
id = 0,
zdm = "qtlhsbgs",
zblx = "KPI",
zbname = "千台冷换设备管束(含整台)更换率",
ndmbz = "≤30‰",
ljz = qc_list[2].ToString(),
ActualValue = qc_list[2].ToString(),
};
r.Add(a3);
object a4 = new
{
id = 0,
zdm = "gylpjrxl",
zblx = "KPI",
zbname = "工业炉(≥10MW)平均热效率",
ndmbz = "≥92.2%",
ljz = qc_list[3].ToString(),
ActualValue = qc_list[3].ToString(),
};
r.Add(a4);
object a5 = new
{
id = 0,
zdm = "hrqjxl",
zblx = "KPI",
zbname = "换热器检修率",
ndmbz = "<2%",
ljz = qc_list[4].ToString(),
ActualValue = qc_list[4].ToString(),
};
r.Add(a5);
object a6 = new
{
id = 0,
zdm = "ylrqdjl",
zblx = "KPI",
zbname = "压力容器定检率",
ndmbz = "1",
ljz = qc_list[5].ToString(),
ActualValue = qc_list[5].ToString(),
};
r.Add(a6);
object a7 = new
{
id = 0,
zdm = "ylgdndjxjhwcl",
zblx = "KPI",
zbname = "压力管道年度检验计划完成率",
ndmbz = "1",
ljz = qc_list[6].ToString(),
ActualValue = qc_list[6].ToString(),
};
r.Add(a7);
object a8 = new
{
id = 0,
zdm = "aqfndjyjhwcl",
zblx = "KPI",
zbname = "安全阀年度校验计划完成率",
ndmbz = "1",
ljz = qc_list[7].ToString(),
ActualValue = qc_list[7].ToString(),
};
r.Add(a8);
object a9 = new
{
id = 0,
zdm = "sbfsjcjhwcl",
zblx = "KPI",
zbname = "设备腐蚀监测计划完成率",
ndmbz = "1",
ljz = qc_list[8].ToString(),
ActualValue = qc_list[8].ToString(),
};
r.Add(a9);
object a10 = new
{
id = 0,
zdm = "jsbjwxychgl",
zblx = "KPI",
zbname = "静设备检维修一次合格率",
ndmbz = ">99%",
ljz = qc_list[9].ToString(),
ActualValue = qc_list[9].ToString(),
};
r.Add(a10);
return r;
}
}
}
return r;
}
public List<object> getObjectDian(string time, string zzid, string zy, string cjname, string chaxunmethod)
{
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
string rolename = pv.Role_Names;//获得角色名
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;//获得用户名
List<object> r = new List<object>();
EquipManagment em = new EquipManagment();
if (chaxunmethod == "全厂")
{
zzid = "全厂";//如果查询方式是全厂
}
else if (chaxunmethod == "装置")
{
zzid = em.getEa_namebyid(Convert.ToInt32(zzid));//如果查询方式是装置将zzid转换为装置的名字
}
else if (chaxunmethod == "车间")
{
zzid = cjname;
}
DateTime Cxtime = DateTime.Now;
string stime;
string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if ((chaxunmethod == "全厂" && !rolename.Contains("管理员")) || (chaxunmethod == "装置") || (chaxunmethod == "车间") && !rolename.Contains("片区长"))
{
List<A15dot1TabDian> res = Jx1.GetDianJxByA2(astime, aetime, zzid, zy);//直接在数据库中查询
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤60分",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "dqwczcs",
zblx = "KPI",
zbname = "电气误操作次数",
ndmbz = "0",
ljz = res[0].dqwczcs,
ActualValue = res[0].dqwczcs,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "jdbhzqdzl",
zblx = "KPI",
zbname = "继电保护正确动作率",
ndmbz = "100%",
ljz = res[0].jdbhzqdzl,
ActualValue = res[0].jdbhzqdzl,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "sbgzl",
zblx = "KPI",
zbname = "设备故障率",
ndmbz = "",
ljz = res[0].sbgzl,
ActualValue = res[0].sbgzl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "djMTBF",
zblx = "KPI",
zbname = "电机MTBF",
ndmbz = "240",
ljz = res[0].djMTBF,
ActualValue = res[0].djMTBF,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "dzdlsbMTBF",
zblx = "KPI",
zbname = "电力电子设备MTBF",
ndmbz = "180",
ljz = res[0].dzdlsbMTBF,
ActualValue = res[0].dzdlsbMTBF,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "zbglys",
zblx = "KPI",
zbname = "主变功率因素",
ndmbz = "",
ljz = res[0].zbglys,
ActualValue = res[0].zbglys,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "dnjlphl",
zblx = "KPI",
zbname = "电能计量平衡率",
ndmbz = "≥99.8%",
ljz = res[0].dnjlphl,
ActualValue = res[0].dnjlphl,
};
r.Add(a8);
return r;
}
else
{
return r;
}
}
else if ((chaxunmethod == "全厂" && rolename.Contains("管理员")) || (chaxunmethod == "车间" && rolename.Contains("片区长")))
{
//再次判断管理员和片区长的查询位置
//首先利用ifqc判断管理员是查询数据库还是计算查询
bool ifqc = Jx1.GetifDianQc(zy, astime, aetime);//如果表中存在超级用户已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (chaxunmethod == "全厂" && ifqc)
{//表中存在超级用户已经提报的全厂的数据,就在数据库中去查
List<A15dot1TabDian> res = Jx1.GetDianJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤60分",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "dqwczcs",
zblx = "KPI",
zbname = "电气误操作次数",
ndmbz = "0",
ljz = res[0].dqwczcs,
ActualValue = res[0].dqwczcs,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "jdbhzqdzl",
zblx = "KPI",
zbname = "继电保护正确动作率",
ndmbz = "100%",
ljz = res[0].jdbhzqdzl,
ActualValue = res[0].jdbhzqdzl,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "sbgzl",
zblx = "KPI",
zbname = "设备故障率",
ndmbz = "",
ljz = res[0].sbgzl,
ActualValue = res[0].sbgzl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "djMTBF",
zblx = "KPI",
zbname = "电机MTBF",
ndmbz = "240",
ljz = res[0].djMTBF,
ActualValue = res[0].djMTBF,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "dzdlsbMTBF",
zblx = "KPI",
zbname = "电力电子设备MTBF",
ndmbz = "180",
ljz = res[0].dzdlsbMTBF,
ActualValue = res[0].dzdlsbMTBF,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "zbglys",
zblx = "KPI",
zbname = "主变功率因素",
ndmbz = "",
ljz = res[0].zbglys,
ActualValue = res[0].zbglys,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "dnjlphl",
zblx = "KPI",
zbname = "电能计量平衡率",
ndmbz = "≥99.8%",
ljz = res[0].dnjlphl,
ActualValue = res[0].dnjlphl,
};
r.Add(a8);
return r;
}
else
{
return r;//数据库没有查到表
}
}
else if (chaxunmethod == "全厂")
{
var qc = Jx1.GetDianQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
if (qc.Count == 5)
{
object a1 = new
{
//id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤60分",
ljz = qc_list[0],
ActualValue = qc_list[0],
};
r.Add(a1);
object a2 = new
{
// id = res[0].Id,
zdm = "dqwczcs",
zblx = "KPI",
zbname = "电气误操作次数",
ndmbz = "0",
ljz = qc_list[1],
ActualValue = qc_list[1],
};
r.Add(a2);
object a3 = new
{
// id = res[0].Id,
zdm = "jdbhzqdzl",
zblx = "KPI",
zbname = "继电保护正确动作率",
ndmbz = "100%",
ljz = qc_list[2],
ActualValue = qc_list[2],
};
r.Add(a3);
object a4 = new
{
// id = res[0].Id,
zdm = "sbgzl",
zblx = "KPI",
zbname = "设备故障率",
ndmbz = "",
ljz = qc_list[3],
ActualValue = qc_list[3],
};
r.Add(a4);
object a5 = new
{
//id = res[0].Id,
zdm = "djMTBF",
zblx = "KPI",
zbname = "电机MTBF",
ndmbz = "240",
ljz = qc_list[4],
ActualValue = qc_list[4],
};
r.Add(a5);
object a6 = new
{
// id = res[0].Id,
zdm = "dzdlsbMTBF",
zblx = "KPI",
zbname = "电力电子设备MTBF",
ndmbz = "180",
ljz = "",
ActualValue = "请人为填写",
};
r.Add(a6);
object a7 = new
{
// id = res[0].Id,
zdm = "zbglys",
zblx = "KPI",
zbname = "主变功率因素",
ndmbz = "",
ljz = "",
ActualValue = "请人为填写",
};
r.Add(a7);
object a8 = new
{
// id = res[0].Id,
zdm = "dnjlphl",
zblx = "KPI",
zbname = "电能计量平衡率",
ndmbz = "≥99.8%",
ljz = "",
ActualValue = "请人为填写",
};
r.Add(a8);
return r;
}
else
{
return r;//有人没有提报装置,计算不到数据
}
}
else if (chaxunmethod == "车间")
{
bool ifcj = Jx1.GetifDianCj(cjname,zy, astime, aetime);//如果表中存在片区长已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (ifcj)
{
List<A15dot1TabDian> res = Jx1.GetDianJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤60分",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "dqwczcs",
zblx = "KPI",
zbname = "电气误操作次数",
ndmbz = "0",
ljz = res[0].dqwczcs,
ActualValue = res[0].dqwczcs,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "jdbhzqdzl",
zblx = "KPI",
zbname = "继电保护正确动作率",
ndmbz = "100%",
ljz = res[0].jdbhzqdzl,
ActualValue = res[0].jdbhzqdzl,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "sbgzl",
zblx = "KPI",
zbname = "设备故障率",
ndmbz = "",
ljz = res[0].sbgzl,
ActualValue = res[0].sbgzl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "djMTBF",
zblx = "KPI",
zbname = "电机MTBF",
ndmbz = "240",
ljz = res[0].djMTBF,
ActualValue = res[0].djMTBF,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "dzdlsbMTBF",
zblx = "KPI",
zbname = "电力电子设备MTBF",
ndmbz = "180",
ljz = res[0].dzdlsbMTBF,
ActualValue = res[0].dzdlsbMTBF,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "zbglys",
zblx = "KPI",
zbname = "主变功率因素",
ndmbz = "",
ljz = res[0].zbglys,
ActualValue = res[0].zbglys,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "dnjlphl",
zblx = "KPI",
zbname = "电能计量平衡率",
ndmbz = "≥99.8%",
ljz = res[0].dnjlphl,
ActualValue = res[0].dnjlphl,
};
r.Add(a8);
return r;
}
else
{
return r;
}
}
else //库中没有数据则直接计算车间权重
{
var qc = Jx1.GetDianQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
object a1 = new
{
//id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤60分",
ljz = qc_list[0],
ActualValue = qc_list[0],
};
r.Add(a1);
object a2 = new
{
// id = res[0].Id,
zdm = "dqwczcs",
zblx = "KPI",
zbname = "电气误操作次数",
ndmbz = "0",
ljz = qc_list[1],
ActualValue = qc_list[1],
};
r.Add(a2);
object a3 = new
{
// id = res[0].Id,
zdm = "jdbhzqdzl",
zblx = "KPI",
zbname = "继电保护正确动作率",
ndmbz = "100%",
ljz = qc_list[2],
ActualValue = qc_list[2],
};
r.Add(a3);
object a4 = new
{
// id = res[0].Id,
zdm = "sbgzl",
zblx = "KPI",
zbname = "设备故障率",
ndmbz = "",
ljz = qc_list[3],
ActualValue = qc_list[3],
};
r.Add(a4);
object a5 = new
{
//id = res[0].Id,
zdm = "djMTBF",
zblx = "KPI",
zbname = "电机MTBF",
ndmbz = "240",
ljz = qc_list[4],
ActualValue = qc_list[4],
};
r.Add(a5);
object a6 = new
{
// id = res[0].Id,
zdm = "dzdlsbMTBF",
zblx = "KPI",
zbname = "电力电子设备MTBF",
ndmbz = "180",
ljz = "",
ActualValue = "请人为填写",
};
r.Add(a6);
object a7 = new
{
// id = res[0].Id,
zdm = "zbglys",
zblx = "KPI",
zbname = "主变功率因素",
ndmbz = "",
ljz = "",
ActualValue = "请人为填写",
};
r.Add(a7);
object a8 = new
{
// id = res[0].Id,
zdm = "dnjlphl",
zblx = "KPI",
zbname = "电能计量平衡率",
ndmbz = "≥99.8%",
ljz = "",
ActualValue = "请人为填写",
};
r.Add(a8);
return r;
}
}
}
return r;
}
public List<object> getObjectYi(string time, string zzid, string zy, string cjname, string chaxunmethod)
{
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
string rolename = pv.Role_Names;//获得角色名
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;//获得用户名
List<object> r = new List<object>();
EquipManagment em = new EquipManagment();
if (chaxunmethod == "全厂")
{
zzid = "全厂";//如果查询方式是全厂
}
else if (chaxunmethod == "装置")
{
zzid = em.getEa_namebyid(Convert.ToInt32(zzid));//如果查询方式是装置将zzid转换为装置的名字
}
else if (chaxunmethod == "车间")
{
zzid = cjname;
}
DateTime Cxtime = DateTime.Now;
string stime;
string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if ((chaxunmethod == "全厂" && !rolename.Contains("管理员")) || (chaxunmethod == "装置") || (chaxunmethod == "车间") && !rolename.Contains("片区长"))
{
List<A15dot1TabYi> res = Jx1.GetYiJxByA2(astime, aetime, zzid, zy);//直接在数据库中查询
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4/50分",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "lsxtzqdzl",
zblx = "KPI",
zbname = "联锁系统正确动作率",
ndmbz = "≥99.8%",
ljz = res[0].lsxtzqdzl,
ActualValue = res[0].lsxtzqdzl,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "kzxtgzcs",
zblx = "KPI",
zbname = "控制系统故障次数",
ndmbz = "≤2",
ljz = res[0].kzxtgzcs,
ActualValue = res[0].kzxtgzcs,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "ybkzl",
zblx = "KPI",
zbname = "仪表控制率",
ndmbz = "0.99",
ljz = res[0].ybkzl,
ActualValue = res[0].ybkzl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "ybsjkzl",
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = res[0].ybsjkzl,
ActualValue = res[0].ybsjkzl,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "lsxttyl",
zblx = "KPI",
zbname = "联锁系统投用率",
ndmbz = "1",
ljz = res[0].lsxttyl,
ActualValue = res[0].lsxttyl,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "gjkzfmgzcs",
zblx = "KPI",
zbname = "关键控制阀门故障次数",
ndmbz = "3",
ljz = res[0].gjkzfmgzcs,
ActualValue = res[0].gjkzfmgzcs,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "kzxtgzbjcs",
zblx = "KPI",
zbname = "控制系统故障报警次数",
ndmbz = "25",
ljz = res[0].kzxtgzbjcs,
ActualValue = res[0].kzxtgzbjcs,
};
r.Add(a8);
object a9 = new
{
id = res[0].Id,
zdm = "cgybgzl",
zblx = "KPI",
zbname = "常规仪表故障率",
ndmbz = "≤1‰",
ljz = res[0].cgybgzl,
ActualValue = res[0].cgybgzl,
};
r.Add(a9);
object a10 = new
{
id = res[0].Id,
zdm = "tjfMDBF",
zblx = "KPI",
zbname = "调节阀MTBF",
ndmbz = "200",
ljz = res[0].tjfMDBF,
ActualValue = res[0].tjfMDBF,
};
r.Add(a10);
return r;
}
else
{
return r;
}
}
else if ((chaxunmethod == "全厂" && rolename.Contains("管理员")) || (chaxunmethod == "车间" && rolename.Contains("片区长")))
{
//再次判断管理员和片区长的查询位置
//首先利用ifqc判断管理员是查询数据库还是计算查询
bool ifqc = Jx1.GetifYiQc(zy, astime, aetime);//如果表中存在超级用户已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (chaxunmethod == "全厂" && ifqc)
{//表中存在超级用户已经提报的全厂的数据,就在数据库中去查
List<A15dot1TabYi> res = Jx1.GetYiJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4/50分",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "lsxtzqdzl",
zblx = "KPI",
zbname = "联锁系统正确动作率",
ndmbz = "≥99.8%",
ljz = res[0].lsxtzqdzl,
ActualValue = res[0].lsxtzqdzl,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "kzxtgzcs",
zblx = "KPI",
zbname = "控制系统故障次数",
ndmbz = "≤2",
ljz = res[0].kzxtgzcs,
ActualValue = res[0].kzxtgzcs,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "ybkzl",
zblx = "KPI",
zbname = "仪表控制率",
ndmbz = "0.99",
ljz = res[0].ybkzl,
ActualValue = res[0].ybkzl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "ybsjkzl",
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = res[0].ybsjkzl,
ActualValue = res[0].ybsjkzl,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "lsxttyl",
zblx = "KPI",
zbname = "联锁系统投用率",
ndmbz = "1",
ljz = res[0].lsxttyl,
ActualValue = res[0].lsxttyl,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "gjkzfmgzcs",
zblx = "KPI",
zbname = "关键控制阀门故障次数",
ndmbz = "3",
ljz = res[0].gjkzfmgzcs,
ActualValue = res[0].gjkzfmgzcs,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "kzxtgzbjcs",
zblx = "KPI",
zbname = "控制系统故障报警次数",
ndmbz = "25",
ljz = res[0].kzxtgzbjcs,
ActualValue = res[0].kzxtgzbjcs,
};
r.Add(a8);
object a9 = new
{
id = res[0].Id,
zdm = "cgybgzl",
zblx = "KPI",
zbname = "常规仪表故障率",
ndmbz = "≤1‰",
ljz = res[0].cgybgzl,
ActualValue = res[0].cgybgzl,
};
r.Add(a9);
object a10 = new
{
id = res[0].Id,
zdm = "tjfMDBF",
zblx = "KPI",
zbname = "调节阀MTBF",
ndmbz = "200",
ljz = res[0].tjfMDBF,
ActualValue = res[0].tjfMDBF,
};
r.Add(a10);
return r;
}
else
{
return r;//数据库没有查到表
}
}
else if (chaxunmethod == "全厂")
{
var qc = Jx1.GetYiQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
if (qc.Count == 10)
{
object a1 = new
{
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4/50分",
ljz = qc_list[0].ToString(),
id = "0",
ActualValue = qc_list[0].ToString(),
};
r.Add(a1);
object a2 = new
{
id = "0",
zdm = "lsxtzqdzl",
zblx = "KPI",
zbname = "联锁系统正确动作率",
// id = res[0].Id,
ndmbz = "≥99.8%",
ljz = qc_list[1].ToString(),
//id = res[0].Id,
ActualValue = qc_list[1].ToString(),
};
r.Add(a2);
object a3 = new
{
id = "0",
zdm = "kzxtgzcs",
// id = res[0].Id,
zblx = "KPI",
zbname = "控制系统故障次数",
ndmbz = "≤2",
ljz = qc_list[2].ToString(),
//id = res[0].Id,
ActualValue = qc_list[2].ToString(),
};
r.Add(a3);
object a4 = new
{
id = "0",
zdm = "ybkzl",
// id = res[3].Id,
zblx = "KPI",
zbname = "仪表控制率",
ndmbz = "0.99",
ljz = qc_list[3].ToString(),
//id = res[0].Id,
ActualValue = qc_list[3].ToString(),
};
r.Add(a4);
object a5 = new
{
id = "0",
zdm = "ybsjkzl",
// id = res[0].Id,
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = qc_list[4].ToString(),
//id = res[0].Id,
ActualValue = qc_list[4].ToString(),
};
r.Add(a5);
object a6 = new
{
id = "0",
zdm = "lsxttyl",
//id = res[0].Id,
zblx = "KPI",
zbname = "联锁系统投用率",
ndmbz = "1",
ljz = qc_list[5].ToString(),
//id = res[0].Id,
ActualValue = qc_list[5].ToString(),
};
r.Add(a6);
object a7 = new
{
id = "0",
zdm = "gjkzfmgzcs",
//id = res[0].Id,
zblx = "KPI",
zbname = "关键控制阀门故障次数",
ndmbz = "3",
ljz = qc_list[6].ToString(),
//id = res[0].Id,
ActualValue = qc_list[6].ToString(),
};
r.Add(a7);
object a8 = new
{
id = "0",
zdm = "kzxtgzbjcs",
// id = res[0].Id,
zblx = "KPI",
zbname = "控制系统故障报警次数",
ndmbz = "25",
ljz = qc_list[7].ToString(),
//id = res[0].Id,
ActualValue = qc_list[7].ToString(),
};
r.Add(a8);
object a9 = new
{
id = "0",
zdm = "cgybgzl",
// id = res[0].Id,
zblx = "KPI",
zbname = "常规仪表故障率",
ndmbz = "≤1‰",
ljz = qc_list[8].ToString(),
//id = res[0].Id,
ActualValue = qc_list[8].ToString(),
};
r.Add(a9);
object a10 = new
{
id = "0",
zdm = "tjfMDBF",
// id = res[0].Id,
zblx = "KPI",
zbname = "调节阀MTBF",
ndmbz = "200",
ljz = qc_list[9].ToString(),
//id = res[0].Id,
ActualValue = qc_list[9].ToString(),
};
r.Add(a10);
return r;
}
else
{
return r;//有人没有提报装置,计算不到数据
}
}
else if (chaxunmethod == "车间")
{
bool ifcj = Jx1.GetifYiCj(cjname,zy, astime, aetime);//如果表中存在片区长已经提报的全厂的数据,就在数据库中去查,否则计算显示.
if (ifcj)
{
List<A15dot1TabYi> res = Jx1.GetYiJxByA2(astime, aetime, zzid, zy);
if (res.Count != 0)
{
object a1 = new
{
id = res[0].Id,
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4/50分",
ljz = res[0].gzqdkf,
ActualValue = res[0].gzqdkf,
};
r.Add(a1);
object a2 = new
{
id = res[0].Id,
zdm = "lsxtzqdzl",
zblx = "KPI",
zbname = "联锁系统正确动作率",
ndmbz = "≥99.8%",
ljz = res[0].lsxtzqdzl,
ActualValue = res[0].lsxtzqdzl,
};
r.Add(a2);
object a3 = new
{
id = res[0].Id,
zdm = "kzxtgzcs",
zblx = "KPI",
zbname = "控制系统故障次数",
ndmbz = "≤2",
ljz = res[0].kzxtgzcs,
ActualValue = res[0].kzxtgzcs,
};
r.Add(a3);
object a4 = new
{
id = res[0].Id,
zdm = "ybkzl",
zblx = "KPI",
zbname = "仪表控制率",
ndmbz = "0.99",
ljz = res[0].ybkzl,
ActualValue = res[0].ybkzl,
};
r.Add(a4);
object a5 = new
{
id = res[0].Id,
zdm = "ybsjkzl",
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = res[0].ybsjkzl,
ActualValue = res[0].ybsjkzl,
};
r.Add(a5);
object a6 = new
{
id = res[0].Id,
zdm = "lsxttyl",
zblx = "KPI",
zbname = "联锁系统投用率",
ndmbz = "1",
ljz = res[0].lsxttyl,
ActualValue = res[0].lsxttyl,
};
r.Add(a6);
object a7 = new
{
id = res[0].Id,
zdm = "gjkzfmgzcs",
zblx = "KPI",
zbname = "关键控制阀门故障次数",
ndmbz = "3",
ljz = res[0].gjkzfmgzcs,
ActualValue = res[0].gjkzfmgzcs,
};
r.Add(a7);
object a8 = new
{
id = res[0].Id,
zdm = "kzxtgzbjcs",
zblx = "KPI",
zbname = "控制系统故障报警次数",
ndmbz = "25",
ljz = res[0].kzxtgzbjcs,
ActualValue = res[0].kzxtgzbjcs,
};
r.Add(a8);
object a9 = new
{
id = res[0].Id,
zdm = "cgybgzl",
zblx = "KPI",
zbname = "常规仪表故障率",
ndmbz = "≤1‰",
ljz = res[0].cgybgzl,
ActualValue = res[0].cgybgzl,
};
r.Add(a9);
object a10 = new
{
id = res[0].Id,
zdm = "tjfMDBF",
zblx = "KPI",
zbname = "调节阀MTBF",
ndmbz = "200",
ljz = res[0].tjfMDBF,
ActualValue = res[0].tjfMDBF,
};
r.Add(a10);
return r;
}
else
{
return r;
}
}
else //如果在库中未查到数据则直接计算车间权重
{
var qc = Jx1.GetYiQc(zy, astime, aetime);//计算的方式获得企业全厂的数据
List<string> qc_list = new List<string>();
foreach (var i in qc)
{
if (i == null)
qc_list.Add("当月无装置提报该kpi");//如果全厂在数据库中没有值,qc_list赋值为空字符串
else
qc_list.Add(i.ToString());
}
object a1 = new
{
zdm = "gzqdkf",
zblx = "KPI",
zbname = "故障强度扣分",
ndmbz = "≤4/50分",
ljz = qc_list[0].ToString(),
id = "0",
ActualValue = qc_list[0].ToString(),
};
r.Add(a1);
object a2 = new
{
id = "0",
zdm = "lsxtzqdzl",
zblx = "KPI",
zbname = "联锁系统正确动作率",
// id = res[0].Id,
ndmbz = "≥99.8%",
ljz = qc_list[1].ToString(),
//id = res[0].Id,
ActualValue = qc_list[1].ToString(),
};
r.Add(a2);
object a3 = new
{
id = "0",
zdm = "kzxtgzcs",
// id = res[0].Id,
zblx = "KPI",
zbname = "控制系统故障次数",
ndmbz = "≤2",
ljz = qc_list[2].ToString(),
//id = res[0].Id,
ActualValue = qc_list[2].ToString(),
};
r.Add(a3);
object a4 = new
{
id = "0",
zdm = "ybkzl",
// id = res[3].Id,
zblx = "KPI",
zbname = "仪表控制率",
ndmbz = "0.99",
ljz = qc_list[3].ToString(),
//id = res[0].Id,
ActualValue = qc_list[3].ToString(),
};
r.Add(a4);
object a5 = new
{
id = "0",
zdm = "ybsjkzl",
// id = res[0].Id,
zblx = "KPI",
zbname = "仪表实际控制率",
ndmbz = "0.93",
ljz = qc_list[4].ToString(),
//id = res[0].Id,
ActualValue = qc_list[4].ToString(),
};
r.Add(a5);
object a6 = new
{
id = "0",
zdm = "lsxttyl",
//id = res[0].Id,
zblx = "KPI",
zbname = "联锁系统投用率",
ndmbz = "1",
ljz = qc_list[5].ToString(),
//id = res[0].Id,
ActualValue = qc_list[5].ToString(),
};
r.Add(a6);
object a7 = new
{
id = "0",
zdm = "gjkzfmgzcs",
//id = res[0].Id,
zblx = "KPI",
zbname = "关键控制阀门故障次数",
ndmbz = "3",
ljz = qc_list[6].ToString(),
//id = res[0].Id,
ActualValue = qc_list[6].ToString(),
};
r.Add(a7);
object a8 = new
{
id = "0",
zdm = "kzxtgzbjcs",
// id = res[0].Id,
zblx = "KPI",
zbname = "控制系统故障报警次数",
ndmbz = "25",
ljz = qc_list[7].ToString(),
//id = res[0].Id,
ActualValue = qc_list[7].ToString(),
};
r.Add(a8);
object a9 = new
{
id = "0",
zdm = "cgybgzl",
// id = res[0].Id,
zblx = "KPI",
zbname = "常规仪表故障率",
ndmbz = "≤1‰",
ljz = qc_list[8].ToString(),
//id = res[0].Id,
ActualValue = qc_list[8].ToString(),
};
r.Add(a9);
object a10 = new
{
id = "0",
zdm = "tjfMDBF",
// id = res[0].Id,
zblx = "KPI",
zbname = "调节阀MTBF",
ndmbz = "200",
ljz = qc_list[9].ToString(),
//id = res[0].Id,
ActualValue = qc_list[9].ToString(),
};
r.Add(a10);
return r;
}
}
}
return r;
}
//public bool ModifyQiYe(string json1)
//{
// JObject item = (JObject)JsonConvert.DeserializeObject(json1);
// A15dot1TabQiYe new_15dot1qiye = new A15dot1TabQiYe();
// bool res=false;
// if(Convert.ToString(item["zzId"])=="全厂")
// {//管理员对于全厂的修改的保存
// DateTime Cxtime = DateTime.Now;
// string time=item["month"].ToString();
// string stime;
// string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
// if (Convert.ToInt32(time) > 1)
// {
// string Reducetime = (Convert.ToInt32(time) - 1).ToString();
// etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
// stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
// }
// else
// {
// string Addtime = (Convert.ToInt32(time) + 1).ToString();
// stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
// etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
// }
// DateTime astime = Convert.ToDateTime(stime);
// DateTime aetime = Convert.ToDateTime(etime);
// new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
// new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
// new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
// new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
// new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
// double a = Convert.ToDouble(item["eventNumber"].ToString().Trim());
// new_15dot1qiye.sjs = Convert.ToInt16(a);
// double b = Convert.ToDouble(item["troubleKoufen"].ToString().Trim());
// new_15dot1qiye.gzqdkf = Convert.ToInt32(b);
// new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
// new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
// new_15dot1qiye.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1qiye.temp3 = Convert.ToString(item["cjname"]);//车间名字存于temp3
// new_15dot1qiye.temp2 = "企业级";//专业名字存于temp2
// new_15dot1qiye.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// new_15dot1qiye.submitTime = DateTime.Now;
// res = Jx1.ModifyQcQyJxItem(new_15dot1qiye, astime, aetime);
// }
// else
// {//管理员对于装置的更改的保存
// new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
// new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
// new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
// new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
// new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
// new_15dot1qiye.sjs = Convert.ToInt32(item["eventNumber"]);
// new_15dot1qiye.Id = Convert.ToInt32(item["kpiid"]);
// new_15dot1qiye.gzqdkf = Convert.ToInt32(item["troubleKoufen"]);
// new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
// new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
// new_15dot1qiye.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1qiye.temp3 = Convert.ToString(item["cjname"]);//车间名字存于temp3
// new_15dot1qiye.temp2 = "企业级";//专业名字存于temp2
// res = Jx1.ModifyJxItem(new_15dot1qiye);
// }
// return res;
//}
//public bool ModifyDong(string json1)
//{
// JObject item = (JObject)JsonConvert.DeserializeObject(json1);
// A15dot1TabDong new_15dot1dong = new A15dot1TabDong();
// string stime;
// string etime;
// bool res = false;
// if (Convert.ToString(item["zzId"]) == "全厂")
// {
// DateTime Cxtime = DateTime.Now;
// string time = item["month"].ToString();
// if (Convert.ToInt32(time) > 1)
// {
// string Reducetime = (Convert.ToInt32(time) - 1).ToString();
// etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
// stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
// }
// else
// {
// string Addtime = (Convert.ToInt32(time) + 1).ToString();
// stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
// etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
// }
// DateTime astime = Convert.ToDateTime(stime);
// DateTime aetime = Convert.ToDateTime(etime);
// double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
// new_15dot1dong.gzqdkf = Convert.ToInt32(g);
// new_15dot1dong.djzgzl = Convert.ToDouble(item["djzgzl"]);
// new_15dot1dong.gzwxl = Convert.ToDouble(item["gzwxl"]);
// new_15dot1dong.qtlxbmfxhl = Convert.ToDouble(item["qtlxbmfxhl"]);
// new_15dot1dong.jjqxgsl = Convert.ToDouble(item["jjqxgsl"]);
// double b = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
// new_15dot1dong.gzqdkf = Convert.ToInt32(b);
// new_15dot1dong.gdpjwcsj = Convert.ToDouble(item["gdpjwcsj"]);
// new_15dot1dong.jxmfpjsm = Convert.ToDouble(item["jxmfpjsm"]);
// new_15dot1dong.zcpjsm = Convert.ToDouble(item["zcpjsm"]);
// new_15dot1dong.sbwhl = Convert.ToDouble(item["sbwhl"]);
// new_15dot1dong.jxychgl = Convert.ToDouble(item["jxychgl"]);
// new_15dot1dong.zyjbpjxl = Convert.ToDouble(item["zyjbpjxl"]);
// new_15dot1dong.jzpjxl = Convert.ToDouble(item["jzpjxl"]);
// new_15dot1dong.wfjzgzl = Convert.ToDouble(item["wfjzgzl"]);
// new_15dot1dong.ndbtjbcfjxtc = Convert.ToDouble(item["ndbtjbcfjxtc"]);
// new_15dot1dong.jbpjwgzjgsjMTBF = Convert.ToDouble(item["jbpjwgzjgsjMTBF"]);
// new_15dot1dong.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1dong.temp2 = "动设备专业";//专业名字存于temp2
// new_15dot1dong.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// new_15dot1dong.submitTime = DateTime.Now;
// res = Jx1.ModifyQcDongJxItem(new_15dot1dong, astime, aetime);
// }
// else
// {
// new_15dot1dong.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
// new_15dot1dong.gdpjwcsj = Convert.ToDouble(item["gdpjwcsj"]);
// new_15dot1dong.jxmfpjsm = Convert.ToDouble(item["jxmfpjsm"]);
// new_15dot1dong.zcpjsm = Convert.ToDouble(item["zcpjsm"]);
// new_15dot1dong.sbwhl = Convert.ToDouble(item["sbwhl"]);
// new_15dot1dong.jxychgl = Convert.ToDouble(item["jxychgl"]);
// new_15dot1dong.Id = Convert.ToInt32(item["kpiid"]);
// new_15dot1dong.zyjbpjxl = Convert.ToDouble(item["zyjbpjxl"]);
// new_15dot1dong.jzpjxl = Convert.ToDouble(item["jzpjxl"]);
// new_15dot1dong.wfjzgzl = Convert.ToDouble(item["wfjzgzl"]);
// new_15dot1dong.ndbtjbcfjxtc = Convert.ToDouble(item["ndbtjbcfjxtc"]);
// new_15dot1dong.jbpjwgzjgsjMTBF = Convert.ToDouble(item["jbpjwgzjgsjMTBF"]);
// new_15dot1dong.submitDepartment = Convert.ToString(item["zzId"]);
// res = Jx1.ModifyJxItemDong(new_15dot1dong);
// }
// return res;
//}
//public bool ModifyJing(string json1)
//{
// JObject item = (JObject)JsonConvert.DeserializeObject(json1);
// A15dot1TabJing new_15dot1jing = new A15dot1TabJing();
// string stime;
// string etime;
// bool res = false;
// if (Convert.ToString(item["zzId"]) == "全厂")
// {
// DateTime Cxtime = DateTime.Now;
// string time = item["month"].ToString();
// if (Convert.ToInt32(time) > 1)
// {
// string Reducetime = (Convert.ToInt32(time) - 1).ToString();
// etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
// stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
// }
// else
// {
// string Addtime = (Convert.ToInt32(time) + 1).ToString();
// stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
// etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
// }
// DateTime astime = Convert.ToDateTime(stime);
// DateTime aetime = Convert.ToDateTime(etime);
// double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
// new_15dot1jing.gzqdkf = Convert.ToInt16(g);
// double s = Convert.ToDouble(item["sbfsxlcs"]);
// new_15dot1jing.sbfsxlcs = Convert.ToInt16(s);
// new_15dot1jing.qtlhsbgs = Convert.ToDouble(item["qtlhsbgs"]);
// new_15dot1jing.gylpjrxl = Convert.ToDouble(item["gylpjrxl"]);
// new_15dot1jing.hrqjxl = Convert.ToDouble(item["hrqjxl"]);
// new_15dot1jing.ylrqdjl = Convert.ToDouble(item["ylrqdjl"]);
// new_15dot1jing.ylgdndjxjhwcl = Convert.ToDouble(item["ylgdndjxjhwcl"]);
// new_15dot1jing.aqfndjyjhwcl = Convert.ToDouble(item["aqfndjyjhwcl"]);
// new_15dot1jing.sbfsjcjhwcl = Convert.ToDouble(item["sbfsjcjhwcl"]);
// new_15dot1jing.jsbjwxychgl = Convert.ToDouble(item["jsbjwxychgl"]);
// new_15dot1jing.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1jing.temp2 = "静设备专业";//专业名字存于temp2
// new_15dot1jing.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// new_15dot1jing.submitTime = DateTime.Now;
// res = Jx1.ModifyQcJingJxItem(new_15dot1jing, astime, aetime);
// }
// else
// {
// new_15dot1jing.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
// new_15dot1jing.sbfsxlcs = Convert.ToInt32(item["sbfsxlcs"]);
// new_15dot1jing.qtlhsbgs = Convert.ToDouble(item["qtlhsbgs"]);
// new_15dot1jing.gylpjrxl = Convert.ToDouble(item["gylpjrxl"]);
// new_15dot1jing.hrqjxl = Convert.ToDouble(item["hrqjxl"]);
// new_15dot1jing.ylrqdjl = Convert.ToDouble(item["ylrqdjl"]);
// new_15dot1jing.Id = Convert.ToInt32(item["kpiid"]);
// new_15dot1jing.ylgdndjxjhwcl = Convert.ToDouble(item["ylgdndjxjhwcl"]);
// new_15dot1jing.aqfndjyjhwcl = Convert.ToDouble(item["aqfndjyjhwcl"]);
// new_15dot1jing.sbfsjcjhwcl = Convert.ToDouble(item["sbfsjcjhwcl"]);
// new_15dot1jing.jsbjwxychgl = Convert.ToDouble(item["jsbjwxychgl"]);
// new_15dot1jing.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1jing.temp2 = "静设备专业";//专业名字存于temp2
// res = Jx1.ModifyJxItemJing(new_15dot1jing);
// }
// return res;
//}
//public bool ModifyDian(string json1)
//{
// JObject item = (JObject)JsonConvert.DeserializeObject(json1);
// A15dot1TabDian new_15dot1Dian = new A15dot1TabDian();
// string stime;
// string etime;
// bool res = false;
// if (Convert.ToString(item["zzId"]) == "全厂")
// {
// DateTime Cxtime = DateTime.Now;
// string time = item["month"].ToString();
// if (Convert.ToInt32(time) > 1)
// {
// string Reducetime = (Convert.ToInt32(time) - 1).ToString();
// etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
// stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
// }
// else
// {
// string Addtime = (Convert.ToInt32(time) + 1).ToString();
// stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
// etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
// }
// DateTime astime = Convert.ToDateTime(stime);
// DateTime aetime = Convert.ToDateTime(etime);
// double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
// new_15dot1Dian.gzqdkf = Convert.ToInt16(g);
// double s = Convert.ToDouble(item["dqwczcs"]);
// new_15dot1Dian.dqwczcs = Convert.ToInt16(s);
// new_15dot1Dian.jdbhzqdzl = Convert.ToDouble(item["jdbhzqdzl"]);
// new_15dot1Dian.sbgzl = Convert.ToDouble(item["sbgzl"]);
// new_15dot1Dian.djMTBF = Convert.ToDouble(item["djMTBF"]);
// new_15dot1Dian.dzdlsbMTBF = Convert.ToDouble(item["dzdlsbMTBF"]);
// new_15dot1Dian.zbglys = Convert.ToDouble(item["zbglys"]);
// new_15dot1Dian.dnjlphl = Convert.ToDouble(item["dnjlphl"]);
// new_15dot1Dian.temp2 = "电气专业";//专业名字存于temp2
// new_15dot1Dian.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// new_15dot1Dian.submitTime = DateTime.Now;
// new_15dot1Dian.submitDepartment = Convert.ToString(item["zzId"]);
// res = Jx1.ModifyQcDianJxItem(new_15dot1Dian, astime, aetime);
// }
// else
// {
// new_15dot1Dian.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
// new_15dot1Dian.dqwczcs = Convert.ToInt32(item["dqwczcs"]);
// new_15dot1Dian.jdbhzqdzl = Convert.ToDouble(item["jdbhzqdzl"]);
// new_15dot1Dian.sbgzl = Convert.ToDouble(item["sbgzl"]);
// new_15dot1Dian.djMTBF = Convert.ToDouble(item["djMTBF"]);
// new_15dot1Dian.dzdlsbMTBF = Convert.ToDouble(item["dzdlsbMTBF"]);
// new_15dot1Dian.Id = Convert.ToInt32(item["kpiid"]);
// new_15dot1Dian.zbglys = Convert.ToDouble(item["zbglys"]);
// new_15dot1Dian.dnjlphl = Convert.ToDouble(item["dnjlphl"]);
// new_15dot1Dian.temp2 = "电气专业";//专业名字存于temp2
// new_15dot1Dian.submitDepartment = Convert.ToString(item["zzId"]);
// res = Jx1.ModifyJxItemDian(new_15dot1Dian);
// }
// return res;
//}
//public bool ModifyYi(string json1)
//{
// JObject item = (JObject)JsonConvert.DeserializeObject(json1);
// A15dot1TabYi new_15dot1Yi = new A15dot1TabYi();
// string stime;
// string etime;
// bool res = false;
// if (Convert.ToString(item["zzId"]) == "全厂")
// {
// DateTime Cxtime = DateTime.Now;
// string time = item["month"].ToString();
// if (Convert.ToInt32(time) > 1)
// {
// string Reducetime = (Convert.ToInt32(time) - 1).ToString();
// etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
// stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
// }
// else
// {
// string Addtime = (Convert.ToInt32(time) + 1).ToString();
// stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
// etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
// }
// DateTime astime = Convert.ToDateTime(stime);
// DateTime aetime = Convert.ToDateTime(etime);
// double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
// new_15dot1Yi.gzqdkf = Convert.ToInt16(g);
// new_15dot1Yi.lsxtzqdzl = Convert.ToDouble(item["lsxtzqdzl"]);
// double k = Convert.ToDouble(item["kzxtgzcs"]);
// new_15dot1Yi.kzxtgzcs = Convert.ToInt16(k);
// new_15dot1Yi.ybkzl = Convert.ToDouble(item["ybkzl"]);
// new_15dot1Yi.ybsjkzl = Convert.ToDouble(item["ybsjkzl"]);
// new_15dot1Yi.lsxttyl = Convert.ToDouble(item["lsxttyl"]);
// double s = Convert.ToDouble(item["gjkzfmgzcs"]);
// new_15dot1Yi.gjkzfmgzcs = Convert.ToInt16(s);
// double c = Convert.ToDouble(item["kzxtgzbjcs"]);
// new_15dot1Yi.kzxtgzbjcs = Convert.ToInt16(c);
// new_15dot1Yi.cgybgzl = Convert.ToDouble(item["cgybgzl"]);
// new_15dot1Yi.tjfMDBF = Convert.ToDouble(item["tjfMDBF"]);
// new_15dot1Yi.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1Yi.temp2 = "仪表专业";//专业名字存于temp2
// new_15dot1Yi.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// new_15dot1Yi.submitTime = DateTime.Now;
// res = Jx1.ModifyQcYiJxItem(new_15dot1Yi, astime, aetime);
// }
// else
// {
// new_15dot1Yi.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
// new_15dot1Yi.lsxtzqdzl = Convert.ToDouble(item["lsxtzqdzl"]);
// new_15dot1Yi.kzxtgzcs = Convert.ToInt32(item["kzxtgzcs"]);
// new_15dot1Yi.ybkzl = Convert.ToDouble(item["ybkzl"]);
// new_15dot1Yi.ybsjkzl = Convert.ToDouble(item["ybsjkzl"]);
// new_15dot1Yi.lsxttyl = Convert.ToDouble(item["lsxttyl"]);
// new_15dot1Yi.Id = Convert.ToInt32(item["kpiid"]);
// new_15dot1Yi.gjkzfmgzcs = Convert.ToInt32(item["gjkzfmgzcs"]);
// new_15dot1Yi.kzxtgzbjcs = Convert.ToInt32(item["kzxtgzbjcs"]);
// new_15dot1Yi.cgybgzl = Convert.ToDouble(item["cgybgzl"]);
// new_15dot1Yi.tjfMDBF = Convert.ToDouble(item["tjfMDBF"]);
// new_15dot1Yi.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1Yi.temp2 = "仪表专业";//专业名字存于temp2
// res = Jx1.ModifyJxItemYi(new_15dot1Yi);
// }
// return res;
//}
public bool ModifyQiYe(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabQiYe new_15dot1qiye = new A15dot1TabQiYe();
DateTime Cxtime = DateTime.Now;
string time = item["month"].ToString();
string stime;
string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
bool res = false;
if (Convert.ToString(item["zzId"]) == "全厂")
{//管理员对于全厂的修改的保存
new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
double a = Convert.ToDouble(item["eventNumber"].ToString().Trim());
new_15dot1qiye.sjs = Convert.ToInt16(a);
double b = Convert.ToDouble(item["troubleKoufen"].ToString().Trim());
new_15dot1qiye.gzqdkf = Convert.ToInt32(b);
new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
new_15dot1qiye.submitDepartment = Convert.ToString(item["zzId"]);
new_15dot1qiye.temp3 = Convert.ToString(item["cjname"]);//车间名字存于temp3
new_15dot1qiye.temp2 = "企业级";//专业名字存于temp2
new_15dot1qiye.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1qiye.submitTime = DateTime.Now;
res = Jx1.ModifyQcQyJxItem(new_15dot1qiye, astime, aetime);
}
//else
//{//管理员对于装置的更改的保存
// new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
// new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
// new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
// new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
// new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
// new_15dot1qiye.sjs = Convert.ToInt32(item["eventNumber"]);
// new_15dot1qiye.Id = Convert.ToInt32(item["kpiid"]);
// new_15dot1qiye.gzqdkf = Convert.ToInt32(item["troubleKoufen"]);
// new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
// new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
// new_15dot1qiye.submitDepartment = Convert.ToString(item["zzId"]);
// new_15dot1qiye.temp3 = Convert.ToString(item["cjname"]);//车间名字存于temp3
// new_15dot1qiye.temp2 = "企业级";//专业名字存于temp2
// res = Jx1.ModifyJxItem(new_15dot1qiye);
//}
else if (Convert.ToString(item["zzId"]) == "车间")
{
new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
double a = Convert.ToDouble(item["eventNumber"].ToString().Trim());
new_15dot1qiye.sjs = Convert.ToInt16(a);
double b = Convert.ToDouble(item["troubleKoufen"].ToString().Trim());
new_15dot1qiye.gzqdkf = Convert.ToInt32(b);
new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
new_15dot1qiye.submitDepartment = Convert.ToString(item["cjname"]);
new_15dot1qiye.temp2 = "企业级";//专业名字存于temp2
new_15dot1qiye.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1qiye.submitTime = DateTime.Now;
res = Jx1.ModifyQcQyJxItem(new_15dot1qiye, astime, aetime);
}
else
{//管理员对于装置的更改的保存
new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
new_15dot1qiye.sjs = Convert.ToInt32(item["eventNumber"]);
new_15dot1qiye.Id = Convert.ToInt32(item["kpiid"]);
new_15dot1qiye.gzqdkf = Convert.ToInt32(item["troubleKoufen"]);
new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
new_15dot1qiye.submitDepartment = Convert.ToString(item["zzId"]);
new_15dot1qiye.temp3 = Convert.ToString(item["cjname"]);//车间名字存于temp3
new_15dot1qiye.temp2 = "企业级";//专业名字存于temp2
res = Jx1.ModifyJxItem(new_15dot1qiye);
}
return res;
}
public bool ModifyDong(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabDong new_15dot1dong = new A15dot1TabDong();
string stime;
string etime;
bool res = false;
DateTime Cxtime = DateTime.Now;
string time = item["month"].ToString();
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if (Convert.ToString(item["zzId"]) == "全厂")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1dong.gzqdkf = Convert.ToInt32(g);
new_15dot1dong.djzgzl = Convert.ToDouble(item["djzgzl"]);
new_15dot1dong.gzwxl = Convert.ToDouble(item["gzwxl"]);
new_15dot1dong.qtlxbmfxhl = Convert.ToDouble(item["qtlxbmfxhl"]);
new_15dot1dong.jjqxgsl = Convert.ToDouble(item["jjqxgsl"]);
double b = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1dong.gzqdkf = Convert.ToInt32(b);
new_15dot1dong.gdpjwcsj = Convert.ToDouble(item["gdpjwcsj"]);
new_15dot1dong.jxmfpjsm = Convert.ToDouble(item["jxmfpjsm"]);
new_15dot1dong.zcpjsm = Convert.ToDouble(item["zcpjsm"]);
new_15dot1dong.sbwhl = Convert.ToDouble(item["sbwhl"]);
new_15dot1dong.jxychgl = Convert.ToDouble(item["jxychgl"]);
new_15dot1dong.zyjbpjxl = Convert.ToDouble(item["zyjbpjxl"]);
new_15dot1dong.jzpjxl = Convert.ToDouble(item["jzpjxl"]);
new_15dot1dong.wfjzgzl = Convert.ToDouble(item["wfjzgzl"]);
new_15dot1dong.ndbtjbcfjxtc = Convert.ToDouble(item["ndbtjbcfjxtc"]);
new_15dot1dong.jbpjwgzjgsjMTBF = Convert.ToDouble(item["jbpjwgzjgsjMTBF"]);
new_15dot1dong.submitDepartment = Convert.ToString(item["zzId"]);
new_15dot1dong.temp2 = "动设备专业";//专业名字存于temp2
new_15dot1dong.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1dong.submitTime = DateTime.Now;
res = Jx1.ModifyQcDongJxItem(new_15dot1dong, astime, aetime);
}
else if (Convert.ToString(item["zzId"]) == "车间")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1dong.gzqdkf = Convert.ToInt32(g);
new_15dot1dong.djzgzl = Convert.ToDouble(item["djzgzl"]);
new_15dot1dong.gzwxl = Convert.ToDouble(item["gzwxl"]);
new_15dot1dong.qtlxbmfxhl = Convert.ToDouble(item["qtlxbmfxhl"]);
new_15dot1dong.jjqxgsl = Convert.ToDouble(item["jjqxgsl"]);
double b = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1dong.gzqdkf = Convert.ToInt32(b);
new_15dot1dong.gdpjwcsj = Convert.ToDouble(item["gdpjwcsj"]);
new_15dot1dong.jxmfpjsm = Convert.ToDouble(item["jxmfpjsm"]);
new_15dot1dong.zcpjsm = Convert.ToDouble(item["zcpjsm"]);
new_15dot1dong.sbwhl = Convert.ToDouble(item["sbwhl"]);
new_15dot1dong.jxychgl = Convert.ToDouble(item["jxychgl"]);
new_15dot1dong.zyjbpjxl = Convert.ToDouble(item["zyjbpjxl"]);
new_15dot1dong.jzpjxl = Convert.ToDouble(item["jzpjxl"]);
new_15dot1dong.wfjzgzl = Convert.ToDouble(item["wfjzgzl"]);
new_15dot1dong.ndbtjbcfjxtc = Convert.ToDouble(item["ndbtjbcfjxtc"]);
new_15dot1dong.jbpjwgzjgsjMTBF = Convert.ToDouble(item["jbpjwgzjgsjMTBF"]);
new_15dot1dong.submitDepartment = Convert.ToString(item["cjname"]);
new_15dot1dong.temp2 = "动设备专业";//专业名字存于temp2
new_15dot1dong.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1dong.submitTime = DateTime.Now;
res = Jx1.ModifyQcDongJxItem(new_15dot1dong, astime, aetime);
}
else
{
new_15dot1dong.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
new_15dot1dong.gdpjwcsj = Convert.ToDouble(item["gdpjwcsj"]);
new_15dot1dong.jxmfpjsm = Convert.ToDouble(item["jxmfpjsm"]);
new_15dot1dong.zcpjsm = Convert.ToDouble(item["zcpjsm"]);
new_15dot1dong.sbwhl = Convert.ToDouble(item["sbwhl"]);
new_15dot1dong.jxychgl = Convert.ToDouble(item["jxychgl"]);
new_15dot1dong.Id = Convert.ToInt32(item["kpiid"]);
new_15dot1dong.zyjbpjxl = Convert.ToDouble(item["zyjbpjxl"]);
new_15dot1dong.jzpjxl = Convert.ToDouble(item["jzpjxl"]);
new_15dot1dong.wfjzgzl = Convert.ToDouble(item["wfjzgzl"]);
new_15dot1dong.ndbtjbcfjxtc = Convert.ToDouble(item["ndbtjbcfjxtc"]);
new_15dot1dong.jbpjwgzjgsjMTBF = Convert.ToDouble(item["jbpjwgzjgsjMTBF"]);
new_15dot1dong.submitDepartment = Convert.ToString(item["zzId"]);
res = Jx1.ModifyJxItemDong(new_15dot1dong);
}
return res;
}
public bool ModifyJing(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabJing new_15dot1jing = new A15dot1TabJing();
string stime;
string etime;
bool res = false;
DateTime Cxtime = DateTime.Now;
string time = item["month"].ToString();
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if (Convert.ToString(item["zzId"]) == "全厂")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1jing.gzqdkf = Convert.ToInt16(g);
double s = Convert.ToDouble(item["sbfsxlcs"]);
new_15dot1jing.sbfsxlcs = Convert.ToInt16(s);
new_15dot1jing.qtlhsbgs = Convert.ToDouble(item["qtlhsbgs"]);
new_15dot1jing.gylpjrxl = Convert.ToDouble(item["gylpjrxl"]);
new_15dot1jing.hrqjxl = Convert.ToDouble(item["hrqjxl"]);
new_15dot1jing.ylrqdjl = Convert.ToDouble(item["ylrqdjl"]);
new_15dot1jing.ylgdndjxjhwcl = Convert.ToDouble(item["ylgdndjxjhwcl"]);
new_15dot1jing.aqfndjyjhwcl = Convert.ToDouble(item["aqfndjyjhwcl"]);
new_15dot1jing.sbfsjcjhwcl = Convert.ToDouble(item["sbfsjcjhwcl"]);
new_15dot1jing.jsbjwxychgl = Convert.ToDouble(item["jsbjwxychgl"]);
new_15dot1jing.submitDepartment = Convert.ToString(item["zzId"]);
new_15dot1jing.temp2 = "静设备专业";//专业名字存于temp2
new_15dot1jing.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1jing.submitTime = DateTime.Now;
res = Jx1.ModifyQcJingJxItem(new_15dot1jing, astime, aetime);
}
else if (Convert.ToString(item["zzId"]) == "车间")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1jing.gzqdkf = Convert.ToInt16(g);
double s = Convert.ToDouble(item["sbfsxlcs"]);
new_15dot1jing.sbfsxlcs = Convert.ToInt16(s);
new_15dot1jing.qtlhsbgs = Convert.ToDouble(item["qtlhsbgs"]);
new_15dot1jing.gylpjrxl = Convert.ToDouble(item["gylpjrxl"]);
new_15dot1jing.hrqjxl = Convert.ToDouble(item["hrqjxl"]);
new_15dot1jing.ylrqdjl = Convert.ToDouble(item["ylrqdjl"]);
new_15dot1jing.ylgdndjxjhwcl = Convert.ToDouble(item["ylgdndjxjhwcl"]);
new_15dot1jing.aqfndjyjhwcl = Convert.ToDouble(item["aqfndjyjhwcl"]);
new_15dot1jing.sbfsjcjhwcl = Convert.ToDouble(item["sbfsjcjhwcl"]);
new_15dot1jing.jsbjwxychgl = Convert.ToDouble(item["jsbjwxychgl"]);
new_15dot1jing.submitDepartment = Convert.ToString(item["cjname"]);
new_15dot1jing.temp2 = "静设备专业";//专业名字存于temp2
new_15dot1jing.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1jing.submitTime = DateTime.Now;
res = Jx1.ModifyQcJingJxItem(new_15dot1jing, astime, aetime);
}
else
{
new_15dot1jing.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
new_15dot1jing.sbfsxlcs = Convert.ToInt32(item["sbfsxlcs"]);
new_15dot1jing.qtlhsbgs = Convert.ToDouble(item["qtlhsbgs"]);
new_15dot1jing.gylpjrxl = Convert.ToDouble(item["gylpjrxl"]);
new_15dot1jing.hrqjxl = Convert.ToDouble(item["hrqjxl"]);
new_15dot1jing.ylrqdjl = Convert.ToDouble(item["ylrqdjl"]);
new_15dot1jing.Id = Convert.ToInt32(item["kpiid"]);
new_15dot1jing.ylgdndjxjhwcl = Convert.ToDouble(item["ylgdndjxjhwcl"]);
new_15dot1jing.aqfndjyjhwcl = Convert.ToDouble(item["aqfndjyjhwcl"]);
new_15dot1jing.sbfsjcjhwcl = Convert.ToDouble(item["sbfsjcjhwcl"]);
new_15dot1jing.jsbjwxychgl = Convert.ToDouble(item["jsbjwxychgl"]);
new_15dot1jing.submitDepartment = Convert.ToString(item["zzId"]);
new_15dot1jing.temp2 = "静设备专业";//专业名字存于temp2
res = Jx1.ModifyJxItemJing(new_15dot1jing);
}
return res;
}
public bool ModifyDian(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabDian new_15dot1Dian = new A15dot1TabDian();
string stime;
string etime;
bool res = false;
DateTime Cxtime = DateTime.Now;
string time = item["month"].ToString();
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if (Convert.ToString(item["zzId"]) == "全厂")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1Dian.gzqdkf = Convert.ToInt16(g);
double s = Convert.ToDouble(item["dqwczcs"]);
new_15dot1Dian.dqwczcs = Convert.ToInt16(s);
new_15dot1Dian.jdbhzqdzl = Convert.ToDouble(item["jdbhzqdzl"]);
new_15dot1Dian.sbgzl = Convert.ToDouble(item["sbgzl"]);
new_15dot1Dian.djMTBF = Convert.ToDouble(item["djMTBF"]);
new_15dot1Dian.dzdlsbMTBF = Convert.ToDouble(item["dzdlsbMTBF"]);
new_15dot1Dian.zbglys = Convert.ToDouble(item["zbglys"]);
new_15dot1Dian.dnjlphl = Convert.ToDouble(item["dnjlphl"]);
new_15dot1Dian.temp2 = "电气专业";//专业名字存于temp2
new_15dot1Dian.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1Dian.submitTime = DateTime.Now;
new_15dot1Dian.submitDepartment = Convert.ToString(item["zzId"]);
res = Jx1.ModifyQcDianJxItem(new_15dot1Dian, astime, aetime);
}
else if (Convert.ToString(item["zzId"]) == "车间")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1Dian.gzqdkf = Convert.ToInt16(g);
double s = Convert.ToDouble(item["dqwczcs"]);
new_15dot1Dian.dqwczcs = Convert.ToInt16(s);
new_15dot1Dian.jdbhzqdzl = Convert.ToDouble(item["jdbhzqdzl"]);
new_15dot1Dian.sbgzl = Convert.ToDouble(item["sbgzl"]);
new_15dot1Dian.djMTBF = Convert.ToDouble(item["djMTBF"]);
new_15dot1Dian.dzdlsbMTBF = Convert.ToDouble(item["dzdlsbMTBF"]);
new_15dot1Dian.zbglys = Convert.ToDouble(item["zbglys"]);
new_15dot1Dian.dnjlphl = Convert.ToDouble(item["dnjlphl"]);
new_15dot1Dian.temp2 = "电气专业";//专业名字存于temp2
new_15dot1Dian.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1Dian.submitTime = DateTime.Now;
new_15dot1Dian.submitDepartment = Convert.ToString(item["cjname"]);
res = Jx1.ModifyQcDianJxItem(new_15dot1Dian, astime, aetime);
}
else
{
new_15dot1Dian.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
new_15dot1Dian.dqwczcs = Convert.ToInt32(item["dqwczcs"]);
new_15dot1Dian.jdbhzqdzl = Convert.ToDouble(item["jdbhzqdzl"]);
new_15dot1Dian.sbgzl = Convert.ToDouble(item["sbgzl"]);
new_15dot1Dian.djMTBF = Convert.ToDouble(item["djMTBF"]);
new_15dot1Dian.dzdlsbMTBF = Convert.ToDouble(item["dzdlsbMTBF"]);
new_15dot1Dian.Id = Convert.ToInt32(item["kpiid"]);
new_15dot1Dian.zbglys = Convert.ToDouble(item["zbglys"]);
new_15dot1Dian.dnjlphl = Convert.ToDouble(item["dnjlphl"]);
new_15dot1Dian.temp2 = "电气专业";//专业名字存于temp2
new_15dot1Dian.submitDepartment = Convert.ToString(item["zzId"]);
res = Jx1.ModifyJxItemDian(new_15dot1Dian);
}
return res;
}
public bool ModifyYi(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabYi new_15dot1Yi = new A15dot1TabYi();
string stime;
string etime;
bool res = false;
DateTime Cxtime = DateTime.Now;
string time = item["month"].ToString();
if (Convert.ToInt32(time) > 1)
{
string Reducetime = (Convert.ToInt32(time) - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + time + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
string Addtime = (Convert.ToInt32(time) + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
if (Convert.ToString(item["zzId"]) == "全厂")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1Yi.gzqdkf = Convert.ToInt16(g);
new_15dot1Yi.lsxtzqdzl = Convert.ToDouble(item["lsxtzqdzl"]);
double k = Convert.ToDouble(item["kzxtgzcs"]);
new_15dot1Yi.kzxtgzcs = Convert.ToInt16(k);
new_15dot1Yi.ybkzl = Convert.ToDouble(item["ybkzl"]);
new_15dot1Yi.ybsjkzl = Convert.ToDouble(item["ybsjkzl"]);
new_15dot1Yi.lsxttyl = Convert.ToDouble(item["lsxttyl"]);
double s = Convert.ToDouble(item["gjkzfmgzcs"]);
new_15dot1Yi.gjkzfmgzcs = Convert.ToInt16(s);
double c = Convert.ToDouble(item["kzxtgzbjcs"]);
new_15dot1Yi.kzxtgzbjcs = Convert.ToInt16(c);
new_15dot1Yi.cgybgzl = Convert.ToDouble(item["cgybgzl"]);
new_15dot1Yi.tjfMDBF = Convert.ToDouble(item["tjfMDBF"]);
new_15dot1Yi.submitDepartment = Convert.ToString(item["zzId"]);
new_15dot1Yi.temp2 = "仪表";//专业名字存于temp2
new_15dot1Yi.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1Yi.submitTime = DateTime.Now;
res = Jx1.ModifyQcYiJxItem(new_15dot1Yi, astime, aetime);
}
else if (Convert.ToString(item["zzId"]) == "车间")
{
double g = Convert.ToDouble(item["gzqdkf"].ToString().Trim());
new_15dot1Yi.gzqdkf = Convert.ToInt16(g);
new_15dot1Yi.lsxtzqdzl = Convert.ToDouble(item["lsxtzqdzl"]);
double k = Convert.ToDouble(item["kzxtgzcs"]);
new_15dot1Yi.kzxtgzcs = Convert.ToInt16(k);
new_15dot1Yi.ybkzl = Convert.ToDouble(item["ybkzl"]);
new_15dot1Yi.ybsjkzl = Convert.ToDouble(item["ybsjkzl"]);
new_15dot1Yi.lsxttyl = Convert.ToDouble(item["lsxttyl"]);
double s = Convert.ToDouble(item["gjkzfmgzcs"]);
new_15dot1Yi.gjkzfmgzcs = Convert.ToInt16(s);
double c = Convert.ToDouble(item["kzxtgzbjcs"]);
new_15dot1Yi.kzxtgzbjcs = Convert.ToInt16(c);
new_15dot1Yi.cgybgzl = Convert.ToDouble(item["cgybgzl"]);
new_15dot1Yi.tjfMDBF = Convert.ToDouble(item["tjfMDBF"]);
new_15dot1Yi.submitDepartment = Convert.ToString(item["cjname"]);
new_15dot1Yi.temp2 = "仪表";//专业名字存于temp2
new_15dot1Yi.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1Yi.submitTime = DateTime.Now;
res = Jx1.ModifyQcYiJxItem(new_15dot1Yi, astime, aetime);
}
else
{
new_15dot1Yi.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
new_15dot1Yi.lsxtzqdzl = Convert.ToDouble(item["lsxtzqdzl"]);
new_15dot1Yi.kzxtgzcs = Convert.ToInt32(item["kzxtgzcs"]);
new_15dot1Yi.ybkzl = Convert.ToDouble(item["ybkzl"]);
new_15dot1Yi.ybsjkzl = Convert.ToDouble(item["ybsjkzl"]);
new_15dot1Yi.lsxttyl = Convert.ToDouble(item["lsxttyl"]);
new_15dot1Yi.Id = Convert.ToInt32(item["kpiid"]);
new_15dot1Yi.gjkzfmgzcs = Convert.ToInt32(item["gjkzfmgzcs"]);
new_15dot1Yi.kzxtgzbjcs = Convert.ToInt32(item["kzxtgzbjcs"]);
new_15dot1Yi.cgybgzl = Convert.ToDouble(item["cgybgzl"]);
new_15dot1Yi.tjfMDBF = Convert.ToDouble(item["tjfMDBF"]);
new_15dot1Yi.submitDepartment = Convert.ToString(item["cjname"]);
new_15dot1Yi.temp2 = "仪表";//专业名字存于temp2
res = Jx1.ModifyJxItemYi(new_15dot1Yi);
}
return res;
}
public ActionResult DongSubmit()
{
PersonManagment pm = new PersonManagment();
submitmodel sm = new submitmodel();
ViewBag.curtime = DateTime.Now;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
sm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(sm);
}
public string qstqc(string grahpic_name, string graphic_zdm, string graphic_zy, string graphic_subdipartment)//获得全厂的趋势图
{
List<object> res = Jx1.qstqc(grahpic_name, graphic_zdm, graphic_zy, graphic_subdipartment);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public bool DongSubmit_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabDong new_15dot1dong = new A15dot1TabDong();
new_15dot1dong.gzqdkf = Convert.ToInt32(item["gzqdkf"]);
new_15dot1dong.djzgzl = Convert.ToDouble(item["djzgzl"]);
new_15dot1dong.gzwxl = Convert.ToDouble(item["gzwxl"]);
new_15dot1dong.qtlxbmfxhl = Convert.ToDouble(item["qtlxbmfxhl"]);
new_15dot1dong.jjqxgsl = Convert.ToDouble(item["jjqxgsl"]);
new_15dot1dong.gdpjwcsj = Convert.ToDouble(item["gdpjwcsj"]);
new_15dot1dong.jxmfpjsm = Convert.ToDouble(item["jxmfpjsm"]);
new_15dot1dong.zcpjsm = Convert.ToDouble(item["zcpjsm"]);
new_15dot1dong.sbwhl = Convert.ToDouble(item["sbwhl"]);
new_15dot1dong.jxychgl = Convert.ToDouble(item["jxychgl"]);
new_15dot1dong.zyjbpjxl = Convert.ToDouble(item["zyjbpjxl"]);
new_15dot1dong.jzpjxl = Convert.ToDouble(item["jzpjxl"]);
new_15dot1dong.wfjzgzl = Convert.ToDouble(item["wfjzgzl"]);
new_15dot1dong.ndbtjbcfjxtc = Convert.ToDouble(item["ndbtjbcfjxtc"]);
new_15dot1dong.jbpjwgzjgsjMTBF = Convert.ToDouble(item["jbpjwgzjgsjMTBF"]);
new_15dot1dong.submitDepartment = item["zzId"].ToString();
new_15dot1dong.temp3 = item["cjname"].ToString();//车间名字存于temp3
new_15dot1dong.temp2 = "动设备专业";//专业名字存于temp2
new_15dot1dong.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1dong.submitTime = DateTime.Now;
bool res = Jx1.AddDongJxItem(new_15dot1dong);
return res;
}
//装置趋势图
//public string Dongqst(string grahpic_name, string zz)
//{
// List<object> res = Jx1.Dongqst(grahpic_name, zz);
// string str = JsonConvert.SerializeObject(res);
// return (str);
//}
public string qstQiYe(string grahpic_name, string zzId)
{
EquipManagment em = new EquipManagment();
string zzname = "";
zzname = em.getEa_namebyid(Convert.ToInt32(zzId));
List<object> res = Jx1.qstQiYe(grahpic_name, zzname);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public string qstDong(string grahpic_name, string zzId)
{
EquipManagment em = new EquipManagment();
string zzname = "";
zzname = em.getEa_namebyid(Convert.ToInt32(zzId));
List<object> res = Jx1.qstDong(grahpic_name, zzname);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public string qstJing(string grahpic_name, string zzId)
{
EquipManagment em = new EquipManagment();
string zzname = "";
zzname = em.getEa_namebyid(Convert.ToInt32(zzId));
List<object> res = Jx1.qstJing(grahpic_name, zzname);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public string qstDian(string grahpic_name, string zzId)
{
EquipManagment em = new EquipManagment();
string zzname = "";
zzname = em.getEa_namebyid(Convert.ToInt32(zzId));
List<object> res = Jx1.qstDian(grahpic_name, zzname);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public string qstYi(string grahpic_name, string zzId)
{
EquipManagment em = new EquipManagment();
string zzname = "";
zzname = em.getEa_namebyid(Convert.ToInt32(zzId));
List<object> res = Jx1.qstYi(grahpic_name, zzname);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public JsonResult Cj_ZzsA2(string json1)
{
JObject A2 = (JObject)JsonConvert.DeserializeObject(json1);
int cj_id = Convert.ToInt32(A2["cj_id"]);
string zy = A2["zy"].ToString();
PersonManagment pm = new PersonManagment();
// EquipManagment em = new EquipManagment();
int p_id = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
List<Equip_Archi> Zz = pm.Get_Person_Zz_ofCj(p_id, cj_id);
List<object> Zz_obj = new List<object>();
DateTime Cxtime = DateTime.Now;
int month = 0;
string stime;
string etime;//设置查询月份的格式,eg:1月15日0:00:00到2月14日23:59:59查询的是2月的数据
if (Cxtime.Day > 15)
month = Cxtime.AddMonths(1).Month;
else
month = Cxtime.Month;
if (month > 1)
{
string Reducetime = (month - 1).ToString();
etime = Cxtime.Year.ToString() + '/' + month + '/' + "14" + " 23:59";
stime = Cxtime.Year.ToString() + '/' + Reducetime + '/' + "15" + " 00:00";
}
else
{
//string Addtime = (month + 1).ToString();
stime = (Cxtime.Year - 1).ToString() + '/' + "12" + '/' + "15" + " 00:00";
etime = Cxtime.Year.ToString() + '/' + "01" + '/' + "14" + " 23:59";
}
DateTime astime = Convert.ToDateTime(stime);
DateTime aetime = Convert.ToDateTime(etime);
int ifTibao = 2;
foreach (var item in Zz)
{
if (zy == "qy")
{
bool iftibao = Jx1.GetifzztibaoQiYe(astime, aetime, item.EA_Name);
if (iftibao)
{
ifTibao = 1;//判断是否该装置已经提报
}
else
{
ifTibao = 0;
}
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name,
Zz_iftibao = ifTibao,
};
Zz_obj.Add(o);
}
else if (zy == "dong")
{
bool iftibao = Jx1.GetifzztibaoDong(astime, aetime, item.EA_Name);
if (iftibao)
{
ifTibao = 1;//判断是否该装置已经提报
}
else
{
ifTibao = 0;
}
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name,
Zz_iftibao = ifTibao,
};
Zz_obj.Add(o);
}
else if (zy == "jing")
{
bool iftibao = Jx1.GetifzztibaoJing(astime, aetime, item.EA_Name);
if (iftibao)
{
ifTibao = 1;//判断是否该装置已经提报
}
else
{
ifTibao = 0;
}
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name,
Zz_iftibao = ifTibao,
};
Zz_obj.Add(o);
}
else if (zy == "dian")
{
bool iftibao = Jx1.GetifzztibaoDian(astime, aetime, item.EA_Name);
if (iftibao)
{
ifTibao = 1;//判断是否该装置已经提报
}
else
{
ifTibao = 0;
}
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name,
Zz_iftibao = ifTibao,
};
Zz_obj.Add(o);
}
else if (zy == "yi")
{
bool iftibao = Jx1.GetifzztibaoYi(astime, aetime, item.EA_Name);
if (iftibao)
{
ifTibao = 1;//判断是否该装置已经提报
}
else
{
ifTibao = 0;
}
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name,
Zz_iftibao = ifTibao,
};
Zz_obj.Add(o);
}
else
{
object o = new
{
Zz_Id = item.EA_Id,
Zz_Name = item.EA_Name,
Zz_iftibao = ifTibao,
};
Zz_obj.Add(o);
}
}
return Json(Zz_obj.ToArray());
}
}
}<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Equip_Archis : BaseDAO, IEquipArchis
{
public bool AddEquip_Archi(int parent_Id, Equip_Archi New_Equip_Archi)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi parent = db.EArchis.Where(a => a.EA_Id == parent_Id).First();
if (parent == null)
return false;
parent.EA_Childs.Add(New_Equip_Archi);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public string getEa_namebyId(int Ea_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.EArchis.Where(a => a.EA_Id == Ea_id).First().EA_Name;
return E;
}
catch
{ return ""; }
}
}
public string getcodebyname(string Ea_name)
{
using (var db = base.NewDB())
{
try
{
var E = db.EArchis.Where(a => a.EA_Name == Ea_name).First().EA_Code;
return E;
}
catch
{ return null; }
}
}
public int getEa_idbyname(string Ea_name)
{
using (var db = base.NewDB())
{
try
{
var E = db.EArchis.Where(a => a.EA_Name == Ea_name).First().EA_Id;
return E;
}
catch
{ return 0; }
}
}
public bool AddEA_Euip(int EA_Id, Equip_Info New_Equip_Info)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Id == EA_Id).First();
if (EA == null)
return false;
EA.Equips_Belong.Add(New_Equip_Info);
db.SaveChanges();
return true;
}
catch { return false; }
}
}
public Equip_Archi getEA_Archi(int EA_Id)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Id == EA_Id).First();
return EA;
}
catch { return null; }
}
}
//开始
public EquipModel.Entities.Equip_Archi GetEquipArchi(int id)
{
using (var db = base.NewDB())
{
return db.EArchis.Where(a => a.EA_Id == id).First();
}
}
public List<EquipModel.Entities.Equip_Archi> GetEquipArchi(string name)
{
using (var db = base.NewDB())
{
return db.EArchis.Where(a => a.EA_Name == name).OrderBy(a => a.EA_Name).ToList();
}
}
public List<EquipModel.Entities.Equip_Archi> GetChildMenu(int id)
{
using (var db = base.NewDB())
{
var menu = db.EArchis.Where(a => a.EA_Id == id).First();
return menu.EA_Childs.ToList();
}
}
public List<EquipModel.Entities.Equip_Archi> GetChildMenu(string name)
{
using (var db = base.NewDB())
{
var menu = db.EArchis.Where(a => a.EA_Name == name).First();
return menu.EA_Childs.ToList();
}
}
public bool AddEquipArchi(int parentID, Equip_Archi newMenu)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi parent = db.EArchis.Where(a => a.EA_Id == parentID).First();
if (parent == null)
return false;
parent.EA_Childs.Add(newMenu);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool DeleteEquipArchi(int id)
{
using (var db = base.NewDB())
{
try
{
var menu = db.EArchis.Where(a => a.EA_Id == id).First();
if (menu == null)
return true;
foreach (var child in menu.EA_Childs)
{
DeleteEquipArchi(child.EA_Id);
}
db.EArchis.Remove(menu);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool ModifyEquipArchi(int id, EquipModel.Entities.Equip_Archi nVal)
{
using (var db = base.NewDB())
{
try
{
var menu = db.EArchis.Where(a => a.EA_Id == id).First();
if (menu == null)
return false;
menu.EA_Name = nVal.EA_Name;
menu.EA_Code = nVal.EA_Code;
menu.EA_Title = nVal.EA_Title;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
//结束
public List<Equip_Archi> getEA_Childs(int EA_Id)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Id == EA_Id).First();
return EA.EA_Childs.ToList(); ;
}
catch { return null; }
}
}
public List<Equip_Archi> getEA_Childs(string EA_Name)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Name == EA_Name).First();
return EA.EA_Childs.ToList();
}
catch { return null; }
}
}
public List<Equip_Archi> getEAs_isCj()
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Title == "车间").First();
return EA.EA_Childs.ToList();
}
catch { return null; }
}
}
public Equip_Archi getEA_Parent(int EA_Id)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Id == EA_Id).First();
return EA.EA_Parent;
}
catch { return null; }
}
}
public List<Equip_Info> getEA_Equips(int EA_Id, string username = null)
{
List<Equip_Info> E = new List<Equip_Info>();
using (var db = base.NewDB())
{
try
{
if (username != null && username!="sa")
{
//List<Equip_Info> e = db.Persons.Where(a => a.Person_Name == username).First().Person_Equips.ToList();
//foreach (var temp in e)
//{
// if (temp.Equip_Location.EA_Id == EA_Id)
// E.Add(temp);
//}
//return E;
E = db.Equips.Where(a => a.Equip_Specialty == "动" && a.Equip_Location.EA_Id == EA_Id).ToList();
return E;
}
else if( username=="sa")
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Id == EA_Id).First();
return EA.Equips_Belong.ToList();
}
else
{
E = db.Equips.Where(a => a.Equip_Specialty == "动" && a.Equip_Location.EA_Id == EA_Id).ToList();
return E;
}
}
catch { return null; }
}
}
public List<Equip_Info> getThEA_Equips(int EA_Id)
{
using (var db = base.NewDB())
{
try
{
List<Equip_Info> E = db.Equips.Where(a => a.Equip_Location.EA_Id == EA_Id&&a.thRecordTable=="1").ToList();
return E;
}
catch { return null; }
}
}
public bool ModifyEquip_Archi(int EA_Id, Equip_Archi New_Equip_Archi)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Id == EA_Id).First();
if (EA == null)
return false;
EA.EA_Name = New_Equip_Archi.EA_Name;
EA.EA_Title = New_Equip_Archi.EA_Title;
db.SaveChanges();
return true;
}
catch { return false; }
}
}
public bool DeleteEquip_Archi(int EA_Id)
{
using (var db = base.NewDB())
{
try
{
Equip_Archi EA = db.EArchis.Where(a => a.EA_Id == EA_Id).First();
if (EA == null)
return false;
EA.Equips_Belong.Clear();
db.EArchis.Remove(EA);
db.SaveChanges();
return true;
}
catch { return false; }
}
}
public Equip_Archi GetEA_Archi(int EA_Id)
{
throw new NotImplementedException();
}
public List<Equip_Archi> GetEA_Archi(string name)
{
throw new NotImplementedException();
}
public string getEA_Name(int EA_Id)
{
using (var db = base.NewDB())
{
try
{
string EA_Name = db.EArchis.Where(a => a.EA_Id == EA_Id).First().EA_Name;
return EA_Name;
}
catch { return null; }
}
}
/// <summary>
/// 通过装置名字获取装置所属车间0917
/// </summary>
/// <param name="EA_Name"></param>
/// <returns></returns>
public string getEA_NameByZzNAme(string EA_Name)
{
using (var db = base.NewDB())
{
try
{
string Name = db.EArchis.Where(a => a.EA_Name == EA_Name).First().EA_Parent.EA_Name;
return Name;
}
catch { return null; }
}
}
//2016-4-22注释
//Equip_Archi IEquipArchis.GetEquipArchi(int EA_Id)
//{
// throw new NotImplementedException();
//}
//List<Equip_Archi> IEquipArchis.getEA_Archi(string name)
//{
// throw new NotImplementedException();
//}
//List<Equip_Archi> IEquipArchis.getEA_Childs(int EA_Id)
//{
// throw new NotImplementedException();
//}
//bool IEquipArchis.AddEquip_Archi(int parent_Id, Equip_Archi New_Equip_Archi)
//{
// throw new NotImplementedException();
//}
//bool IEquipArchis.DeleteEquip_Archi(int EA_Id)
//{
// throw new NotImplementedException();
//}
//bool IEquipArchis.ModifyEquip_Archi(int EA_Id, Equip_Archi New_Equip_Archi)
//{
// throw new NotImplementedException();
//}
}
}
<file_sep>using FlowEngine.TimerManage;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Routing;
using WebApp.Models;
namespace WebApp
{
public class MvcApplication : System.Web.HttpApplication
{
private const string DummyPageUrl = @"http://localhost/Cache/Index";
private const string DummyKey = @"ForGlobalTimer";
protected void Application_Start()
{
//FileStream fs = new FileStream("D:\\web\\ZJtest.txt", FileMode.Append, FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs); // 创建写入流
//sw.WriteLine("App_Start" + " " + DateTime.Now.ToString()); // 写入
//sw.Close(); //关闭文件
// Database.SetInitializer(new UserAccount());
Database.SetInitializer(new WorkFlowInit());
//Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EquipModel.Context.EquipWebContext>());
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
//CTimerManage.InitTimerManager();
//CTimerManage.Start();
RegisterCacheEntry();
}
//protected void Application_End()
//{
// FileStream fs = new FileStream("D:\\web\\ZJtest.txt", FileMode.Append, FileAccess.Write);
// StreamWriter sw = new StreamWriter(fs); // 创建写入流
// sw.WriteLine("App_End" + " " + DateTime.Now.ToString()); // 写入
// sw.Close(); //关闭文件
//}
private void RegisterCacheEntry()
{
//FileStream fs = new FileStream("D:\\web\\ZJtest.txt", FileMode.Append, FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs); // 创建写入流
//sw.WriteLine("RegisterCacheEntry" + " " + DateTime.Now.ToString()); // 写入
//sw.Close(); //关闭文件
if (HttpContext.Current.Cache[DummyKey] != null)
return;
HttpContext.Current.Cache.Add(DummyKey, "Timer", null, DateTime.MaxValue, TimeSpan.FromMinutes(1), System.Web.Caching.CacheItemPriority.NotRemovable,
new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemovedCallback));
}
public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
//FileStream fs = new FileStream("D:\\web\\ZJtest.txt", FileMode.Append, FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs); // 创建写入流
//sw.WriteLine("CacheItemRemovedCallback" + " " + DateTime.Now.ToString()); // 写入
//sw.Close(); //关闭文件
WebClient client = new WebClient();
client.DownloadData(DummyPageUrl);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
//FileStream fs = new FileStream("D:\\web\\ZJtest.txt", FileMode.Append, FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs); // 创建写入流
//sw.WriteLine("Application_BeginRequest" + " " + DateTime.Now.ToString()); // 写入
//sw.Close(); //关闭文件
if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
RegisterCacheEntry();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class NWorkFlowSer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string WF_Name { get; set; }
/// <summary>
/// 父节点
/// </summary>
public string WE_Ser { get; set; }
public DateTime time { get; set; }
}
}
<file_sep>using EquipDAL.Implement;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class DsWorkManagment
{
MyDsWorks md = new MyDsWorks();
//public bool IsAlreadySave(string work_name, string event_name, string year, string month)
//{
// return md.IsAlreadySave(work_name,event_name,year,month);
//}
public string getDstime(string work_name,string event_name)
{
return md.getDstime(work_name, event_name);
}
public int AddDsEvent(DSEventDetail ds)
{
return md.AddDsEvent(ds);
}
public DSEventDetail getdetailbyE_id(int entity_id)
{
return md.getdetailbyE_id(entity_id);
}
public bool modifystate(int entity_id, string event_name)
{
return md.modifystate(entity_id, event_name);
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A13dot2Controller :CommonController
{
//
// GET: /A13dot2/
public ActionResult Index()
{
return View(getA13dot2_Model());
}
public string click_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string Equip_Code = item["Equip_Code"].ToString();
string Jx_Reason = item["Jx_Reason"].ToString();
string flowname = "A8dot2";
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
if (wfe != null)
{
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(Equip_Code);
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
int flow_id = wfe.EntityID;
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxSubmit_done"] = "true";
signal["Cj_Name"] = Equip_ZzBelong[1].EA_Name; //Cj_Name
signal["Zz_Name"] = Equip_ZzBelong[0].EA_Name; //Zz_Name
signal["Equip_GyCode"] = eqinfo.Equip_GyCode;
signal["Equip_Code"] = eqinfo.Equip_Code;
signal["Equip_Type"] = eqinfo.Equip_Type;
signal["Zy_Type"] = eqinfo.Equip_Specialty;
signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
signal["Jx_Reason"] = Jx_Reason;// "一级缺陷";//计划检修原因 PM?
signal["Data_Src"] = "A13dot2";
//record
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(flow_id, signal, record);
return ("/A8dot2/Index");
}
else
return "/A13dot2/Index";
}
catch (Exception e)
{
return "";
}
//return ("/A13dot2/Index");
}
}
}<file_sep>using EquipDAL.Implement;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.FileManagment
{
public class File_Cat_Manager
{
private CatalogTreeNode BuildCatNodes(File_Catalog parent)
{
CatalogTreeNode pd = new CatalogTreeNode();
pd.text = parent.Catalog_Name;
pd.tags.Add(parent.Catalog_Id.ToString());
pd.selectable = true;
foreach(var cd in parent.Child_Catalogs.ToList())
{
pd.nodes.Add(BuildCatNodes(cd));
}
return pd;
}
//构建文件种类树
public List<CatalogTreeNode> BuildCatTree()
{
List<CatalogTreeNode> nodes = new List<CatalogTreeNode>();
FileCatalogs fcs = new FileCatalogs();
DbSet<File_Catalog> ta = fcs.GetCatalogsSet();
var roots = ta.Where(s => s.parent_Catalog == null).ToList();
foreach(var root in roots)
{
nodes.Add(BuildCatNodes(root));
}
return nodes;
}
/// <summary>
/// 增加一个文件分类
/// </summary>
/// <param name="parentID"></param>
/// <param name="newCatalog"></param>
/// <returns></returns>
public bool AddNewCatalog(int parentID, string newCatalog)
{
FileCatalogs fcs = new FileCatalogs();
return fcs.AddNewCatalog(parentID, newCatalog);
}
public bool DeleteCatalog(int ID)
{
return (new FileCatalogs()).DeleteCatalog(ID);
}
public bool ModifyFileCatalog(int ID, string name)
{
return (new FileCatalogs()).ModifyCatalog(ID, name);
}
public List<FileItem> GetFilesInCatalog(int ID)
{
List<File_Info> files = (new FileCatalogs()).GetFiles(ID);
List<FileItem> fs = new List<FileItem>();
foreach(var f in files)
{
FileItem fi = new FileItem();
fi.id = Convert.ToString(f.File_Id);
fi.fileName = f.File_OldName;
fi.updateTime = f.File_UploadTime.ToString();
fi.ext = f.File_ExtType;
fi.path = f.File_SavePath;
fi.fileNamePresent = f.File_NewName;
fs.Add(fi);
}
return fs;
}
public bool AddNewFile(int pID, FileItem fi, int uID)
{
File_Info nf = new File_Info();
nf.File_NewName = fi.fileNamePresent;
nf.File_OldName = fi.fileName;
nf.File_UploadTime = Convert.ToDateTime(fi.updateTime);
nf.File_Submiter = (new Person_Infos()).GetPerson_info(uID);
nf.File_SavePath = fi.path;
nf.File_ExtType = fi.ext;
return (new FileCatalogs()).AddFiletoCatalog(pID, nf);
}
public bool DeleteFile(int fID)
{
return (new Files()).delete(fID);
}
}
}
<file_sep>using FlowEngine.DAL;
using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FlowEngine.TimerManage
{
/// <summary>
/// 定时任务管理器
/// </summary>
public class CTimerManage
{
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="timer_deviation">定时器误差</param>
public CTimerManage(int timer_deviation = 5)
{
}
#endregion
#region 属性
/// <summary>
/// 定时任务管理的定时时间间隔, 毫秒为单位
/// </summary>
public static int time_interval { get; set; }
/// <summary>
/// 任务列表: 由于missions在多个线程中被访问, 需要加锁
/// </summary>
private static List<CTimerMission> missions = new List<CTimerMission>();
/// <summary>
/// 主定时器
/// </summary>
private static Timer m_mainTimer;
#endregion
#region 公共方法
/// <summary>
/// 开始工作
/// </summary>
public static void Start()
{
m_mainTimer.Change(0, time_interval);
}
/// <summary>
/// 添加一个定时性任务
/// </summary>
/// <param name="tm">添加的任务</param>
public static void AppendMissionToActiveList(CTimerMission tm)
{
//如果添加的任务状态为ACTIVE
if (tm.status == TM_STATUS.TM_STATUS_ACTIVE)
{
//添加到当前任务列表
lock (missions) //任务列表加锁
{
if (missions.Find(delegate(CTimerMission mis) { return mis.ID == tm.ID; }) == null)
missions.Add(tm);
}
//tm.manage = this;
}
}
/// <summary>
/// 初始化定时任务管理器
/// 主要工作: 从数据库中读取定时任务信息(ACTIVE)
/// </summary>
public static void InitTimerManager(int interval = 1000)
{
time_interval = 1000; //默认时间间隔为1s
m_mainTimer = new Timer(new TimerCallback(__Worker), null, 0, Timeout.Infinite);
CTimerMission.Timer_deviation = (time_interval / 1000);
//暂停定时器
m_mainTimer.Change(0, Timeout.Infinite);
//清空任务列表
//加锁: 加锁成功说明定时器任务执行完毕
lock (missions)
{
missions.Clear();
}
//加载数据库中处于ACTIVE的工作任务
Jobs timer_jobs = new Jobs();
List<Timer_Jobs> db_jobs = timer_jobs.GetJobsByStatus(TM_STATUS.TM_STATUS_ACTIVE);
foreach(var j in db_jobs)
{
missions.Add(CreateTimerMission(j));
}
}
/// <summary>
/// 针对具体任务, 活动列表的响应操作
/// </summary>
/// <param name="tm"></param>
public static void ActiveListActionForMission(CTimerMission tm)
{
if (tm == null)
return;
lock(missions)
{
CTimerMission t = missions.Find(delegate(CTimerMission miss) { return miss.ID == tm.ID; });
if (tm.status == TM_STATUS.TM_STATUS_ACTIVE && t == null) //tm的状态为激活状态, 且未添加到活动列表
missions.Add(tm);
else if (tm.status == TM_STATUS.TM_STATUS_ACTIVE && t != null) //tm的状态为激活状态, 且已添加到活动列表
{
missions.Remove(t);
missions.Add(tm);
}
else if (tm.status != TM_STATUS.TM_STATUS_ACTIVE && t != null) //tm的状态为非激活, 且已添加到活动列表
missions.Remove(t);
}
}
/// <summary>
/// 将tm移除当前任务列表
/// </summary>
/// <param name="tm">待移除任务</param>
public static CTimerMission RemoveFromActiveList(int tmID)
{
CTimerMission t;
//从任务列表中移除tm
lock(missions)
{
t = missions.Find(delegate(CTimerMission miss) { return miss.ID == tmID; });
if (t != null)
missions.Remove(t);
}
return t;
}
#endregion
#region 私有方法
/// <summary>
/// 工作线程
/// </summary>
private static void __Worker(object sender)
{
Trace.WriteLine(string.Format("Entering Manage Worker \t {0}", DateTime.Now.ToString()));
lock (missions) //任务列表加锁
{
foreach (var mi in missions)
{
mi.DoJob();
}
}
}
#endregion
#region 静态方法
/// <summary>
/// 创建一个空任务
/// </summary>
/// <returns></returns>
public static CTimerMission CreateAEmptyMission()
{
CTimerEmptyMission empty = new CTimerEmptyMission();
empty.CreateTime = DateTime.Now;
//empty.Save();
return empty;
}
/// <summary>
/// 更行定时性任务的属性
/// </summary>
/// <param name="mId">定时性任务ID</param>
/// <param name="property">定时性任务属性名集合</param>
/// <param name="val">待更新的值集合</param>
/// <returns></returns>
public static CTimerMission UpdateTimerMission(int mId, List<string> property, List<object> val)
{
Jobs timer_jobs = new Jobs();
CTimerMission tm = CreateTimerMission(timer_jobs.UpdateJob(mId, property, val));
ActiveListActionForMission(tm);
return tm;
}
/// <summary>
/// 加载定时性任务
/// </summary>
/// <param name="mId"></param>
/// <returns></returns>
public static CTimerMission LoadTimerMission(int mId)
{
Jobs timer_jobs = new Jobs();
return CreateTimerMission(timer_jobs.GetTimerJob(mId));
}
/// <summary>
/// 根据Timer_Jobs创建相应的对象
/// </summary>
/// <param name="job"></param>
/// <returns></returns>
public static CTimerMission CreateTimerMission(Timer_Jobs job)
{
if (job == null)
return null;
CTimerMission J_val;
switch (job.Job_Type)
{
case TIMER_JOB_TYPE.CREATE_WORKFLOW:
CTimerCreateWF J_create = new CTimerCreateWF();
J_create.Load(job);
J_val = J_create;
break;
case TIMER_JOB_TYPE.CHANGE_STATUS:
CTimerWFStatus J_status = new CTimerWFStatus();
J_status.Load(job);
J_val = J_status;
break;
case TIMER_JOB_TYPE.TIME_OUT:
CTimerTimeout J_timeout = new CTimerTimeout();
J_timeout.Load(job);
J_val = J_timeout;
break;
case TIMER_JOB_TYPE.EMPTY:
CTimerEmptyMission J_empty = new CTimerEmptyMission();
J_empty.Load(job);
J_val = J_empty;
break;
case TIMER_JOB_TYPE.Normal:
CTimerNormalMission J_Normal = new CTimerNormalMission();
J_Normal.Load(job);
J_val = J_Normal;
break;
default:
J_val = null;
break;
}
return J_val;
}
/// <summary>
/// 获取全部定时性任务列表
/// </summary>
/// <returns></returns>
public static List<CTimerMission> GetTimerJobs()
{
Jobs timer_jobs = new Jobs();
List<Timer_Jobs> db_jobs = timer_jobs.GetAllTimerJob();
List<CTimerMission> miss = new List<CTimerMission>();
foreach (var j in db_jobs)
{
miss.Add(CreateTimerMission(j));
}
return miss;
}
public static List<CTimerMission> GetTimerJobsForCustom()
{
Jobs timer_jobs = new Jobs();
List<Timer_Jobs> db_jobs = timer_jobs.GetJobsByUsing(TIMER_USING.FOR_CUSTOM);
List<CTimerMission> miss = new List<CTimerMission>();
foreach (var j in db_jobs)
{
miss.Add(CreateTimerMission(j));
}
return miss;
}
/// <summary>
/// 删除一个定时任务
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static CTimerMission DeleteTimerJob(int id)
{
Jobs timer_jobs = new Jobs();
return CTimerManage.CreateTimerMission(timer_jobs.DeleteJob(id));
}
#endregion
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.FileManagment
{
public class WSCatalogTreeNode
{
//名称
public string text;
//
public Boolean selectable;
//子节点
public List<WSCatalogTreeNode> nodes = new List<WSCatalogTreeNode>();
//标识
public List<string> tags = new List<string>();
}
}
<file_sep>using FlowEngine.Flow;
using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FlowEngine.Event
{
/// <summary>
/// 循环事件
/// </summary>
public class CLoopEvent : CEvent
{
#region 构造函数
public CLoopEvent(CWorkFlow parent) : base(parent)
{
m_waiting = new CWaitingEvent(parent);
}
~CLoopEvent()
{
}
#endregion
#region 属性
/// <summary>
/// 等待事件
/// </summary>
private CWaitingEvent m_waiting;
/// <summary>
/// 循环条件
/// </summary>
private string m_loopCondition = "";
private string m_cornString = "";
#endregion
#region 公共接口
public override void InstFromXmlNode(XmlNode xmlNode)
{
//基类成员解析
base.InstFromXmlNode(xmlNode);
//循环条件解析
XmlNode loopCondition = xmlNode.SelectSingleNode("loop_contidion");
if (loopCondition != null)
m_loopCondition = loopCondition.InnerText;
else
m_loopCondition = "1 !> 1";
//成员解析
m_waiting.name = name + ":wating";
Parent.events.Add(m_waiting.name, m_waiting);
m_waiting.m_timer.mission_name = m_waiting.name + ":timer";
//新增flow
CFlow flow_w2s = new CFlow(Parent.paramstable, false);
flow_w2s.expression = "1 == 1";
flow_w2s.source_event = m_waiting.name;
flow_w2s.destination_event = this.name;
flow_w2s.PrePase();
Parent.AppendFlow(flow_w2s);
CFlow flow_s2w = new CFlow(Parent.paramstable, false);
flow_s2w.expression = m_loopCondition;
flow_s2w.source_event = this.name;
flow_s2w.destination_event = m_waiting.name;
flow_s2w.PrePase();
Parent.AppendFlow(flow_s2w);
//循环时间控制
XmlNode cornStr = xmlNode.SelectSingleNode("loop_time");
m_cornString = cornStr.InnerText;
XmlNode attTimer = xmlNode.SelectSingleNode("attach_timer");
if (attTimer != null && attTimer.InnerText.Trim() != "")
m_waiting.m_timerID = Convert.ToInt32(attTimer.InnerText);
m_waiting.SetWaitingTime(m_cornString.Trim());
}
public override XmlNode WriteToXmlNode()
{
//1. 反解析基类部分成员
XmlNode xn = base.WriteToXmlNode();
//2. 反解析NormalEvent的成员
XmlElement xe = (XmlElement)xn;
xe.SetAttribute("type", "loopevent");
//3. 反解析循环条件
XmlDocument doc = new XmlDocument();
XmlElement con_elem = doc.CreateElement("loop_contidion");
con_elem.AppendChild(doc.CreateCDataSection(m_loopCondition));
xn.AppendChild(xn.OwnerDocument.ImportNode(con_elem, true));
//4. 反解析循环时间
XmlElement looptime = doc.CreateElement("loop_time");
looptime.AppendChild(doc.CreateCDataSection(m_waiting.GetWaitingTime()));
xn.AppendChild(xn.OwnerDocument.ImportNode(looptime, true));
XmlElement attTimer = doc.CreateElement("attach_timer");
attTimer.InnerText = Convert.ToString(m_waiting.m_timerID);
xn.AppendChild(xn.OwnerDocument.ImportNode(attTimer, true));
return xn;
}
/// <summary>
/// 进入该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void EnterEvent(string strjson)
{
if (beforeaction != "")
{
string strjson1 = "{param:'{";
foreach (var par in m_beforeActionParams)
{
string tmp = string.Format("{0}:\"{1}\",", par.Key, parselEventActionParams(par.Value));
strjson1 += tmp;
}
strjson1.TrimEnd(new char[] { ',' });
strjson1 += "}'}";
try
{
byte[] bytes = Encoding.UTF8.GetBytes(strjson1);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(beforeaction);
request.ContentType = @"application/json";
request.Accept = "application/xml";
request.Method = "POST";
request.ContentLength = bytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Dispose();
//结束动作函数返回值
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//对返回结果进行处理
OpResutsfromAction(sr.ReadToEnd());
}
catch (Exception e)
{
Trace.WriteLine("EnterEvent error:" + e.Message);
//return;
}
}
base.UpdateCurrentEvent();
m_timeout.RegTimeoutTimer(false);
}
/// <summary>
/// 离开该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void LeaveEvent(string strjson)
{
if (beforeaction != "")
{
string strjson1 = "{param:'{";
foreach (var par in m_afterActionParams)
{
string tmp = string.Format("{0}:\"{1}\",", par.Key, parselEventActionParams(par.Value));
strjson1 += tmp;
}
strjson1.TrimEnd(new char[] { ',' });
strjson1 += "}'}";
try
{
byte[] bytes = Encoding.UTF8.GetBytes(strjson1);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(afteraction);
request.ContentType = @"application/json";
request.Accept = "application/xml";
request.Method = "POST";
request.ContentLength = bytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Dispose();
//结束动作函数返回值
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//对返回结果进行处理
OpResutsfromAction(sr.ReadToEnd());
}
catch (Exception e)
{
Trace.WriteLine("EnterEvent error:" + e.Message);
//return;
}
}
//保存信息到数据库
base.InsertMissionToDB();
m_timeout.UnregTimeoutTimer();
}
#endregion
}
}
<file_sep>///////////////////////////////////////////////////////////
// CFlow.cs
// Implementation of the Class CFlow
// Generated by Enterprise Architect
// Created on: 28-10月-2015 13:58:42
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine;
using FlowEngine.Flow;
using System.Xml;
namespace FlowEngine.Flow {
public class CFlow : IXMLEntity, IFlow {
/// <summary>
/// 流(Flow)的目的事件(Event)
/// </summary>
private string m_DestEvent = "";
/// <summary>
/// 流程(Flow)的条件表达式
/// </summary>
private string m_expression = "";
/// <summary>
/// 流(Flow)的源事件
/// </summary>
private string m_SourceEvent = "";
/// <summary>
/// 用以解析、计算流的条件表达式
/// </summary>
private FlowEngine.Flow.CExpressionEvaluator m_ExpressionEvaluator;
private bool m_serial;
///
/// <param name="pt">pt用以传递参数表</param>
public CFlow(FlowEngine.Param.CParamTable pt, bool serial = true){
m_ExpressionEvaluator = new CExpressionEvaluator(pt);
m_serial = serial;
}
~CFlow(){
}
/// <summary>
/// 获得/设置流程(Flow)的目的事件
/// </summary>
public string destination_event{
get{
return m_DestEvent;
}
set{
m_DestEvent = value;
}
}
/// <summary>
/// 计算流(Flow)表达式的值
/// 返回值:真假
/// </summary>
public bool Evaluate(){
CSymbol v = m_ExpressionEvaluator.Evaluate();
return Convert.ToBoolean(v.value);
}
/// <summary>
/// 获取/设置流(Flow)表达式
/// </summary>
public string expression{
get{
return m_expression;
}
set{
m_expression = value;
}
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public void InstFromXmlNode(XmlNode xmlNode){
//1. 判断xmlNode是否为Flow节点
if (xmlNode.Name != "flow")
return;
//2. 设置Flow对象的属性
m_DestEvent = xmlNode.Attributes["destination"].Value;
m_SourceEvent = xmlNode.Attributes["source"].Value;
//3. 解析Flow的表达式
m_expression = xmlNode.SelectSingleNode("condition").InnerText;
//表达式对象处理
m_ExpressionEvaluator.Parse(m_expression);
m_ExpressionEvaluator.InfixToPostfix();
}
public void PrePase()
{
if (m_expression == "")
return;
//表达式对象处理
m_ExpressionEvaluator.Parse(m_expression);
m_ExpressionEvaluator.InfixToPostfix();
}
/// <summary>
/// 获得/设置流程(Flow)的源事件(Event)的名称
/// </summary>
public string source_event{
get{
return m_SourceEvent;
}
set{
m_SourceEvent = value;
}
}
/// <summary>
/// 反解析到XML元素
/// </summary>
public XmlNode WriteToXmlNode(){
if (!m_serial)
return null;
XmlDocument doc = new XmlDocument();
//1. 创建Flow节点
XmlElement fn = doc.CreateElement("flow");
//2. 设置Flow属性
fn.SetAttribute("source", m_SourceEvent);
fn.SetAttribute("destination", m_DestEvent);
//3. 设置条件表达式
XmlElement exp = doc.CreateElement("condition");
exp.AppendChild(doc.CreateCDataSection(m_expression));
fn.AppendChild(exp);
return fn;
}
}//end CFlow
}//end namespace Flow<file_sep>using FlowEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Models;
using WebApp.Models.User;
using EquipBLL.AdminManagment;
using EquipModel.Entities;
using System.Security.Cryptography;
using System.Text;
namespace WebApp.Controllers
{
public class LoginController : Controller
{
//
// GET: /Login/
public ActionResult Index()
{
return View();
}
public ActionResult chaoshi()
{
return View();
}
public ActionResult VerCheck()
{
return View();
}
[HttpPost]
public string LogOn(string userName, string userPwd)
{
/* PersonManagment pm = new PersonManagment();
Person_Info p = pm.Get_Person(userName);
if (p == null)
return "Index";
else
{
CWFEngine.authority_params["currentuser"] = userName;
Session["User"] = p;
return "/Main/Index0";
}*/
int a;
PersonManagment pm = new PersonManagment();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(userPwd.Trim()));
// pm.ModifyPerson_Pwd(userName, result);
Person_Info p = pm.Get_Person(userName);
if (p == null)
{
return "Index";
}
else
{
byte[] r = p.Person_Pwd;
string userPwdMD5 = System.Text.UTF8Encoding.Unicode.GetString(result);
string userPwDb = System.Text.UTF8Encoding.Unicode.GetString(r);
if (!userPwDb.Equals(userPwdMD5))
return "Index";
//// string =System.Text.Encoding.Default.GetString(result);
else
{
Dictionary<string, object> dict_authority = new Dictionary<string, object>();
dict_authority["currentuser"] = userName;
Session["authority"] = dict_authority;
CWFEngine.authority_params = "authority";
Session["User"] = p;
return "/Main/Index0";
}
}
}
public ActionResult ModifyPWD_Index()
{
ViewBag.userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
return View();
}
public string ModifyPWD(string userName, string userPwd, string newUserPWd)
{
int a;
PersonManagment pm = new PersonManagment();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(userPwd.Trim()));
//pm.ModifyPerson_Pwd(userName, result);
Person_Info p = pm.Get_Person(userName);
if (p == null)
{
return "ModifyPWD_Index";
}
else
{
byte[] r = p.Person_Pwd;
string userPwdMD5 = System.Text.UTF8Encoding.Unicode.GetString(result);
string userPwDb = System.Text.UTF8Encoding.Unicode.GetString(r);
if (!userPwDb.Equals(userPwdMD5))
return "ModifyPWD_Index";
// string =System.Text.Encoding.Default.GetString(result);
else
{
result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(newUserPWd.Trim()));
if (pm.ModifyPerson_Pwd(userName, result))
return "/Main/Home";
else
return "ModifyPWD_Index";
}
}
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using FlowEngine.DAL;
using FlowEngine.Modals;
using FlowEngine.Param;
using WebApp.Models.DateTables;
using System.Collections.Specialized;
using EquipBLL.AdminManagment.MenuConfig;
using System.Xml;
using FlowEngine.TimerManage;
namespace WebApp.Controllers
{
public class A14dot3dot2Controller : CommonController
{
EquipManagment Em = new EquipManagment();
public ActionResult Index(string job_title)
{
ViewBag.jobtitle = job_title;
return View();
}
public ActionResult ZzSubmit(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public class EquipListModel
{
public int Equip_Id;
public string Equip_GyCode;
public string Equip_Code;
public string Equip_Type;
public string Equip_Specialty;
public string Equip_ABCMark;
}
public string get_equip_info(string wfe_id)
{
WorkFlows wfsd = new WorkFlows();
Mission db_miss = wfsd.GetWFEntityMissions(Convert.ToInt16(wfe_id)).Last();//获取该实体最后一个任务
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(Convert.ToInt16(wfe_id));
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui = new UI_MISSION();
ui.WE_Entity_Ser = wfe.WE_Ser;
ui.WE_Event_Desc = db_miss.Miss_Desc;
ui.WE_Event_Name = db_miss.Event_Name;
ui.WE_Name = db_miss.Miss_Name;
ui.Mission_Url = ""; //历史任务的页面至空
ui.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui.Miss_Params[cp.name] = cp.value;
ui.Miss_ParamsDesc[cp.name] = cp.description;
}
List<EquipListModel> EquipList = Zz_Equips(ui.Miss_Params["Zz_Name"].ToString());
List<object> miss_obj = new List<object>();
int i = 1;
foreach (var item in EquipList)
{
object m = new
{
index = i,
Equip_Id = item.Equip_Id,
Equip_GyCode = item.Equip_GyCode,
Equip_Code = item.Equip_Code,
Equip_Type = item.Equip_Type,
Equip_Specialty = item.Equip_Specialty,
Equip_ABCMark = item.Equip_ABCMark
};
miss_obj.Add(m);
i++;
}
string str = JsonConvert.SerializeObject(miss_obj);
return ("{" + "\"data\": " + str + "}");
}
public List<EquipListModel> Zz_Equips(string Zz_name)
{
EquipManagment pm = new EquipManagment();
EquipArchiManagment em = new EquipArchiManagment();
List<Equip_Info> Equips_of_Zz = new List<Equip_Info>();
List<EquipListModel> Equip_obj = new List<EquipListModel>();
Equips_of_Zz = pm.getEquips_OfZz(em.getEa_idbyname(Zz_name.ToString()));
foreach (var item in Equips_of_Zz)
{
EquipListModel io = new EquipListModel();
io.Equip_Id = item.Equip_Id;
io.Equip_GyCode = item.Equip_GyCode;
io.Equip_Code = item.Equip_Code;
io.Equip_Type = item.Equip_Type;
io.Equip_Specialty = item.Equip_Specialty;
io.Equip_ABCMark = item.Equip_ABCmark;
Equip_obj.Add(io);
}
return Equip_obj;
}
public string CreateA14dot3s_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
EquipManagment tm = new EquipManagment();
string temp = item["sample"].ToString();
JArray jsonVal = JArray.Parse(temp) as JArray;
dynamic table2 = jsonVal;
foreach (dynamic T in table2)
{
//加载原工作流工作流
CWorkFlow m_workFlow = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
WorkFlow_Define wf_define = wfs.GetWorkFlowDefine("A14dot3dot3");
m_workFlow = null;
if (wf_define != null)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wf_define.W_Xml));
m_workFlow = new CWorkFlow();
m_workFlow.InstFromXmlNode((XmlNode)doc.DocumentElement);
m_workFlow.DefineID = wf_define.W_ID;
}
//加载超时属性数据
TimerCreateWFPa TCP = new TimerCreateWFPa();
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
//time_set.Offset_time = (DateTime.Now.AddMinutes(3) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("PqAssess", time_set);
//创建写入timeout属性的工作流
CWorkFlow wf = new CWorkFlow();
wf.InstFromXmlNode(m_workFlow.WriteToXmlNode());
//修改定时器
foreach (var ti in TCP.wf_timer)
{
try
{
DateTime? dt = null;
if (ti.Value["ExactTime"] != "")
dt = DateTime.Parse(ti.Value["ExactTime"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("exact_time", dt);
TimeSpan? ts = null;
if (ti.Value["OffsetTime"] != "")
ts = TimeSpan.Parse(ti.Value["OffsetTime"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("offset_time", ts);
wf.events[ti.Key].TimeOutProperty.SetAttribute("time_start", ti.Value["TimeStart"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("action", ti.Value["Action"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("call_back", ti.Value["CallBack"]);
}
catch
{
continue;
}
}
//创建工作流
wf.CreateEntityBySelf();
//开启工作流
Dictionary<string, string> record = new Dictionary<string, string>();
record.Add("username", "system_temporary");
record.Add("time", DateTime.Now.ToString());
TCP.wf_record = record;
wf.Start((IDictionary<string, string>)(TCP.wf_record));
Dictionary<string, string> signal = new Dictionary<string, string>();
string Equip_Code = T.Equip_Code;
int Equip_location_EA_Id = tm.getEA_id_byCode(Equip_Code);
signal["Zz_Name"] = tm.getZzName(Equip_location_EA_Id);
signal["Equip_GyCode"] = T.Equip_GyCode;
signal["Equip_Code"] = T.Equip_Code;
signal["Equip_ABCMark"] = T.Equip_ABCMark;
signal["SubmitJxPlan_Done"] = "true";
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(wf.EntityID), signal, record1);
}
}
catch (Exception e)
{
return "";
}
return ("/A14dot3/Index");
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A11dot4Controller : CommonController
{
//
// GET: /A11dot4/
public JsonResult List_AccessGroup()
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> AccessGroup_obj = DM.BuildAccessGroupPersonList();
return Json(AccessGroup_obj.ToArray());
}
public ActionResult Index()
{
return View(getIndexListRecords("A11dot4", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
public JsonResult List_Workflow()
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> Menu_obj = DM.BuildMenuList("3");
return Json(Menu_obj.ToArray());
}
// GET: /A11dot4/提报无页面,由其他流程转入并自动完成
public ActionResult PreSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A11dot4/成立风险评估小组
public ActionResult CreateAssessGroup(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot4/风险评估小组确定并上传评估报告
public ActionResult ConfirmAndUpload(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string CreateAssessGroup_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CreateAssessGroup_done"] = item["CreateAssessGroup_done"].ToString();
signal["Group_Header"] = item["Group_Header"].ToString();
signal["Group_Member"] = item["Group_Member"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot4/Index");
}
public string ConfirmAndUpload_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
signal["Risk_IsAcceptable"] = item["Risk_IsAcceptable"].ToString();
signal["ConfirmAndUpload_done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A11dot4/Index");
}
}
}<file_sep>using FlowEngine.DAL;
using FlowEngine.Event;
using FlowEngine.Modals;
using FlowEngine.Param;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FlowEngine.TimerManage
{
//创建工作流所需的参数
public class TimerCreateWFPa
{
public Dictionary<string, string> wf_params = new Dictionary<string, string>();
public Dictionary<string, string> wf_record = new Dictionary<string, string>();
//创建工作流时对各个event设置定时器(TimeOut)
//其结构及含义如下:
//wf_timer =
// {
// event11: {
// ExactTime: ******,
// TimeStart: ******,
// OffsetTime: ****
// },
// event12: {
// ExactTime: ******,
// StartTime: ******,
// OffsetTime: *****
// },
// ......
// }
//为保证使用安全,请勿直接访问该属性
public Dictionary<string, Dictionary<string, string>> wf_timer = new Dictionary<string, Dictionary<string, string>>();
public class TimerSetting
{
public string Exact_time;
public string Time_start; //"wf_create"或"ev_enter"
public string Offset_time;
public string Action;
public string Call_back;
}
//添加一个定时器设置
public void AppendTimer(string ev_name, TimerSetting ts)
{
if (wf_timer.ContainsKey(ev_name))
{
wf_timer[ev_name]["ExactTime"] = ts.Exact_time;
wf_timer[ev_name]["TimeStart"] = ts.Time_start;
wf_timer[ev_name]["OffsetTime"] = ts.Offset_time;
wf_timer[ev_name]["Action"] = ts.Action;
wf_timer[ev_name]["CallBack"] = ts.Call_back;
}
else
{
Dictionary<string, string> time_value = new Dictionary<string, string>();
time_value["ExactTime"] = ts.Exact_time;
time_value["TimeStart"] = ts.Time_start;
time_value["OffsetTime"] = ts.Offset_time;
time_value["Action"] = ts.Action;
time_value["CallBack"] = ts.Call_back;
wf_timer[ev_name] = time_value;
}
}
}
/// <summary>
/// 创建工作流实体定时性任务
/// </summary>
public class CTimerCreateWF : CTimerMission
{
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
public CTimerCreateWF()
{
//允许一个定时任务创建多个工作流
m_run_params = new List<TimerCreateWFPa>();
m_run_result = new List<int>();
type = "CreateWorkFlow";
}
#endregion
#region 属性
/// <summary>
/// 任务执行对象
/// </summary>
private CWorkFlow m_workFlow = new CWorkFlow();
/// <summary>
/// Affer Create 回调
/// </summary>
public string CreateCallback
{
get;
set;
}
#endregion
#region 公共方法
/// <summary>
/// 获得与之关联的工作流
/// </summary>
/// <returns></returns>
public override CWorkFlow GetAttachWorkFlow()
{
return m_workFlow;
}
/// <summary>
/// 清空创建工作流实体参数
/// </summary>
public void ClearCreateParams()
{
((List<TimerCreateWFPa>)m_run_params).Clear();
}
/// <summary>
/// 添加新建工作流实体变量
/// </summary>
/// <param name="newCreate"></param>
public void AppendCreateParam(TimerCreateWFPa newCreate)
{
((List<TimerCreateWFPa>)m_run_params).Add(newCreate);
}
/// <summary>
/// 保存到数据库
/// </summary>
public override void Save(Timer_Jobs job = null)
{
Timer_Jobs self_Job = new Timer_Jobs();
self_Job.workflow_ID = m_workFlow.DefineID;
self_Job.Job_Type = TIMER_JOB_TYPE.CREATE_WORKFLOW;
CustomAction = CreateCallback;
base.Save(self_Job);
}
/// <summary>
/// 绑定执行对象
/// </summary>
/// <param name="wf">工作流</param>
/// <returns></returns>
public bool attachTarget(WorkFlow_Define wf)
{
if (wf == null)
return false;
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wf.W_Xml));
m_workFlow.InstFromXmlNode((XmlNode)doc.DocumentElement);
m_workFlow.DefineID = wf.W_ID;
return true;
}
/// <summary>
/// 从数据库记录加载类对象
/// </summary>
/// <param name="job">数据库记录</param>
public override void Load(Timer_Jobs job)
{
//加载工作流定义
WorkFlows wfs = new WorkFlows();
WorkFlow_Define wf_define = wfs.GetWorkFlowDefineByID(job.workflow_ID);
m_workFlow = null;
if (wf_define != null)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wf_define.W_Xml));
m_workFlow = new CWorkFlow();
m_workFlow.InstFromXmlNode((XmlNode)doc.DocumentElement);
m_workFlow.DefineID = job.workflow_ID;
}
base.Load(job);
CreateCallback = CustomAction;
}
/// <summary>
/// 将RunParams 解析成JObject
/// </summary>
/// <returns></returns>
public override object ParseRunParamsToJObject()
{
JArray jObj = new JArray();
foreach (var pa in (List<TimerCreateWFPa>)m_run_params)
{
JObject jpar = new JObject();
jpar["PARAMS"] = ParseDictionaryToJObject(pa.wf_params);
jpar["RECORD"] = ParseDictionaryToJObject(pa.wf_record);
jpar["TIMER"] = ParseDictionaryToJObject(pa.wf_timer);
jObj.Add(jpar);
}
return jObj;
}
/// <summary>
/// 将RunResult 解析成JObject
/// </summary>
/// <returns></returns>
public override object ParseRunResultToJobject()
{
JArray jObj = new JArray();
foreach (var rr in (List<int>)m_run_result)
{
JValue jrr = new JValue(rr);
jObj.Add(jrr);
}
return jObj;
}
/// <summary>
/// 解析CreateWF参数
/// </summary>
/// <param name="strPars"></param>
public override void ParseRunParam(string strPars)
{
if (strPars == "null")
return;
((List<TimerCreateWFPa>)m_run_params).Clear();
//解析多个创建工作流实体的参数
JArray j_pars = JArray.Parse(strPars);
//对JSon数组元素进行遍历
for (int i = 0; i < j_pars.Count(); i++)
{
var par = j_pars[i];
if (par is JObject)
{
Dictionary<string, string> dict_params = null;
Dictionary<string, string> dict_record = null;
Dictionary<string, Dictionary<string, string>> dict_timer = null;
var enumerator = ((JObject)par).GetEnumerator();
while (enumerator.MoveNext())
{
var Jval = enumerator.Current;
//解析传递给工作流实体参数的信息
if (Jval.Key == "PARAMS")
dict_params = ParseJObjectToDictionary((JObject)Jval.Value);
//解析传递给工作流实体的Record信息
if (Jval.Key == "RECORD")
dict_record = ParseJObjectToDictionary((JObject)Jval.Value);
//解析Timer
if (Jval.Key == "TIMER")
dict_timer = ParseJObjectToDictionary((JObject)Jval.Value, true);
//如果两者解析都合法
if (dict_params != null && dict_record != null && dict_timer != null)
{
TimerCreateWFPa creatPas = new TimerCreateWFPa();
creatPas.wf_params = dict_params;
creatPas.wf_record = dict_record;
creatPas.wf_timer = dict_timer;
((List<TimerCreateWFPa>)m_run_params).Add(creatPas);
}
}
}
}
}
/// <summary>
/// 将数据库中的run_result解析到对象中
/// </summary>
/// <param name="strResult"></param>
public override void ParseRunResult(string strResult)
{
if (strResult == "" || strResult == "null" || strResult == null)
return;
JArray jobj = JArray.Parse(strResult);
((List<int>)m_run_result).Clear();
foreach (var jj in jobj)
{
((List<int>)m_run_result).Add(Convert.ToInt32(((JValue)jj).Value));
}
}
public List<int> GetCreatedWFEntities()
{
return (List<int>)m_run_result;
}
#endregion
#region 私有方法
/// <summary>
/// 创建工作流后的回调
/// </summary>
private void AfterCreate(int wfeId)
{
string custom_param = "{\"wfe_id\":" + wfeId.ToString() + "}";
base.CallCustomAction(custom_param);
}
/// <summary>
///
/// </summary>
/// <param name="jobj"></param>
private Dictionary<string, string> ParseJObjectToDictionary(JObject jobj)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
var enumerator = jobj.GetEnumerator();
while (enumerator.MoveNext())
{
var jval = enumerator.Current;
dict[jval.Key] = jval.Value.ToString();
}
return dict;
}
private Dictionary<string, Dictionary<string, string>> ParseJObjectToDictionary(JObject jobj, bool bToDict)
{
Dictionary<string, Dictionary<string, string>> dict = new Dictionary<string, Dictionary<string, string>>();
var enumerator = jobj.GetEnumerator();
while (enumerator.MoveNext())
{
var jval = enumerator.Current;
dict[jval.Key] = ParseJObjectToDictionary(jval.Value as JObject);
}
return dict;
}
/// <summary>
/// 将字典解析为JObject
/// </summary>
/// <param name="dict"></param>
/// <returns></returns>
private JObject ParseDictionaryToJObject(Dictionary<string, string> dict)
{
JObject jobj = new JObject();
foreach (var di in dict)
{
jobj[di.Key] = di.Value.ToString();
}
return jobj;
}
private JObject ParseDictionaryToJObject(Dictionary<string, Dictionary<string, string>> dict)
{
JObject jobj = new JObject();
if (dict!=null)
{
foreach (var di in dict)
{
jobj[di.Key] = ParseDictionaryToJObject(di.Value);
}
}
return jobj;
}
/// <summary>
/// 执行工作流创建工作
/// </summary>
protected override void __processing()
{
//Trace.WriteLine(string.Format("Creating WorkFlow {0}", m_workFlow.name));
foreach (var rp in (List<TimerCreateWFPa>)m_run_params)
{
if (rp.wf_timer != null)
{ //创建工作流
CWorkFlow wf = new CWorkFlow();
wf.InstFromXmlNode(m_workFlow.WriteToXmlNode());
//修改定时器
foreach (var ti in rp.wf_timer)
{
try
{
DateTime? dt = null;
if (ti.Value["ExactTime"] != "")
dt = DateTime.Parse(ti.Value["ExactTime"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("exact_time", dt);
TimeSpan? ts = null;
if (ti.Value["OffsetTime"] != "")
ts = TimeSpan.Parse(ti.Value["OffsetTime"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("offset_time", ts);
wf.events[ti.Key].TimeOutProperty.SetAttribute("time_start", ti.Value["TimeStart"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("action", ti.Value["Action"]);
wf.events[ti.Key].TimeOutProperty.SetAttribute("call_back", ti.Value["CallBack"]);
}
catch
{
continue;
}
}
//更新工作流变量
foreach (var pp in ((Dictionary<string, string>)(rp.wf_params)))
{
try
{
CParam pa = wf.paramstable[pp.Key];
pa.value = pp.Value;
if (pp.Key == "Zz_Name" || pp.Key == "ZzName" || pp.Key == "Pqname" || pp.Key == "Equip_GyCode")
wf.description = wf.description + "(" + pp.Value + ")";
}
catch
{
continue;
}
}
//创建工作流
wf.CreateEntityBySelf();
//
//回调
AfterCreate(wf.EntityID);
((List<int>)m_run_result).Add(wf.EntityID);
//工作流开始工作
wf.Start((IDictionary<string, string>)(rp.wf_record));
}
}
}
#endregion
}
}
<file_sep>///////////////////////////////////////////////////////////
// CParam.cs
// Implementation of the Class CParam
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine;
using System.Xml;
using System.Diagnostics;
namespace FlowEngine.Param {
/// <summary>
/// 参数,即工作流的业务数据
/// </summary>
public class CParam : IXMLEntity {
/// <summary>
/// 变量描述
/// </summary>
private string m_description = "";
/// <summary>
/// 变量名称
/// </summary>
private string m_name = "";
/// <summary>
/// 变量类型:string, int, bool, float
/// </summary>
private string m_type = "";
/// <summary>
/// 变量值
/// </summary>
private object m_value;
/// <summary>
/// 记录哪些事件(Event)需要对该变量进行处理
/// </summary>
private List<string> m_linkEventsName = new List<string>();
private Dictionary<string, string> m_linkEventsApp_res = new Dictionary<string, string>();
public CParam(){
}
~CParam(){
}
/// <summary>
/// 变量描述
/// </summary>
public string description{
get{
return m_description;
}
set{
m_description = value;
}
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public void InstFromXmlNode(XmlNode xmlNode){
//1. 判断xmlNode类型
if (xmlNode.Name != "param")
return;
//2. 设置Param的属性
m_name = xmlNode.Attributes["name"].Value;
m_description = xmlNode.Attributes["desc"].Value;
m_type = xmlNode.Attributes["type"].Value;
if (xmlNode.Attributes["value"] != null)
value = xmlNode.Attributes["value"].Value;
//3. 解析LinkEvents
XmlNode linkevents = xmlNode.SelectSingleNode("linkevents");
foreach(XmlNode lexn in linkevents.ChildNodes)
{
if (lexn.Name == "linkevent")
{
m_linkEventsName.Add(lexn.InnerText);
m_linkEventsApp_res[lexn.InnerText] = ((XmlElement)lexn).GetAttribute("app_reserve");
}
}
//4. 根据type设定默认值
SetInitValue();
}
/// <summary>
/// 变量名称
/// </summary>
public string name{
get{
return m_name;
}
set {
m_name = value;
}
}
/// <summary>
/// 变量类型
/// </summary>
public string type{
get{
return m_type;
}
set{
m_type = value;
}
}
/// <summary>
/// 变量值
/// </summary>
public object value{
get{
return m_value;
}
set{
switch (m_type)
{
case "string":
m_value = value.ToString();
break;
case "int":
m_value = Convert.ToInt32(value);
break;
case "bool":
m_value = Convert.ToBoolean(value);
break;
case "float":
m_value = Convert.ToDouble(value);
break;
default:
throw new Exception("Unkown Param type");
}
}
}
public object value1
{
get
{
if (m_type == "string")
return "\"" + m_value + "\"";
else
return m_value;
}
}
/// <summary>
/// 反解析到XML元素
/// </summary>
public XmlNode WriteToXmlNode(){
XmlDocument xd = new XmlDocument();
//1. 创建Param节点
XmlElement paramXe = xd.CreateElement("param");
//2. 反解析Param属性
paramXe.SetAttribute("name", m_name);
paramXe.SetAttribute("desc", m_description);
paramXe.SetAttribute("type", m_type);
paramXe.SetAttribute("value", Convert.ToString(m_value));
if (m_type == "string")
paramXe.SetAttribute("value", (string)m_value);
//3. 反解析LinkEvents
XmlElement lesxe = xd.CreateElement("linkevents");
foreach(string en in m_linkEventsName)
{
XmlElement lexe = xd.CreateElement("linkevent");
lexe.SetAttribute("app_reserve", m_linkEventsApp_res[en]);
lexe.InnerText = en;
lesxe.AppendChild(lexe);
}
paramXe.AppendChild(lesxe);
return paramXe;
}
/// <summary>
/// 记录哪些事件(Event)需要对该变量进行处理
/// </summary>
public List<string> linkEvents{
get{
return m_linkEventsName;
}
}
public Dictionary<string, string> linkEventsApp_res
{
get
{
return m_linkEventsApp_res;
}
}
/// <summary>
/// 根据变量类型设置初始值
/// </summary>
private void SetInitValue(){
if (m_value != null)
return;
try
{
switch(m_type)
{
case "string":
m_value = "";
break;
case "int":
m_value = 0;
break;
case "bool":
m_value = false;
break;
case "float":
m_value = 1.0;
break;
default:
throw new Exception("Unkown Param type");
}
}
catch(Exception e)
{
Trace.WriteLine(e.Message);
}
}
/// <summary>
/// 监测值value是否可以设置为该变量的值
/// </summary>
/// <param name="value"></param>
public bool ValueTest(string value){
try
{
switch(m_type)
{
case "string":
Convert.ToString(value);
break;
case "int":
Convert.ToInt32(value);
break;
case "bool":
Convert.ToBoolean(value);
break;
case "float":
Convert.ToDouble(value);
break;
default:
throw new Exception("Unkown Param type");
}
}
catch
{
Trace.WriteLine(value + " can't convert to " + m_type);
return false;
}
return true;
}
}//end CParam
}//end namespace Param<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApp.Models.DateTables
{
public class DtRequest
{
public static Dictionary<string, object> HttpData(IEnumerable<KeyValuePair<string, string>> dataIn)
{
var dataOut = new Dictionary<string, object>();
if (dataIn != null)
{
foreach (var pair in dataIn)
{
var value = _HttpConv(pair.Value);
if (pair.Key.Contains('['))
{
var keys = pair.Key.Split('[');
var innerDic = dataOut;
string key;
for (int i = 0, ien = keys.Count() - 1; i < ien; i++)
{
key = keys[i].TrimEnd(']');
if (key == "")
{
// If the key is empty it is an array index value
key = innerDic.Count().ToString();
}
if (!innerDic.ContainsKey(key))
{
innerDic.Add(key, new Dictionary<string, object>());
}
innerDic = innerDic[key] as Dictionary<string, object>;
}
key = keys.Last().TrimEnd(']');
if (key == "")
{
key = innerDic.Count().ToString();
}
innerDic.Add(key, value);
}
else
{
dataOut.Add(pair.Key, value);
}
}
}
return dataOut;
}
public static object _HttpConv(string dataIn)
{
// Boolean
if (dataIn == "true")
{
return true;
}
if (dataIn == "false")
{
return false;
}
// Numeric looking data, but with leading zero
if (dataIn.IndexOf('0') == 0 && dataIn.Length > 1)
{
return dataIn;
}
try
{
return Convert.ToInt32(dataIn);
}
catch (Exception) { }
try
{
return Convert.ToDecimal(dataIn);
}
catch (Exception) { }
return dataIn;
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using FlowEngine.TimerManage;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A5dot2Controller : CommonController
{
private SxglManagment Sx = new SxglManagment();
public ActionResult Index1()
{
DateTime time = DateTime.Now;
string morentime = time.Year.ToString() + "-" + time.Month.ToString();
ViewBag.currenttime = morentime;
return View();
}
public ActionResult Index()
{
return View(getRecord());
}
//GET: /A5dot1/装置提报
public ActionResult ShuxiangCheck(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult PqConfirm(string id)
{
return View(getRecord_detail(id));
}
public ActionResult SBShuxiang(DateTime time)
{
return View(getRecord_detailTab2(time));
}
public ActionResult JdcSummary(DateTime time)
{
return View(jdcSummy(time));
}
public class Index_ModelforA5dot2
{
public List<A5dot2Tab1> Am;
public List<A5dot2Tab1> Hm;
public string time;
public int jwxry;
public int kxxgcs;
public int jdc;
}
public class Index_ModelforA5dot2Tab2
{
public List<A5dot2Tab2> Am;
public List<A5dot2Tab2> Hm;
public string title;
}
public Index_ModelforA5dot2 getRecord()
{
Index_ModelforA5dot2 RecordforA5dot2 = new Index_ModelforA5dot2();
RecordforA5dot2.time = DateTime.Now.ToString();
//ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
RecordforA5dot2.Am = new List<A5dot2Tab1>();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("检维修人员") || pv.Role_Names.Contains("现场工程师"))
RecordforA5dot2.jwxry = 1;
else
RecordforA5dot2.jwxry = 0;
if (pv.Role_Names.Contains("机动处"))
RecordforA5dot2.jdc = 1;
else
RecordforA5dot2.kxxgcs = 0;
if (pv.Department_Name.Contains("机动处"))
RecordforA5dot2.jdc = 1;
else
RecordforA5dot2.jdc = 0;
if (pv.Role_Names.Contains("可靠性工程师"))
{
List<string> cjname = new List<string>();
List<Equip_Archi> EA = pm.Get_Person_Cj(UserId);
foreach (var ea in EA)
{
cjname.Add(ea.EA_Name);
}
List<A5dot2Tab1> miss = Sx.GetSxItem(cjname);
foreach (var item in miss)
{
A5dot2Tab1 a = new A5dot2Tab1();
a.zzName = item.zzName;
a.sbGyCode = item.sbGyCode;
a.sbCode = item.sbCode;
a.jxUserName = item.jxUserName;
a.jxSubmitTime = item.jxSubmitTime;
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.Id = item.Id;
a.temp2 = DateTime.Now.ToString();
RecordforA5dot2.Am.Add(a);
}
RecordforA5dot2.Hm = new List<A5dot2Tab1>();
// List<A5dot2Tab1> His = Jx.GetHisJxItem();
// foreach (var item in His)
// {
// A5dot2Tab1 a = new A5dot2Tab1();
// a.Id = item.Id;
// a.state = item.state;
//
// a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
// RecordforA5dot2.Hm.Add(a);
// }
return RecordforA5dot2;
}
return RecordforA5dot2;
}
public Index_ModelforA5dot2 getRecord_detail(string id)
{
Index_ModelforA5dot2 RecordforA5dot2 = new Index_ModelforA5dot2();
RecordforA5dot2.Am = new List<A5dot2Tab1>();
RecordforA5dot2.Hm = new List<A5dot2Tab1>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int IntId = Convert.ToInt32(id);
List<A5dot2Tab1> miss = Sx.GetSxItem_detail(IntId);
foreach (var item in miss)
{
A5dot2Tab1 a = new A5dot2Tab1();
a.cjName = item.cjName;
a.zzName = item.zzName;
a.sbGyCode = item.sbGyCode;
a.sbCode = item.sbCode;
a.sbType = item.sbType;
a.zyType = item.zyType;
string[] str = (item.problemDescription).Split(new[] { "(未整改)" }, StringSplitOptions.None);
a.problemDescription = str[0];
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.state = item.state;
a.Id = item.Id;
RecordforA5dot2.Am.Add(a);
}
return RecordforA5dot2;
}
public Index_ModelforA5dot2Tab2 getRecordforIndex()
{
Index_ModelforA5dot2Tab2 record = new Index_ModelforA5dot2Tab2();
record.Am = new List<A5dot2Tab2>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
DateTime time = DateTime.Now;
string yearandmonth = "";
if (time.Day > 15)
{
time = time.AddMonths(+1);
yearandmonth = time.Year + "年" + time.Month;
//record.title = time.Year.ToString() + "-" + time.AddMonths(1).Month.ToString() + "月" + "最脏十台机泵";
}
else if (time.Day < 15)
{
yearandmonth = time.Year + "年" + time.Month;
//record.title = time.Year.ToString() + "-" + time.Month.ToString() + "月" + "最脏十台机泵";
}
record.title = "2016-8月最脏十台机泵";
List<A5dot2Tab2> miss = Sx.jdcsum("2016年8");
foreach (var item in miss)
{
A5dot2Tab2 a = new A5dot2Tab2();
//List<A5dot2Tab1> uncomplete = Sx.uncom(item.sbCode,time);
a.cjName = item.cjName;
a.zzName = item.zzName;
a.sbGyCode = item.sbGyCode;
a.sbCode = item.sbCode;
a.sbType = item.sbType;
a.nProblemsInCurMonth = item.nProblemsInCurMonth;
a.nProblemsInCurYear = item.nProblemsInCurYear;//这台最脏设备累计未整改数
a.problemDescription = item.problemDescription;
//string lastmonth = time.Year + "年" + (time.Month-1);
//string lastmp = Sx.lastmonthproblem(lastmonth, item.sbCode);
//if(lastmp!=null)
//{
//string[] distiproblem = lastmp.Split(new char[] { '$' });
//for (int i = 0; i < distiproblem.Length;i++ )
//{
// if(distiproblem[i].Contains("(未整改)"))
// {
// string[] str = distiproblem[i].Split(new[] { "(未整改)" }, StringSplitOptions.None);
// a.problemDescription= a.problemDescription+"$"+str[0] + "(上月未整改)";
// }
//}
//}
a.Id = item.Id;
record.Am.Add(a);
}
return record;
}
//A5最脏十台
public string A5zuizang()
{
List<object> r = new List<object>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
DateTime time = DateTime.Now;
string yearandmonth = "";
if(time.Day>15)
{
time = time.AddMonths(+1);
yearandmonth = time.Year + "年" + time.Month;
}
else if(time.Day<15)
{
yearandmonth = time.Year + "年" + time.Month;
}
List<A5dot2Tab2> miss = Sx.jdcsum(yearandmonth);
for (int i = 0; i < miss.Count;i++ )
{
List<A5dot2Tab1> uncomplete = Sx.uncom(miss[i].sbCode, time);
object o = new
{
index = i + 1,
cjname = miss[i].cjName,
zzname = miss[i].zzName,
sbGyCode = miss[i].sbGyCode,
sbCode = miss[i].sbCode,
sbType = miss[i].sbType,
nProblemsInCurMonth = miss[i].nProblemsInCurMonth,
AllProblem = (uncomplete.Count).ToString()//这台最脏设备累计未整改数
};
r.Add(o);
}
//foreach (var item in miss)
//{
// A5dot2Tab2 a = new A5dot2Tab2();
// List<A5dot2Tab1> uncomplete = Sx.uncom(item.sbCode, time);
// a.cjName = item.cjName;
// a.zzName = item.zzName;
// a.sbGyCode = item.sbGyCode;
// a.sbCode = item.sbCode;
// a.sbType = item.sbType;
// a.nProblemsInCurMonth = item.nProblemsInCurMonth;
// a.temp3 = (uncomplete.Count).ToString();//这台最脏设备累计未整改数
// a.problemDescription = item.problemDescription;
// string lastmonth = time.Year + "年" + (time.Month - 1);
// string lastmp = Sx.lastmonthproblem(lastmonth, item.sbCode);
// string[] distiproblem = lastmp.Split(new char[] { '$' });
// for (int i = 0; i < distiproblem.Length; i++)
// {
// if (distiproblem[i].Contains("(未整改)"))
// {
// string[] str = distiproblem[i].Split(new[] { "(未整改)" }, StringSplitOptions.None);
// a.problemDescription = a.problemDescription + "$" + str[0] + "(上月未整改)";
// }
// }
// a.Id = item.Id;
// record.Am.Add(a);
//}
//return record;
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string zuizhang10bytime(string time)
{
DateTime morentime = DateTime.Now;
if(time==null)
{
if (morentime.Day>=15)
{
time = morentime.Year.ToString() + "-" + morentime.AddMonths(1).Month.ToString();
}
else
{
time = morentime.Year.ToString() + "-" + morentime.Month.ToString();
}
}
List<object> r = new List<object>();
List<A5dot2Tab2> zuizang10 = new List<A5dot2Tab2>();
string[] s = time.Split(new char[] { '-' });
string ym = s[0] + "年" + s[1];
DateTime time1 = DateTime.Now;
zuizang10 = Sx.jdcsum(ym);
for (int i = 0; i < zuizang10.Count; i++)
{
//List<A5dot2Tab1> uncomplete = Sx.uncom(zuizang10[i].sbCode, time1);
string problemDescription = zuizang10[i].problemDescription;
//string lastmonth = time1.Year + "年" + (time1.Month - 1);
//string lastmp = Sx.lastmonthproblem(lastmonth, zuizang10[i].sbCode);
//if (lastmp != null)
//{
// string[] distiproblem = lastmp.Split(new char[] { '$' });
// for (int k = 0; k < distiproblem.Length; i++)
// {
// if (distiproblem[k].Contains("(未整改)"))
// {
// string[] str1 = distiproblem[k].Split(new[] { "(未整改)" }, StringSplitOptions.None);
// problemDescription = problemDescription + "$" + str1[0] + "(上月未整改)";
// }
// }
//}
object o = new
{
//index = i + 1,
cjname = zuizang10[i].cjName,
zzname = zuizang10[i].zzName,
sbGyCode = zuizang10[i].sbGyCode,
sbCode = zuizang10[i].sbCode,
sbType = zuizang10[i].sbType,
nProblemsInCurMonth = zuizang10[i].nProblemsInCurMonth,
AllProblem = zuizang10[i].nProblemsInCurYear,
//AllProblem = (uncomplete.Count).ToString(),//这台最脏设备累计未整改数
problemDescription = problemDescription
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public JsonResult ShuxiangCheck_submitsignal(string json1)
{
GetNWorkSerManagment gnm = new GetNWorkSerManagment();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A5dot2Tab1 new_5dot2 = new A5dot2Tab1();
new_5dot2.cjName = item["cjName"].ToString();
new_5dot2.zzName = item["zzName"].ToString();
new_5dot2.sbGyCode = item["sbGyCode"].ToString();
new_5dot2.sbCode = item["sbCode"].ToString();
new_5dot2.sbType = item["sbType"].ToString();
new_5dot2.zyType = item["zyType"].ToString();
new_5dot2.problemDescription = item["problemDescription"].ToString();
new_5dot2.jxSubmitTime = DateTime.Now;
new_5dot2.jxUserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_5dot2.isRectified = 0;
new_5dot2.state = 0;
new_5dot2.temp2 = gnm.AddNWorkEntity("A5dot2").WE_Ser; ;
bool res = Sx.AddSxItem(new_5dot2);
return Json(new { result = res });
}
public JsonResult Pq_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A5dot2Tab1 new_5dot21 = new A5dot2Tab1();
new_5dot21.pqCheckTime = DateTime.Now;
new_5dot21.pqUserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_5dot21.isRectified = Convert.ToInt32(item["isRectified"]);
new_5dot21.state = 1;
if (Convert.ToInt32(item["isRectified"])==1)
{
//string[] str = (item["problemDescription"].ToString()).Split(new[] { "(未整改)" }, StringSplitOptions.None);//以字符串作为分割条件
new_5dot21.problemDescription = item["problemDescription"].ToString() + "(已整改)";
}
if (Convert.ToInt32(item["isRectified"]) == 0)
{
new_5dot21.problemDescription = item["problemDescription"].ToString() + "(未整改)";
}
new_5dot21.Id = Convert.ToInt32(item["A5dot2Tab1_id"].ToString());
string res = Sx.ModifySxItem(new_5dot21);
int a_id = Convert.ToInt32(item["A5dot2Tab1_id"].ToString());
if (Sx.getAllbyid(a_id).temp3 != null)
{
int missId = Convert.ToInt32(Sx.getAllbyid(a_id).temp3);
var t = CTimerManage.LoadTimerMission(missId);
if (t != null)
{
t.status = TM_STATUS.TM_FINISH;
t.Save();
CTimerManage.RemoveFromActiveList(t.ID);
}
}
//接收返回的设备工艺号
A5dot2Tab2 new_5dot22 = new A5dot2Tab2();
List<A5dot2Tab2> IsExist = Sx.GetA5dot2Tab2Item(res);
if(IsExist.Count==0)
{
//传到表2若没有则添加一条数据,如果有则修改该条数据
DateTime i = DateTime.Now;
string yearmonth = "";
if (i.Day >= 15)
{
yearmonth = i.Year.ToString() + "年" + i.AddMonths(1).Month.ToString();
}
else
{
yearmonth = i.Year.ToString() + "年"+ i.Month.ToString();
}
new_5dot22.cjName = item["cjName"].ToString();
new_5dot22.zzName = item["zzName"].ToString();
new_5dot22.sbGyCode = item["sbGyCode"].ToString();
new_5dot22.sbCode = item["sbCode"].ToString();
new_5dot22.sbType = item["sbType"].ToString();
new_5dot22.zyType = item["zyType"].ToString();
if (Convert.ToInt32(item["isRectified"]) == 1)
{
new_5dot22.problemDescription = item["problemDescription"].ToString() + "(已整改)";
}
if (Convert.ToInt32(item["isRectified"]) == 0)
{
new_5dot22.problemDescription = item["problemDescription"].ToString() + "(未整改)";
}
new_5dot22.state = 1;
new_5dot22.nProblemsInCurMonth = 1;
new_5dot22.nProblemsInCurYear = 1;
new_5dot22.isSetAsTop10Worst = 0;
new_5dot22.yearMonthForStatistic = yearmonth;
bool has=Sx.AddA5dot2Tab2Item(new_5dot22);
}
//修改该条数据
else
{
DateTime i = DateTime.Now;
string yearmonth = "";
if (i.Day >= 15)
{
yearmonth = i.Year.ToString() + "年" + i.AddMonths(1).Month.ToString();
}
else
{
yearmonth = i.Year.ToString() + "年" + i.Month.ToString();
}
new_5dot22.cjName = item["cjName"].ToString();
new_5dot22.zzName = item["zzName"].ToString();
new_5dot22.sbGyCode = item["sbGyCode"].ToString();
new_5dot22.sbCode = item["sbCode"].ToString();
new_5dot22.sbType = item["sbType"].ToString();
if (Convert.ToInt32(item["isRectified"]) == 1)
{
new_5dot22.problemDescription = item["problemDescription"].ToString() + "(已整改)";
}
if (Convert.ToInt32(item["isRectified"]) == 0)
{
new_5dot22.problemDescription = item["problemDescription"].ToString() + "(未整改)";
}
new_5dot22.zyType = item["zyType"].ToString();
new_5dot22.sbCode = item["sbCode"].ToString();
new_5dot22.state = 1;
new_5dot22.nProblemsInCurMonth = 1;
new_5dot22.nProblemsInCurYear = 1;
new_5dot22.isSetAsTop10Worst = 0;
new_5dot22.yearMonthForStatistic = yearmonth;
bool has = Sx.ModifyA5dot2Tab2Item(new_5dot22);
}
return Json(new { result = res });
}
public Index_ModelforA5dot2Tab2 getRecord_detailTab2(DateTime time)
{
Index_ModelforA5dot2Tab2 RecordforA5dot2Tab2 = new Index_ModelforA5dot2Tab2();
RecordforA5dot2Tab2.Am = new List<A5dot2Tab2>();
RecordforA5dot2Tab2.Hm = new List<A5dot2Tab2>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string yearandmonth = time.Year + "年" + time.Month;
List<A5dot2Tab2> miss = Sx.GetA5dot2Tab2ItemForPq(yearandmonth);
foreach(var item in miss)
{
A5dot2Tab2 a = new A5dot2Tab2();
a.cjName = item.cjName;
a.zzName = item.zzName;
a.sbGyCode = item.sbGyCode;
a.sbCode = item.sbCode;
a.nProblemsInCurMonth = item.nProblemsInCurMonth;
a.nProblemsInCurYear = Sx.GetnProblemsInYearItem(item.sbCode);
a.Id = item.Id;
RecordforA5dot2Tab2.Am.Add(a);
}
//List<A5dot2Tab1> miss = Sx.GetSxItem_detail(IntId);
//foreach (var item in miss)
//{
// A5dot2Tab1 a = new A5dot2Tab1();
// a.cjName = item.cjName;
// a.zzName = item.zzName;
// a.sbGyCode = item.sbGyCode;
// a.sbCode = item.sbCode;
// a.sbType = item.sbType;
// a.zyType = item.zyType;
// a.problemDescription = item.problemDescription;
// a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
// a.state = item.state;
// a.Id = item.Id;
// RecordforA5dot2.Am.Add(a);
//}
return RecordforA5dot2Tab2;
}
public JsonResult SBShuxiang_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
bool res = false;
string jdcuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string IDArray = item["IDArray"].ToString();
string[] ID = IDArray.Split(new char[] { ',' });
for (int i = 0; i < ID.Length-1;i++ )
{
res = Sx.IsSetWorse(ID[i], jdcuser);
}
return Json(new { result = res });
}
public Index_ModelforA5dot2Tab2 jdcSummy(DateTime time)
{
Index_ModelforA5dot2Tab2 jdcSummy = new Index_ModelforA5dot2Tab2();
jdcSummy.Am = new List<A5dot2Tab2>();
jdcSummy.Hm = new List<A5dot2Tab2>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string yearandmonth = time.Year + "年" + time.Month;
List<A5dot2Tab2> miss = Sx.jdcsum(yearandmonth);
foreach (var item in miss)
{
A5dot2Tab2 a = new A5dot2Tab2();
a.cjName = item.cjName;
a.zzName = item.zzName;
a.sbGyCode = item.sbGyCode;
a.sbCode = item.sbCode;
a.problemDescription = item.problemDescription;
a.Id = item.Id;
jdcSummy.Am.Add(a);
}
return jdcSummy;
}
}
}<file_sep>using FlowDesigner.ConfigItems;
using FlowDesigner.customcontrol;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml;
namespace FlowDesigner.Management
{
public class param
{
public string Name { get; set; }
public string Type { get; set; }
public string Desc { get; set; }
}
/// <summary>
/// 工作流管理
/// </summary>
public class WorkFlowMan
{
public WorkFlowMan(string name, string desc)
{
Name = name;
Description = desc;
designer = new DesignerPage();
designer.Title = Name;
designer.parent_man = this;
designer.LinkClick(this.OnCanvasClick);
designer.LinkMouseMove(this.OnCanvasMouseMove);
//PerAddNEvent = false;
perAddNFlow = 0;
params_table = new ObservableCollection<param>();
designer.ParamsList.ItemsSource = params_table;
}
#region private property
/// <summary>
/// 工作流设计界面
/// </summary>
private DesignerPage designer;
/// <summary>
/// 工作流设计界面插入到父界面元素
/// </summary>
private TabControl parent;
/// <summary>
/// 工作流的定义元素
/// </summary>
private List<ConfigItem> wf_itmes = new List<ConfigItem>();
private int for_events = 1;
private bool m_perAddNEvent = false;
private ConfigItem Curr_Selected = null;
public void InitStartAndEnd()
{
//start
ConfigEvent newSE = new ConfigEvent("StartEvent");
newSE.name = "Start";
newSE.description = "Start";
newSE.OnSelected += this.Proj.win_main.OnConfigItem_Selected;
newSE.SetPos(50, 50);
wf_itmes.Add(newSE);
this.designer.Client.Children.Add(newSE.GetShowItem());
//end
ConfigEvent newEE = new ConfigEvent("EndEvent");
newEE.name = "End";
newEE.description = "End";
newEE.OnSelected += this.Proj.win_main.OnConfigItem_Selected;
newEE.SetPos(50, 150);
wf_itmes.Add(newEE);
this.designer.Client.Children.Add(newEE.GetShowItem());
}
#endregion
#region public property
/// <summary>
/// 工作流名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 工作流描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 变量表
/// </summary>
public ObservableCollection<param> params_table { get; set; }
public string NewEventType { get; set; }
public bool PerAddNEvent
{
get
{
return m_perAddNEvent;
}
set
{
m_perAddNEvent = value;
if (m_perAddNEvent == false)
{
this.Proj.win_main.EndAddNEvent();
}
}
}
public int perAddNFlow { get; set; }
public WorkFlowsProj Proj { get; set; }
//新添加的flow
private ConfigFlow ForAdd = null;
public ConfigItem SelectedItem {
get {
return Curr_Selected;
}
set {
foreach(ConfigItem ce in wf_itmes)
{
if (ce != value)
ce.UnSelect();
else
ce.Selected();
}
if (perAddNFlow == 1) //为flow设置起始Event
{
if (value.GetType().Name == "ConfigEvent"
|| value.GetType().Name == "ConfigSubEvent"
|| value.GetType().Name == "ConfigLoopEvent")
{
//创建新flow
ForAdd = new ConfigFlow();
ForAdd.Start = ((ConfigEvent)value);
designer.Client.Children.Add(ForAdd.GetShowItem());
perAddNFlow = 2;
}
}
else if (perAddNFlow == 2) //为flow设置
{
//暂时不允许flow的start, end相等
if ((value.GetType().Name == "ConfigEvent"
|| value.GetType().Name == "ConfigSubEvent"
|| value.GetType().Name == "ConfigLoopEvent")
&& value != Curr_Selected)
{
ForAdd.End = ((ConfigEvent)value);
ForAdd.Connect();
wf_itmes.Add(ForAdd);
((ConfigEvent)ForAdd.Start).AttachFlows(ForAdd);
((ConfigEvent)ForAdd.End).AttachFlows(ForAdd);
ForAdd.OnSelected += this.Proj.win_main.OnConfigItem_Selected;
ForAdd.OnRightButtonUp += ((MainWindow)Application.Current.MainWindow).pop_itemmenu;
perAddNFlow = 0;
Proj.win_main.AddNewFlow.IsChecked = false;
}
}
Curr_Selected = value;
}
}
public List<ConfigEvent> GetAllEvents()
{
List<ConfigEvent> events = new List<ConfigEvent>();
foreach(ConfigItem ci in wf_itmes)
{
if (ci.GetType().Name == "ConfigEvent"
|| ci.GetType().Name == "ConfigSubEvent")
events.Add((ConfigEvent)ci);
}
return events;
}
#endregion
#region method
/// <summary>
/// 将设计界面插入到主界面中
/// </summary>
/// <param name="mainTab"></param>
public void LinkToMainTab(TabControl mainTab )
{
mainTab.Items.Add(this.designer);
mainTab.SelectedItem = this.designer;
parent = mainTab;
}
public void UnLinkFromMainTab(TabControl mainTab)
{
if (mainTab.Items.Contains(this.designer))
mainTab.Items.Remove(this.designer);
parent = null;
}
public void DeleteParam(string paramName)
{
foreach(param pa in params_table)
{
if (pa.Name == paramName)
{
params_table.Remove(pa);
break;
}
}
foreach (ConfigItem ci in wf_itmes)
{
if (ci.GetType().Name == "ConfigEvent"
|| ci.GetType().Name == "ConfigSubEvent")
{
((ConfigEvent)ci).LinkParams.Remove(paramName);
}
}
}
public void DeleteItem(ConfigItem deleted)
{
if (deleted.GetType().Name == "ConfigFlow")
{
this.designer.Client.Children.Remove(deleted.GetShowItem());
(deleted as ConfigFlow).Start.DetachFlow((ConfigFlow)deleted);
(deleted as ConfigFlow).End.DetachFlow((ConfigFlow)deleted);
wf_itmes.Remove(deleted);
}
else if (deleted.GetType().Name == "ConfigEvent" || deleted.GetType().Name == "ConfigSubEvent")
{
List<ConfigFlow> flows = deleted.GetAttachFolws();
foreach (ConfigFlow cf in flows)
{
this.designer.Client.Children.Remove(cf.GetShowItem());
wf_itmes.Remove(deleted);
}
flows.Clear();
this.designer.Client.Children.Remove(deleted.GetShowItem());
wf_itmes.Remove(deleted);
}
}
/// <summary>
/// 添加一个事件
/// </summary>
/// <param name="eType"></param>
public ConfigEvent AddNewEvent(string eType)
{
ConfigEvent newE = null;
switch(eType)
{
case "NormalEvent":
newE = new ConfigEvent(eType);
break;
case "SubProcess":
newE = new ConfigSubEvent(eType);
break;
case "StartEvent":
newE = new ConfigEvent(eType);
break;
case "EndEvent":
newE = new ConfigEvent(eType);
break;
case "LoopEvent":
newE = new ConfigLoopEvent(eType);
break;
default:
newE = null;
break;
}
if (newE == null)
return null;
newE.name = "event" + for_events.ToString();
newE.description = "event" + for_events.ToString();
newE.OnSelected += this.Proj.win_main.OnConfigItem_Selected;
if (eType != "StartEvent" && eType != "EndEvent")
newE.OnRightButtonUp += ((MainWindow)Application.Current.MainWindow).pop_itemmenu;
wf_itmes.Add(newE);
for_events += 1;
return newE;
}
/// <summary>
/// 左边树形菜单有元素被选择(双击)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSelected(object sender, MouseButtonEventArgs e)
{
if ((TabControl)designer.Parent == null)
parent.Items.Add(this.designer);
((TabControl)designer.Parent).SelectedItem = this.designer;
Proj.CurrentWF = this;
Proj.win_main.OnConfigItem_Selected(SelectedItem);
}
public void UnlinkOtherWFM(WorkFlowMan wfm)
{
if (wfm == null)
return;
foreach (ConfigItem ci in wf_itmes)
{
if (ci.GetType().Name == "ConfigSubEvent")
{
if (((ConfigSubEvent)ci).LinkWorkFLow == wfm.Name)
{
((ConfigSubEvent)ci).LinkWorkFLow = "";
((ConfigSubEvent)ci).LinkParams.Clear();
}
}
}
}
public void OnCanvasClick(object sender, MouseButtonEventArgs e)
{
if (PerAddNEvent == true)
{
ConfigEvent ne = AddNewEvent(NewEventType);
ne.SetPos((int)e.GetPosition((Canvas)sender).X - 75, (int)e.GetPosition((Canvas)sender).Y - 35);
designer.Client.Children.Add(ne.GetShowItem());
PerAddNEvent = false;
Proj.win_main.AddNEvent.IsChecked = false;
Proj.win_main.AddSEvent.IsChecked = false;
}
}
public void OnCanvasMouseMove(object sender, MouseEventArgs e)
{
if (perAddNFlow == 2) //已设置好起点
{
ForAdd.DynamicDraw(e.GetPosition((Canvas)sender));
}
}
public XmlElement SaveWorkFlow(XmlDocument Owner)
{
XmlElement wf_xml = Owner.CreateElement("work_flow");
wf_xml.SetAttribute("name", Name);
wf_xml.SetAttribute("desc", Description);
//
XmlElement eId = Owner.CreateElement("for_events");
eId.SetAttribute("value", for_events.ToString());
wf_xml.AppendChild(eId);
//params
XmlElement pas_xml = Owner.CreateElement("params");
foreach(param pa in params_table)
{
XmlElement pa_xml = Owner.CreateElement("param");
pa_xml.SetAttribute("name", pa.Name);
pa_xml.SetAttribute("type", pa.Type);
pa_xml.SetAttribute("desc", pa.Desc);
pas_xml.AppendChild(pa_xml);
}
wf_xml.AppendChild(pas_xml);
//ConfigItem
XmlElement items_xml = Owner.CreateElement("configitems");
foreach (ConfigItem ci in wf_itmes)
{
XmlElement item_xml = ci.SaveConfigItem(Owner);
items_xml.AppendChild(item_xml);
}
wf_xml.AppendChild(items_xml);
return wf_xml;
}
public bool LoadWorkFlow(XmlElement source)
{
//params
XmlElement pars_xml = (XmlElement)source.SelectSingleNode("params");
XmlNodeList parss = pars_xml.SelectNodes("param");
foreach(XmlNode xn in parss)
{
XmlElement xe = (XmlElement)xn;
bool flag = false;
foreach(param pa in params_table)
{
if (pa.Name == xe.GetAttribute("name"))
{
flag = true;
break;
}
}
if (flag == false)
{
params_table.Add(new param()
{
Name = xe.GetAttribute("name"),
Type = xe.GetAttribute("type"),
Desc = xe.GetAttribute("desc")
});
}
}
//ConfigItem
XmlElement items_xml = (XmlElement)source.SelectSingleNode("configitems");
foreach (XmlNode xn1 in items_xml.SelectNodes("item"))
{
XmlElement xe1 = (XmlElement)xn1;
if (xe1.GetAttribute("item_type") == "event")
{
ConfigEvent ce = AddNewEvent(xe1.GetAttribute("event_type"));
ce.authority = xe1.GetAttribute("authority");
ce.GetShowItem().Margin = new Thickness(
Convert.ToDouble(((XmlElement)xe1.SelectSingleNode("shape")).GetAttribute("margin").Split(',')[0]),
Convert.ToDouble(((XmlElement)xe1.SelectSingleNode("shape")).GetAttribute("margin").Split(',')[1]),
Convert.ToDouble(((XmlElement)xe1.SelectSingleNode("shape")).GetAttribute("margin").Split(',')[1]),
Convert.ToDouble(((XmlElement)xe1.SelectSingleNode("shape")).GetAttribute("margin").Split(',')[1]));
ce.CurrentAction = ((XmlElement)xe1.SelectSingleNode("actions")).GetAttribute("currentaction");
XmlElement ba = (XmlElement)(xe1.SelectSingleNode("actions").SelectSingleNode("beforeaction"));
XmlElement aa = (XmlElement)(xe1.SelectSingleNode("actions").SelectSingleNode("afteraction"));
if (ba != null) //新版本
{
ce.BeforeAction.url = ba.GetAttribute("url");
XmlNodeList act_pars = ba.SelectSingleNode("action_params").SelectNodes("param");
ce.BeforeAction.action_params.Clear();
foreach (XmlNode parxn in act_pars)
{
ce.BeforeAction.action_params[((XmlElement)parxn).GetAttribute("name")] = ((XmlElement)parxn).InnerText;
}
ce.AfterAction.url = aa.GetAttribute("url");
XmlNodeList act_pars1 = aa.SelectSingleNode("action_params").SelectNodes("param");
ce.AfterAction.action_params.Clear();
foreach (XmlNode parxn in act_pars1)
{
ce.AfterAction.action_params[((XmlElement)parxn).GetAttribute("name")] = ((XmlElement)parxn).InnerText;
}
}
else
{
ce.BeforeAction.url = ((XmlElement)xe1.SelectSingleNode("actions")).GetAttribute("beforeaction");
ce.AfterAction.url = ((XmlElement)xe1.SelectSingleNode("actions")).GetAttribute("afteraction");
}
XmlNodeList parsss = xn1.SelectSingleNode("link_params").SelectNodes("param");
foreach(XmlNode xn2 in parsss)
{
ce.LinkParams.Add(((XmlElement)xn2).GetAttribute("name"), ((XmlElement)xn2).GetAttribute("app_reserve"));
}
ce.name = xe1.GetAttribute("name");
ce.description = xe1.GetAttribute("desc");
//time_out
XmlNode time_out = xn1.SelectSingleNode("time_out");
if (time_out != null)
{
Dictionary<string, object> timeout_setting = (ce.Time_Out as Dictionary<string, object>);
XmlNode time_start = time_out.SelectSingleNode("start");
if (time_start == null)
timeout_setting["start"] = "";
else
timeout_setting["start"] = time_start.InnerText;
XmlNode time_offset = time_out.SelectSingleNode("offset");
if (time_offset == null || time_offset.InnerText == "")
timeout_setting["offset"] = (null as TimeSpan?);
else
{
TimeSpan? ts = TimeSpan.Parse(time_offset.InnerText);
timeout_setting["offset"] = ts;
}
XmlNode time_exact = time_out.SelectSingleNode("exact");
if (time_exact == null || time_exact.InnerText == "")
timeout_setting["exact"] = (null as DateTime?);
else
{
DateTime? dt = DateTime.Parse(time_exact.InnerText);
timeout_setting["exact"] = dt;
}
XmlNode time_action = time_out.SelectSingleNode("action");
if (time_action == null)
timeout_setting["action"] = "";
else
timeout_setting["action"] = time_action.InnerText;
XmlNode time_callback = time_out.SelectSingleNode("callback");
if (time_callback == null)
timeout_setting["callback"] = "";
else
timeout_setting["callback"] = time_callback.InnerText;
}
if (ce.GetType().Name == "ConfigSubEvent")
{
((ConfigSubEvent)ce).SetWorkModel(((XmlElement)xe1.SelectSingleNode("LinkWorkflow")).GetAttribute("model"));
((ConfigSubEvent)ce).LinkWorkFLow = ((XmlElement)xe1.SelectSingleNode("LinkWorkflow")).GetAttribute("name");
XmlNodeList param_transfer = ((XmlElement)xe1.SelectSingleNode("LinkWorkflow")).SelectNodes("ParamTransfer");
foreach(XmlNode pt in param_transfer)
{
((ConfigSubEvent)ce).ParamTransfer.Add(new paramtransfer_item()
{
parent = ((XmlElement)pt).GetAttribute("source"),
child = ((XmlElement)pt).GetAttribute("dest"),
direction = ((XmlElement)pt).GetAttribute("direction") == "from" ? transfer_direction.from : transfer_direction.to
});
}
}
if (ce.GetType().Name == "ConfigLoopEvent")
{
((ConfigLoopEvent)ce).LoopCondition = (xe1.SelectSingleNode("LoopSetting").SelectSingleNode("condition") as XmlElement).InnerText;
((ConfigLoopEvent)ce).TimeWaiting = (xe1.SelectSingleNode("LoopSetting").SelectSingleNode("waiting_time") as XmlElement).InnerText;
}
designer.Client.Children.Add(ce.GetShowItem());
}
}
//flow
foreach (XmlNode xn3 in items_xml.SelectNodes("item"))
{
XmlElement xe2 = (XmlElement)xn3;
if (xe2.GetAttribute("item_type") == "flow")
{
ConfigFlow cf = new ConfigFlow();
foreach(ConfigItem ci in wf_itmes)
{
if ((ci.GetType().Name == "ConfigEvent" || ci.GetType().Name == "ConfigSubEvent" || ci.GetType().Name == "ConfigLoopEvent")
&& ci.name == ((XmlElement)xe2.SelectSingleNode("shape")).GetAttribute("source"))
{
cf.Start = (ConfigEvent)ci;
((ConfigEvent)ci).AttachFlows(cf);
}
if ((ci.GetType().Name == "ConfigEvent" || ci.GetType().Name == "ConfigSubEvent" || ci.GetType().Name == "ConfigLoopEvent")
&& ci.name == ((XmlElement)xe2.SelectSingleNode("shape")).GetAttribute("dest"))
{
cf.End = (ConfigEvent)ci;
((ConfigEvent)ci).AttachFlows(cf);
}
}
cf.Express = xe2.GetAttribute("condition");
cf.OnSelected += this.Proj.win_main.OnConfigItem_Selected;
cf.OnRightButtonUp += ((MainWindow)Application.Current.MainWindow).pop_itemmenu;
designer.Client.Children.Add(cf.GetShowItem());
cf.Connect();
wf_itmes.Add(cf);
}
}
for_events = Convert.ToInt32(((XmlElement)source.SelectSingleNode("for_events")).GetAttribute("value"));
return true;
}
private XmlElement ComplieParamTable(XmlDocument Owner)
{
XmlElement root = Owner.CreateElement("paramtable");
foreach (param pa in params_table)
{
XmlElement pa_xml = Owner.CreateElement("param");
pa_xml.SetAttribute("name", pa.Name);
pa_xml.SetAttribute("desc", pa.Desc);
pa_xml.SetAttribute("type", pa.Type);
//linkevents
XmlElement les = Owner.CreateElement("linkevents");
foreach(ConfigItem ci in wf_itmes)
{
if (ci.GetType().Name != "ConfigEvent"
&& ci.GetType().Name != "ConfigSubEvent"
&& ci.GetType().Name != "ConfigLoopEvent")
continue;
if (((ConfigEvent)ci).LinkParams.ContainsKey(pa.Name))
{
XmlElement le = Owner.CreateElement("linkevent");
le.SetAttribute("app_reserve", ((ConfigEvent)ci).LinkParams[pa.Name]);
le.InnerText = ci.name;
les.AppendChild(le);
}
}
pa_xml.AppendChild(les);
root.AppendChild(pa_xml);
}
return root;
}
private XmlElement CompleLinkWorkFlowForSubEvent(XmlDocument Owner, ConfigSubEvent se)
{
XmlElement link = Owner.CreateElement("linkworkflow");
link.SetAttribute("name", se.LinkWorkFLow);
link.SetAttribute("workingmodel", se.WorkingModel.ToString());
XmlElement pt = Owner.CreateElement("paramtransfer");
foreach(paramtransfer_item pi in se.ParamTransfer)
{
XmlElement tr = Owner.CreateElement("item");
tr.SetAttribute("parent", pi.parent);
tr.SetAttribute("child", pi.child);
tr.SetAttribute("direction", pi.direction.ToString());
pt.AppendChild(tr);
}
link.AppendChild(pt);
return link;
}
private XmlElement CompleEvents(XmlDocument Owner)
{
XmlElement events = Owner.CreateElement("events");
foreach (ConfigItem ci in wf_itmes)
{
if (ci.GetType().Name != "ConfigEvent"
&& ci.GetType().Name != "ConfigSubEvent"
&& ci.GetType().Name != "ConfigLoopEvent")
continue;
XmlElement ev = Owner.CreateElement("event");
ev.SetAttribute("name", ci.name);
ev.SetAttribute("desc", ci.description);
ev.SetAttribute("type", ((ConfigEvent)ci).GetEventType().ToLower());
XmlElement actions = Owner.CreateElement("actions");
XmlElement ba = Owner.CreateElement("beforeaction");
XmlElement baurl = Owner.CreateElement("url");
baurl.AppendChild(Owner.CreateCDataSection(((ConfigEvent)ci).BeforeAction.url));
ba.AppendChild(baurl);
XmlElement ba_params = Owner.CreateElement("action_params");
foreach(var pp in ((ConfigEvent)ci).BeforeAction.action_params)
{
XmlElement pe = Owner.CreateElement("param");
pe.SetAttribute("name", pp.Key);
pe.InnerText = pp.Value;
ba_params.AppendChild(pe);
}
ba.AppendChild(ba_params);
actions.AppendChild(ba);
XmlElement ca = Owner.CreateElement("currentaction");
ca.AppendChild(Owner.CreateCDataSection(((ConfigEvent)ci).CurrentAction));
actions.AppendChild(ca);
XmlElement aa = Owner.CreateElement("afteraction");
XmlElement aaurl = Owner.CreateElement("url");
aaurl.AppendChild(Owner.CreateCDataSection(((ConfigEvent)ci).AfterAction.url));
aa.AppendChild(aaurl);
XmlElement aa_params = Owner.CreateElement("action_params");
foreach (var pp in ((ConfigEvent)ci).AfterAction.action_params)
{
XmlElement pe = Owner.CreateElement("param");
pe.SetAttribute("name", pp.Key);
pe.InnerText = pp.Value;
aa_params.AppendChild(pe);
}
aa.AppendChild(aa_params);
actions.AppendChild(aa);
ev.AppendChild(actions);
XmlElement auts = Owner.CreateElement("authority");
auts.AppendChild(Owner.CreateCDataSection(((ConfigEvent)ci).authority));
ev.AppendChild(auts);
//构建timeout
XmlElement toNode = Owner.CreateElement("timeout_setting");
Dictionary<string, object> time_out = (((ConfigEvent)ci).Time_Out as Dictionary<string, object>);
toNode.SetAttribute("action", time_out.ContainsKey("action") ? time_out["action"] as string : "");
//1. 构建具体时间节点
if ((time_out["exact"] as DateTime?) != null)
{
XmlElement et = Owner.CreateElement("exact_time");
et.InnerText = time_out.ContainsKey("exact") ? (time_out["exact"] as DateTime?).Value.ToString() : "";
toNode.AppendChild(et);
}
//2. 构建偏移时间节点
if ((time_out["start"] as string) != "" && (time_out["offset"] as TimeSpan?) != null)
{
XmlElement ot = Owner.CreateElement("offset_time");
string time_start = time_out.ContainsKey("start") ? (time_out["start"] as string) : "";
ot.SetAttribute("time_start", time_start);
ot.SetAttribute("time_offset", time_out.ContainsKey("offset") ? (time_out["offset"] as TimeSpan?).Value.ToString() : "");
toNode.AppendChild(ot);
}
//3. 构建callback节点
XmlElement cb = Owner.CreateElement("call_back");
cb.AppendChild(Owner.CreateCDataSection(time_out.ContainsKey("callback") ? (time_out["callback"] as string) : ""));
toNode.AppendChild(cb);
ev.AppendChild(toNode);
if (ci.GetType().Name == "ConfigSubEvent")
ev.AppendChild(CompleLinkWorkFlowForSubEvent(Owner, (ConfigSubEvent)ci));
if (ci.GetType().Name == "ConfigLoopEvent")
{
XmlElement con_elem = Owner.CreateElement("loop_contidion");
con_elem.AppendChild(Owner.CreateCDataSection((ci as ConfigLoopEvent).LoopCondition));
ev.AppendChild(con_elem);
XmlElement looptime = Owner.CreateElement("loop_time");
looptime.AppendChild(Owner.CreateCDataSection((ci as ConfigLoopEvent).TimeWaiting));
ev.AppendChild(looptime);
}
events.AppendChild(ev);
}
return events;
}
private XmlElement CompleFlows(XmlDocument Owner)
{
XmlElement flows = Owner.CreateElement("flows");
foreach (ConfigItem ci in wf_itmes)
{
if (ci.GetType().Name != "ConfigFlow")
continue;
XmlElement flow = Owner.CreateElement("flow");
flow.SetAttribute("source", ((ConfigFlow)ci).StartEvent);
flow.SetAttribute("destination", ((ConfigFlow)ci).EndEvent);
XmlElement condition = Owner.CreateElement("condition");
condition.AppendChild(Owner.CreateCDataSection(((ConfigFlow)ci).Express));
flow.AppendChild(condition);
flows.AppendChild(flow);
}
return flows;
}
public bool Complie(string filePath)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("workflow");
//1. set workflow attributions
root.SetAttribute("name", Name);
root.SetAttribute("desc", Description);
root.SetAttribute("current_event", "");
//2. comple paramtable
XmlElement paramtable = ComplieParamTable(doc);
root.AppendChild(paramtable);
//3. comple events
XmlElement events = CompleEvents(doc);
root.AppendChild(events);
//4. comple flows
XmlElement flows = CompleFlows(doc);
root.AppendChild(flows);
//5. comple records
XmlElement records = doc.CreateElement("recorditems");
foreach(RecordItem ri in Proj.Record_Items)
{
XmlElement item = doc.CreateElement("item");
item.InnerText = ri.Name;
records.AppendChild(item);
}
root.AppendChild(records);
doc.AppendChild(root);
doc.Save(filePath);
return true;
}
#endregion
}
}
<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class SxglManagment
{
private Sxgl db_Sxgl = new Sxgl();
public bool AddSxItem(A5dot2Tab1 add)
{
return db_Sxgl.AddSxRecord(add);
}
public List<A5dot2Tab1> GetSxItem(List<string> cjname)
{
return db_Sxgl.GetSxRecord(cjname);
}
public List<A5dot2Tab1> GetSxItem_detail(int id)
{
return db_Sxgl.GetSxRecord_detail(id);
}
public string ModifySxItem(A5dot2Tab1 add)
{
return db_Sxgl.ModifySxRecord(add);
}
public A5dot2Tab1 getAllbyid(int a_id)
{
return db_Sxgl.getAllbyid(a_id);
}
public string ModifySxItem1(A5dot2Tab1 add)
{
return db_Sxgl.ModifySxRecord1(add);
}
public bool AddA5dot2Tab2Item(A5dot2Tab2 add)
{
return db_Sxgl.AddA5dot2Tab2(add);
}
public List<A5dot2Tab2> GetA5dot2Tab2Item(string add)
{
return db_Sxgl.GetA5dot2Tab2(add);
}
public bool ModifyA5dot2Tab2Item(A5dot2Tab2 add)
{
return db_Sxgl.ModifyA5dot2Tab2(add);
}
public List<A5dot2Tab2> GetA5dot2Tab2ItemForPq(string yearandmonth)
{
return db_Sxgl.GetA5dot2Tab2ForPq(yearandmonth);
}
public int GetnProblemsInYearItem(string sbCode)
{
return db_Sxgl.GetnProblemsInYear(sbCode);
}
public bool IsSetWorse(string id,string user)
{
int IntId = Convert.ToInt32(id);
return db_Sxgl.SetWorse(IntId,user);
}
public List<A5dot2Tab2> jdcsum(string yearandmonth)
{
return db_Sxgl.jdcsummy(yearandmonth);
}
public List<A5dot2Tab1> uncom(string sbCode,DateTime time)
{
return db_Sxgl.uncomp(sbCode,time);
}
public string lastmonthproblem(string lastmonth, string sbCode)
{
return db_Sxgl.forlastmonthproblem(lastmonth, sbCode);
}
public List<A5dot2Tab1> GetLS_listbywfe_id(List<int> wfe_id)
{
return db_Sxgl.GetLS_listbywfe_id(wfe_id);
}
}
}
<file_sep>///////////////////////////////////////////////////////////
// BaseDAO.cs
// Implementation of the Class BaseDAO
// Generated by Enterprise Architect
// Created on: 13-11ÔÂ-2015 14:40:41
// Original author: Chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine.Modals;
namespace FlowEngine.DAL {
public class BaseDAO {
public BaseDAO(){
}
~BaseDAO(){
}
protected FlowEngine.Modals.WorkFlowContext NewDB(){
return new WorkFlowContext();
}
}//end BaseDAO
}//end namespace FlowEngine.DAL<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using FlowEngine.Modals;
using FlowEngine.DAL;
using FlowEngine.Param;
using System.Data;
namespace WebApp.Controllers
{
public class A11dot3Controller : CommonController
{
//
// GET: /A11dot3/
public ActionResult Index()
{
return View(getIndexListRecords("A11dot3", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
public ActionResult CjFollow(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdAdvise(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UpToDirector(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ImplementPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WaitStop(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult Submit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult JdcConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult RiskAccept(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult CreateGroup(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult RiskRegister(string wfe_id)
{
return View(getRecordforRiskRegister(wfe_id));
}
//工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//******************风险登记表取数据******************************//
public class RiskRegisterModel
{
public string zz;//装置
public string sbGycode;//设备位号
public string sbCode;//设备编号
public string problemDesc;//风险问题描述
public string RiskRecognitionResult;//危害识别结果
public string PlanName;//管控措施文件名
public string PlanPath;//管控措施文件路径
public string PlanDesc;//管控措施描述
public string RiskIsAccept;//风险是否可接受
public string CjFollowResult="通过";//车间定期跟踪评估结果
public string YDorTG_Result;
public string WF_Ser;//工作流串号
public string WF_Id;//工作流实体号
}
public RiskRegisterModel getRecordforRiskRegister(string wfe_id)
{
RiskRegisterModel record = new RiskRegisterModel();
WorkFlows wfsd = new WorkFlows();
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(Convert.ToInt32(wfe_id));
List<WorkFlow_Entity> getentity = wfsd.GetWorkFlowEntitiesbySer(wfe.WE_Ser);//通过实体号得到串号,通过串号在得到11.1或11.2的实体号及参数
record.WF_Ser = wfe.WE_Ser;
record.WF_Id = wfe_id;
foreach (var item in getentity)
{
WorkFlow_Define getentity_name = wfsd.GetWorkFlowDefine(item.WE_Id);//通过每个实体号找到该实体号的名字,就可以确定每个实体号的内容
if (getentity_name.W_Name == "A11dot2")
{
List<Mission> db_miss = wfsd.GetWFEntityMissions(item.WE_Id);
foreach(var atc in db_miss)
{
if (atc.Miss_Desc == "现场工程师提报隐患")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.zz = ui_mi.Miss_Params["Zz_Name"].ToString();
record.sbGycode = ui_mi.Miss_Params["Equip_GyCode"].ToString();
record.sbCode = ui_mi.Miss_Params["Equip_Code"].ToString();
record.problemDesc = ui_mi.Miss_Params["Problem_Desc"].ToString();
}
if (atc.Miss_Desc == "可靠性工程师风险矩阵评估")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["RiskMatrix_Color"].ToString() == "yellow")
{
record.RiskRecognitionResult = "一般风险";
}
if (ui_mi.Miss_Params["RiskMatrix_Color"].ToString() == "red")
{
record.RiskRecognitionResult = "重大风险";
}
}
if (atc.Miss_Desc == "专业团队确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Plan_DescFilePath"].ToString() != "")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
if (atc.Miss_Desc == "车间确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Plan_DescFilePath"].ToString() != "")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
if (atc.Miss_Desc == "管控措施实施后确认风险是否可接受,并进行风险登记")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.RiskIsAccept = ui_mi.Miss_Params["RiskIsAcceptable"].ToString();
}
if (atc.Miss_Desc == "管控措施实施后确认风险是否消除,并进行风险登记")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.RiskIsAccept = ui_mi.Miss_Params["RiskIsAcceptable"].ToString();
}
}
}
if (getentity_name.W_Name == "A11dot1")
{
List<Mission> db_miss = wfsd.GetWFEntityMissions(item.WE_Id);
foreach (var atc in db_miss)
{
if (atc.Miss_Desc == "风险提报")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.zz = ui_mi.Miss_Params["Zz_Name"].ToString();
record.sbGycode = ui_mi.Miss_Params["Equip_GyCode"].ToString();
record.sbCode = ui_mi.Miss_Params["Equip_Code"].ToString();
record.problemDesc = ui_mi.Miss_Params["SubmitProblemDesc"].ToString();
}
if (atc.Miss_Desc == "危害识别")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Risk_Type"].ToString() == "一般风险")
{
record.RiskRecognitionResult = "一般风险";
}
if (ui_mi.Miss_Params["Risk_Type"].ToString() == "重大风险")
{
record.RiskRecognitionResult = "重大风险";
}
}
if (atc.Miss_Desc == "评估小组确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Plan_DescFilePath"].ToString() != "")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
if (atc.Miss_Desc == "车间确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if( ui_mi.Miss_Params["Plan_DescFilePath"].ToString()!="")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
}
}
}
return record;
}
//************************************************//
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Risk_IsAcceptable"] = item["Risk_IsAcceptable"].ToString();
signal["flag_NandD"] = item["flag_NandD"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string CjFollow_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CjFollow_Result"] = item["CjFollow_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string WaitStop_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["WaitStop_Result"] = item["WaitStop_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string ZytdAdvise_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
signal["ZytdAdvise_Result"] = item["ZytdAdvise_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string UpToDirector_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["UpToDirector_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string ImplementPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ImplementPlan_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string JdcConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JdcConfirm_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string RiskAccept_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["RiskAccept_Result"] = item["RiskAccept_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string CreateGroup_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CreateGroup_Done"] = item["CreateGroup_Done"].ToString();
signal["Group_Header"] = item["Group_Header"].ToString();
signal["Group_Member"] = item["Group_Member"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public string RiskRegister_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//补充跳转A14dot3的变量,Equip_ABCMark
Dictionary<string, object> paras1 = new Dictionary<string, object>();
paras1["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(Convert.ToInt32(flowname), paras1);
//获取设备ABC标识
EquipManagment tm = new EquipManagment();
Equip_Info getZy = tm.getEquip_ByGyCode(paras1["Equip_GyCode"].ToString());
signal["Equip_ABCMark"] = getZy.Equip_ABCmark;
signal["RiskRegister_Done"] = "true";
signal["YDorTG_Result"] = item["YDorTG_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot3/Index");
}
public class Gxqmodel
{
public string WE_Ser;
public int WE_Id;
}
public string A11HistoryList(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
List<object> or = new List<object>();
string WE_Status = "3";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username,M.Event_Name";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "' and M.Event_Name='RiskRegister" + "' and R.username is not null";
string record_filter = "username is not null";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<HistroyModel> Hm = new List<HistroyModel>();
int ind = 1;
foreach (var arc in Gmlist)
{
RiskRegisterModel record = new RiskRegisterModel();
WorkFlows wfsd = new WorkFlows();
List<WorkFlow_Entity> getentity = wfsd.GetWorkFlowEntitiesbySer(arc.WE_Ser);//通过实体号得到串号,通过串号在得到11.1或11.2的实体号及参数
record.WF_Ser = arc.WE_Ser;
record.WF_Id = Convert.ToString(arc.WE_Id);
foreach (var item in getentity)
{
WorkFlow_Define getentity_name = wfsd.GetWorkFlowDefine(item.WE_Id);//通过每个实体号找到该实体号的名字,就可以确定每个实体号的内容
//List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.WE_Id);
//if (AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc == "风险登记")
//{ }
if (getentity_name.W_Name == "A11dot3")
{
List<Mission> db_miss = wfsd.GetWFEntityMissions(item.WE_Id);
foreach (var atc in db_miss)
{
if (atc.Miss_Desc == "风险登记")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.YDorTG_Result = ui_mi.Miss_Params["YDorTG_Result"].ToString();
}
}
}
if (getentity_name.W_Name == "A11dot2")
{
List<Mission> db_miss = wfsd.GetWFEntityMissions(item.WE_Id);
foreach (var atc in db_miss)
{
if (atc.Miss_Desc == "现场工程师提报隐患")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.zz = ui_mi.Miss_Params["Zz_Name"].ToString();
record.sbGycode = ui_mi.Miss_Params["Equip_GyCode"].ToString();
record.sbCode = ui_mi.Miss_Params["Equip_Code"].ToString();
record.problemDesc = ui_mi.Miss_Params["Problem_Desc"].ToString();
}
if (atc.Miss_Desc == "可靠性工程师风险矩阵评估")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["RiskMatrix_Color"].ToString() == "yellow")
{
record.RiskRecognitionResult = "一般风险";
}
if (ui_mi.Miss_Params["RiskMatrix_Color"].ToString() == "red")
{
record.RiskRecognitionResult = "重大风险";
}
}
if (atc.Miss_Desc == "专业团队确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Plan_DescFilePath"].ToString() != "")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
if (atc.Miss_Desc == "车间确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Plan_DescFilePath"].ToString() != "")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
if (atc.Miss_Desc == "管控措施实施后确认风险是否可接受,并进行风险登记")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.RiskIsAccept = ui_mi.Miss_Params["RiskIsAcceptable"].ToString();
}
if (atc.Miss_Desc == "管控措施实施后确认风险是否消除,并进行风险登记")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.RiskIsAccept = ui_mi.Miss_Params["RiskIsAcceptable"].ToString();
}
}
}
if (getentity_name.W_Name == "A11dot1")
{
List<Mission> db_miss = wfsd.GetWFEntityMissions(item.WE_Id);
foreach (var atc in db_miss)
{
if (atc.Miss_Desc == "风险提报")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.zz = ui_mi.Miss_Params["Zz_Name"].ToString();
record.sbGycode = ui_mi.Miss_Params["Equip_GyCode"].ToString();
record.sbCode = ui_mi.Miss_Params["Equip_Code"].ToString();
record.problemDesc = ui_mi.Miss_Params["SubmitProblemDesc"].ToString();
}
if (atc.Miss_Desc == "危害识别")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Risk_Type"].ToString() == "一般风险")
{
record.RiskRecognitionResult = "一般风险";
}
if (ui_mi.Miss_Params["Risk_Type"].ToString() == "重大风险")
{
record.RiskRecognitionResult = "重大风险";
}
}
if (atc.Miss_Desc == "评估小组确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Plan_DescFilePath"].ToString() != "")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
if (atc.Miss_Desc == "车间确立管控措施")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi.Miss_Params["Plan_DescFilePath"].ToString() != "")
{
string[] PlanFile = ui_mi.Miss_Params["Plan_DescFilePath"].ToString().Split(new char[] { '$' });
record.PlanName = PlanFile[0];
record.PlanPath = PlanFile[1];
}
record.PlanDesc = ui_mi.Miss_Params["Plan_Desc"].ToString();
}
if (atc.Miss_Desc == "管控措施实施后确认风险是否可接受,并进行风险登记")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.RiskIsAccept = ui_mi.Miss_Params["Risk_IsAcceptable"].ToString();
}
if (atc.Miss_Desc == "管控措施实施后确认风险是否消除,并进行风险登记")
{
UI_MISSION ui_mi = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(atc.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
record.RiskIsAccept = ui_mi.Miss_Params["Risk_IsAcceptable"].ToString();
}
}
}
}
object o = new
{
index=ind,
zz = record.zz,
equip_gycode = record.sbGycode,
sbcode = record.sbCode,
problemdesc = record.problemDesc,
RiskRecognitionResult = record.RiskRecognitionResult,
PlanDesc=record.PlanDesc,
PlanName ="/Upload/"+record.PlanPath + "$$" + record.PlanName,
SSQK = "已实施",
RiskIsAccept = record.RiskIsAccept,
FollowResult = record.CjFollowResult,
PlanCategory = record.YDorTG_Result,
};
or.Add(o);
ind++;
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApp.Models.DateTables
{
/// <summary>
/// 分析DataTables的Json返回,定义的一个类
/// 某些字段含义不明
/// </summary>
public class DtResponse
{
public int? draw;
public List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
public int? recordsTotal;
public int? recordsFiltered;
public string error;
public List<FieldError> fieldErrors = new List<FieldError>();
public int? id;
public Dictionary<string, object> meta = new Dictionary<string, object>();
public Dictionary<string, object> options = new Dictionary<string, object>();
public Dictionary<string, Dictionary<string, Dictionary<string, object>>> files =
new Dictionary<string, Dictionary<string, Dictionary<string, object>>>();
public ResponseUpload upload =
new ResponseUpload();
public class FieldError
{
public string name { get; set; }
public string status { get; set; }
}
public class ResponseUpload
{
public dynamic id { get; set; }
}
}
}<file_sep>using FlowEngine.DAL;
using FlowEngine.Modals;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FlowEngine.TimerManage
{
/// <summary>
/// 定时任务
/// </summary>
public abstract class CTimerMission
{
#region 构造函数
public CTimerMission()
{
m_jobFunc = new JobProcessing(this.__processing);
manage = null;
job_id = -1;
type = "";
CustomFlag = 0;
}
#endregion
#region 属性
/// <summary>
/// 任务类型
/// </summary>
public string type { get; set; }
/// <summary>
/// 任务ID
/// </summary>
private int job_id;
public int ID { get { return job_id; } set { job_id = value; } }
/// <summary>
/// 是否处于执行状态
/// </summary>
private Int32 m_isRun = 0;
/// <summary>
/// 定时器误差
/// </summary>
public static int Timer_deviation = 0;
/// <summary>
/// 用于执行任务时,传递的参数列表
/// </summary>
protected object m_run_params;
/// <summary>
/// 任务执行结果
/// </summary>
protected object m_run_result;
/// <summary>
/// 当前任务前一次触发时间
/// </summary>
protected DateTime? m_perTime;
public DateTime? PerTime
{
get { return m_perTime; }
}
/// <summary>
/// 当前任务创建时间
/// </summary>
protected DateTime m_createTime;
public DateTime CreateTime
{
get { return m_createTime; }
set { m_createTime = value; }
}
/// <summary>
/// 用户定义的事件
/// </summary>
public string CustomAction
{
get;
set;
}
/// <summary>
/// 用户定义标签
/// </summary>
public int CustomFlag { get; set; }
/// <summary>
/// 任务执行实体函数
/// </summary>
delegate void JobProcessing();
protected abstract void __processing();
private JobProcessing m_jobFunc;
public CTimerManage manage { get; set; }
/// <summary>
/// 任务状态
/// TM_STATUS_ACTIVE : 激活状态
/// TM_STATUS_STOP: 停止状态
/// </summary>
public TM_STATUS status { get; set; }
/// <summary>
/// 触发时间
/// </summary>
protected TriggerTiming m_triggerT = new TriggerTiming();
/// <summary>
/// 任务名称
/// </summary>
public string mission_name { get; set; }
/// <summary>
/// 任务用途
/// </summary>
public TIMER_USING for_using { get; set; }
private Dictionary<string, object> m_reserve = new Dictionary<string, object>();
#endregion
#region 公共方法
/// <summary>
/// 设置触发时间
/// </summary>
/// <param name="cornStr">Cron 表达式</param>
/// <returns>是正确的Cron表达式,返回true, 否则返回false</returns>
public bool SetTriggerTiming(string cornStr)
{
return m_triggerT.FromString(cornStr);
}
/// <summary>
/// 获得出发时间的字符串表达式
/// </summary>
/// <returns></returns>
public string GetTriggerTimmingString()
{
return m_triggerT.ToString();
}
/// <summary>
/// 解析数据库参数到运行参数
/// </summary>
/// <param name="strPars"></param>
public abstract void ParseRunParam(string strPars);
/// <summary>
/// 解析数据库结果到运行结果
/// </summary>
/// <param name="strResult"></param>
public abstract void ParseRunResult(string strResult);
/// <summary>
/// 解析运行参数到数据库
/// </summary>
/// <returns></returns>
public abstract object ParseRunParamsToJObject();
/// <summary>
/// 解析运行结果到数据库
/// </summary>
/// <returns></returns>
public abstract object ParseRunResultToJobject();
/// <summary>
/// 获得与之关联的工作流
/// </summary>
/// <returns></returns>
public virtual CWorkFlow GetAttachWorkFlow()
{
return null;
}
/// <summary>
/// 检测当前系统时间是否满足触发条件
/// </summary>
/// <returns></returns>
public bool checkTiming()
{
try
{
//获得当前系统时间
DateTime dt = DateTime.Now;
if (m_triggerT.NextTiming == null)
m_triggerT.RefreshNextTiming(dt);
DateTime nextdt = m_triggerT.NextTiming.Value;
//考虑到定时器误差
if (Math.Abs((dt - nextdt).TotalSeconds) <= CTimerMission.Timer_deviation)
return true;
}
catch
{
return false;
}
return false;
}
/// <summary>
/// 设置保留字段的值
/// </summary>
/// <param name="res_name"></param>
/// <param name="value"></param>
public void Set_Res_Value(string res_name, object value)
{
try
{
switch (res_name)
{
case "STR_RES_1":
m_reserve["STR_RES_1"] = Convert.ToString(value);
break;
case "STR_RES_2":
m_reserve["STR_RES_2"] = Convert.ToString(value);
break;
case "STR_RES_3":
m_reserve["STR_RES_3"] = Convert.ToString(value);
break;
case "INT_RES_1":
m_reserve["INT_RES_1"] = Convert.ToInt32(value);
break;
case "INT_RES_2":
m_reserve["INT_RES_2"] = Convert.ToInt32(value);
break;
case "INT_RES_3":
m_reserve["INT_RES_3"] = Convert.ToInt32(value);
break;
default:
break;
}
}
catch
{
Trace.WriteLine("Type Error!");
}
}
/// <summary>
/// 读取保留字段的值
/// </summary>
/// <param name="res_name"></param>
/// <returns></returns>
public object Read_Res_Value(string res_name)
{
try
{
return m_reserve[res_name];
}
catch
{
return null;
}
}
/// <summary>
/// 执行相应工作
/// </summary>
public void DoJob()
{
//设置当前任务正在执行
//若当前任务处于真正运行状态,则不做任何操作返回
if (Interlocked.Exchange(ref m_isRun, 1) == 1)
return;
if ((checkTiming() == false) || (status != TM_STATUS.TM_STATUS_ACTIVE))
{
Interlocked.Exchange(ref m_isRun, 0);
return;
}
//更新触发时间
//原理上上次触发时间应更新为当前时间
//单考虑到定时误差,故将上次触发时间设置为准确触发时间
m_perTime = m_triggerT.NextTiming;
//以准确触发时间更新下次触发时间
m_triggerT.RefreshNextTiming(m_triggerT.NextTiming.Value);
//异步执行, 加快定时器处理速度
m_jobFunc.BeginInvoke(new AsyncCallback(this.__JobCallBack), this);
}
/// <summary>
/// 保存到数据库
/// </summary>
public virtual void Save(Timer_Jobs job = null)
{
//任务名称
job.job_name = mission_name;
//上一次执行时间
job.PreTime = m_perTime;
//创建时间
job.create_time = m_createTime;
//任务状态
job.status = status;
//任务用途
job.t_using = for_using;
//cron表达式
job.corn_express = m_triggerT.ToString();
//job ID
job.JOB_ID = job_id;
//运行参数
object rp = ParseRunParamsToJObject();
job.run_params = rp == null ? "[]" : rp.ToString();
//运行结果
object rr = ParseRunResultToJobject();
job.run_result = rr == null ? "" : rr.ToString();
//自定义事件
job.custom_action = CustomAction;
//自定义标签
job.custom_flag = CustomFlag;
//保留字段
foreach (var p in m_reserve)
{
switch (p.Key)
{
case "STR_RES_1":
job.STR_RES_1 = Convert.ToString(p.Value);
break;
case "STR_RES_2":
job.STR_RES_2 = Convert.ToString(p.Value);
break;
case "STR_RES_3":
job.STR_RES_3 = Convert.ToString(p.Value);
break;
case "INT_RES_1":
job.INT_RES_1 = Convert.ToInt32(p.Value);
break;
case "INT_RES_2":
job.INT_RES_2 = Convert.ToInt32(p.Value);
break;
case "INT_RES_3":
job.INT_RES_3 = Convert.ToInt32(p.Value);
break;
default:
break;
}
}
Jobs t_j = new Jobs();
this.job_id = t_j.SaveJob(job);
}
/// <summary>
/// 从数据库记录加载类对象
/// </summary>
/// <param name="job"></param>
public virtual void Load(Timer_Jobs job)
{
//ID
job_id = job.JOB_ID;
//前一次执行时间
m_perTime = job.PreTime;
//任务状态
status = job.status;
//执行时间
m_triggerT.FromString(job.corn_express);
m_triggerT.RefreshNextTiming(DateTime.Now);
//解析运行参数
ParseRunParam(job.run_params);
//解析运行结果
ParseRunResult(job.run_result);
//名称
mission_name = job.job_name;
//创建时间
m_createTime = job.create_time;
//自定义事件
CustomAction = job.custom_action;
//自定义标签
CustomFlag = job.custom_flag;
//读取保留字段
m_reserve.Clear();
if (job.STR_RES_1 != "null")
m_reserve["STR_RES_1"] = job.STR_RES_1;
if (job.STR_RES_2 != "null")
m_reserve["STR_RES_2"] = job.STR_RES_2;
if (job.STR_RES_3 != "null")
m_reserve["STR_RES_3"] = job.STR_RES_3;
m_reserve["INT_RES_1"] = job.INT_RES_1;
m_reserve["INT_RES_2"] = job.INT_RES_2;
m_reserve["INT_RES_3"] = job.INT_RES_3;
}
#endregion
#region 内部方法
/// <summary>
/// 调用自定义事件
/// </summary>
/// <param name="json_params">传递的用户参数, 该参数为json结构,具体字段根据实际需求指定,到响应处理函数中进行解析</param>
/// <returns></returns>
protected string CallCustomAction(string json_params)
{
if (CustomAction != "")
{
string strjson1 = string.Format("{{timer_id:{0}, user_params:'{1}'}}", ID, json_params);
try
{
byte[] bytes = Encoding.UTF8.GetBytes(strjson1);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(CustomAction);
request.ContentType = @"application/json";
request.Accept = "application/xml";
request.Method = "POST";
request.ContentLength = bytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Dispose();
//结束动作函数返回值
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//对返回结果进行处理
return sr.ReadToEnd();
}
catch (Exception e)
{
Trace.WriteLine("EnterEvent error:" + e.Message);
return "failed";
}
}
else
return "";
}
/// <summary>
/// 执行任务函数的回调
/// </summary>
/// <param name="sender"></param>
protected virtual void __JobCallBack(object sender)
{
AsyncResult asyRes = (AsyncResult)sender;
//如果下次执行时间为空,则说明任务执行完毕
if (((CTimerMission)(asyRes.AsyncState)).m_triggerT.NextTiming == null)
((CTimerMission)(asyRes.AsyncState)).status = TM_STATUS.TM_FINISH;
//若在任务执行过程中,改变了任务状态, 则需要将该任务从待执行任务列表中移除
if (((CTimerMission)(asyRes.AsyncState)).status != TM_STATUS.TM_STATUS_ACTIVE)
CTimerManage.RemoveFromActiveList(((CTimerMission)(asyRes.AsyncState)).ID);
((CTimerMission)(asyRes.AsyncState)).Save();
//到此,本次任务执行完成, 将标识置为不在运行状态
Interlocked.Exchange(ref ((CTimerMission)(asyRes.AsyncState)).m_isRun, 0);
(asyRes.AsyncDelegate as JobProcessing).EndInvoke(asyRes);
}
#endregion
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using FlowEngine.TimerManage;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A5dot1Controller : CommonController
{
//
// GET: /A5dot1/
public ActionResult A5()
{
return View();
}
public class NameandNum
{
public int Equip_Num;
public string name;
}
public class PqcheckModel
{
public A5dot1Tab1 a5dot1Tab1;
public string UserName;
public DateTime currenttime;
}
public class indexmodel
{
public int xcgcs;
public int kxxgcs;
public int jxdw;
public int jdc;
}
public class index0model
{
public string title;
public List<A5dot1Tab2> worst10;
public List<double> cj_bwh;
public List<double> pq_bwh;
public double qc_bwh;
}
//A5最差十台表
public string A5zuicha()
{
List<object> r = new List<object>();
index0model i0m = new index0model();
DateTime my = DateTime.Now;
string ym;
if (my.Day >= 15)
{
ym = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
ym = my.Year.ToString() + my.Month.ToString();
}
TablesManagment tm = new TablesManagment();
i0m.worst10 = tm.get_worst10byym(ym);
for (int i = 0; i < i0m.worst10.Count; i++)
{
object o = new
{
index = i + 1,
cjname = i0m.worst10[i].cjName,
zzname = i0m.worst10[i].zzName,
sbGyCode = i0m.worst10[i].sbGyCode,
sbCode = i0m.worst10[i].sbCode,
timesNotGood = i0m.worst10[i].timesNotGood,
countAllNoRectifed = i0m.worst10[i].timesNotGood,//这台最差设备当月累计未整改数
notGoodContents = i0m.worst10[i].notGoodContents
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public index0model getindex0()
{
index0model i0m = new index0model();
DateTime my = DateTime.Now;
string title = "";
string ym;
if (my.Day >= 15)
{
title = my.Year.ToString() + "-" + my.AddMonths(1).Month.ToString() + "月" + "最差十台机泵";
ym = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
title = my.Year.ToString() + "-" + my.Month.ToString() + "月" + "最差十台机泵";
ym = my.Year.ToString() + my.Month.ToString();
}
i0m.title = title;
TablesManagment tm = new TablesManagment();
i0m.worst10 = tm.get_worst10byym(ym);
EquipManagment Em = new EquipManagment();
List<EANummodel> E = Em.getequipnum_byarchi();
List<Equip_Archi> AllCj_List = Em.GetAllCj();
List<NameandNum> cj = new List<NameandNum>();
List<NameandNum> pq = new List<NameandNum>();
for (int i = 0; i < AllCj_List.Count; i++)
{
int count = 0;
NameandNum temp1 = new NameandNum();
temp1.name = AllCj_List[i].EA_Name;
for (int j = 0; j < E.Count; j++)
{
if (AllCj_List[i].EA_Id == Em.getEA_parentid(E[j].EA_Id))
count += E[j].Equip_Num;
}
temp1.Equip_Num = count;
cj.Add(temp1);
count = 0;
}
List<string> pq_name_list = new List<string>();
pq_name_list.Add("联合一片区");
pq_name_list.Add("联合二片区");
pq_name_list.Add("联合三片区");
pq_name_list.Add("联合四片区");
pq_name_list.Add("化工片区");
pq_name_list.Add("综合片区");
pq_name_list.Add("其他");
for (int i = 0; i < pq_name_list.Count; i++)
{
int count = 0;
NameandNum temp1 = new NameandNum();
temp1.name = pq_name_list[i];
List<Pq_Zz_map> Pq_Zz_map = Em.GetZzsofPq(pq_name_list[i]);
for (int j = 0; j < Pq_Zz_map.Count;j++ )
{
for (int z = 0; z < E.Count; z++)
{
if (Pq_Zz_map[j].Zz_Name == Em.getEa_namebyid(E[z].EA_Id))
count += E[z].Equip_Num;
}
}
temp1.Equip_Num = count;
pq.Add(temp1);
count = 0;
}
//全场不完好
int qc_count = 0;
for (int i = 0; i < pq.Count; i++)
{
qc_count += pq[i].Equip_Num;
}
List<A5dot1Tab1> qc_list = tm.get_All();
double qcbwh = 0.000;
double qc_bxhcount = 0;
int wzgcount = 0;
if (qc_list.Count > 0)
{
qc_bxhcount = 0;
wzgcount = 0;
string sbcode_temp = qc_list[0].sbCode;
for (int j = 0; j < qc_list.Count; j++)
{
qc_list = tm.get_All();
if (qc_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(qc_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzgcount++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzgcount > 0)
{
qc_bxhcount++;
}
wzgcount = 0;
}
// cjbwh.Add(f);
}
}
for (int n = 0; n < qc_list.Count; n++)
{
tm.modifytemp1_byid(qc_list[n].Id, null);
}
qcbwh = Math.Round(((double)qc_bxhcount / qc_count), 6);
i0m.qc_bwh = qcbwh;
List<double> cjbwh = new List<double>();
List<double> pqbwh = new List<double>();
//车间不完好
for (int i = 0; i < cj.Count; i++)
{
List<A5dot1Tab1> cj_list = tm.get_cj_bwh(cj[i].name, cj[i].Equip_Num);
double cj_bxhcount = 0;
int wzg_count = 0;
if (cj_list.Count > 0)
{
cj_bxhcount = 0;
wzg_count = 0;
string sbcode_temp = cj_list[0].sbCode;
for (int j = 0; j < cj_list.Count; j++)
{
cj_list = tm.get_cj_bwh(cj[i].name, cj[i].Equip_Num);
if (cj_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(cj_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzg_count++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzg_count > 0)
{
cj_bxhcount++;
}
wzg_count = 0;
}
// cjbwh.Add(f);
}
}
for (int n = 0; n < cj_list.Count; n++)
{
tm.modifytemp1_byid(cj_list[n].Id, null);
}
if (cj[i].Equip_Num != 0)
cjbwh.Add(Math.Round(((double)cj_bxhcount / cj[i].Equip_Num), 6));
else
cjbwh.Add(0.0);
}
i0m.cj_bwh = cjbwh;
//片区不完好
for (int i = 0; i < pq.Count; i++)
{
List<A5dot1Tab1> pq_list = tm.get_pq_bwh(pq[i].name, pq[i].Equip_Num);
double pq_bxhcount = 0;
int wzg_count = 0;
if (pq_list.Count > 0)
{
pq_bxhcount = 0;
wzg_count = 0;
string sbcode_temp = pq_list[0].sbCode;
for (int j = 0; j < pq_list.Count; j++)
{
pq_list = tm.get_cj_bwh(cj[i].name, cj[i].Equip_Num);
if (pq_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(pq_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzg_count++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzg_count > 0)
{
pq_bxhcount++;
}
wzg_count = 0;
}
// cjbwh.Add(f);
}
}
for (int n = 0; n < pq_list.Count; n++)
{
tm.modifytemp1_byid(pq_list[n].Id, null);
}
pqbwh.Add(Math.Round(((double)pq_bxhcount / pq[i].Equip_Num), 6));
}
i0m.pq_bwh = pqbwh;
return i0m;
}
public PqcheckModel getPqcheckModel(int a_id)
{
PqcheckModel mm = new PqcheckModel();
mm.UserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
TablesManagment tm = new TablesManagment();
mm.a5dot1Tab1 = tm.GetA_byid(a_id);
mm.currenttime = DateTime.Now;
return mm;
}
public ActionResult Index()
{
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
indexmodel im = new indexmodel();
if (pv.Role_Names.Contains("现场工程师"))
im.xcgcs = 1;
else
im.xcgcs = 0;
if (pv.Role_Names.Contains("可靠性工程师"))
im.kxxgcs = 1;
else
im.kxxgcs = 0;
if (pv.Role_Names.Contains("检维修人员"))
im.jxdw = 1;
else
im.jxdw = 0;
if (pv.Department_Name.Contains("机动处") && pv.Role_Names.Contains("专业团队"))
im.jdc = 1;
else
im.jdc = 0;
return View(im);
}
public ActionResult Index0()
{
return View(getindex0());
}
//GET: /A5dot1/装置提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult Pqcheck(int a_id)
{
return View(getPqcheckModel(a_id));
}
public ActionResult HistoryCheck(int a_id)
{
return View(getPqcheckModel(a_id));
}
// GET: /A5dot1/可靠性工程师汇总
public ActionResult PqSummary()
{
return View();
}
// GET: /A5dot1/机动处汇总
public ActionResult JdcSummary(string flowname)
{
return View(getA5_Model(flowname));
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string[] notgood = item["Incomplete_content"].ToString().Split('|');
A5dot1Tab1 a5dot1Tab1 = new A5dot1Tab1();
DateTime my = DateTime.Now;
string yearmonth = "";
EquipManagment Em = new EquipManagment();
GetNWorkSerManagment gnm=new GetNWorkSerManagment();
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
}
if (notgood[notgood.Count() - 1] == "")
{
for (int i = 0; i < notgood.Count() - 1; i++)
{
a5dot1Tab1.cjName = item["Cj_Name"].ToString();
a5dot1Tab1.zzName = item["Zz_Name"].ToString();
a5dot1Tab1.sbGyCode = item["Equip_GyCode"].ToString();
a5dot1Tab1.sbCode = item["Equip_Code"].ToString();
a5dot1Tab1.sbType = item["Equip_Type"].ToString();
a5dot1Tab1.zyType = item["Zy_Type"].ToString();
a5dot1Tab1.notGoodContent = notgood[i];
a5dot1Tab1.isRectified = 0;
a5dot1Tab1.zzSubmitTime = DateTime.Now;
a5dot1Tab1.zzUserName = item["ZzsubmitName"].ToString();
a5dot1Tab1.yearMonthForStatistic = yearmonth;
a5dot1Tab1.pqName = Em.GetPqofZz(item["Zz_Name"].ToString()).Pq_Name;
a5dot1Tab1.dataSource = gnm.AddNWorkEntity("A5dot1").WE_Ser;
TablesManagment tm = new TablesManagment();
tm.Zzsubmit(a5dot1Tab1);
}
}
else
{
for (int i = 0; i < notgood.Count(); i++)
{
a5dot1Tab1.cjName = item["Cj_Name"].ToString();
a5dot1Tab1.zzName = item["Zz_Name"].ToString();
a5dot1Tab1.sbGyCode = item["Equip_GyCode"].ToString();
a5dot1Tab1.sbCode = item["Equip_Code"].ToString();
a5dot1Tab1.sbType = item["Equip_Type"].ToString();
a5dot1Tab1.zyType = item["Zy_Type"].ToString();
a5dot1Tab1.notGoodContent = notgood[i];
a5dot1Tab1.isRectified = 0;
a5dot1Tab1.zzSubmitTime = DateTime.Now;
a5dot1Tab1.zzUserName = item["ZzsubmitName"].ToString();
a5dot1Tab1.yearMonthForStatistic = yearmonth;
a5dot1Tab1.pqName = Em.GetPqofZz(item["Zz_Name"].ToString()).Pq_Name;
a5dot1Tab1.dataSource = gnm.AddNWorkEntity("A5dot1").WE_Ser;
TablesManagment tm = new TablesManagment();
tm.Zzsubmit(a5dot1Tab1);
}
}
//SubmitDSEventDetails("A5.1","设备完好提报");
}
catch (Exception e)
{
return "";
}
return ("/A5dot1/Index");
}
public string JxSubmit(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A5dot1Tab2 a5dot1Tab2 = new A5dot1Tab2();
DateTime my = DateTime.Now;
string yearmonth = "";
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
}
int userid = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
string pqname = "";
int pqid = pm.Get_Person_Depart(userid).Depart_Id;
if (2 <= pqid && pqid <= 12)
{
pqname = pm.Get_Person_Depart(userid).Depart_Name;
}
else
{
pqname = pm.Get_Person_DepartOfParent(userid).Depart_Name;
}
a5dot1Tab2.cjName = item["Cj_Name"].ToString();
a5dot1Tab2.zzName = item["Zz_Name"].ToString();
a5dot1Tab2.sbGyCode = item["Equip_GyCode"].ToString();
a5dot1Tab2.sbCode = item["Equip_Code"].ToString();
a5dot1Tab2.sbType = item["Equip_Type"].ToString();
a5dot1Tab2.zyType = item["Zy_Type"].ToString();
a5dot1Tab2.notGoodContents = item["Incomplete_contents"].ToString();
a5dot1Tab2.problemAnalysisAdvise = item["wtfx"].ToString();
a5dot1Tab2.processMeansMethods = item["chlsd"].ToString();
a5dot1Tab2.processReuslt = item["cljg"].ToString();
a5dot1Tab2.yearMonthForStatistic = yearmonth;
a5dot1Tab2.countAllNoRectifed = 1;
a5dot1Tab2.timesNotGood = 1;
a5dot1Tab2.state = 1;
a5dot1Tab2.jxdwUserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
a5dot1Tab2.isSetAsTop5Worst = 1;
a5dot1Tab2.pqName = pqname;
//a5dot1Tab2.D = item["Data_Src"].ToString();
a5dot1Tab2.yearMonthForStatistic = yearmonth;
TablesManagment tm = new TablesManagment();
tm.savefivesb(a5dot1Tab2);
}
catch (Exception e)
{
return "";
}
return ("/A5dot1/JxEdit");
}
public string JxEditSubmit()
{
string userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
DateTime my = DateTime.Now;
string yearmonth = "";
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
}
TablesManagment tm = new TablesManagment();
List<A5dot1Tab2> E = tm.GetAll2_byymandstate(yearmonth, 1);
for (int i = 0; i < E.Count; i++)
{
tm.setstate_byid(E[i].Id, 2, userName);
}
return ("/A5dot1/Index");
}
public string dcl_list()
{
TablesManagment tm = new TablesManagment();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
List<object> r = new List<object>();
if (pv.Role_Names.Contains("可靠性工程师"))
{
List<string> cjname = new List<string>();
List<Equip_Archi> EA = pm.Get_Person_Cj(UserId);
foreach (var ea in EA)
{
cjname.Add(ea.EA_Name);
}
List<A5dot1Tab1> E = tm.Getdcl_listbyisZG(0, cjname);
for (int i = 0; i < E.Count; i++)
{
object o = new
{
index = i + 1,
zzname = E[i].zzName.ToString(),
sbgybh = E[i].sbGyCode.ToString(),
sbcode = E[i].sbCode.ToString(),
notgood = E[i].notGoodContent.ToString(),
a_id = E[i].Id
};
r.Add(o);
}
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string ycl_list()
{
TablesManagment tm = new TablesManagment();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
List<object> r = new List<object>();
if (pv.Role_Names.Contains("可靠性工程师"))
{
List<string> cjname = new List<string>();
List<Equip_Archi> EA = pm.Get_Person_Cj(UserId);
foreach (var ea in EA)
{
cjname.Add(ea.EA_Name);
}
List<A5dot1Tab1> E = tm.Getdcl_listbyisZG(1, cjname);
//List<object> r = new List<object>();
for (int i = 0; i < E.Count; i++)
{
object o = new
{
index = i + 1,
zzname = E[i].zzName.ToString(),
sbgybh = E[i].sbGyCode.ToString(),
sbcode = E[i].sbCode.ToString(),
notgood = E[i].notGoodContent.ToString(),
a_id = E[i].Id
};
r.Add(o);
}
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string list()
{
DateTime my = DateTime.Now;
DateTime lastmonth = DateTime.Now.AddMonths(-1);
string yearmonth = "";
string last = "";
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
last = lastmonth.Year.ToString() + lastmonth.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
last = lastmonth.Year.ToString() + lastmonth.Month.ToString();
}
TablesManagment tm = new TablesManagment();
List<string> cjname = new List<string>();
PersonManagment pm = new PersonManagment();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
//Depart_Archi da= pm.Get_Person_Depart(UserId);
//string pq = da.Depart_Name;
List<Equip_Archi> EA = pm.Get_Person_Cj(UserId);
foreach (var ea in EA)
{
cjname.Add(ea.EA_Name);
}
List<A5dot1Tab1> e = tm.GetAll1_byym(yearmonth, cjname);
//List<A5dot1Tab1> laste = tm.GetAll1_byym(last, cjname);
List<object> r = new List<object>();
string temp = e[0].sbCode;
string s = "";
string lasts = "";
string isZG = "";
string problemDescription = "";
int bwhcs = 0;
int bwhxs = 0;
for (int j = 0; j < e.Count; j++)
{
e = tm.GetAll1_byym(yearmonth, cjname);
bwhcs = 0;
bwhxs = 0;
if (e[j].temp1 == null)
{
List<A5dot1Tab1> E = tm.GetAll1_byymandcode(yearmonth, e[j].sbCode);
for (int i = 0; i < E.Count; i++)
{
if (E[i].isRectified == 0)
{
isZG = "未整改";
bwhxs++;
}
else
isZG = "已整改";
s += E[i].notGoodContent + " (" + isZG + ") ";
problemDescription += E[i].notGoodContent;
//if (i > 0&&E[i].zzSubmitTime.Value.Second - E[i - 1].zzSubmitTime.Value.Second >= 2)
bwhcs++;
tm.modifytemp1_byid(E[i].Id, "已合并");
}
List<A5dot1Tab1> lastE = tm.GetAll1_byymandcode(last, e[j].sbCode);
for (int k = 0; k < lastE.Count; k++)
{
if (lastE[k].isRectified == 0)
{
lasts += lastE[k].notGoodContent;
}
}
if (lasts != "")
s = s + " 上月未整改内容:" + lasts;
else
s = s + " 上月无未整改内容。";
if (e[j].temp2 == null)
e[j].temp2 = "";
//string pq = "";
//if (e[j].zzName.ToString() == "消防队" || e[j].zzName.ToString() == "计量站")
// pq = e[j].zzName.ToString();
//else
// pq = pm.Get_PqnamebyCjname(e[j].zzName.ToString());
object o = new
{
//index = count++,
zzname = e[j].zzName.ToString(),
sbgybh = e[j].sbGyCode.ToString(),
sbcode = e[j].sbCode.ToString(),
notgood = s,
cjName = e[j].cjName.ToString(),
sbType = e[j].sbType.ToString(),
zyType = e[j].zyType.ToString(),
a_id = e[j].Id,
ym = e[j].yearMonthForStatistic,
entityid = e[j].temp2.ToString(),
wtfx = "",
clsd = "",
cljg = "",
wtms = problemDescription,
bwhxs = bwhxs,
bwhcs = bwhcs,
//pq=pq
};
r.Add(o);
s = "";
}
}
for (int k = 0; k < e.Count; k++)
{
tm.modifytemp1_byid(e[k].Id, null);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string list2()
{
DateTime my = DateTime.Now;
string yearmonth = "";
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
}
TablesManagment tm = new TablesManagment();
List<A5dot1Tab2> E = tm.GetAll2_byymandstate(yearmonth, 1);
List<object> r = new List<object>();
for (int i = 0; i < E.Count; i++)
{
object o = new
{
//index = i + 1,
zzname = E[i].zzName.ToString(),
sbgybh = E[i].sbGyCode.ToString(),
sbcode = E[i].sbCode.ToString(),
notgood = E[i].notGoodContents.ToString(),
a_id = E[i].Id
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string list3()
{
DateTime my = DateTime.Now;
string yearmonth = "";
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
}
TablesManagment tm = new TablesManagment();
List<A5dot1Tab2> E = tm.GetAll2_byymandstate(yearmonth, 2);
List<object> r = new List<object>();
for (int i = 0; i < E.Count; i++)
{
object o = new
{
//index = i + 1,
zzname = E[i].zzName.ToString(),
sbgybh = E[i].sbGyCode.ToString(),
sbcode = E[i].sbCode.ToString(),
notgood = E[i].notGoodContents.ToString(),
a_id = E[i].Id
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string Pqcheck_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string pqname = item["pqUserName"].ToString();
int a_id = Convert.ToInt32(item["a_id"]);
DateTime time = DateTime.Now;
TablesManagment tm = new TablesManagment();
tm.Pqcheck_byid(a_id, pqname, time);
if (tm.GetA_byid(a_id).temp3 != null)
{
int missId = Convert.ToInt32(tm.GetA_byid(a_id).temp3);
var t = CTimerManage.LoadTimerMission(missId);
if (t != null)
{
t.status = TM_STATUS.TM_FINISH;
t.Save();
CTimerManage.RemoveFromActiveList(t.ID);
}
}
}
catch (Exception e)
{
return "";
}
return ("/A5dot1/Index");
}
public string save5(string json1)
{
//List<string> json = new List<string>();
JArray jsonVal = JArray.Parse(json1) as JArray;
dynamic table2 = jsonVal;
string userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int userid = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
TablesManagment tm = new TablesManagment();
A5dot1Tab2 a = new A5dot1Tab2();
// List<A5dot1Tab2> temp = new List<A5dot1Tab2>();
foreach (dynamic T in table2)
{
a.cjName = T.CjName;
a.zzName = T.ZzName;
a.sbGyCode = T.sbGyCode;
a.sbCode = T.sbCode;
a.notGoodContents = T.notGoodContents;
a.zyType = T.zyType;
a.sbType = T.sbType;
a.yearMonthForStatistic = T.ym;
a.isSetAsTop5Worst = 1;
a.state = 1;
a.pqUserName = userName;
a.problemAnalysisAdvise = T.wtfx;
a.processMeansMethods = T.clsd;
a.processReuslt = T.cljg;
a.problemDescription = T.wtms;
a.timesNotGood = T.bwhcs;
a.countAllNoRectifed = T.bwhxs;
if (a.cjName == "消防队" || a.cjName == "计量站")
a.pqName = a.cjName;
else
a.pqName = pm.Get_PqnamebyCjname(a.cjName.ToString());
a.temp2 = T.entityid;
tm.savefivesb(a);
}
return null;
}
public string save10(string json1)
{
//List<string> json = new List<string>();
string userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
DateTime my = DateTime.Now;
string yearmonth = "";
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
}
TablesManagment tm = new TablesManagment();
A5dot1Tab2 a = new A5dot1Tab2();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string[] a_id = item["a_id"].ToString().Split('|');
List<A5dot1Tab2> E = tm.GetAll2_byymandstate(yearmonth, 2);
for (int i = 0; i < E.Count; i++)
{
tm.setstate_byid(E[i].Id, 3, userName);
}
for (int j = 0; j < a_id.Count(); j++)
{
tm.setisworst10_byid(Convert.ToInt16(a_id[j]), 1);
}
return ("/A5dot1/Index");
}
public ActionResult JxEdit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public string delete_worst5(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
int a_id = Convert.ToInt32(item["a_id"]);
TablesManagment tm = new TablesManagment();
tm.delete_byid(a_id);
return "删除成功";
}
public string OutputExcel(string time)
{
try
{
DateTime my = DateTime.Now;
string title = "";
string ym;
if (my.Day >= 15)
{
title = my.Year.ToString() + "年" + my.AddMonths(1).Month.ToString() + "月" + "最差十台机泵";
//ym = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
title = my.Year.ToString() + "年" + my.Month.ToString() + "月" + "最差十台机泵";
// ym = my.Year.ToString() + my.Month.ToString();
}
if (time == "")
{
if (my.Day >= 15)
{
ym = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
ym = my.Year.ToString() + my.Month.ToString();
}
}
else
{
string[] s = time.Split(new char[] { '-' });
ym = s[0] + s[1];
}
TablesManagment tm = new TablesManagment();
List<A5dot1Tab2> worst10 = tm.get_worst10byym(ym);
// 创建Excel 文档
HSSFWorkbook wk = new HSSFWorkbook();
ISheet tb = wk.CreateSheet("sheet1");
//设置单元的宽度
tb.SetColumnWidth(0, 25 * 256);
tb.SetColumnWidth(1, 20 * 256);
tb.SetColumnWidth(2, 20 * 256);
tb.SetColumnWidth(3, 20 * 256);
tb.SetColumnWidth(4, 20 * 256);
tb.SetColumnWidth(5, 20 * 256);
tb.SetColumnWidth(6, 45 * 256);
//合并标题头,该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 6));
IRow head = tb.CreateRow(0);
head.Height = 20 * 30;
ICell head_first_cell = head.CreateCell(0);
ICellStyle cellStyle_head = wk.CreateCellStyle();
//对齐
cellStyle_head.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
// 边框
/*
cellStyle_head.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
* */
// 字体
IFont font = wk.CreateFont();
font.FontName = "微软雅黑";
font.Boldweight = 8;
font.FontHeightInPoints = 16;
cellStyle_head.SetFont(font);
head_first_cell.CellStyle = head.CreateCell(1).CellStyle
= head.CreateCell(2).CellStyle
= head.CreateCell(3).CellStyle
= head.CreateCell(4).CellStyle
= head.CreateCell(5).CellStyle
= head.CreateCell(6).CellStyle
= cellStyle_head;
head_first_cell.SetCellValue(title);
IRow table_head = tb.CreateRow(1);
ICellStyle cellStyle_normal = wk.CreateCellStyle();
cellStyle_normal.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
ICell table_head_cj = table_head.CreateCell(0);
table_head_cj.CellStyle = cellStyle_normal;
table_head_cj.SetCellValue("车间");
ICell table_head_zz = table_head.CreateCell(1);
table_head_zz.CellStyle = cellStyle_normal;
table_head_zz.SetCellValue("装置");
ICell table_head_sbgycode = table_head.CreateCell(2);
table_head_sbgycode.CellStyle = cellStyle_normal;
table_head_sbgycode.SetCellValue("设备位号");
ICell table_head_sbcode = table_head.CreateCell(3);
table_head_sbcode.CellStyle = cellStyle_normal;
table_head_sbcode.SetCellValue("设备编号");
ICell table_head_bwh = table_head.CreateCell(4);
table_head_bwh.CellStyle = cellStyle_normal;
table_head_bwh.SetCellValue("当月不完好数");
ICell table_head_bwhxs = table_head.CreateCell(5);
table_head_bwhxs.CellStyle = cellStyle_normal;
table_head_bwhxs.SetCellValue("当前累计未整改不完好数");
ICell table_head_bhwxq = table_head.CreateCell(6);
table_head_bhwxq.CellStyle = cellStyle_normal;
table_head_bhwxq.SetCellValue("不完好内容详情");
ICellStyle thjl_record_cellStyle = wk.CreateCellStyle();
thjl_record_cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
//水平对齐
thjl_record_cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
//垂直对齐
thjl_record_cellStyle.VerticalAlignment = VerticalAlignment.Top;
//自动换行
thjl_record_cellStyle.WrapText = true;
int row_index = 2;
for (int i = 0; i < worst10.Count; i++)
{
IRow thjl_row = tb.CreateRow(row_index);
ICell cj = thjl_row.CreateCell(0);
cj.CellStyle = thjl_record_cellStyle;
cj.SetCellValue(worst10[i].cjName.ToString());
ICell zz = thjl_row.CreateCell(1);
zz.CellStyle = thjl_record_cellStyle;
zz.SetCellValue(worst10[i].zzName.ToString());
ICell sbgycode = thjl_row.CreateCell(2);
sbgycode.CellStyle = thjl_record_cellStyle;
sbgycode.SetCellValue(worst10[i].sbGyCode.ToString());
ICell sbcode = thjl_row.CreateCell(3);
sbcode.CellStyle = thjl_record_cellStyle;
sbcode.SetCellValue(worst10[i].sbCode.ToString());
ICell bwh = thjl_row.CreateCell(4);
bwh.CellStyle = thjl_record_cellStyle;
bwh.SetCellValue(worst10[i].timesNotGood.ToString());
ICell bwhxs = thjl_row.CreateCell(5);
bwhxs.CellStyle = thjl_record_cellStyle;
bwhxs.SetCellValue(worst10[i].countAllNoRectifed.ToString());
ICell bwhxq = thjl_row.CreateCell(6);
bwhxq.CellStyle = thjl_record_cellStyle;
bwhxq.SetCellValue(worst10[i].notGoodContents.ToString());
row_index++;
}
string path = Server.MapPath("~/Upload//最差十台机泵.xls");
using (FileStream fs = System.IO.File.OpenWrite(path)) //打开一个xls文件,如果没有则自行创建,如果存在myxls.xls文件则在创建是不要打开该文件!
{
wk.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。
Console.WriteLine("提示:创建成功!");
}
return Path.Combine("/Upload", "最差十台机泵.xls");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return "";
}
}
public string OutputExcel_2()
{
try
{
DateTime my = DateTime.Now;
string ym;
TablesManagment tm = new TablesManagment();
if (my.Day >= 15)
{
ym = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
ym = my.Year.ToString() + my.Month.ToString();
}
EquipManagment Em = new EquipManagment();
List<EANummodel> E = Em.getequipnum_byarchi();
List<NameandNum> cj = new List<NameandNum>();
List<NameandNum> pq = new List<NameandNum>();
int count = 0;
for (int i = 0; i < 8; i++)
{
count += E[i].Equip_Num;
}
NameandNum temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "联合一车间";
cj.Add(temp);
count = 0;
for (int i = 8; i < 11; i++)
{
count += E[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "联合二车间";
cj.Add(temp);
count = 0;
for (int i = 11; i < 15; i++)
{
count += E[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "联合三车间";
cj.Add(temp);
count = 0;
for (int i = 15; i < 17; i++)
{
count += E[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "焦化车间";
cj.Add(temp);
count = 0;
for (int i = 17; i < 18; i++)
{
count += E[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "铁路车间";
cj.Add(temp);
count = 0;
for (int i = 18; i < 22; i++)
{
count += E[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "气加车间";
cj.Add(temp);
count = 0;
for (int i = 22; i < 24; i++)
{
count += E[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "聚丙烯车间";
cj.Add(temp);
count = 0;
for (int i = 24; i < 26; i++)
{
count += E[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "综合车间";
cj.Add(temp);
count = 0;
List<string> s = new List<string>();
s.Add("油品车间");
s.Add("排水车间");
s.Add("供水车间");
s.Add("热点车间");
s.Add("码头车间");
s.Add("消防队");
s.Add("计量站");
for (int i = 26; i < 33; i++)
{
count = E[i].Equip_Num;
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = s[i - 26];
cj.Add(temp);
count = 0;
}
for (int i = 0; i < 1; i++)
{
count += cj[i].Equip_Num;
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "联合一片区";
pq.Add(temp);
count = 0;
}
for (int i = 1; i < 2; i++)
{
count += cj[i].Equip_Num;
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "联合二片区";
pq.Add(temp);
count = 0;
}
for (int i = 2; i < 3; i++)
{
count += cj[i].Equip_Num;
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "联合三片区";
pq.Add(temp);
count = 0;
}
for (int i = 3; i < 5; i++)
{
count += cj[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "焦化片区";
pq.Add(temp);
count = 0;
for (int i = 5; i < 7; i++)
{
count += cj[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "化工片区";
pq.Add(temp);
count = 0;
for (int i = 7; i < 8; i++)
{
count += cj[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "综合片区";
pq.Add(temp);
count = 0;
for (int i = 8; i < 13; i++)
{
count += cj[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "系统片区";
pq.Add(temp);
count = 0;
for (int i = 13; i < 15; i++)
{
count += cj[i].Equip_Num;
}
temp = new NameandNum();
temp.Equip_Num = count;
temp.name = "其他";
pq.Add(temp);
count = 0;
for (int i = 0; i < pq.Count; i++)
{
count += pq[i].Equip_Num;
}
List<A5dot1Tab1> qc_list = tm.get_All();
double qcbwh = 0.000;
double qc_bxhcount = 0;
int wzgcount = 0;
if (qc_list.Count > 0)
{
qc_bxhcount = 0;
wzgcount = 0;
string sbcode_temp = qc_list[0].sbCode;
for (int j = 0; j < qc_list.Count; j++)
{
qc_list = tm.get_All();
if (qc_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(qc_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzgcount++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzgcount > 0)
{
qc_bxhcount++;
}
wzgcount = 0;
}
// cjbwh.Add(f);
}
}
for (int n = 0; n < qc_list.Count; n++)
{
tm.modifytemp1_byid(qc_list[n].Id, null);
}
qcbwh = Math.Round(((double)qc_bxhcount / count), 6);
List<double> cjbwh = new List<double>();
List<double> pqbwh = new List<double>();
for (int i = 0; i < cj.Count; i++)
{
List<A5dot1Tab1> cj_list = tm.get_cj_bwh(cj[i].name, cj[i].Equip_Num);
double cj_bxhcount = 0;
int wzg_count = 0;
if (cj_list.Count > 0)
{
cj_bxhcount = 0;
wzg_count = 0;
string sbcode_temp = cj_list[0].sbCode;
for (int j = 0; j < cj_list.Count; j++)
{
cj_list = tm.get_cj_bwh(cj[i].name, cj[i].Equip_Num);
if (cj_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(cj_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzg_count++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
}
}
if (wzg_count > 0)
{
cj_bxhcount++;
}
}
else
{
cjbwh.Add(0.000);
}
for (int n = 0; n < cj_list.Count; n++)
{
tm.modifytemp1_byid(cj_list[n].Id, null);
}
cjbwh.Add(Math.Round(((double)cj_bxhcount / cj[i].Equip_Num), 6));
}
for (int i = 0; i < pq.Count; i++)
{
List<A5dot1Tab1> pq_list = tm.get_pq_bwh(pq[i].name, pq[i].Equip_Num);
double pq_bxhcount = 0;
int wzg_count = 0;
if (pq_list.Count > 0)
{
pq_bxhcount = 0;
wzg_count = 0;
string sbcode_temp = pq_list[0].sbCode;
for (int j = 0; j < pq_list.Count; j++)
{
pq_list = tm.get_cj_bwh(cj[i].name, cj[i].Equip_Num);
if (pq_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(pq_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzg_count++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzg_count > 0)
{
pq_bxhcount++;
}
wzg_count = 0;
}
}
}
for (int n = 0; n < pq_list.Count; n++)
{
tm.modifytemp1_byid(pq_list[n].Id, null);
}
pqbwh.Add(Math.Round(((double)pq_bxhcount / pq[i].Equip_Num), 6));
}
// 创建Excel 文档
HSSFWorkbook wk = new HSSFWorkbook();
ISheet tb = wk.CreateSheet("sheet1");
//设置单元的宽度
tb.SetColumnWidth(0, 25 * 256);
tb.SetColumnWidth(1, 20 * 256);
tb.SetColumnWidth(2, 20 * 256);
tb.SetColumnWidth(3, 20 * 256);
tb.SetColumnWidth(4, 20 * 256);
//合并标题头,该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 4));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(5, 6, 0, 0));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(5, 6, 1, 1));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 8, 0, 0));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 8, 1, 1));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(10, 14, 0, 0));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(10, 14, 1, 1));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(15, 16, 0, 0));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(15, 16, 1, 1));
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 16, 4, 4));
IRow head = tb.CreateRow(0);
head.Height = 20 * 30;
ICell head_first_cell = head.CreateCell(0);
ICellStyle cellStyle_head = wk.CreateCellStyle();
//对齐
cellStyle_head.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
// 边框
/*
cellStyle_head.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
* */
// 字体
IFont font = wk.CreateFont();
font.FontName = "微软雅黑";
font.Boldweight = 8;
font.FontHeightInPoints = 16;
cellStyle_head.SetFont(font);
head_first_cell.CellStyle = head.CreateCell(1).CellStyle
= head.CreateCell(2).CellStyle
= head.CreateCell(3).CellStyle
= head.CreateCell(4).CellStyle
= cellStyle_head;
head_first_cell.SetCellValue("不完好率统计表");
//1
IRow table_head = tb.CreateRow(1);
ICellStyle cellStyle_normal = wk.CreateCellStyle();
cellStyle_normal.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
ICell table_head_cj = table_head.CreateCell(0);
table_head_cj.CellStyle = cellStyle_normal;
table_head_cj.SetCellValue("片区名称");
ICell table_head_zz = table_head.CreateCell(1);
table_head_zz.CellStyle = cellStyle_normal;
table_head_zz.SetCellValue("片区不完好率");
ICell table_head_sbgycode = table_head.CreateCell(2);
table_head_sbgycode.CellStyle = cellStyle_normal;
table_head_sbgycode.SetCellValue("车间名称");
ICell table_head_sbcode = table_head.CreateCell(3);
table_head_sbcode.CellStyle = cellStyle_normal;
table_head_sbcode.SetCellValue("车间不完好率");
ICell table_head_bwh = table_head.CreateCell(4);
table_head_bwh.CellStyle = cellStyle_normal;
table_head_bwh.SetCellValue("全场不完好率");
ICellStyle thjl_record_cellStyle = wk.CreateCellStyle();
thjl_record_cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
//水平对齐
thjl_record_cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
//垂直对齐
thjl_record_cellStyle.VerticalAlignment = VerticalAlignment.Top;
//自动换行
thjl_record_cellStyle.WrapText = true;
//2
IRow row_2 = tb.CreateRow(2);
ICell qp_1 = row_2.CreateCell(0);
qp_1.CellStyle = thjl_record_cellStyle;
qp_1.SetCellValue("联合一片区");
ICell pq_bwh = row_2.CreateCell(1);
pq_bwh.CellStyle = thjl_record_cellStyle;
pq_bwh.SetCellValue(pqbwh[0].ToString());
ICell cj_1 = row_2.CreateCell(2);
cj_1.CellStyle = thjl_record_cellStyle;
cj_1.SetCellValue("联合一车间");
ICell cj_bwh = row_2.CreateCell(3);
cj_bwh.CellStyle = thjl_record_cellStyle;
cj_bwh.SetCellValue(cjbwh[0].ToString());
ICell qc_bwh = row_2.CreateCell(4);
qc_bwh.CellStyle = thjl_record_cellStyle;
qc_bwh.SetCellValue(qcbwh.ToString());
//3
IRow row_3 = tb.CreateRow(3);
ICell qp_2 = row_3.CreateCell(0);
qp_2.CellStyle = thjl_record_cellStyle;
qp_2.SetCellValue("联合二片区");
ICell pq2_bwh = row_3.CreateCell(1);
pq2_bwh.CellStyle = thjl_record_cellStyle;
pq2_bwh.SetCellValue(pqbwh[1].ToString());
ICell cj_2 = row_3.CreateCell(2);
cj_2.CellStyle = thjl_record_cellStyle;
cj_2.SetCellValue("联合二车间");
ICell cj2_bwh = row_3.CreateCell(3);
cj2_bwh.CellStyle = thjl_record_cellStyle;
cj2_bwh.SetCellValue(cjbwh[1].ToString());
//4
IRow row_4 = tb.CreateRow(4);
ICell qp_3 = row_4.CreateCell(0);
qp_3.CellStyle = thjl_record_cellStyle;
qp_3.SetCellValue("联合三片区");
ICell pq3_bwh = row_4.CreateCell(1);
pq3_bwh.CellStyle = thjl_record_cellStyle;
pq3_bwh.SetCellValue(pqbwh[2].ToString());
ICell cj_3 = row_4.CreateCell(2);
cj_3.CellStyle = thjl_record_cellStyle;
cj_3.SetCellValue("联合三车间");
ICell cj3_bwh = row_4.CreateCell(3);
cj3_bwh.CellStyle = thjl_record_cellStyle;
cj3_bwh.SetCellValue(cjbwh[2].ToString());
//5
IRow row_5 = tb.CreateRow(5);
ICell qp_4 = row_5.CreateCell(0);
qp_4.CellStyle = thjl_record_cellStyle;
qp_4.SetCellValue("焦化片区");
ICell pq4_bwh = row_5.CreateCell(1);
pq4_bwh.CellStyle = thjl_record_cellStyle;
pq4_bwh.SetCellValue(pqbwh[3].ToString());
ICell cj_4 = row_5.CreateCell(2);
cj_4.CellStyle = thjl_record_cellStyle;
cj_4.SetCellValue("焦化车间");
ICell cj4_bwh = row_5.CreateCell(3);
cj4_bwh.CellStyle = thjl_record_cellStyle;
cj4_bwh.SetCellValue(cjbwh[3].ToString());
//6
IRow row_6 = tb.CreateRow(6);
ICell cj_5 = row_6.CreateCell(2);
cj_5.CellStyle = thjl_record_cellStyle;
cj_5.SetCellValue("铁路车间");
ICell cj5_bwh = row_6.CreateCell(3);
cj5_bwh.CellStyle = thjl_record_cellStyle;
cj5_bwh.SetCellValue(cjbwh[4].ToString());
//7
IRow row_7 = tb.CreateRow(7);
ICell qp_6 = row_7.CreateCell(0);
qp_6.CellStyle = thjl_record_cellStyle;
qp_6.SetCellValue("化工片区");
ICell pq6_bwh = row_7.CreateCell(1);
pq6_bwh.CellStyle = thjl_record_cellStyle;
pq6_bwh.SetCellValue(pqbwh[4].ToString());
ICell cj_6 = row_7.CreateCell(2);
cj_6.CellStyle = thjl_record_cellStyle;
cj_6.SetCellValue("气加车间");
ICell cj6_bwh = row_7.CreateCell(3);
cj6_bwh.CellStyle = thjl_record_cellStyle;
cj6_bwh.SetCellValue(cjbwh[5].ToString());
//8
IRow row_8 = tb.CreateRow(8);
ICell cj_7 = row_8.CreateCell(2);
cj_7.CellStyle = thjl_record_cellStyle;
cj_7.SetCellValue("聚丙烯车间");
ICell cj7_bwh = row_8.CreateCell(3);
cj7_bwh.CellStyle = thjl_record_cellStyle;
cj7_bwh.SetCellValue(cjbwh[6].ToString());
//9
IRow row_9 = tb.CreateRow(9);
ICell qp_8 = row_9.CreateCell(0);
qp_8.CellStyle = thjl_record_cellStyle;
qp_8.SetCellValue("综合片区");
ICell pq8_bwh = row_9.CreateCell(1);
pq8_bwh.CellStyle = thjl_record_cellStyle;
pq8_bwh.SetCellValue(pqbwh[5].ToString());
ICell cj_8 = row_9.CreateCell(2);
cj_8.CellStyle = thjl_record_cellStyle;
cj_8.SetCellValue("综合车间");
ICell cj8_bwh = row_9.CreateCell(3);
cj8_bwh.CellStyle = thjl_record_cellStyle;
cj8_bwh.SetCellValue(cjbwh[7].ToString());
//10
IRow row_10 = tb.CreateRow(10);
ICell qp_9 = row_10.CreateCell(0);
qp_9.CellStyle = thjl_record_cellStyle;
qp_9.SetCellValue("系统片区");
ICell pq9_bwh = row_10.CreateCell(1);
pq9_bwh.CellStyle = thjl_record_cellStyle;
pq9_bwh.SetCellValue(pqbwh[6].ToString());
ICell cj_9 = row_10.CreateCell(2);
cj_9.CellStyle = thjl_record_cellStyle;
cj_9.SetCellValue("油品车间");
ICell cj9_bwh = row_10.CreateCell(3);
cj9_bwh.CellStyle = thjl_record_cellStyle;
cj9_bwh.SetCellValue(cjbwh[8].ToString());
//11
IRow row_11 = tb.CreateRow(11);
ICell cj_10 = row_11.CreateCell(2);
cj_10.CellStyle = thjl_record_cellStyle;
cj_10.SetCellValue("排水车间");
ICell cj10_bwh = row_11.CreateCell(3);
cj10_bwh.CellStyle = thjl_record_cellStyle;
cj10_bwh.SetCellValue(cjbwh[9].ToString());
//12
IRow row_12 = tb.CreateRow(12);
ICell cj_11 = row_12.CreateCell(2);
cj_11.CellStyle = thjl_record_cellStyle;
cj_11.SetCellValue("供水车间");
ICell cj11_bwh = row_12.CreateCell(3);
cj11_bwh.CellStyle = thjl_record_cellStyle;
cj11_bwh.SetCellValue(cjbwh[10].ToString());
//13
IRow row_13 = tb.CreateRow(13);
ICell cj_12 = row_13.CreateCell(2);
cj_12.CellStyle = thjl_record_cellStyle;
cj_12.SetCellValue("热电车间");
ICell cj12_bwh = row_13.CreateCell(3);
cj12_bwh.CellStyle = thjl_record_cellStyle;
cj12_bwh.SetCellValue(cjbwh[11].ToString());
//14
IRow row_14 = tb.CreateRow(14);
ICell cj_13 = row_14.CreateCell(2);
cj_13.CellStyle = thjl_record_cellStyle;
cj_13.SetCellValue("热电车间");
ICell cj13_bwh = row_14.CreateCell(3);
cj13_bwh.CellStyle = thjl_record_cellStyle;
cj13_bwh.SetCellValue(cjbwh[12].ToString());
//15
IRow row_15 = tb.CreateRow(15);
ICell qp_14 = row_15.CreateCell(0);
qp_14.CellStyle = thjl_record_cellStyle;
qp_14.SetCellValue("其他");
ICell pq14_bwh = row_15.CreateCell(1);
pq14_bwh.CellStyle = thjl_record_cellStyle;
pq14_bwh.SetCellValue(pqbwh[7].ToString());
ICell cj_14 = row_15.CreateCell(2);
cj_14.CellStyle = thjl_record_cellStyle;
cj_14.SetCellValue("消防队");
ICell cj14_bwh = row_15.CreateCell(3);
cj14_bwh.CellStyle = thjl_record_cellStyle;
cj14_bwh.SetCellValue(cjbwh[13].ToString());
//16
IRow row_16 = tb.CreateRow(16);
ICell cj_15 = row_16.CreateCell(2);
cj_15.CellStyle = thjl_record_cellStyle;
cj_15.SetCellValue("计量站");
ICell cj15_bwh = row_16.CreateCell(3);
cj15_bwh.CellStyle = thjl_record_cellStyle;
cj15_bwh.SetCellValue(cjbwh[14].ToString());
string path = Server.MapPath("~/Upload//不完好率统计表.xls");
using (FileStream fs = System.IO.File.OpenWrite(path)) //打开一个xls文件,如果没有则自行创建,如果存在myxls.xls文件则在创建是不要打开该文件!
{
wk.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。
Console.WriteLine("提示:创建成功!");
}
return Path.Combine("/Upload", "不完好率统计表.xls");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return "";
}
}
public double getqcbwh_bytime(DateTime time)
{
EquipManagment Em = new EquipManagment();
TablesManagment tm = new TablesManagment();
List<EANummodel> E = Em.getequipnum_byarchi();
int qcsb_count = 0;
for (int i = 0; i < E.Count; i++)
{
qcsb_count += E[i].Equip_Num;
}
List<A5dot1Tab1> qc_list = tm.get_Allbytime(time);
double qcbwh = 0.000;
double qc_bxhcount = 0;
int wzgcount = 0;
if (qc_list.Count > 0)
{
qc_bxhcount = 0;
wzgcount = 0;
string sbcode_temp = qc_list[0].sbCode;
for (int j = 0; j < qc_list.Count; j++)
{
qc_list = tm.get_Allbytime(time);
if (qc_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(qc_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0 || cj_bycode[k].pqCheckTime == null || cj_bycode[k].pqCheckTime > time)
{
wzgcount++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzgcount > 0)
{
qc_bxhcount++;
}
wzgcount = 0;
}
// cjbwh.Add(f);
}
}
for (int n = 0; n < qc_list.Count; n++)
{
tm.modifytemp1_byid(qc_list[n].Id, null);
}
qcbwh = Math.Round(((double)qc_bxhcount / qcsb_count), 6);
return qcbwh;
}
public string Incomplete()
{
DateTime my = DateTime.Now;
Double incomplete_1;
Double incomplete_2;
Double incomplete_3;
Double incomplete_4;
Double incomplete_5;
Double incomplete_6;
string nowmonth;//获取当前月份
if (my.Day >= 15)
{
nowmonth = my.AddMonths(1).Month.ToString();
}
else
{
nowmonth = my.Month.ToString();
}
Double[] incomplete = new Double[Convert.ToInt32(nowmonth)];//创建一个大小根据月份来确定对的数组如9月,数组长度为9
incomplete[Convert.ToInt32(nowmonth) - 1] = 1 - getqcbwh_bytime(my);//1-getqcbwh_bytime(my)为当月完好率,是完好
for (int i = Convert.ToInt32(nowmonth); i > 1; i--)
{
DateTime lasttime = Convert.ToDateTime(my.Year + "/" + (i - 1) + "/" + 15 + " 00:00:00");
incomplete[i - 2] = 1 - getqcbwh_bytime(lasttime);//完好率
}
////前一个月不完好率根据nowmonth取
//DateTime lasttime2 = Convert.ToDateTime(my.Year + "/" + (Convert.ToInt32(nowmonth) - 2) + "/" + 15 + " 00:00:00");
//incomplete_3 = getqcbwh_bytime(lasttime2);
//DateTime lasttime3 = Convert.ToDateTime(my.Year + "/" + (Convert.ToInt32(nowmonth) - 3) + "/" + 15 + " 00:00:00");
//incomplete_4 = getqcbwh_bytime(lasttime3);
//DateTime lasttime4 = Convert.ToDateTime(my.Year + "/" + (Convert.ToInt32(nowmonth) - 4) + "/" + 15 + " 00:00:00");
//incomplete_5 = getqcbwh_bytime(lasttime4);
//DateTime lasttime5 = Convert.ToDateTime(my.Year + "/" + (Convert.ToInt32(nowmonth) - 5) + "/" + 15 + " 00:00:00");
//incomplete_6 = getqcbwh_bytime(lasttime5);
// string result=incomplete_1+"$"+incomplete_2+"$"+incomplete_3+"$"+incomplete_4+"$"+incomplete_5+"$"+incomplete_6+"$"+nowmonth;
string result = "";
for (int k = 0; k < Convert.ToInt32(nowmonth); k++)
{
result += incomplete[k] + "$";
}
return result;
}
public string Query_worst10bytime(string time)
{
List<object> r = new List<object>();
List<A5dot1Tab2> worst10 = new List<A5dot1Tab2>();
string[] s = time.Split(new char[] { '-' });
string ym = s[0] + s[1];
TablesManagment tm = new TablesManagment();
worst10 = tm.get_worst10byym(ym);
for (int i = 0; i < worst10.Count; i++)
{
object o = new
{
// index = i + 1,
cjname = worst10[i].cjName,
zzname = worst10[i].zzName,
sbGyCode = worst10[i].sbGyCode,
sbCode = worst10[i].sbCode,
timesNotGood = worst10[i].timesNotGood,
countAllNoRectifed = worst10[i].timesNotGood,//这台最差设备当月累计未整改数
notGoodContents = worst10[i].notGoodContents
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment.MenuConfig
{
public class SysMenuManagment
{
private IMenus db_menus = new Menus();
//添加一个菜单
//parentID == -1 ,添加到根节点
public bool AddMenuItem(int parentID, Menu add)
{
if (parentID == -1)
{
Menu root = GetRootItem();
return db_menus.AddMenu(root.Menu_Id, add);
}
else
return db_menus.AddMenu(parentID, add);
}
//修改一个菜单
public bool ModifyMenuItem(Menu modify)
{
return db_menus.ModifyMenu(modify.Menu_Id, modify);
}
//删除一个菜单
public bool DeleteMenuItem(int del)
{
return db_menus.DeleteMenu(del);
}
//获得菜单的根节点
public Menu GetRootItem()
{
try
{
List<Menu> res = db_menus.GetMenu("root");
if (res.Count > 1)
throw new Exception("DB has not only one root item");
return res[0];
}
catch(Exception e)
{
return null;
}
}
public Menu GetItemById(int id)
{
return db_menus.GetMenu(id);
}
//获得某一个菜单项的子节点
public List<Menu> GetChildsMenu(int menuID)
{
List<Menu> childs = new List<Menu>();
childs = db_menus.GetChildMenu(menuID);
return childs;
}
private MenuTree BuildChildTree(int parentId)
{
MenuTree cRoot = new MenuTree();
Menu cRootM = GetItemById(parentId);
cRoot.Menu_Id = cRootM.Menu_Id;
cRoot.Menu_Name = cRootM.Menu_Name;
cRoot.Menu_Icon = cRootM.Menu_Icon;
cRoot.Link_Url = cRootM.Link_Url;
List<Menu> childs = GetChildsMenu(parentId);
foreach(Menu m in childs)
{
MenuTree mt = BuildChildTree(m.Menu_Id);
cRoot.childs.Add(mt);
}
return cRoot;
}
public MenuTree BuildMenuTree()
{
Menu root = GetRootItem();
return BuildChildTree(root.Menu_Id);
}
private void BuildMenuList_inter(MenuListNode parent, List<MenuListNode> list)
{
List<Menu> childs = GetChildsMenu(parent.Menu_Id);
foreach (Menu m in childs)
{
MenuListNode mn = new MenuListNode();
mn.Menu_Id = m.Menu_Id;
mn.Menu_Name = m.Menu_Name;
mn.Menu_Icon = m.Menu_Icon;
mn.Link_Url = m.Link_Url;
if (m.Link_Url != null)
{
//在前台的页面中,本意是选择用Link_Url作为一个标签的id值,但是在id值中出现“/”的情况会使得根据id选择对象时出现问题,故在此统一转换。这段添加的代码功能是:将例如“/A3dot/Index”的字符串转成“A3dot3”
string[] s = (m.Link_Url).Split(new char[] { '/' });
string str = s[1];
mn.url_id = str;
};
mn.Parent_id = parent.Menu_Id;
mn.level = parent.level + 1;
parent.Childs.Add(mn.Menu_Id);
list.Add(mn);
BuildMenuList_inter(mn, list);
mn.Childs.ForEach(i => parent.Childs.Add(i));
}
}
public List<MenuListNode> BuildMenuList()
{
Menu root = GetRootItem();
MenuListNode rmn = new MenuListNode();
rmn.Menu_Id = root.Menu_Id;
rmn.Menu_Name = root.Menu_Name;
rmn.Menu_Icon = root.Menu_Icon;
rmn.Link_Url = root.Link_Url;
rmn.level = -1;
List<MenuListNode> list = new List<MenuListNode>();
BuildMenuList_inter(rmn, list);
foreach (MenuListNode mn in list)
{
if (mn.Parent_id == root.Menu_Id)
mn.Parent_id = 0;
}
return list;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Security.AccessControl;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Collections;
//using System.Runtime.Serialization.Json;
using EquipBLL.FileManagment;
using Newtonsoft.Json;
namespace WebApp.Controllers
{
public class A3dot3Controller : Controller
{
public class File
{
public string text;
public Boolean selectable;
public ArrayList nodes;
public File(string text, Boolean selectable, ArrayList nodes)
{
this.text = text;
this.selectable = selectable;
this.nodes = nodes;
}
}
public ActionResult Index()
{
return View();
}
string url_father = "<a target=" + "'_blank'" + " href=";
string url_last = "</a>";
public ArrayList GetAll(DirectoryInfo dir, string lianjie)//搜索文件夹中的文件
{
ArrayList FileList = new ArrayList();
FileInfo[] allFile = dir.GetFiles();
//遍历文件
foreach (FileInfo fi in allFile)
{
File temp = new File(url_father + lianjie + @"/" + fi.Name + "'>" + fi.Name + url_last, true, null);
FileList.Add(temp);//+" "+flag);
}
//遍历文件夹
DirectoryInfo[] allDir = dir.GetDirectories();
foreach (DirectoryInfo d in allDir)
{
File temp = new File(d.Name, false, GetAll(d, lianjie + @"/" + d.Name));
FileList.Add(temp);
}
return FileList;
}
public string tree(object sender, EventArgs e)
{
//string url = @"'../A3.3FileArch";
//string strPath = Server.MapPath(@"..\A3.3FileArch\");
//DirectoryInfo d = new DirectoryInfo(strPath);
//ArrayList Flst = new ArrayList();
//Flst.Add(GetAll(d, url));
File_Cat_Manager fcm = new File_Cat_Manager();
var Flst = fcm.BuildCatTree();
string result = Newtonsoft.Json.JsonConvert.SerializeObject(Flst);
return result;
}
[HttpPost]
public bool AddFileCatalog(int parentID, string newCataName)
{
File_Cat_Manager fcm = new File_Cat_Manager();
return fcm.AddNewCatalog(parentID, newCataName);
}
[HttpPost]
public bool DeleteFileCatalog(int cataID)
{
return (new File_Cat_Manager()).DeleteCatalog(cataID);
}
[HttpPost]
public bool ModifyFileCatalog(int ID, string newName)
{
return (new File_Cat_Manager()).ModifyFileCatalog(ID, newName);
}
[HttpPost]
public JsonResult GetFilesLIst(int cataID)
{
List<object> file_list = new List<object>();
if (cataID == -1)
{
;
}
else
{
List<FileItem> fs = (new File_Cat_Manager()).GetFilesInCatalog(cataID);
foreach (var fi in fs)
{
object o = new
{
fID = fi.id,
fName = fi.fileName,
fTime = fi.updateTime,
fRName = fi.fileNamePresent,
fPath = fi.path,
ext = fi.ext
};
file_list.Add(o);
}
}
return Json(new { data = file_list.ToArray() });
}
[HttpPost]
public bool DelFileById(int fileID)
{
return (new File_Cat_Manager()).DeleteFile(fileID);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EquipModel.Entities;
using EquipDAL.Implement;
namespace EquipBLL.AdminManagment
{
public class GD_InfoModal
{
public string GD_Id;
public string GD_Notice_Id;
public string GD_UserState;
public string GD_Desc;
public string GD_State;
public string GD_EquipCode;
}
public class ERPInfoManagement
{ //适用于流程A8.2
//输入:工单号
//输出:GD_InfoModal{记录工单的通知单号、用户状态和简要说明信息}
public GD_InfoModal getGD_Modal_GDId(string gd_Id)
{
ERP_Infos gd = new ERP_Infos();
GongDan r_gd= gd.getGD_info(gd_Id);
if (r_gd != null)
{
GD_InfoModal r = new GD_InfoModal();
r.GD_Id = r_gd.GD_Id;
r.GD_Notice_Id = r_gd.GD_Notice_Id;
r.GD_UserState = r_gd.GD_State;
r.GD_Desc = r_gd.GD_Desc;
r.GD_State = r_gd.GD_State;
r.GD_EquipCode = r_gd.GD_EquipCode;
return r;
}
else
return null;
}
//适用于流程A14.3
//输入:通知单单号
//输出:GD_InfoModal{记录工单的工单号、用户状态和简要说明信息}
public GD_InfoModal getGD_Modal_Notice(string gd_Notice_Id)
{
ERP_Infos gd = new ERP_Infos();
GongDan r_gd = gd.getGD_Notice_info(gd_Notice_Id);
if (r_gd != null)
{
GD_InfoModal r = new GD_InfoModal();
r.GD_Id = r_gd.GD_Id;
r.GD_Notice_Id = r_gd.GD_Notice_Id;
r.GD_UserState = r_gd.GD_State;
r.GD_Desc = r_gd.GD_Desc;
return r;
}
else
return null;
}
public List<OilInfo> getOilInfo_overdue()
{
string curdate = DateTime.Now.ToString("yyyyMMdd");
ERP_Infos gd = new ERP_Infos();
return gd.getOilInfo_Overdue(curdate);
}
//public List<OilInfo> getOilInfo_overdue()
//{
// string curdate=DateTime.Now.ToString("YYYYMMdd");
// ERP_Infos gd = new ERP_Infos();
// return gd.getOilInfo_Overdue(curdate);
//}
//影响级别为1级,非计划停工通知单数
public int getNoticesYx_1(string Pq_Code)
{
ERP_Infos erp = new ERP_Infos();
List<Notice> notices = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除");
return notices.Where(a => a.Notice_FaultYx == "1").Count();
}
//影响级别为2级 单个装置非计划停工、多套装置生产波动的通知单数目
public int getNoticeYx_2(string Pq_Code)
{
ERP_Infos erp = new ERP_Infos();
List<Notice> notices = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除");
return notices.Where(a => a.Notice_FaultYx == "2").Count();
}
//影响级别3级 单个生产装置降量或局部切除,大机组急停
public int getNoticeYx_3(string Pq_Code)
{
ERP_Infos erp = new ERP_Infos();
List<Notice> notices = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除");
return notices.Where(a => a.Notice_FaultYx == "3").Count();
}
//影响级别4级 单个生产装置局部波动
public int getNoticeYx_4(string Pq_Code)
{
ERP_Infos erp = new ERP_Infos();
List<Notice> notices = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除");
return notices.Where(a => a.Notice_FaultYx == "4").Count();
}
//故障维修率F
public double getFaultRation(string Pq_Code)
{
ERP_Infos erp = new ERP_Infos();
List<Notice> noticesUp = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除","3");
List<Notice> noticesDown = erp.getNoticeInfos_ByNoticeTypes(Pq_Code,"删除", "3");
if (noticesDown.Count() != 0)
return (noticesUp.Count() / noticesDown.Count()) * 100;
else
return 0;
}
//一般机泵设备平均无故障间隔周期
public double getNonFaultInterVal(string Pq_Code)
{
ERP_Infos erp = new ERP_Infos();
List<Notice> noticesUp = erp.getNoticeInfos(Pq_Code,"投用");
List<Notice> noticesDown1 = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除", "2");
List<Notice> noticesDown2 = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除", "3");
if (noticesDown1.Count() + noticesDown2.Count() != 0)
return (noticesUp.Count() / (noticesDown1.Count() + noticesDown2.Count())) * 100;
else
return -1;
}
//设备投用率
public double DeliverRatio(string Pq_Code)
{
double faultTimeSum = 0;
DateTime D_end, D_start;
ERP_Infos erp = new ERP_Infos();
List<Notice> noticesUp = erp.getNoticeInfos_ByNoticeType(Pq_Code, "M2", "删除");
List<Notice> noticesDown = erp.getNoticeInfos(Pq_Code, "投用");
foreach (var n in noticesUp)
{
if (n.Notice_FaultEnd != "00000000")
{
D_end = DateTime.ParseExact(n.Notice_FaultEnd, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
D_start = DateTime.ParseExact(n.Notice_FaultStart, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
faultTimeSum = faultTimeSum + (D_end - D_start).Days * 24;
}
}
if (noticesDown.Count() != 0)
return 1 - (faultTimeSum / (noticesDown.Count() * 30 * 24));
else
return 100;
}
//维修平均工时
public double faultServiceTime_Avg(string Pq_Code)
{
double faultTimeSum = 0;
DateTime D_end, D_start;
ERP_Infos erp = new ERP_Infos();
List<Notice> noticesUp = erp.getNoticeInfos_ByNoticeType(Pq_Code, "M2", "删除");
List<Notice> noticesDown = erp.getNoticeInfos(Pq_Code, "投用");
foreach (var n in noticesUp)
{
if (n.Notice_FaultEnd != "00000000")
{
D_end = DateTime.ParseExact(n.Notice_FaultEnd, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
D_start = DateTime.ParseExact(n.Notice_FaultStart, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
faultTimeSum = faultTimeSum + (D_end - D_start).Days * 24;
}
}
if (noticesDown.Count() != 0)
return (faultTimeSum / (noticesDown.Count()));
else
return 0;
}
//public double DeliverRatio(string Pq_Code)
//{
// double faultTimeSum = 0;
// ERP_Infos erp = new ERP_Infos();
// List<Notice> noticesUp = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除");
// List<Notice> noticesDown = erp.getNoticeInfos(Pq_Code,"投用");
// foreach(var n in noticesUp)
// {
// faultTimeSum = faultTimeSum + (000.000);
// }
// if (noticesDown.Count() != 0)
// return 1 - (faultTimeSum / (noticesDown.Count() * 30 * 24));
// else
// return 100;
//}
////维修平均工时
//public double faultServiceTime_Avg(string Pq_Code)
//{
// double faultTimeSum = 0;
// ERP_Infos erp = new ERP_Infos();
// List<Notice> noticesUp = erp.getNoticeInfos_ByNoticeType(Pq_Code,"M2", "删除");
// List<Notice> noticesDown = erp.getNoticeInfos(Pq_Code,"投用");
// foreach (var n in noticesUp)
// {
// faultTimeSum = faultTimeSum + (000.000);
// }
// if (noticesDown.Count() != 0)
// return (faultTimeSum / (noticesDown.Count()));
// else
// return 0;
//}
//大机组统计,全厂统计Pq_Code=ALL
public double bigEquipsRatio(string Pq_Code)
{
double faultTimeSum = 0;
DateTime D_end, D_start;
ERP_Infos erp = new ERP_Infos();
List<Notice> noticesUp = erp.getNoticeInfos_BigEquip(Pq_Code, "M2", "删除", "3");
int bigEquipCount = erp.geBigEquip_Num(Pq_Code);
foreach (var n in noticesUp)
{
if (n.Notice_FaultEnd != "00000000")
{
D_end = DateTime.ParseExact(n.Notice_FaultEnd + n.Notice_FaultEndTime, "yyyyMMddhhmmss", System.Globalization.CultureInfo.CurrentCulture);
D_start = DateTime.ParseExact(n.Notice_FaultStart + n.Notice_FaultEndTime, "yyyyMMddhhmmss", System.Globalization.CultureInfo.CurrentCulture);
faultTimeSum = faultTimeSum + (D_end - D_start).Days * 24 + (D_end - D_start).Hours;
}
}
if (bigEquipCount != -1 && bigEquipCount != 0)
return (faultTimeSum / (bigEquipCount * 30 * 24));
else
return -1;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment.MenuConfig
{
public class MenuListNode
{
public MenuListNode()
{
Childs = new List<int>();
}
public int Menu_Id { get; set; }
//菜单名称
public string Menu_Name { get; set; }
//菜单连接的URL
public string Link_Url { get; set; }
public string url_id { get; set; }
//菜单对应ICON
public string Menu_Icon { get; set; }
public int Parent_id { get; set; }
public List<int> Childs { get; set; }
public int level { get; set; }
}
//2016-4-28修改开始
public class MenuListNode1
{
public MenuListNode1()
{
Childs = new List<int>();
}
public int EA_Id { get; set; }
//菜单名称
public string EA_Name { get; set; }
//菜单连接的URL
public string EA_Code { get; set; }
//菜单对应ICON
public string EA_Title { get; set; }
public int Parent_id { get; set; }
public List<int> Childs { get; set; }
public int level { get; set; }
}
//结束
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Menu
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Menu_Id { get; set; }
[Required()]
//菜单名称
public string Menu_Name { get; set; }
//菜单连接的URL
public string Link_Url { get; set; }
//菜单对应ICON
public string Menu_Icon { get; set; }
//该菜单项的子菜单
public virtual ICollection<Menu> child_menus { get; set; }
/// <summary>
/// 具有改该菜单项操作功能的用户
/// </summary>
public virtual ICollection<Person_Info> Menu_Persons { get; set; }
/// <summary>
/// 具有某系统功能菜单的角色
/// </summary>
public virtual ICollection<Role_Info> Menu_Roles { get; set; }
public virtual ICollection<ZhiduFile> ZhiduFiles { get; set; }
public virtual ICollection<Person_Info> WorkFlow_Persons { get; set; }
}
}
<file_sep>///////////////////////////////////////////////////////////
// CEvent.cs
// Implementation of the Class CEvent
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine.Event;
using System.Xml;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Diagnostics;
using FlowEngine.Param;
using FlowEngine.Authority;
using System.Data.Entity.Core.Objects;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace FlowEngine.Event {
/// <summary>
/// 各种事件(Event)的基类,提供它们相同的操作
/// </summary>
public abstract class CEvent : IXMLEntity, IEvent {
/// <summary>
/// 事件(Event)名称
/// </summary>
private string m_name = "";
/// <summary>
/// 事件(Event)的描述
/// </summary>
private string m_description = "";
/// <summary>
/// After Action: 离开事件(Event)首先执行的动作
/// Action(动作):对应于MVC的Controller
/// 注意:After Action联系的Controller不建议设置成页面controller,否则会引起自动页面跳转
/// </summary>
private string m_afferAction = "";
/// <summary>
/// After Action 事件的参数
/// </summary>
protected Dictionary<string, string> m_afterActionParams = new Dictionary<string, string>();
/// <summary>
/// Before Action: 进入事件(Event)首先执行的动作
/// Action(动作):对应于MVC的Controller
/// 注意:BeforAction联系的Controller不建议设置成页面controller,否则会引起自动页面跳转
/// </summary>
private string m_beforAction = "";
/// <summary>
/// Before Action 事件的参数
/// </summary>
protected Dictionary<string, string> m_beforeActionParams = new Dictionary<string, string>();
/// <summary>
/// Current Action: 事件(Event)的主动作
/// Action(动作):对应于MVC的Controller
/// </summary>
private string m_currentAction = "";
/// <summary>
/// 与Event相关联的参数
/// </summary>
protected Dictionary<string, CParam> m_params = new Dictionary<string, CParam>();
protected Dictionary<string, string> m_paramsApp_res = new Dictionary<string, string>();
/// <summary>
/// 权限判定
/// </summary>
private CAuthority m_authority = new CAuthority();
/// <summary>
/// 所属工作流
/// </summary>
protected CWorkFlow m_parentWF;
/// <summary>
/// 超时控制
/// </summary>
protected CTimeOutProperty m_timeout;
public CTimeOutProperty TimeOutProperty
{
get
{
return m_timeout;
}
}
public CWorkFlow Parent
{
get { return m_parentWF; }
}
public CEvent(CWorkFlow parent){
m_parentWF = parent;
m_timeout = new CTimeOutProperty(this);
}
~CEvent(){
}
/// <summary>
/// 获取相关联的参数
/// </summary>
public Dictionary<string, CParam> paramlist
{
get{
return m_params;
}
}
public Dictionary<string, string> paramsApp_res
{
get
{
return m_paramsApp_res;
}
}
/// <summary>
/// 事件(Event)名称
/// </summary>
public string name{
get{
return m_name;
}
set
{
m_name = value;
}
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public virtual void InstFromXmlNode(XmlNode xmlNode){
XmlElement xe = (XmlElement)xmlNode;
//1. 判断xmlnode是否为“event”
if (xmlNode.Name.ToLower() != "event")
return;
//2. 读取event的属性
m_name = xmlNode.Attributes["name"].Value;
m_description = xmlNode.Attributes["desc"].Value;
//3. 读取Actions
XmlNode actions = xe.SelectSingleNode("actions");
XmlNode ba = actions.SelectSingleNode("beforeaction");
XmlNode aa = actions.SelectSingleNode("afteraction");
XmlNode ca = actions.SelectSingleNode("currentaction");
m_currentAction = ca.InnerText;
//3.1 afterAction
m_afferAction = aa.SelectSingleNode("url").InnerText;
m_afterActionParams.Clear();
XmlNodeList aparams = ((XmlElement)(aa.SelectSingleNode("action_params"))).SelectNodes("param");
foreach(var xnn in aparams)
{
m_afterActionParams[((XmlElement)xnn).GetAttribute("name")] = ((XmlElement)xnn).InnerText;
}
//3.2 beforeAction
m_beforAction = ba.SelectSingleNode("url").InnerText;
m_beforeActionParams.Clear();
XmlNodeList bparams = ((XmlElement)(ba.SelectSingleNode("action_params"))).SelectNodes("param");
foreach(var xnn in bparams)
{
m_beforeActionParams[((XmlElement)xnn).GetAttribute("name")] = ((XmlElement)xnn).InnerText;
}
//4. 读取权限
XmlNode aut = xe.SelectSingleNode("authority");
m_authority.InstFromXmlNode(aut);
//5. 读取超时
XmlNode to = xe.SelectSingleNode("timeout_setting");
if (to != null)
m_timeout.InstFromXmlNode(to);
}
/// <summary>
/// 反解析到XML元素
/// </summary>
public virtual XmlNode WriteToXmlNode(){
XmlDocument xd = new XmlDocument();
//1. 创建Event节点
XmlElement eventXe = xd.CreateElement("event");
//2. 设置Event属性
eventXe.SetAttribute("name", m_name);
eventXe.SetAttribute("desc", m_description);
//3. 设置动作(Actions)节点
XmlElement actions = xd.CreateElement("actions");
XmlElement ba = xd.CreateElement("beforeaction");
XmlElement ca = xd.CreateElement("currentaction");
XmlElement aa = xd.CreateElement("afteraction");
ca.AppendChild(xd.CreateCDataSection(m_currentAction));
//3.1 beforeAction
XmlElement baurl = xd.CreateElement("url");
baurl.AppendChild(xd.CreateCDataSection(m_beforAction));
ba.AppendChild(baurl);
XmlElement baparams = xd.CreateElement("action_params");
foreach(var bp in m_beforeActionParams)
{
XmlElement pee = xd.CreateElement("param");
pee.SetAttribute("name", bp.Key);
pee.InnerText = bp.Value;
baparams.AppendChild(pee);
}
ba.AppendChild(baparams);
//3.2 afterAction
XmlElement aaurl = xd.CreateElement("url");
aaurl.AppendChild(xd.CreateCDataSection(m_afferAction));
aa.AppendChild(aaurl);
XmlElement aaparams = xd.CreateElement("action_params");
foreach(var ap in m_afterActionParams)
{
XmlElement pee = xd.CreateElement("param");
pee.SetAttribute("name", ap.Key);
pee.InnerText = ap.Value;
aaparams.AppendChild(pee);
}
aa.AppendChild(aaparams);
actions.AppendChild(ba);
actions.AppendChild(ca);
actions.AppendChild(aa);
eventXe.AppendChild(actions);
//4. 设置权限节点
XmlNode auts = m_authority.WriteToXmlNode();
eventXe.AppendChild(xd.ImportNode(auts, true));
//5.设置timeout节点
XmlNode to = m_timeout.WriteToXmlNode();
eventXe.AppendChild(xd.ImportNode(to, true));
return eventXe;
}
/// <summary>
/// 事件(Event)的描述
/// </summary>
public string description{
get{
return m_description;
}
set
{
m_description = value;
}
}
/// <summary>
/// After Action
/// </summary>
public string afteraction{
get{
return m_afferAction;
}
set{
m_afferAction = value;
}
}
/// <summary>
/// Before Action
/// </summary>
public string beforeaction{
get {
return m_beforAction;
}
set {
m_beforAction = value;
}
}
/// <summary>
/// 事件的主事件
/// </summary>
public virtual string currentaction{
get{
return m_currentAction;
}
set{
m_currentAction = value;
}
}
/// <summary>
/// 进入该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public abstract void EnterEvent(string strjson);
/// <summary>
/// 离开该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public abstract void LeaveEvent(string strjson);
/// <summary>
/// 跟新与之相关的变量的值
/// </summary>
/// <param name="strjson"></param>
/// <returns></returns>
public virtual bool UpdateParams(string strjson)
{
JArray ja = (JArray)JsonConvert.DeserializeObject(strjson);
//1. 判断传达的变量是否合法
foreach (JObject jo in ja)
{
string parname = jo["name"].ToString();
string parvalue = jo["value"].ToString();
//检测变量量是否合法
if (!m_params.ContainsKey(parname))
return false;
//检测变量值是否合法
if (!m_params[parname].ValueTest(parvalue))
return false;
}
//2. 将变量的值更新
foreach (JObject jo in ja)
{
string parname = jo["name"].ToString();
string parvalue = jo["value"].ToString();
m_params[parname].value = parvalue;
}
return true;
}
/// <summary>
/// 处理Action返回的结果
/// strjon包含两个属性,即status,状态(OK, ERROR);
/// description, 描述
/// </summary>
/// <param name="strjon"></param>
protected void OpResutsfromAction(string strjon){
JObject jo = (JObject)JsonConvert.SerializeObject(strjon);
Trace.WriteLine("status:" + jo["status"].ToString());
Trace.WriteLine("description:" + jo["desc"].ToString());
}
/// <summary>
/// 权限检查
/// </summary>
public bool CheckAuthority<T>(Dictionary<string, object> outer_paras, ObjectContext oc)
{
Dictionary<string, object> inter_params = new Dictionary<string, object>();
foreach (var pa in m_params)
inter_params[pa.Key] = pa.Value.value;
return m_authority.CheckAuth<T>(inter_params, outer_paras, oc);
}
protected void InsertMissionToDB()
{
WorkFlows wfs = new WorkFlows();
Mission mis = new Mission();
mis.Miss_Name = this.name;
mis.Miss_WFentity = null;
mis.Miss_Desc = this.description;
mis.Event_Name = this.name;
mis.next_Mission = null;
mis.pre_Mission = null;
mis.Record_Info = null;
try
{
wfs.AddMissionRecord(m_parentWF.EntityID, mis);
List<Mission_Param> pars = new List<Mission_Param>();
foreach(var pa in m_params)
{
Mission_Param par = new Mission_Param();
par.Param_Name = pa.Value.name;
par.Param_Type = pa.Value.type;
par.Param_Value = Convert.ToString(pa.Value.value);
par.Param_Desc = pa.Value.description;
pars.Add(par);
}
wfs.LinkParamsToMiss(mis.Miss_Id, pars);
}
catch(Exception e)
{
return;
}
}
/// <summary>
/// 将当前任务更新到数据库CURR_Misson
/// </summary>
/// <param name="clearFlag"></param>
protected void UpdateCurrentEvent(bool clearFlag = false)
{
CURR_Mission cur_mis = new CURR_Mission();
cur_mis.After_Action = afteraction;
cur_mis.Before_Action = beforeaction;
cur_mis.Current_Action = currentaction;
cur_mis.Miss_Desc = description;
cur_mis.Miss_Name = name;
//将内部变量的值预填充到权限认证字符串
Dictionary<string, object> inter_params = new Dictionary<string, object>();
foreach (var pa in m_params)
inter_params[pa.Key] = pa.Value.value;
cur_mis.Str_Authority = m_authority.FillParams(inter_params, null);
try
{
WorkFlows wfs = new WorkFlows();
if (clearFlag == true)
wfs.UpdateCurrentMission(m_parentWF.EntityID, null);
else
wfs.UpdateCurrentMission(m_parentWF.EntityID, cur_mis);
}
catch(Exception e)
{
Trace.WriteLine("UpdateCurrentEvent error:" + e.Message);
}
}
protected string parselEventActionParams(string param)
{
//如果param不是变量,则认为param是一个常量
if (param[0] != '@')
return param;
else if (param.IndexOf("@ATT_") == 0)
{
string pName = param.Substring(5);
string pValue = "";
switch(pName)
{
case "Entity_ID":
pValue = m_parentWF.EntityID.ToString();
break;
case "Name":
pValue = m_parentWF.name;
break;
case "Description":
pValue = m_parentWF.description;
break;
case "Serial":
pValue = m_parentWF.EntitySerial;
break;
default:
pValue = "";
break;
}
return pValue;
}
else if (param.IndexOf("@PAR_") == 0)
{
string pName = param.Substring(5);
string pValue = "";
if (m_params.ContainsKey(pName))
pValue = Convert.ToString(m_params[pName].value);
return pValue;
}
else
return param;
}
public void RegTimeOut(bool bCreated)
{
m_timeout.RegTimeoutTimer(bCreated);
}
/// <summary>
/// 获得权限字符串
/// </summary>
/// <returns></returns>
public string GetAuthorityString()
{
return m_authority.auth_string;
}
/// <summary>
/// 获得timeout属性
/// </summary>
/// <returns></returns>
public CTimeOutProperty GetTimeOutProperty()
{
return m_timeout;
}
}//end CEvent
}//end namespace Event<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using iTextSharp.text.pdf;
using iTextSharp.text;
using EquipBLL.AdminManagment.MenuConfig;
namespace WebApp.Controllers
{
public class A15dot1qiyeController : CommonController
{
private KpiManagement Jx = new KpiManagement();
public ActionResult Index()
{
return View(getRecord());
}
public class Index_ModelforA15
{
public List<A15dot1TabQiYe> Am;
public List<A15dot1TabQiYe> Hm;
public int isSubmit;
public int kkxgcs;
public int am;
public int hm;
}
public Index_ModelforA15 getRecord()
{
Index_ModelforA15 RecordforA15 = new Index_ModelforA15();
//ViewBag.curtime = DateTime.Now.ToString();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
RecordforA15.Am = new List<A15dot1TabQiYe>();
if (pv.Role_Names.Contains("可靠性工程师") || pv.Role_Names.Contains("检维修人员"))
RecordforA15.isSubmit = 1;
else
RecordforA15.isSubmit = 0;
if (pv.Role_Names.Contains("可靠性工程师"))
RecordforA15.kkxgcs = 1;
else
RecordforA15.kkxgcs = 0;
List<string> cjname = new List<string>();
List<Equip_Archi> EA = pm.Get_Person_Cj(UserId);
foreach (var ea in EA)
{
cjname.Add(ea.EA_Name);
}
List<A15dot1TabQiYe> miss = Jx.GetJxItem(pv.Role_Names, pv.Department_Name, pv.Person_Name,cjname);
foreach (var item in miss)
{
A15dot1TabQiYe a = new A15dot1TabQiYe();
a.zzkkxzs = item.zzkkxzs;
a.wxfyzs = item.wxfyzs;
a.qtlxbmfxhl = item.qtlxbmfxhl;
a.qtlhsbgsghl = item.qtlhsbgsghl;
a.ybsjkzl = item.ybsjkzl;
a.sjs = item.sjs;
a.gzqdkf = item.gzqdkf;
a.xmyql = item.xmyql;
a.pxjnl = item.pxjnl;
a.submitDepartment = item.submitDepartment;
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.jdcOperator = item.jdcOperator;
a.jdcOperateTime = item.jdcOperateTime;
a.reportType = item.reportType;
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.state = item.state;
a.Id = item.Id;
RecordforA15.Am.Add(a);
}
RecordforA15.Hm = new List<A15dot1TabQiYe>();
List<A15dot1TabQiYe> His = Jx.GetHisJxItem(pv.Role_Names, pv.Department_Name, pv.Person_Name);
foreach (var item in His)
{
A15dot1TabQiYe a = new A15dot1TabQiYe();
a.Id = item.Id;
a.state = item.state;
a.jdcOperateTime = item.jdcOperateTime;
a.jdcOperator = item.jdcOperator;
a.temp1 = Convert.ToString(His.IndexOf(item) + 1);
RecordforA15.Hm.Add(a);
}
return RecordforA15;
}
public Index_ModelforA15 getRecord_detail(string id)
{
Index_ModelforA15 RecordforA15 = new Index_ModelforA15();
RecordforA15.Am = new List<A15dot1TabQiYe>();
RecordforA15.Hm = new List<A15dot1TabQiYe>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int IntId = Convert.ToInt32(id);
List<A15dot1TabQiYe> miss = Jx.GetJxItem_detail(IntId);
foreach (var item in miss)
{
A15dot1TabQiYe a = new A15dot1TabQiYe();
a.zzkkxzs = item.zzkkxzs;
a.wxfyzs = item.wxfyzs;
a.qtlxbmfxhl = item.qtlxbmfxhl;
a.qtlhsbgsghl = item.qtlhsbgsghl;
a.ybsjkzl = item.ybsjkzl;
a.sjs = item.sjs;
a.gzqdkf = item.gzqdkf;
a.xmyql = item.xmyql;
a.pxjnl = item.pxjnl;
a.submitDepartment = item.submitDepartment;
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.jdcOperator = item.jdcOperator;
a.jdcOperateTime = item.jdcOperateTime;
a.reportType = item.reportType;
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.state = item.state;
a.temp3 = item.temp3;
a.reliabilityConclusion = item.reliabilityConclusion;
a.Id = item.Id;
RecordforA15.Am.Add(a);
}
string name = RecordforA15.Am[0].submitUser;
PersonManagment pm = new PersonManagment();
int UserId = pm.Get_Person(name).Person_Id;
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
RecordforA15.am = 1;
else
RecordforA15.am = 0;
List<A15dot1TabQiYe> His = Jx.GetHisJxItem_detail(IntId);
foreach (var item in His)
{
A15dot1TabQiYe a = new A15dot1TabQiYe();
a.zzkkxzs = item.zzkkxzs;
a.wxfyzs = item.wxfyzs;
a.qtlxbmfxhl = item.qtlxbmfxhl;
a.qtlhsbgsghl = item.qtlhsbgsghl;
a.ybsjkzl = item.ybsjkzl;
a.sjs = item.sjs;
a.gzqdkf = item.gzqdkf;
a.xmyql = item.xmyql;
a.pxjnl = item.pxjnl;
a.submitDepartment = item.submitDepartment;
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.jdcOperator = item.jdcOperator;
a.jdcOperateTime = item.jdcOperateTime;
a.reportType = item.reportType;
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.state = item.state;
a.Id = item.Id;
RecordforA15.Hm.Add(a);
}
name = RecordforA15.Hm[0].submitUser;
UserId = pm.Get_Person(name).Person_Id;
pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
RecordforA15.hm = 1;
else
RecordforA15.hm = 0;
return RecordforA15;
}
public class submitmodel
{
public string equipReliableExponent;//装置可靠性指数
public string maintainChargeExponent;//维修费用指数
public string thousandLXBrate;//千台离心泵(机泵)密封消耗率
public string thousandColdChangeRate;//千台冷换设备管束(含整台)更换率
public string instrumentControlRate;//仪表实际控制率
public string eventNumber;//事件数
public string troubleKoufen;//故障强度扣分
public string projectLateRate;//项目逾期率
public string trainAndAbility;//培训及能力
//public int kkxgcs;
//public int jwxry;
public List<Equip_Archi> UserHasEquips;
}
public ActionResult Submit()
{
PersonManagment pm = new PersonManagment();
submitmodel sm = new submitmodel();
ViewBag.curtime = DateTime.Now;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
//int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
//PersonManagment pm = new PersonManagment();
//EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
//if (pv.Role_Names.Contains("可靠性工程师"))
// sm.kkxgcs = 1;
//if (pv.Role_Names.Contains("检维修人员"))
// sm.jwxry = 1;
sm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(sm);
}
public string qst(string grahpic_name, string zz)
{
List<object> res = Jx.qst(grahpic_name, zz);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public ActionResult KkxSubmit(string id)
{
return View(getRecord_detail(id));
}
public ActionResult JdcSubmit(string id)
{
return View(getRecord_detail(id));
}
public bool Submit_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabQiYe new_15dot1qiye = new A15dot1TabQiYe();
new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
new_15dot1qiye.sjs = Convert.ToInt32(item["eventNumber"]);
new_15dot1qiye.gzqdkf = Convert.ToInt32(item["troubleKoufen"]);
new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
new_15dot1qiye.pxjnl = Convert.ToInt32(item["trainAndAbility"]);
new_15dot1qiye.submitDepartment = Convert.ToString(item["zzId"]);//存储装置的名字
new_15dot1qiye.temp3 = Convert.ToString(item["cjname"]);//车间名字存于temp3
new_15dot1qiye.temp2 = "企业级";//专业名字存于temp2
new_15dot1qiye.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1qiye.submitTime = DateTime.Now;
bool res = Jx.AddJxItem(new_15dot1qiye);
return res;
}
public JsonResult Modify_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabQiYe new_15dot1qiye = new A15dot1TabQiYe();
new_15dot1qiye.zzkkxzs = Convert.ToDouble(item["equipReliableExponent"]);
new_15dot1qiye.wxfyzs = Convert.ToDouble(item["maintainChargeExponent"]);
new_15dot1qiye.qtlxbmfxhl = Convert.ToDouble(item["thousandLXBrate"]);
new_15dot1qiye.qtlhsbgsghl = Convert.ToDouble(item["thousandColdChangeRate"]);
new_15dot1qiye.ybsjkzl = Convert.ToDouble(item["instrumentControlRate"]);
new_15dot1qiye.sjs = Convert.ToInt32(item["eventNumber"]);
new_15dot1qiye.gzqdkf = Convert.ToInt32(item["troubleKoufen"]);
new_15dot1qiye.xmyql = Convert.ToDouble(item["projectLateRate"]);
new_15dot1qiye.pxjnl = Convert.ToDouble(item["trainAndAbility"]);
new_15dot1qiye.reliabilityConclusion = Convert.ToString(item["reliabilityConclusion"]);
new_15dot1qiye.submitDepartment = Convert.ToString(item["zzId"]);
new_15dot1qiye.temp2 = "企业级";
new_15dot1qiye.Id = Convert.ToInt32(item["A15dot1_id"]);
new_15dot1qiye.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1qiye.submitTime = DateTime.Now;
new_15dot1qiye.state = Convert.ToInt32(item["state"]);
bool res = Jx.ModifyJxItem(new_15dot1qiye);
return Json(new { result = res });
}
}
}<file_sep>using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.DAL
{
/// <summary>
/// 定时性任务管理
/// </summary>
public class Jobs : BaseDAO
{
/// <summary>
/// 获取一个定时任务
/// </summary>
/// <param name="job_id">任务ID</param>
/// <returns></returns>
public Timer_Jobs GetTimerJob(int job_id)
{
try
{
using(var db = base.NewDB())
{
return db.timer_jobs.Where(a => a.JOB_ID == job_id).First();
}
}
catch
{
return null;
}
}
/// <summary>
/// 获得所有的工作
/// </summary>
/// <returns></returns>
public List<Timer_Jobs> GetAllTimerJob()
{
try
{
using(var db = base.NewDB())
{
return db.timer_jobs.ToList();
}
}
catch(Exception e)
{
return new List<Timer_Jobs>();
}
}
/// <summary>
/// 根据任务状态选择定时性任务
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
public List<Timer_Jobs> GetJobsByStatus(TM_STATUS status)
{
try
{
using(var db = base.NewDB())
{
return db.timer_jobs.Where(a => a.status == status).ToList();
}
}
catch
{
return new List<Timer_Jobs>();
}
}
/// <summary>
/// 根据任务用途选择定时性任务
/// </summary>
/// <param name="useTag"></param>
/// <returns></returns>
public List<Timer_Jobs> GetJobsByUsing(TIMER_USING useTag)
{
try
{
using(var db = base.NewDB())
{
return db.timer_jobs.Where(a => a.t_using == useTag).ToList();
}
}
catch
{
return new List<Timer_Jobs>();
}
}
/// <summary>
/// 根绝任务的类型选择定时性任务
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public List<Timer_Jobs> GetJobsByType(TIMER_JOB_TYPE type)
{
try
{
using (var db = base.NewDB())
{
return db.timer_jobs.Where(a => a.Job_Type == type).ToList();
}
}
catch
{
return new List<Timer_Jobs>();
}
}
/// <summary>
/// 添加一个定时性任务
/// </summary>
/// <param name="job"></param>
/// <returns>新定时性任务的ID</returns>
public int AppendJob(Timer_Jobs job)
{
try
{
using (var db = base.NewDB())
{
Timer_Jobs j = db.timer_jobs.Add(job);
if (db.SaveChanges() != 1)
return -1;
return j.JOB_ID;
}
}
catch
{
return -1;
}
}
/// <summary>
/// 保存一个定时任务
/// </summary>
/// <param name="job"></param>
/// <returns></returns>
public int SaveJob(Timer_Jobs job)
{
try
{
using(var db = base.NewDB())
{
//1. 查找是否存在该任务
var list = db.timer_jobs.Where(a => a.JOB_ID == job.JOB_ID);
//2. 如果存在则更新
if (list.ToList().Count != 0)
{
Timer_Jobs j = list.First();
j.copy(job);
if (db.SaveChanges() != 1)
return -1;
return j.JOB_ID;
}
//3. 不存在则添加一条新记录
else
{
job.JOB_ID = -1;
job = db.timer_jobs.Add(job);
if (db.SaveChanges() != 1)
return -1;
return job.JOB_ID;
}
}
}
catch(Exception e)
{
return -1;
}
}
/// <summary>
/// 更新一个定时任务
/// </summary>
/// <param name="id"></param>
/// <param name="propertis"></param>
/// <param name="vals"></param>
/// <returns></returns>
public Timer_Jobs UpdateJob(int id, List<string> propertis, List<object> vals)
{
try
{
using (var db = base.NewDB())
{
var job = db.timer_jobs.Where(a => a.JOB_ID == id).First();
if (propertis.Count == 0)
return job;
for (int i = 0; i < propertis.Count; i++)
{
string property = propertis[i];
object val = vals[i];
switch (property)
{
case "job_name":
job.job_name = val as string;
break;
case "workflow":
job.workflow_ID = (int)val;
break;
case "job_type":
job.Job_Type = (TIMER_JOB_TYPE)val;
break;
case "status":
job.status = (TM_STATUS)val;
break;
case "workflow_ID":
job.workflow_ID = (int)val;
break;
case "run_params":
job.run_params = val as string;
break;
case "corn_express":
job.corn_express = val as string;
break;
case "INT_RES_1":
job.INT_RES_1 = (int)val;
break;
case "INT_RES_2":
job.INT_RES_2 = (int)val;
break;
case "INT_RES_3":
job.INT_RES_3 = (int)val;
break;
case "STR_RES_1":
job.STR_RES_1 = val as string;
break;
case "STR_RES_2":
job.STR_RES_2 = val as string;
break;
case "STR_RES_3":
job.STR_RES_3 = val as string;
break;
default: //其他字段
break;
}
}
if (db.SaveChanges() != 1)
return null;
return job;
}
}
catch(Exception e)
{
return null;
}
}
/// <summary>
/// 删除一个定时任务
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public Timer_Jobs DeleteJob(int id)
{
try
{
using (var db = base.NewDB())
{
var job = db.timer_jobs.FirstOrDefault(a => a.JOB_ID == id);
if (job != null)
db.timer_jobs.Remove(job);
if (db.SaveChanges() != 1)
return null;
return job;
}
}
catch(Exception e)
{
return null;
}
}
public List<Timer_Jobs> GetDSRemind()
{
try
{
using (var db = base.NewDB())
{
var job = db.timer_jobs.Where(a => a.Job_Type == TIMER_JOB_TYPE.TIME_OUT&&a.status==0).ToList();
return job;
}
}
catch (Exception e)
{
return null;
}
}
public Timer_Jobs GetDSnexttime(string jobname, int wfe_id)
{
try
{
using (var db = base.NewDB())
{
var job = db.timer_jobs.Where(a => a.Job_Type == TIMER_JOB_TYPE.TIME_OUT && a.job_name == jobname && a.workflow_ID == wfe_id);
if (job.Count() > 0)
return job.First();
else
return null;
}
}
catch (Exception e)
{
return null;
}
}
public List<Timer_Jobs> GetDSbyWorkflow(int wf_id)
{
try
{
using (var db = base.NewDB())
{
var job = db.timer_jobs.Where(a => a.Job_Type == TIMER_JOB_TYPE.CREATE_WORKFLOW && a.workflow_ID == wf_id && a.status == TM_STATUS.TM_STATUS_ACTIVE).ToList();
return job;
}
}
catch (Exception e)
{
return null;
}
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using iTextSharp.text.pdf;
using iTextSharp.text;
using EquipBLL.AdminManagment.MenuConfig;
namespace WebApp.Controllers
{
public class A15dot1Controller : CommonController
{
private JxpgManagment Jx = new JxpgManagment();
public class submitmodel
{
public string timesNonPlanStop;//非计划停工次数
public string scoreDeductFaultIntensity;//四类以上故障强度扣分
public string rateBigUnitFault;//大机组故障率K
public string rateFaultMaintenance;//故障维修率F
public string MTBF;//一般机泵设备平均无故障间隔期MTBF
public string rateEquipUse; // 设备投用率R
public string avgLifeSpanSeal;//密封平均寿命S
public string avgLifeSpanAxle;//轴承平均寿命B
public string percentEquipAvailability;//设备完好率W
public string percentPassOnetimeRepair;//检修一次合格率
public int kkxgcs;
public int jwxry;
}
public ActionResult Index()
{
return View(getRecord());
}
public ActionResult Submit()
{
submitmodel sm = new submitmodel();
ViewBag.curtime = DateTime.Now;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
sm.kkxgcs = 1;
if (pv.Role_Names.Contains("检维修人员"))
sm.jwxry = 1;
return View(sm);
}
public ActionResult PqSubmit(string id)
{
return View(getRecord_detail(id));
}
public ActionResult JdcSubmit(string id)
{
return View(getRecord_detail(id));
}
public ActionResult History(string id)
{
return View(getRecord_detail(id));
}
public class Index_ModelforA15
{
public List<A15dot1Tab> Am;
public List<A15dot1Tab> Hm;
public int isSubmit;
public int kkxgcs;
public int am;
public int hm;
}
public Index_ModelforA15 getRecord()
{
Index_ModelforA15 RecordforA15 = new Index_ModelforA15();
//ViewBag.curtime = DateTime.Now.ToString();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
RecordforA15.Am=new List<A15dot1Tab>();
if (pv.Role_Names.Contains("可靠性工程师") || pv.Role_Names.Contains("检维修人员"))
RecordforA15.isSubmit = 1;
else
RecordforA15.isSubmit = 0;
if (pv.Role_Names.Contains("可靠性工程师"))
RecordforA15.kkxgcs = 1;
else
RecordforA15.kkxgcs = 0;
List<string> cjname = new List<string>();
List<Equip_Archi> EA = pm.Get_Person_Cj(UserId);
foreach (var ea in EA)
{
cjname.Add(ea.EA_Name);
}
List<A15dot1Tab> miss = Jx.GetJxItem(pv.Role_Names,pv.Department_Name,pv.Person_Name);
foreach (var item in miss)
{
A15dot1Tab a = new A15dot1Tab();
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.rateUrgentRepairWorkHour = item.rateUrgentRepairWorkHour;
a.hourWorkOrderFinish = item.hourWorkOrderFinish;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.avgEfficiencyPump = item.avgEfficiencyPump;
a.avgEfficiencyUnit = item.avgEfficiencyUnit;
a.hiddenDangerInvestigation = item.hiddenDangerInvestigation;
a.rateLoad = item.rateLoad;
a.gyChange = item.gyChange;
a.equipChange = item.equipChange;
a.otherDescription = item.otherDescription;
a.evaluateEquipRunStaeDesc = item.evaluateEquipRunStaeDesc;
a.evaluateEquipRunStaeImgPath = item.evaluateEquipRunStaeImgPath;
a.reliabilityConclusion = item.reliabilityConclusion;
a.jdcAdviseImproveMeasures = item.jdcAdviseImproveMeasures;
a.submitDepartment = item.submitDepartment;
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.jdcOperator = item.jdcOperator;
a.jdcOperateTime = item.jdcOperateTime;
a.reportType = item.reportType;
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.state = item.state;
a.Id = item.Id;
RecordforA15.Am.Add(a);
}
RecordforA15.Hm = new List<A15dot1Tab>();
List<A15dot1Tab> His = Jx.GetHisJxItem(pv.Role_Names, pv.Department_Name, pv.Person_Name);
foreach (var item in His)
{
A15dot1Tab a = new A15dot1Tab();
a.Id = item.Id;
a.state = item.state;
a.jdcOperateTime = item.jdcOperateTime;
a.jdcOperator = item.jdcOperator;
a.temp1 = Convert.ToString(His.IndexOf(item) + 1);
RecordforA15.Hm.Add(a);
}
return RecordforA15;
}
public Index_ModelforA15 getRecord_detail(string id)
{
Index_ModelforA15 RecordforA15 = new Index_ModelforA15();
RecordforA15.Am = new List<A15dot1Tab>();
RecordforA15.Hm = new List<A15dot1Tab>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int IntId = Convert.ToInt32(id);
List<A15dot1Tab> miss = Jx.GetJxItem_detail(IntId);
foreach (var item in miss)
{
A15dot1Tab a = new A15dot1Tab();
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.rateUrgentRepairWorkHour = item.rateUrgentRepairWorkHour;
a.hourWorkOrderFinish = item.hourWorkOrderFinish;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.avgEfficiencyPump = item.avgEfficiencyPump;
a.avgEfficiencyUnit = item.avgEfficiencyUnit;
a.hiddenDangerInvestigation = item.hiddenDangerInvestigation;
a.rateLoad = item.rateLoad;
a.gyChange = item.gyChange;
a.equipChange = item.equipChange;
a.otherDescription = item.otherDescription;
a.evaluateEquipRunStaeDesc = item.evaluateEquipRunStaeDesc;
a.evaluateEquipRunStaeImgPath = item.evaluateEquipRunStaeImgPath;
a.reliabilityConclusion = item.reliabilityConclusion;
a.jdcAdviseImproveMeasures = item.jdcAdviseImproveMeasures;
a.submitDepartment = item.submitDepartment;
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.jdcOperator = item.jdcOperator;
a.jdcOperateTime = item.jdcOperateTime;
a.reportType = item.reportType;
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.state = item.state;
a.Id = item.Id;
//增加变量--参与统计台数
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA15.Am.Add(a);
}
string name = RecordforA15.Am[0].submitUser;
PersonManagment pm = new PersonManagment();
int UserId = pm.Get_Person(name).Person_Id;
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
RecordforA15.am = 1;
else
RecordforA15.am = 0;
List<A15dot1Tab> His = Jx.GetHisJxItem_detail(IntId);
foreach (var item in His)
{
A15dot1Tab a = new A15dot1Tab();
a.timesNonPlanStop = item.timesNonPlanStop;
a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
a.rateBigUnitFault = item.rateBigUnitFault;
a.rateFaultMaintenance = item.rateFaultMaintenance;
a.MTBF = item.MTBF;
a.rateEquipUse = item.rateEquipUse;
a.rateUrgentRepairWorkHour = item.rateUrgentRepairWorkHour;
a.hourWorkOrderFinish = item.hourWorkOrderFinish;
a.avgLifeSpanSeal = item.avgLifeSpanSeal;
a.avgLifeSpanAxle = item.avgLifeSpanAxle;
a.percentEquipAvailability = item.percentEquipAvailability;
a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
a.avgEfficiencyPump = item.avgEfficiencyPump;
a.avgEfficiencyUnit = item.avgEfficiencyUnit;
a.hiddenDangerInvestigation = item.hiddenDangerInvestigation;
a.rateLoad = item.rateLoad;
a.gyChange = item.gyChange;
a.equipChange = item.equipChange;
a.otherDescription = item.otherDescription;
a.evaluateEquipRunStaeDesc = item.evaluateEquipRunStaeDesc;
a.evaluateEquipRunStaeImgPath = item.evaluateEquipRunStaeImgPath;
a.reliabilityConclusion = item.reliabilityConclusion;
a.jdcAdviseImproveMeasures = item.jdcAdviseImproveMeasures;
a.submitDepartment = item.submitDepartment;
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.jdcOperator = item.jdcOperator;
a.jdcOperateTime = item.jdcOperateTime;
a.reportType = item.reportType;
a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
a.submitUser = item.submitUser;
a.submitTime = item.submitTime;
a.state = item.state;
a.Id = item.Id;
//增加变量--参与统计台数
a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
a.Count_MTBF = item.Count_MTBF;
a.Count_rateEquipUse = item.Count_rateEquipUse;
a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
RecordforA15.Hm.Add(a);
}
name = RecordforA15.Hm[0].submitUser;
UserId = pm.Get_Person(name).Person_Id;
pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
RecordforA15.hm = 1;
else
RecordforA15.hm = 0;
return RecordforA15;
}
public JsonResult Submit_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1Tab new_15dot1 = new A15dot1Tab();
new_15dot1.timesNonPlanStop = Convert.ToInt32(item["timesNonPlanStop"].ToString());
new_15dot1.scoreDeductFaultIntensity = Convert.ToInt32(item["scoreDeductFaultIntensity"].ToString());
new_15dot1.rateBigUnitFault = Convert.ToDouble(item["scoreDeductFaultIntensity"].ToString());
new_15dot1.rateFaultMaintenance = Convert.ToDouble(item["rateFaultMaintenance"].ToString());
new_15dot1.MTBF = Convert.ToInt32(item["MTBF"].ToString());
new_15dot1.rateEquipUse = Convert.ToDouble(item["rateEquipUse"].ToString());
if (item["rateUrgentRepairWorkHour"].ToString() != "")
{
new_15dot1.rateUrgentRepairWorkHour = Convert.ToDouble(item["rateUrgentRepairWorkHour"].ToString());
}
if (item["hourWorkOrderFinish"].ToString() != "")
{
new_15dot1.hourWorkOrderFinish = Convert.ToDouble(item["hourWorkOrderFinish"].ToString());
}
new_15dot1.avgLifeSpanSeal = Convert.ToInt32(item["avgLifeSpanSeal"].ToString());
new_15dot1.avgLifeSpanAxle = Convert.ToInt32(item["avgLifeSpanAxle"].ToString());
new_15dot1.percentEquipAvailability = Convert.ToDouble(item["percentEquipAvailability"].ToString());
new_15dot1.percentPassOnetimeRepair = Convert.ToDouble(item["percentPassOnetimeRepair"].ToString());
new_15dot1.Count_timesNonPlanStop = Convert.ToInt32(item["Count_timesNonPlanStop"].ToString());
new_15dot1.Count_scoreDeductFaultIntensity = Convert.ToInt32(item["Count_scoreDeductFaultIntensity"].ToString());
new_15dot1.Count_rateBigUnitFault = Convert.ToInt32(item["Count_rateBigUnitFault"].ToString());
new_15dot1.Count_rateFaultMaintenance = Convert.ToInt32(item["Count_rateFaultMaintenance"].ToString());
new_15dot1.Count_MTBF = Convert.ToInt32(item["Count_MTBF"].ToString());
new_15dot1.Count_rateEquipUse = Convert.ToInt32(item["Count_rateEquipUse"].ToString());
new_15dot1.Count_avgLifeSpanSeal = Convert.ToInt32(item["Count_avgLifeSpanSeal"].ToString());
new_15dot1.Count_avgLifeSpanAxle = Convert.ToInt32(item["Count_avgLifeSpanAxle"].ToString());
new_15dot1.Count_percentEquipAvailability = Convert.ToInt32(item["Count_percentEquipAvailability"].ToString());
new_15dot1.Count_percentPassOnetimeRepair = Convert.ToInt32(item["Count_percentPassOnetimeRepair"].ToString());
if (item["avgEfficiencyPump"].ToString() != "")
{
new_15dot1.avgEfficiencyPump = Convert.ToDouble(item["avgEfficiencyPump"].ToString());
}
if (item["avgEfficiencyUnit"].ToString() != "")
{
new_15dot1.avgEfficiencyUnit = Convert.ToDouble(item["avgEfficiencyUnit"].ToString());
}
new_15dot1.hiddenDangerInvestigation = item["hiddenDangerInvestigation"].ToString();
new_15dot1.rateLoad = item["rateLoad"].ToString();
new_15dot1.gyChange = item["gyChange"].ToString();
new_15dot1.equipChange = item["equipChange"].ToString();
new_15dot1.otherDescription = item["otherDescription"].ToString();
new_15dot1.evaluateEquipRunStaeDesc = item["evaluateEquipRunStaeDesc"].ToString();
new_15dot1.evaluateEquipRunStaeImgPath = item["evaluateEquipRunStaeImgPath"].ToString();
new_15dot1.reliabilityConclusion = item["reliabilityConclusion"].ToString();
new_15dot1.jdcAdviseImproveMeasures = "";
new_15dot1.submitDepartment = item["submitDepartment"].ToString();
new_15dot1.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1.submitTime = DateTime.Now;
new_15dot1.jdcOperator = "";
//new_15dot1.state = Convert.ToInt32(item["state"].ToString());
new_15dot1.reportType = item["reportType"].ToString();
bool res = Jx.AddJxItem(new_15dot1);
return Json(new { result = res });
}
public JsonResult DSSubmit_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1Tab new_15dot1 = new A15dot1Tab();
new_15dot1.timesNonPlanStop = Convert.ToInt32(item["timesNonPlanStop"].ToString());
new_15dot1.scoreDeductFaultIntensity = Convert.ToInt32(item["scoreDeductFaultIntensity"].ToString());
new_15dot1.rateBigUnitFault = Convert.ToDouble(item["scoreDeductFaultIntensity"].ToString());
new_15dot1.rateFaultMaintenance = Convert.ToDouble(item["rateFaultMaintenance"].ToString());
new_15dot1.MTBF = Convert.ToInt32(item["MTBF"].ToString());
new_15dot1.rateEquipUse = Convert.ToDouble(item["rateEquipUse"].ToString());
if (item["rateUrgentRepairWorkHour"].ToString() != "")
{
new_15dot1.rateUrgentRepairWorkHour = Convert.ToDouble(item["rateUrgentRepairWorkHour"].ToString());
}
if (item["hourWorkOrderFinish"].ToString() != "")
{
new_15dot1.hourWorkOrderFinish = Convert.ToDouble(item["hourWorkOrderFinish"].ToString());
}
new_15dot1.avgLifeSpanSeal = Convert.ToInt32(item["avgLifeSpanSeal"].ToString());
new_15dot1.avgLifeSpanAxle = Convert.ToInt32(item["avgLifeSpanAxle"].ToString());
new_15dot1.percentEquipAvailability = Convert.ToDouble(item["percentEquipAvailability"].ToString());
new_15dot1.percentPassOnetimeRepair = Convert.ToDouble(item["percentPassOnetimeRepair"].ToString());
new_15dot1.Count_timesNonPlanStop = Convert.ToInt32(item["Count_timesNonPlanStop"].ToString());
new_15dot1.Count_scoreDeductFaultIntensity = Convert.ToInt32(item["Count_scoreDeductFaultIntensity"].ToString());
new_15dot1.Count_rateBigUnitFault = Convert.ToInt32(item["Count_rateBigUnitFault"].ToString());
new_15dot1.Count_rateFaultMaintenance = Convert.ToInt32(item["Count_rateFaultMaintenance"].ToString());
new_15dot1.Count_MTBF = Convert.ToInt32(item["Count_MTBF"].ToString());
new_15dot1.Count_rateEquipUse = Convert.ToInt32(item["Count_rateEquipUse"].ToString());
new_15dot1.Count_avgLifeSpanSeal = Convert.ToInt32(item["Count_avgLifeSpanSeal"].ToString());
new_15dot1.Count_avgLifeSpanAxle = Convert.ToInt32(item["Count_avgLifeSpanAxle"].ToString());
new_15dot1.Count_percentEquipAvailability = Convert.ToInt32(item["Count_percentEquipAvailability"].ToString());
new_15dot1.Count_percentPassOnetimeRepair = Convert.ToInt32(item["Count_percentPassOnetimeRepair"].ToString());
if (item["avgEfficiencyPump"].ToString() != "")
{
new_15dot1.avgEfficiencyPump = Convert.ToDouble(item["avgEfficiencyPump"].ToString());
}
if (item["avgEfficiencyUnit"].ToString() != "")
{
new_15dot1.avgEfficiencyUnit = Convert.ToDouble(item["avgEfficiencyUnit"].ToString());
}
new_15dot1.hiddenDangerInvestigation = item["hiddenDangerInvestigation"].ToString();
new_15dot1.rateLoad = item["rateLoad"].ToString();
new_15dot1.gyChange = item["gyChange"].ToString();
new_15dot1.equipChange = item["equipChange"].ToString();
new_15dot1.otherDescription = item["otherDescription"].ToString();
new_15dot1.evaluateEquipRunStaeDesc = item["evaluateEquipRunStaeDesc"].ToString();
new_15dot1.evaluateEquipRunStaeImgPath = item["evaluateEquipRunStaeImgPath"].ToString();
new_15dot1.reliabilityConclusion = item["reliabilityConclusion"].ToString();
new_15dot1.jdcAdviseImproveMeasures = "";
new_15dot1.submitDepartment = item["submitDepartment"].ToString();
new_15dot1.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1.submitTime = DateTime.Now;
new_15dot1.jdcOperator = "";
//new_15dot1.state = Convert.ToInt32(item["state"].ToString());
new_15dot1.reportType = item["reportType"].ToString();
bool res = Jx.AddJxItem(new_15dot1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return Json(new { result = res });
}
public JsonResult Modify_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1Tab new_15dot1 = new A15dot1Tab();
new_15dot1.Id = Convert.ToInt32(item["A15dot1_id"].ToString());
new_15dot1.timesNonPlanStop = Convert.ToInt32(item["timesNonPlanStop"].ToString());
new_15dot1.scoreDeductFaultIntensity = Convert.ToInt32(item["scoreDeductFaultIntensity"].ToString());
new_15dot1.rateBigUnitFault = Convert.ToDouble(item["scoreDeductFaultIntensity"].ToString());
new_15dot1.rateFaultMaintenance = Convert.ToDouble(item["rateFaultMaintenance"].ToString());
new_15dot1.MTBF = Convert.ToInt32(item["MTBF"].ToString());
new_15dot1.rateEquipUse = Convert.ToDouble(item["rateEquipUse"].ToString());
if (item["rateUrgentRepairWorkHour"].ToString() != "")
{
new_15dot1.rateUrgentRepairWorkHour = Convert.ToDouble(item["rateUrgentRepairWorkHour"].ToString());
}
else
new_15dot1.rateUrgentRepairWorkHour = 0.0;
if (item["hourWorkOrderFinish"].ToString() != "")
{
new_15dot1.hourWorkOrderFinish = Convert.ToDouble(item["hourWorkOrderFinish"].ToString());
}
new_15dot1.hourWorkOrderFinish = 0.0;
new_15dot1.avgLifeSpanSeal = Convert.ToInt32(item["avgLifeSpanSeal"].ToString());
new_15dot1.avgLifeSpanAxle = Convert.ToInt32(item["avgLifeSpanAxle"].ToString());
new_15dot1.percentEquipAvailability = Convert.ToDouble(item["percentEquipAvailability"].ToString());
new_15dot1.percentPassOnetimeRepair = Convert.ToDouble(item["percentPassOnetimeRepair"].ToString());
if (item["avgEfficiencyPump"].ToString() != "")
{
new_15dot1.avgEfficiencyPump = Convert.ToDouble(item["avgEfficiencyPump"].ToString());
}
new_15dot1.avgEfficiencyPump = 0.0;
if (item["avgEfficiencyUnit"].ToString() != "")
{
new_15dot1.avgEfficiencyUnit = Convert.ToDouble(item["avgEfficiencyUnit"].ToString());
}
new_15dot1.avgEfficiencyUnit = 0.0;
new_15dot1.Count_timesNonPlanStop = Convert.ToInt32(item["Count_timesNonPlanStop"].ToString());
new_15dot1.Count_scoreDeductFaultIntensity = Convert.ToInt32(item["Count_scoreDeductFaultIntensity"].ToString());
new_15dot1.Count_rateBigUnitFault = Convert.ToInt32(item["Count_rateBigUnitFault"].ToString());
new_15dot1.Count_rateFaultMaintenance = Convert.ToInt32(item["Count_rateFaultMaintenance"].ToString());
new_15dot1.Count_MTBF = Convert.ToInt32(item["Count_MTBF"].ToString());
new_15dot1.Count_rateEquipUse = Convert.ToInt32(item["Count_rateEquipUse"].ToString());
new_15dot1.Count_avgLifeSpanSeal = Convert.ToInt32(item["Count_avgLifeSpanSeal"].ToString());
new_15dot1.Count_avgLifeSpanAxle = Convert.ToInt32(item["Count_avgLifeSpanAxle"].ToString());
new_15dot1.Count_percentEquipAvailability = Convert.ToInt32(item["Count_percentEquipAvailability"].ToString());
new_15dot1.Count_percentPassOnetimeRepair = Convert.ToInt32(item["Count_percentPassOnetimeRepair"].ToString());
new_15dot1.hiddenDangerInvestigation = item["hiddenDangerInvestigation"].ToString();
new_15dot1.rateLoad = item["rateLoad"].ToString();
new_15dot1.gyChange = item["gyChange"].ToString();
new_15dot1.equipChange = item["equipChange"].ToString();
new_15dot1.otherDescription = item["otherDescription"].ToString();
new_15dot1.evaluateEquipRunStaeDesc = item["evaluateEquipRunStaeDesc"].ToString();
new_15dot1.evaluateEquipRunStaeImgPath = item["evaluateEquipRunStaeImgPath"].ToString();
new_15dot1.reliabilityConclusion = item["reliabilityConclusion"].ToString();
new_15dot1.jdcAdviseImproveMeasures = "";
new_15dot1.submitDepartment = item["submitDepartment"].ToString();
new_15dot1.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1.submitTime = DateTime.Now;
new_15dot1.state = Convert.ToInt32(item["state"].ToString());
new_15dot1.reportType = item["reportType"].ToString();
bool res = Jx.ModifyJxItem(new_15dot1);
return Json(new { result = res });
}
public JsonResult JdcModify_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1Tab new_15dot1 = new A15dot1Tab();
new_15dot1.Id = Convert.ToInt32(item["A15dot1_id"].ToString());
new_15dot1.jdcAdviseImproveMeasures = item["jdcAdviseImproveMeasures"].ToString();
new_15dot1.jdcOperator = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1.jdcOperateTime = DateTime.Now;
new_15dot1.state = Convert.ToInt32(item["state"].ToString());
bool res = Jx.JdcModifyJxItem(new_15dot1);
return Json(new { result = res });
}
public string qst(string grahpic_name,string pianqu)
{
List<object> res = Jx.qst(grahpic_name, pianqu);
string str = JsonConvert.SerializeObject(res);
return (str);
}
public string out_pdf(string json1)
{
// BaseFont bfchinese = BaseFont.CreateFont(@"c:\windows\fonts\simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//使用c盘系统中的字体,中文
string fontpath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\Plugins\\pdf_font\\SIMKAI.TTF";//把C盘中的字体复制到项目中使用,中文
BaseFont bfchinese = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font ChFont = new Font(bfchinese, 10, Font.NORMAL, new BaseColor(0, 0, 0));//正文,设置字体大小,颜色
Font ChFont_title = new Font(bfchinese, 20, Font.NORMAL, new BaseColor(0, 0, 0));//主标题
Font ChFont_title_1 = new Font(bfchinese, 15, Font.NORMAL, new BaseColor(0, 0, 0));//小标题
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string col_1 = item["col1"].ToString();
string[] s1 = col_1.Split(new char[] { ',' });
string col_2 = item["col2"].ToString();
string[] s2 = col_2.Split(new char[] { ',' });
string col_3 = item["col3"].ToString();
string[] s3 = col_3.Split(new char[] { ',' });
string col_4 = item["col4"].ToString();
string[] s4 = col_4.Split(new char[] { ',' });
string col_5 = item["col5"].ToString();
string[] s5 = col_5.Split(new char[] { ',' });
Document document = new Document(PageSize.A4); //初始化一个目标文档类
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/Upload//武汉石化绩效评估表.pdf"), FileMode.Create));
document.Open(); //打开目标文档类
Font pdfFont = new Font(Font.FontFamily.ZAPFDINGBATS, 7);//根据字体类型和字体大小属性创建PDF文档字体
PdfPTable pdfTable = new PdfPTable(5); //根据数据表内容创建一个PDF格式的表,括号为表格的列数
//表的标题
PdfPCell cell = new PdfPCell(new Phrase("武汉石化绩效评估表", ChFont_title));
cell.Colspan = 5;
cell.Border = 0;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell);
//报告信息
string submitDepartment = item["submitDepartment"].ToString();
string reportType = item["reportType"].ToString();
int A15dot1_id =Convert.ToInt16(item["A15dot1_id"].ToString());
PdfPCell cell_type = new PdfPCell(new Phrase("报告类型:" + reportType, ChFont));
cell_type.Colspan = 3;
cell_type.Border = 0;
cell_type.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_type);
PdfPCell cell_time = new PdfPCell(new Phrase("评估时间:" , ChFont));
cell_time.Colspan = 1;
cell_time.Border = 0;
cell_time.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_time);
List<A15dot1Tab> ss = new List<A15dot1Tab>();
ss = Jx.GetJxItem_detail(A15dot1_id);
DateTime time=Convert.ToDateTime(ss[0].submitTime);
string subtime = "";
if (reportType == "月报")
{
subtime = time.ToString("yyyy/MM");
}
else
{
subtime = time.ToString("yyyy") + "年";
}
PdfPCell cell_time_1 = new PdfPCell(new Phrase(subtime, ChFont));
cell_time_1.Colspan = 1;
cell_time_1.Border = 0;
cell_time_1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_time_1);
PdfPCell cell_submit = new PdfPCell(new Phrase("提交单位:" + submitDepartment, ChFont));
cell_submit.Colspan = 3;
cell_submit.Border = 0;
cell_submit.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_submit);
PdfPCell cell_Person = new PdfPCell(new Phrase("提交人:" , ChFont));
cell_Person.Colspan = 1;
cell_Person.Border = 0;
cell_Person.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_Person);
PdfPCell cell_person_1 = new PdfPCell(new Phrase(((Session["User"] as EquipModel.Entities.Person_Info).Person_Name), ChFont));
cell_person_1.Colspan = 1;
cell_person_1.Border = 0;
cell_person_1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_person_1);
//PdfPTable nested_7_2 = new PdfPTable(1);
//nested_7_2.AddCell(new Phrase("报告类型:" + reportType, ChFont));
//PdfPCell nesthousing_7_2 = new PdfPCell(nested_7_2);
//nesthousing_7_2.HorizontalAlignment = 0;
//nesthousing_7_2.Border = 0;
//nesthousing_7_2.Padding = 0f;
//pdfTable.AddCell(nesthousing_7_2);
//PdfPCell detail_7_2 = new PdfPCell(new Phrase("评估时间:" + reportType, ChFont));
//detail_7_2.Border = 0;
//detail_7_2.HorizontalAlignment = 2;
//detail_7_2.Colspan = 4;
//pdfTable.AddCell(detail_7_2);
//PdfPTable nested_7_1 = new PdfPTable(1);
//nested_7_1.AddCell(new Phrase("提交单位:" + submitDepartment, ChFont));
//PdfPCell nesthousing_7_1 = new PdfPCell(nested_7_1);
//nesthousing_7_1.Padding = 0f;
//pdfTable.AddCell(nesthousing_7_1);
//PdfPCell detail_7_1 = new PdfPCell(new Phrase("提交人:" + submitDepartment, ChFont));
//detail_7_1.Colspan = 4;
//pdfTable.AddCell(detail_7_1);
//一. KPI指标
PdfPCell cell_1 = new PdfPCell(new Phrase("一.KPI指标", ChFont_title_1));
cell_1.Colspan = 5;
cell_1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_1);
pdfTable.AddCell(new Phrase("指标类型", ChFont));
pdfTable.AddCell(new Phrase("KPI指标", ChFont));
pdfTable.AddCell(new Phrase("指标说明", ChFont));
pdfTable.AddCell(new Phrase("炼油目标值", ChFont));
pdfTable.AddCell(new Phrase("实际值", ChFont));
for (int i = 0; i < s1.Length; i++)
{
pdfTable.AddCell(new Phrase(s1[i], ChFont));
pdfTable.AddCell(new Phrase(s2[i], ChFont));
pdfTable.AddCell(new Phrase(s3[i], ChFont));
pdfTable.AddCell(new Phrase(s4[i], ChFont));
pdfTable.AddCell(new Phrase(s5[i], ChFont));
}
//二. 隐患排查情况
PdfPCell cell_2 = new PdfPCell(new Phrase("二.隐患排查情况", ChFont_title_1));
cell_2.Colspan = 5;
cell_2.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_2);
string hiddenDangerInvestigation = item["hiddenDangerInvestigation"].ToString();
PdfPTable nested_2 = new PdfPTable(1);
nested_2.AddCell(new Phrase("隐患排查情况", ChFont));
PdfPCell nesthousing_2 = new PdfPCell(nested_2);
nesthousing_2.Padding = 0f;
pdfTable.AddCell(nesthousing_2);
PdfPCell detail_2 = new PdfPCell(new Phrase(hiddenDangerInvestigation, ChFont));
detail_2.Colspan = 4;
pdfTable.AddCell(detail_2);
//三. 装置生产运行概况
PdfPCell cell_3 = new PdfPCell(new Phrase("三.装置生产运行概况", ChFont_title_1));
cell_3.Colspan = 5;
cell_3.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_3);
string rateLoad = item["rateLoad"].ToString();
string gyChange = item["gyChange"].ToString();
string equipChange = item["equipChange"].ToString();
string otherDescription = item["otherDescription"].ToString();
PdfPTable nested_3_1 = new PdfPTable(1);
nested_3_1.AddCell(new Phrase("负荷率", ChFont));
PdfPCell nesthousing_3_1 = new PdfPCell(nested_3_1);
nesthousing_3_1.Padding = 0f;
pdfTable.AddCell(nesthousing_3_1);
PdfPCell detail_3_1 = new PdfPCell(new Phrase(rateLoad, ChFont));
detail_3_1.Colspan = 4;
pdfTable.AddCell(detail_3_1);
PdfPTable nested_3_2 = new PdfPTable(1);
nested_3_2.AddCell(new Phrase("工艺变更", ChFont));
PdfPCell nesthousing_3_2 = new PdfPCell(nested_3_2);
nesthousing_3_2.Padding = 0f;
pdfTable.AddCell(nesthousing_3_2);
PdfPCell detail_3_2 = new PdfPCell(new Phrase(gyChange, ChFont));
detail_3_2.Colspan = 4;
pdfTable.AddCell(detail_3_2);
PdfPTable nested_3_3 = new PdfPTable(1);
nested_3_3.AddCell(new Phrase("设备变更", ChFont));
PdfPCell nesthousing_3_3 = new PdfPCell(nested_3_3);
nesthousing_3_3.Padding = 0f;
pdfTable.AddCell(nesthousing_3_3);
PdfPCell detail_3_3 = new PdfPCell(new Phrase(equipChange, ChFont));
detail_3_3.Colspan = 4;
pdfTable.AddCell(detail_3_3);
PdfPTable nested_3_4 = new PdfPTable(1);
nested_3_4.AddCell(new Phrase("其他说明", ChFont));
PdfPCell nesthousing_3_4 = new PdfPCell(nested_3_4);
nesthousing_3_4.Padding = 0f;
pdfTable.AddCell(nesthousing_3_4);
PdfPCell detail_3_4 = new PdfPCell(new Phrase(otherDescription, ChFont));
detail_3_4.Colspan = 4;
pdfTable.AddCell(detail_3_4);
//四 装置设备运行情况基本评估
PdfPCell cell_4 = new PdfPCell(new Phrase("四.装置设备运行情况基本评估", ChFont_title_1));
cell_4.Colspan = 5;
cell_4.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_4);
string evaluateEquipRunStaeDesc = item["evaluateEquipRunStaeDesc"].ToString();
PdfPTable nested_4 = new PdfPTable(1);
nested_4.AddCell(new Phrase("装置设备运行情况基本评估", ChFont));
PdfPCell nesthousing_4 = new PdfPCell(nested_4);
nesthousing_4.Padding = 0f;
pdfTable.AddCell(nesthousing_4);
PdfPCell detail_4 = new PdfPCell(new Phrase(evaluateEquipRunStaeDesc, ChFont));
detail_4.Colspan = 4;
pdfTable.AddCell(detail_4);
//五 可靠性结论
PdfPCell cell_5 = new PdfPCell(new Phrase("五.可靠性结论", ChFont_title_1));
cell_5.Colspan = 5;
cell_5.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_5);
string reliabilityConclusion = item["reliabilityConclusion"].ToString();
PdfPTable nested_5= new PdfPTable(1);
nested_5.AddCell(new Phrase("可靠性结论", ChFont));
PdfPCell nesthousing_5 = new PdfPCell(nested_5);
nesthousing_5.Padding = 0f;
pdfTable.AddCell(nesthousing_5);
PdfPCell detail_5 = new PdfPCell(new Phrase(reliabilityConclusion, ChFont));
detail_5.Colspan = 4;
pdfTable.AddCell(detail_5);
//六 机动处建议及改进措施
PdfPCell cell_6 = new PdfPCell(new Phrase("六.机动处建议及改进措施", ChFont_title_1));
cell_6.Colspan = 5;
cell_6.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
pdfTable.AddCell(cell_6);
string jdcAdviseImproveMeasures = item["jdcAdviseImproveMeasures"].ToString();
PdfPTable nested_6 = new PdfPTable(1);
nested_6.AddCell(new Phrase("机动处建议及改进措施", ChFont));
PdfPCell nesthousing_6 = new PdfPCell(nested_6);
nesthousing_6.Padding = 0f;
pdfTable.AddCell(nesthousing_6);
PdfPCell detail_6 = new PdfPCell(new Phrase(jdcAdviseImproveMeasures, ChFont));
detail_6.Colspan = 4;
pdfTable.AddCell(detail_6);
//七, 图片
string jpg_name = item["jpgname"].ToString();
if (jpg_name.Contains(".jpg") || jpg_name.Contains(".JPG") || jpg_name.Contains(".png") || jpg_name.Contains(".PNG"))
{
PdfPCell cell_7 = new PdfPCell(new Phrase("附:装置设备运行情况基本评估附图", ChFont_title_1));
cell_7.Colspan = 5;
cell_7.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
cell_7.Border = 0;
pdfTable.AddCell(cell_7);
}
document.Add(pdfTable);
document.AddTitle("武汉石化绩效评估表");
if(jpg_name.Contains(".jpg") ||jpg_name.Contains(".JPG") || jpg_name.Contains(".png") || jpg_name.Contains(".PNG")){
//显示图片的代码开始部分
string imagepath = Server.MapPath("~/Upload");
// Image jpg = Image.GetInstance(imagepath + "/课表.jpg");
Image jpg = Image.GetInstance(imagepath + "/" + jpg_name);
jpg.Alignment = Image.ALIGN_MIDDLE;//图片居中显示
// jpg.ScaleToFit(150,300);
jpg.ScaleToFit(400, 400);//图片容器大小
document.Add(jpg);
//显示图片的代码结束部分
}
document.Close();
writer.Close();
return Path.Combine("/Upload", "武汉石化绩效评估表.pdf");
}
catch (Exception)
{
throw;
}
//return "打印失败";
// return ("213");
}
public ActionResult DSZzSubmit(string wfe_id)
{
submitmodel sm = new submitmodel();
ViewBag.curtime = DateTime.Now;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
sm.kkxgcs = 1;
if (pv.Role_Names.Contains("检维修人员"))
sm.jwxry = 1;
ERPInfoManagement erp = new ERPInfoManagement();
EquipArchiManagment em = new EquipArchiManagment();
UI_MISSION mi = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
Dictionary<string, object> mi_params = mi.Miss_Params;
ViewBag.Pqname = mi.Miss_Params["Pqname"].ToString();
string ea_code = em.getEa_codebyname(mi.Miss_Params["Pqname"].ToString());
ViewBag.timesNonPlanStop=erp.getNoticesYx_1(mi.Miss_Params["Pqname"].ToString());
ViewBag.scoreDeductFaultIntensity = (erp.getNoticesYx_1(mi.Miss_Params["Pqname"].ToString()) * 50) + (erp.getNoticeYx_2(mi.Miss_Params["Pqname"].ToString()) * 30) + (erp.getNoticeYx_3(mi.Miss_Params["Pqname"].ToString()) * 20) + (erp.getNoticeYx_4(mi.Miss_Params["Pqname"].ToString()) * 5);
ViewBag.rateFaultMaintenance = erp.getFaultRation(mi.Miss_Params["Pqname"].ToString());
ViewBag.MTBF = erp.getNonFaultInterVal(mi.Miss_Params["Pqname"].ToString());
ViewBag.rateEquipUse = erp.DeliverRatio(mi.Miss_Params["Pqname"].ToString());
ViewBag.rateBigUnitFault = erp.bigEquipsRatio(mi.Miss_Params["Pqname"].ToString());
ViewBag.wfe_id = wfe_id;
TablesManagment tm = new TablesManagment();
EquipManagment Em = new EquipManagment();
List<EANummodel> E = Em.getequipnum_byarchi();
List<Equip_Archi> AllCj_List = Em.GetAllCj();
List<WebApp.Controllers.A5dot1Controller.NameandNum> cj = new List<WebApp.Controllers.A5dot1Controller.NameandNum>();
List<WebApp.Controllers.A5dot1Controller.NameandNum> pq = new List<WebApp.Controllers.A5dot1Controller.NameandNum>();
for (int i = 0; i < AllCj_List.Count; i++)
{
int count = 0;
WebApp.Controllers.A5dot1Controller.NameandNum temp1 = new WebApp.Controllers.A5dot1Controller.NameandNum();
temp1.name = AllCj_List[i].EA_Name;
for (int j = 0; j < E.Count; j++)
{
if (AllCj_List[i].EA_Id == Em.getEA_parentid(E[j].EA_Id))
count += E[j].Equip_Num;
}
temp1.Equip_Num = count;
cj.Add(temp1);
count = 0;
}
WebApp.Controllers.A5dot1Controller.NameandNum temp = new WebApp.Controllers.A5dot1Controller.NameandNum();
temp.name = mi.Miss_Params["Pqname"].ToString();
List<Pq_Zz_map> Pq_Zz_map = Em.GetZzsofPq(mi.Miss_Params["Pqname"].ToString());
int count1 = 0;
for (int j = 0; j < Pq_Zz_map.Count; j++)
{
for (int z = 0; z < E.Count; z++)
{
if (Pq_Zz_map[j].Zz_Name == Em.getEa_namebyid(E[z].EA_Id))
count1 += E[z].Equip_Num;
}
}
temp.Equip_Num = count1;
pq.Add(temp);
double pq_bwh = 0.00;
for (int i = 0; i < pq.Count; i++)
{
List<A5dot1Tab1> pq_list = tm.get_pq_bwh(pq[i].name, pq[i].Equip_Num);
double pq_bxhcount = 0;
int wzg_count = 0;
if (pq_list.Count > 0)
{
pq_bxhcount = 0;
wzg_count = 0;
string sbcode_temp = pq_list[0].sbCode;
for (int j = 0; j < pq_list.Count; j++)
{
pq_list = tm.get_cj_bwh(cj[i].name, cj[i].Equip_Num);
if (pq_list[j].temp1 == null)
{
List<A5dot1Tab1> cj_bycode = tm.GetAll1_bycode(pq_list[j].sbCode);
for (int k = 0; k < cj_bycode.Count; k++)
{
if (cj_bycode[k].isRectified == 0)
{
wzg_count++;
}
tm.modifytemp1_byid(cj_bycode[k].Id, "已合并");
}
if (wzg_count > 0)
{
pq_bxhcount++;
}
wzg_count = 0;
}
// cjbwh.Add(f);
}
}
for (int n = 0; n < pq_list.Count; n++)
{
tm.modifytemp1_byid(pq_list[n].Id, null);
}
pq_bwh=Math.Round(((double)pq_bxhcount / pq[i].Equip_Num), 6);
}
ViewBag.Pq_bwh = (1-pq_bwh)*100;
return View(sm);
}
}
}<file_sep>using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.TimerManage
{
/// <summary>
/// 空任务
/// </summary>
public class CTimerEmptyMission : CTimerMission
{
#region 构造函数
public CTimerEmptyMission()
{
type = "Empty";
status = TM_STATUS.TM_STATUS_STOP;
}
#endregion
/// <summary>
/// 解析运行结果
/// </summary>
/// <returns></returns>
public override object ParseRunResultToJobject()
{
throw new NotImplementedException();
}
/// <summary>
/// 解析运行结果
/// </summary>
/// <param name="strResult"></param>
public override void ParseRunResult(string strResult)
{
throw new NotImplementedException();
}
protected override void __processing()
{
return;
}
public override void ParseRunParam(string strPars)
{
return;
}
public override object ParseRunParamsToJObject()
{
return null;
}
#region 公共方法
public override void Save(Timer_Jobs job = null)
{
Timer_Jobs job1 = new Timer_Jobs();
job1.Job_Type = TIMER_JOB_TYPE.EMPTY;
base.Save(job1);
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EquipBLL.AdminManagment.MenuConfig;
using EquipBLL.AdminManagment;
using EquipModel.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using FlowEngine;
using FlowEngine.UserInterface;
using EquipModel.Context;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
namespace WebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class qiyemodel
{
public double ?zzkkxzs { get; set; }
//维修费用指数
public double ?wxfyzs { get; set; }
//千台离心泵(机泵)密封消耗率
public double? qtlxbmfxhl { get; set; }
//千台冷换设备管束(含整台)更换率
public double? qtlhsbgsghl { get; set; }
//仪表实际控制率
public double? ybsjkzl { get; set; }
//事件数
public double? sjs { get; set; }
//故障强度扣分
public double? gzqdkf { get; set; }
//项目逾期率
public double? xmyql { get; set; }
//培训及能力
public double? pxjnl { get; set; }
}
}
<file_sep>using EquipDAL.Implement;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class BaseDataManagment
{
private Depart_Archis DA = new Depart_Archis();
private Speciaties SD = new Speciaties();
private Equip_Archis EA = new Equip_Archis();
private Roles RD = new Roles();
private Menus MD = new Menus();
//功能:获取系统基础数据库中定义的所有角色,返回List<Role_Info>集合信息
//参数:空
//返回值:List<Role_Info>
public List<Role_Info> GetAllRoles()
{
try
{
var r = RD.getRoles();
return r;
}
catch { return null; }
}
//功能:获取权限所对应的所有Menu集合List<Menu>,各权限重复的Menu会自动剔除
//参数:PersonRoles,为权限Id,注意:这里的PersonRoles可以是一个权限的Id,也可以是多个权限的Id,如果是多个权限的Id,各个权限Id之间用","隔开,Example:"1,4"
//返回值:List<Menu>
public List<Menu> GetRole_Menus(string PersonRoles)
{
try
{
var r = RD.getPerson_Role_Menus(PersonRoles);
return r;
}
catch { return null; }
}
public Depart_Archi GetRootTree()
{
try
{
Depart_Archi res = DA.getDepart_root("root");
if (res == null)
throw new Exception("DB has not only one root item");
return res;
}
catch (Exception e)
{
return null;
}
}
//显示部门树形机构表
private void BuildDepartList_inter(TreeListNode parent, List<TreeListNode> list)
{
List<Depart_Archi> Childs = DA.getDepart_Childs(parent.text);
foreach (Depart_Archi item in Childs)
{
TreeListNode mn = new TreeListNode();
mn.text = item.Depart_Name;
mn.id = item.Depart_Id;
if (DA.getDepart_Childs(item.Depart_Id).Count == 0) mn.selectable = true;
parent.nodes.Add(mn);
if (parent.text == "root") list.Add(mn);
BuildDepartList_inter(mn, list);
}
}
//功能:获取系统基础数据所有的部门层次树形结构节点集合
//参数:空
//返回值:List<TreeListNode> 在前台程序中可以利用Treeview显示树形结构
public List<TreeListNode> BuildDepartList()
{
Depart_Archi root = GetRootTree();
TreeListNode rnode = new TreeListNode();
rnode.text = root.Depart_Name;
rnode.selectable = false;
List<TreeListNode> list = new List<TreeListNode>();
BuildDepartList_inter(rnode, list);
return list;
}
private void BuildAccessGroupPersonList_inter(TreeListNode parent, List<TreeListNode> list)
{
List<Depart_Archi> Childs = DA.getDepart_Childs(parent.text);
foreach (Depart_Archi item in Childs)
{
if (item.Depart_Name.Equals("机动处")|| item.Depart_Name.Equals("设备支持中心")||item.Depart_Name.Equals("检安公司")||item.Depart_Name.Equals("调度处")||item.Depart_Name.Equals("工程处"))
{ TreeListNode mn = new TreeListNode();
mn.text = item.Depart_Name;
mn.id = item.Depart_Id;
mn.selectable = false;
parent.nodes.Add(mn);
if (parent.text == "root") list.Add(mn);
{
List<Person_Info> listP = DA.getPersons_Belong(item.Depart_Id);
TreeListNode mn_person;
foreach (Person_Info pitem in listP)
{
mn_person = new TreeListNode();
mn_person.text = pitem.Person_Name;
mn_person.id = pitem.Person_Id;
mn_person.selectable = true;
mn.nodes.Add(mn_person);
}
}
}
}
}
private void BuildDepartPersonList_inter(TreeListNode parent, List<TreeListNode> list)
{
List<Depart_Archi> Childs = DA.getDepart_Childs(parent.text);
foreach (Depart_Archi item in Childs)
{
TreeListNode mn = new TreeListNode();
mn.text = item.Depart_Name;
mn.id = item.Depart_Id;
mn.selectable = false;
parent.nodes.Add(mn);
if (parent.text == "root") list.Add(mn);
if (DA.getDepart_Childs(item.Depart_Id).Count > 0) BuildDepartPersonList_inter(mn, list);
else
{
List<Person_Info> listP = DA.getPersons_Belong(item.Depart_Id);
TreeListNode mn_person;
foreach (Person_Info pitem in listP)
{
mn_person = new TreeListNode();
mn_person.text = pitem.Person_Name;
mn_person.id = pitem.Person_Id;
mn_person.selectable = true;
mn.nodes.Add(mn_person);
}
}
}
}
private void BuildEquipArchiList_inter(TreeListNode parent, List<TreeListNode> list)
{
List<Equip_Archi> Childs = EA.getEA_Childs(parent.text);
foreach (Equip_Archi item in Childs)
{
TreeListNode mn = new TreeListNode();
mn.text = item.EA_Name;
mn.id = item.EA_Id;
//if (EA.getEA_Childs(item.EA_Id).Count == 0)
mn.selectable = true;
parent.nodes.Add(mn);
if (parent.text == "root") list.Add(mn);
BuildEquipArchiList_inter(mn, list);
}
}
//功能:获取系统基础数据中所有专业信息的层次树形结构节点集合
//参数:空
//返回值:List<TreeListNode> 在前台程序中可以利用Treeview显示树形结构
public List<TreeListNode> BuildEquipArchiList()
{
TreeListNode rnode = new TreeListNode();
rnode.text = "root";
rnode.selectable = false;
List<TreeListNode> list = new List<TreeListNode>();
BuildEquipArchiList_inter(rnode, list);
return list;
}
//功能:获取系统基础数据中所有人员,此处按照人员所在的部门返回层次结构树形结构节点集合
//参数:空
//返回值:List<TreeListNode> 在前台程序中可以利用Treeview显示树形结构
public List<TreeListNode> BuildDepartPersonList()
{
Depart_Archi root = GetRootTree();
TreeListNode rnode = new TreeListNode();
rnode.text = root.Depart_Name;
rnode.selectable = false;
List<TreeListNode> list = new List<TreeListNode>();
BuildDepartPersonList_inter(rnode, list);
return list;
}
public List<TreeListNode> BuildAccessGroupPersonList()
{
Depart_Archi root = GetRootTree();
TreeListNode rnode = new TreeListNode();
rnode.text = root.Depart_Name;
rnode.selectable = false;
List<TreeListNode> list = new List<TreeListNode>();
BuildAccessGroupPersonList_inter(rnode, list);
return list;
}
//显示专业部门树形结构表
private void BuildSpecialtyList_inter(TreeListNode parent, List<TreeListNode> list)
{
List<Speciaty_Info> Childs = SD.getSepciaty_Childs(parent.text);
foreach (Speciaty_Info item in Childs)
{
TreeListNode mn = new TreeListNode();
mn.text = item.Specialty_Name;
mn.id = item.Specialty_Id;
// if (SD.getSepciaty_Childs(item.Specialty_Id).Count == 0)
mn.selectable = true;
parent.nodes.Add(mn);
if (parent.text == "root") list.Add(mn);
BuildSpecialtyList_inter(mn, list);
}
}
//功能:获取系统基础数据中所有专业信息的层次树形结构节点集合
//参数:空
//返回值:List<TreeListNode> 在前台程序中可以利用Treeview显示树形结构
public List<TreeListNode> BuildSpeciatyList()
{
TreeListNode rnode = new TreeListNode();
rnode.text = "root";
rnode.selectable = false;
List<TreeListNode> list = new List<TreeListNode>();
BuildSpecialtyList_inter(rnode, list);
return list;
}
//显示系统菜单部门树形结构表
private void BuildMenuList_inter(TreeListNode parent, List<TreeListNode> list, List<Menu> hasMenus)
{
List<Menu> Childs = MD.GetChildMenu(parent.text);
foreach (Menu item in Childs)
{
TreeListNode mn = new TreeListNode();
mn.text = item.Menu_Name;
mn.id = item.Menu_Id;
if (MD.GetChildMenu(item.Menu_Id).Count == 0) mn.selectable = true;
if (hasMenus.Where(s => s.Menu_Id == item.Menu_Id).Count() > 0) mn.state.selected = true;
parent.nodes.Add(mn);
if (parent.text == "root") list.Add(mn);
BuildMenuList_inter(mn, list, hasMenus);
}
}
//功能:获取系统基础数据中所有系统菜单信息的层次树形结构节点集合
//参数:空
//返回值:List<TreeListNode> 在前台程序中可以利用Treeview显示树形结构
public List<TreeListNode> BuildMenuList(string Role_ids)
{
TreeListNode rnode = new TreeListNode();
List<Menu> hasMenus = RD.getPerson_Role_Menus(Role_ids);
rnode.text = "root";
rnode.selectable = false;
List<TreeListNode> list = new List<TreeListNode>();
BuildMenuList_inter(rnode, list, hasMenus);
return list;
}
}
}
<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class GetNWorkSerManagment
{
GetNWorkSer NSer = new GetNWorkSer();
public NWorkFlowSer AddNWorkEntity(string wfName, string WE_Ser = "")
{
return NSer.AddNWorkEntity(wfName, WE_Ser);
}
}
}
<file_sep>///////////////////////////////////////////////////////////
// IFlow.cs
// Implementation of the Interface IFlow
// Generated by Enterprise Architect
// Created on: 28-10月-2015 13:58:42
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace FlowEngine.Flow {
/// <summary>
/// 流程接口
/// 主要负责维护事件(Event)之间的联系——状态迁移
/// </summary>
public interface IFlow {
/// <summary>
/// 获得/设置流程(Flow)的目的事件
/// </summary>
string destination_event{
get;
set;
}
/// <summary>
/// 计算流(Flow)表达式的值
/// 返回值:真假
/// </summary>
bool Evaluate();
/// <summary>
/// 获取/设置流(Flow)表达式
/// </summary>
string expression{
get;
set;
}
/// <summary>
/// 获得/设置流程(Flow)的源事件(Event)的名称
/// </summary>
string source_event{
get;
set;
}
}//end IFlow
}//end namespace Flow<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowDesigner
{
/// <summary>
/// AddNewParam.xaml 的交互逻辑
/// </summary>
public partial class AddNewParam : Window
{
public AddNewParam()
{
InitializeComponent();
}
private void Ok_Click(object sender, RoutedEventArgs e)
{
if (name.Text == "")
this.DialogResult = false;
else
this.DialogResult = true;
this.Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
foreach(LinkParam lp in Event_List.Items)
{
if (lp.Name == (string)(((CheckBox)sender).Tag))
lp.Selected = (bool)((CheckBox)sender).IsChecked;
}
}
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
(sender as ComboBox).ItemsSource = ((MainWindow)Application.Current.MainWindow).main_proj.Param_AppRes;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowDesigner.PropertyEditor
{
/// <summary>
/// EventActionParamAdd.xaml 的交互逻辑
/// </summary>
public partial class EventActionParamAdd : Window
{
public E_Param _NewParam = new E_Param();
public List<string> _linkParams = new List<string>();
public EventActionParamAdd()
{
InitializeComponent();
}
private void LinkValue(object sender, RoutedEventArgs e)
{
ActionValueSelector vs = new ActionValueSelector();
vs.LinkParams = _linkParams;
if (vs.ShowDialog().Equals(true))
{
Param_Value.Text = vs.ret_value;
}
}
private void Ok_Click(object sender, RoutedEventArgs e)
{
if ((Param_Value.Text == "") || (Param_Name.Text == ""))
return;
_NewParam.p_name = Param_Name.Text;
_NewParam.p_value = Param_Value.Text;
this.DialogResult = true;
this.Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
}
}
<file_sep>using FlowDesigner.ConfigItems;
using System;
using System.Activities.Presentation.Converters;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.PropertyEditing;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
namespace FlowDesigner.PropertyEditor
{
public class TimeoutEditor : DialogPropertyValueEditor
{
public TimeoutEditor()
{
string template = @"
<DataTemplate
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:pe='clr-namespace:System.Activities.Presentation.PropertyEditing;assembly=System.Activities.Presentation'>
<DockPanel LastChildFill='True'>
<pe:EditModeSwitchButton TargetEditMode='Dialog' Name='EditButton_Action'
DockPanel.Dock='Right'>...</pe:EditModeSwitchButton>
<TextBlock Text='设置' Margin='2,0,0,0' VerticalAlignment='Center'/>
</DockPanel>
</DataTemplate>";
using (var sr = new MemoryStream(Encoding.UTF8.GetBytes(template)))
{
this.InlineEditorTemplate = XamlReader.Load(sr) as DataTemplate;
}
}
public override void ShowDialog(PropertyValue propertyValue, System.Windows.IInputElement commandSource)
{
TimeoutWin wn = new TimeoutWin();
Dictionary<string, object> action = propertyValue.Value as Dictionary<string, object>;
wn.time_start = action.ContainsKey("start") ? (action["start"] as string) : "";
wn.time_offset = action.ContainsKey("offset") ? (action["offset"] as TimeSpan?) : null;
wn.time_exact = action.ContainsKey("exact") ? (action["exact"] as DateTime?) : null;
wn.time_callback = action.ContainsKey("callback") ? (action["callback"] as string) : "";
wn.time_action = action.ContainsKey("action") ? (action["action"] as string) : "";
if (wn.ShowDialog().Equals(true))
{
var ownerActivityConverter = new ModelPropertyEntryToOwnerActivityConverter();
ModelItem activityItem = ownerActivityConverter.Convert(propertyValue.ParentProperty, typeof(ModelItem), false, null) as ModelItem;
using (ModelEditingScope editingScope = activityItem.BeginEdit())
{
Dictionary<string, object> newValue = new Dictionary<string, object>();
newValue["start"] = wn.time_start;
newValue["offset"] = wn.time_offset;
newValue["exact"] = wn.time_exact;
newValue["action"] = wn.time_action;
newValue["callback"] = wn.time_callback;
propertyValue.Value = newValue;
editingScope.Complete();
var control = commandSource as Control;
var oldData = control.DataContext;
control.DataContext = null;
control.DataContext = oldData;
}
}
}
}
}
<file_sep># equip-web
for wust 10-711
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Xceed.Wpf.Toolkit;
namespace FlowDesigner.PropertyEditor
{
/// <summary>
/// TimeoutWin.xaml 的交互逻辑
/// </summary>
public partial class TimeoutWin : Window
{
public string time_start = "";
public TimeSpan? time_offset = null;
public DateTime? time_exact = null;
public string time_action = "";
public string time_callback = "INVALID";
public TimeoutWin()
{
InitializeComponent();
}
private void radio_offset_Unchecked(object sender, RoutedEventArgs e)
{
select_timestart.IsEnabled = false;
select_escape.IsEnabled = false;
input_timeoffset.IsEnabled = false;
}
private void radio_offset_Checked(object sender, RoutedEventArgs e)
{
select_timestart.IsEnabled = true;
select_escape.IsEnabled = true;
input_timeoffset.IsEnabled = true;
}
private void radio_exact_Checked(object sender, RoutedEventArgs e)
{
exact_picker.IsEnabled = true;
}
private void radio_exact_Unchecked(object sender, RoutedEventArgs e)
{
exact_picker.IsEnabled = false;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (radio_offset.IsChecked == true)
{
time_start = ((select_timestart.SelectedItem as ComboBoxItem).Tag as string);
TimeSpan t = new TimeSpan(0);
switch((select_escape.SelectedItem as ComboBoxItem).Tag as string)
{
case "Date":
t = t + new TimeSpan(Convert.ToInt32(input_timeoffset.Text), 0, 0, 0);
break;
case "Hour":
t = t + new TimeSpan(0, Convert.ToInt32(input_timeoffset.Text), 0, 0);
break;
case "Minute":
t = t + new TimeSpan(0, 0, Convert.ToInt32(input_timeoffset.Text), 0);
break;
}
time_offset = t;
time_exact = null;
}
else if (radio_exact.IsChecked == true)
{
time_exact = exact_picker.Value;
time_start = "";
time_offset = null;
}
time_callback = input_callback.Text;
time_action = (select_action.SelectedItem as ComboBoxItem).Tag as string;
this.DialogResult = true;
Close();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
Close();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (time_exact != null)
{
radio_exact.IsChecked = true;
exact_picker.Value = time_exact;
select_timestart.IsEnabled = false;
select_escape.IsEnabled = false;
input_timeoffset.IsEnabled = false;
}
else if (time_start != "")
{
exact_picker.IsEnabled = false;
foreach(var item in select_timestart.Items)
{
if (((item as ComboBoxItem).Tag as string) == time_start)
(item as ComboBoxItem).IsSelected = true;
}
radio_offset.IsChecked = true;
exact_picker.Value = null;
if (time_offset != null)
{
if (time_offset.Value.Days != 0)
{
select_escape.Text = "天";
input_timeoffset.Text = Convert.ToString(time_offset.Value.Days);
}
else if (time_offset.Value.Hours != 0)
{
select_escape.Text = "小时";
input_timeoffset.Text = Convert.ToString(time_offset.Value.Hours);
}
else if (time_offset.Value.Minutes != 0)
{
select_escape.Text = "分钟";
input_timeoffset.Text = Convert.ToString(time_offset.Value.Minutes);
}
}
}
else
{
radio_offset.IsChecked = true;
exact_picker.IsEnabled = false;
select_timestart.IsEnabled = true;
select_escape.IsEnabled = true;
input_timeoffset.IsEnabled = true;
}
foreach(var item in select_action.Items)
{
if (((item as ComboBoxItem).Tag as string) == time_action)
(item as ComboBoxItem).IsSelected = true;
}
input_callback.Text = time_callback;
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System.Collections.Specialized;
using WebApp.Models.DateTables;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A14dot3dot4Controller : CommonController
{
//月度计划DRBPM
public ActionResult SubmitJxPlan(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string getA14dot3dot4dcl_list(string WorkFlow_Name)
{
List<A14dot3dot4Model> Am = new List<A14dot3dot4Model>();
List<A14dot3dot4_ModelInfo> YueduDRBPM = new List<A14dot3dot4_ModelInfo>();
YueduDRBPM=getA14dot3dot4_Model().A14dot3dot4_ModelInfoList;
for (int j = 0; j < YueduDRBPM.Count; j++)
{
A14dot3dot4Model o = new A14dot3dot4Model();
o.index_Id = j+1;
o.zz_name = YueduDRBPM[j].Zz_Name;
o.sb_gycode = YueduDRBPM[j].Equip_GyCode;
o.sb_code = YueduDRBPM[j].Equip_Code;
o.sb_type = YueduDRBPM[j].Equip_Type;
o.sb_ABCMark = YueduDRBPM[j].Equip_ABCMark;
o.plan_name = "来自DRBPM";
o.jxreason = YueduDRBPM[j].Jx_Reason;
o.xcconfirm = "同意";
o.kkconfirm2 = "同意";
o.zytdconfirm2 = "同意";
o.job_order2 = YueduDRBPM[j].Job_Order;
o.notice_order2 = "";//通过工单号获取通知单号 Q1:会有无法获取通知单号的情况吗,是否允许手动填写
if (!string.IsNullOrEmpty(YueduDRBPM[j].JxSubmit_done.Trim()))
{
o.missionname = "已跳转至A8.2";
}
else
o.missionname = "审核已完成,工单待填写";
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
o.role = pv.Role_Names;
Am.Add(o);
}
string str = JsonConvert.SerializeObject(Am);
return ("{" + "\"data\": " + str + "}");
}
public string testgetA14dot3dot4dcl_list(string WorkFlow_Name)
{
List<A14dot3dot4Model> Am = new List<A14dot3dot4Model>();
A14dot3dot4Model o = new A14dot3dot4Model();
o.index_Id =1;
o.zz_name = "1#常压装置";
o.sb_gycode = "1#常压常一中泵P112A";
o.sb_code = "210000034";
o.sb_type = "150HDS-91";
o.sb_ABCMark ="C";
o.plan_name = "来自DRBPM";
o.jxreason = "就是想检修";
o.xcconfirm = "同意";
o.kkconfirm2 = "同意";
o.zytdconfirm2 = "同意";
o.job_order2 = "23333";
o.notice_order2 = "";//通过工单号获取通知单号 Q1:会有无法获取通知单号的情况吗,是否允许手动填写
o.missionname = "";
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
o.role = pv.Role_Names;
Am.Add(o);
string str = JsonConvert.SerializeObject(Am);
return ("{" + "\"data\": " + str + "}");
}
public string submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["SubmitJxPlan_Done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
signal["Plan_Name"] = item["Plan_Name"].ToString();
signal["JxCauseDesc"] = item["JxCauseDesc"].ToString();
signal["Data_Src"] = "月度计划DRBPM";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot3/Index");
}
private List<KeyValuePair<string, string>> ParsePostForm(NameValueCollection Form)
{
var list = new List<KeyValuePair<string, string>>();
if (Form != null)
{
foreach (var f in Form.AllKeys)
{
list.Add(new KeyValuePair<string, string>(f, Form[f]));
}
}
return list;
}
public string click_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
ERPInfoManagement erp = new ERPInfoManagement();
GD_InfoModal res = erp.getGD_Modal_GDId(item["Job_Order"].ToString());
if (res != null)
{
if (String.Compare(res.GD_EquipCode.Trim(), item["Equip_Code"].ToString().Trim()) != 0)
{
return "工单号与设备不匹配";
}
}
else
{
return "系统中无此工单";
}
string Equip_Code = item["Equip_Code"].ToString();
string Jx_Reason = item["Jx_Reason"].ToString();
string flowname = "A8dot2";
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
if (wfe != null)
{
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(Equip_Code);
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
int flow_id = wfe.EntityID;
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxSubmit_done"] = "true";
signal["Cj_Name"] = Equip_ZzBelong[1].EA_Name; //Cj_Name
signal["Zz_Name"] = Equip_ZzBelong[0].EA_Name; //Zz_Name
signal["Equip_GyCode"] = eqinfo.Equip_GyCode;
signal["Equip_Code"] = eqinfo.Equip_Code;
signal["Equip_Type"] = eqinfo.Equip_Type;
signal["Zy_Type"] = eqinfo.Equip_Specialty;
signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
signal["Jx_Reason"] = Jx_Reason;//计划检修原因 PM?
signal["Data_Src"] = "月度计划DRBPM";
signal["Job_Name"] = "来自DRBPM";
signal["Job_Order"] = item["Job_Order"].ToString();
//record
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(flow_id, signal, record);
return ("/A8dot2/Index");
}
else
return "/A14dot1/Index";
}
catch (Exception e)
{
return "";
}
//return ("/A14dot1/Index");
}
private DtResponse ProcessRequest(List<KeyValuePair<string, string>> data)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
var Data = http["data"] as Dictionary<string, object>;
int wfe_id = -1;
foreach (var d in Data)
{
wfe_id = Convert.ToInt32(d.Key);
}
string jx_reason="";
string E_code="";
string job_order="";
string notice_order="";
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
foreach (var dd in d.Value as Dictionary<string, object>)
{
ERPInfoManagement erp = new ERPInfoManagement();
//sb_code、jxreason与设备绑定在一起传过来,当通知单号工单号填完后满足向A8.2跳转条件
if (dd.Key == "sb_code")
{
E_code=dd.Value.ToString();
}
if (dd.Key == "jxreason")
{
jx_reason=dd.Value.ToString();
}
if (dd.Key == "notice_order2")
{
if (dd.Value.ToString() == "")
continue;
notice_order="00"+dd.Value.ToString();
GD_InfoModal res = erp.getGD_Modal_Notice(notice_order);
if (res != null)
job_order=res.GD_Id;
}
if (dd.Key == "job_order2")
{
if (dd.Value.ToString() == "")
continue;
job_order = "00" + dd.Value.ToString();
GD_InfoModal res = erp.getGD_Modal_GDId(job_order);
if (res != null)
notice_order = res.GD_Notice_Id;
}
//if (dd.Key == "JumpA8dot2DR")
//{
// string Equip_Code = E_code;
// string Jx_Reason = jx_reason;
// string flowname = "A8dot2";
// UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
// if (wfe != null)
// {
// EquipManagment em = new EquipManagment();
// Equip_Info eqinfo = em.getEquip_Info(Equip_Code);
// List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
// Dictionary<string, string> record = wfe.GetRecordItems();
// record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// record["time"] = DateTime.Now.ToString();
// wfe.Start(record);
// int flow_id = wfe.EntityID;
// //paras
// Dictionary<string, string> signal = new Dictionary<string, string>();
// signal["JxSubmit_done"] = "true";
// signal["Cj_Name"] = Equip_ZzBelong[1].EA_Name; //Cj_Name
// signal["Zz_Name"] = Equip_ZzBelong[0].EA_Name; //Zz_Name
// signal["Equip_GyCode"] = eqinfo.Equip_GyCode;
// signal["Equip_Code"] = eqinfo.Equip_Code;
// signal["Equip_Type"] = eqinfo.Equip_Type;
// signal["Zy_Type"] = eqinfo.Equip_Specialty;
// signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
// signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
// signal["Jx_Reason"] = Jx_Reason;//计划检修原因 PM?
// signal["Job_Name"] = "来自DRBPM";
// signal["Job_Order"] = job_order;
// //record
// record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// record["time"] = DateTime.Now.ToString();
// //submit
// CWFEngine.SubmitSignal(flow_id, signal, record);
// }
//}
}
}
Dictionary<string, object> m_kv = new Dictionary<string, object>();
EquipManagment em1 = new EquipManagment();
Equip_Info eqinfo1 = em1.getEquip_Info(E_code);
List<Equip_Archi> Equip_ZzBelong1 = em1.getEquip_ZzBelong(eqinfo1.Equip_Id);
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
m_kv["index_Id"] = wfe_id;
m_kv["zz_name"] =Equip_ZzBelong1[0].EA_Name; //Zz_Name
m_kv["sb_gycode"] = eqinfo1.Equip_GyCode;
m_kv["sb_code"] = E_code;
m_kv["sb_type"] = eqinfo1.Equip_Type;
m_kv["sb_ABCMark"] = eqinfo1.Equip_ABCmark;
m_kv["plan_name"] ="来自DRBPM";
m_kv["jxreason"] =jx_reason;
m_kv["kkconfirm2"] = "同意";
m_kv["zytdconfirm2"] ="同意";
m_kv["job_order2"] = job_order;
m_kv["notice_order2"] = notice_order;
m_kv["missionname"] = "完善工单与通知单后跳转";
m_kv["role"] = pv.Role_Names;
dt.data.Add(m_kv);
return dt;
}
public JsonResult PostChanges()
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = ProcessRequest(list);
return Json(dtRes);
}
}
}<file_sep>using FlowDesigner.ConfigItems;
using FlowDesigner.customcontrol;
using FlowDesigner.Management;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Control;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
namespace FlowDesigner
{
class LinkParam
{
public string Name { get; set; }
public bool Selected { get; set; }
public string App_res { get; set; }
}
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public WorkFlowsProj main_proj;
private int id_for_workflow = 0;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
AddNEvent.IsEnabled = false;
AddSEvent.IsEnabled = false;
AddNewFlow.IsEnabled = false;
AddLEvent.IsEnabled = false;
Save_button.IsEnabled = false;
AddNewParam.IsEnabled = false;
Complie.IsEnabled = false;
ToDb.IsEnabled = false;
}
public void OnConfigItem_Selected(ConfigItem sender)
{
main_proj.CurrentWF.SelectedItem = sender;
property.SelectedObject = sender;
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
}
private void mainCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
}
/// <summary>
/// 新建工作流工程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void new_proj_Click(object sender, RoutedEventArgs e)
{
CloseAll();
if (main_proj == null)
{
main_proj = new WorkFlowsProj();
NewWorkFlowProj newWF = new NewWorkFlowProj();
newWF.Owner = this;
if (!newWF.ShowDialog().Value)
{
main_proj = null;
return;
}
string proj_name = newWF.newProj_name;
string proj_path = newWF.newProj_path;
main_proj.Name = proj_name;
main_proj.Path = proj_path;
main_proj.win_main = this;
main_proj.DB_Config = newWF.db_config;
main_proj.Record_Items = newWF.Record_Items;
TreeViewItem projItem = new TreeViewItem();
StackPanel stack = new StackPanel();
stack.Orientation = System.Windows.Controls.Orientation.Horizontal;
Image im = new Image();
im.Width = 16;
im.Height = 16;
im.Source = new BitmapImage(new Uri("new_wfs.ico", UriKind.RelativeOrAbsolute));
stack.Children.Add(im);
TextBlock tb = new TextBlock();
tb.VerticalAlignment = VerticalAlignment.Center;
tb.Text = main_proj.Name;
stack.Children.Add(tb);
projItem.Header = stack;
System.Windows.Controls.ContextMenu cm = this.FindResource("proj_prop") as System.Windows.Controls.ContextMenu;
cm.PlacementTarget = sender as System.Windows.Controls.TreeViewItem;
projItem.ContextMenu = cm;
main_treeView.Items.Add(projItem);
AddFlow.IsEnabled = true;
Save_button.IsEnabled = true;
}
}
private void AddFlow_Click(object sender, RoutedEventArgs e)
{
if (main_proj != null)
{
NewFolwWin fw = new NewFolwWin();
fw.Owner = this;
if (fw.ShowDialog().Value != true)
{
return;
}
WorkFlowMan new_wf = main_proj.NewWrokFlowMan(fw.flowName, fw.flowDesc);
if (new_wf == null)
{
System.Windows.MessageBox.Show(fw.flow_name + "已存在");
return;
}
TreeViewItem projItem = new TreeViewItem();
StackPanel stack = new StackPanel();
stack.Orientation = System.Windows.Controls.Orientation.Horizontal;
Image im = new Image();
im.Width = 16;
im.Height = 16;
im.Source = new BitmapImage(new Uri("workflow.ico", UriKind.RelativeOrAbsolute));
stack.Children.Add(im);
TextBlock tb = new TextBlock();
tb.VerticalAlignment = VerticalAlignment.Center;
tb.Text = new_wf.Name;
stack.Children.Add(tb);
projItem.Header = stack;
((TreeViewItem)main_treeView.Items[0]).Items.Add(projItem);
projItem.MouseDoubleClick += new_wf.OnSelected;
projItem.MouseRightButtonUp += this.ProjectItem_menu;
projItem.Tag = new_wf.Name;
new_wf.LinkToMainTab(mainTab);
id_for_workflow += 1;
main_proj.CurrentWF = new_wf;
AddNEvent.IsEnabled = true;
AddSEvent.IsEnabled = true;
AddLEvent.IsEnabled = true;
AddNewFlow.IsEnabled = true;
Save_button.IsEnabled = true;
AddNewParam.IsEnabled = true ;
Complie.IsEnabled = true;
ToDb.IsEnabled = true;
}
}
private void ProjectItem_menu(object sender, MouseButtonEventArgs e)
{
System.Windows.Controls.ContextMenu cm = this.FindResource("proj_menu") as System.Windows.Controls.ContextMenu;
cm.PlacementTarget = sender as System.Windows.Controls.TreeViewItem;
cm.Tag = (sender as System.Windows.Controls.TreeViewItem).Tag;
cm.IsOpen = true;
}
private void AddNEvent_Click(object sender, RoutedEventArgs e)
{
//((System.Windows.Controls.RadioButton)sender).IsChecked = !((System.Windows.Controls.RadioButton)sender).IsChecked;
if (sender == AddNEvent)
main_proj.CurrentWF.NewEventType = "NormalEvent";
else if (sender == AddSEvent)
main_proj.CurrentWF.NewEventType = "SubProcess";
else if (sender == AddLEvent)
main_proj.CurrentWF.NewEventType = "LoopEvent";
main_proj.CurrentWF.PerAddNEvent = ((System.Windows.Controls.CheckBox)sender).IsChecked.Value;
//this.Cou
}
public void EndAddNEvent()
{
AddNEvent.IsChecked = false;
AddSEvent.IsChecked = false;
}
private void main_treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
}
private void mainTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
/// <summary>
/// 添加Flow
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddNewFlow_Click(object sender, RoutedEventArgs e)
{
main_proj.CurrentWF.perAddNFlow = 1;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ObservableCollection<LinkParam> lv_source = new ObservableCollection<LinkParam>();
AddNewParam par_win = new AddNewParam();
par_win.Owner = this;
List<ConfigEvent> evs = main_proj.CurrentWF.GetAllEvents();
foreach (ConfigEvent ce in evs)
{
lv_source.Add(new LinkParam() { Name = ce.name, Selected = false, App_res="" });
}
par_win.Event_List.ItemsSource = lv_source;
if (par_win.ShowDialog().Value == true)
{
//检查是否有重名的变量名
foreach (param pa in main_proj.CurrentWF.params_table)
if (pa.Name == par_win.name.Text.Trim())
break;
//添加变量
main_proj.CurrentWF.params_table.Add(new param()
{
Name = par_win.name.Text,
Desc = par_win.desc.Text,
Type = par_win.type.SelectedItem.ToString()
});
foreach (LinkParam it in par_win.Event_List.Items)
{
foreach(ConfigEvent ee in evs)
{
if (ee.name == it.Name)
{
if (it.Selected == true)
ee.LinkParams.Add(par_win.name.Text, it.App_res);
}
}
}
}
}
public void Confi_Param(param pa)
{
ObservableCollection<LinkParam> lv_source = new ObservableCollection<LinkParam>();
AddNewParam par_win = new AddNewParam();
par_win.Owner = this;
par_win.name.Text = pa.Name;
par_win.name.IsEnabled = false;
par_win.desc.Text = pa.Desc;
par_win.type.SelectedItem = pa.Type;
List<ConfigEvent> evs = main_proj.CurrentWF.GetAllEvents();
foreach (ConfigEvent ce in evs)
{
lv_source.Add(new LinkParam() {
Name = ce.name,
Selected = ce.LinkParams.ContainsKey(pa.Name),
App_res = (ce.LinkParams.ContainsKey(pa.Name) ? ce.LinkParams[pa.Name] : "")
});
}
par_win.Event_List.ItemsSource = lv_source;
if (par_win.ShowDialog().Value == true)
{
pa.Type = par_win.type.Text;
pa.Desc = par_win.desc.Text;
foreach (LinkParam it in par_win.Event_List.Items)
{
foreach (ConfigEvent ee in evs)
{
if (ee.name == it.Name)
{
if (it.Selected == true)
{
if (!ee.LinkParams.ContainsKey(par_win.name.Text))
ee.LinkParams.Add(par_win.name.Text, it.App_res);
else
ee.LinkParams[par_win.name.Text] = it.App_res;
}
}
}
}
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
main_proj.SaveWorkFlowProj();
}
private void CloseAll()
{
if (main_proj != null)
{
main_treeView.Items.Clear();
mainTab.Items.Clear();
main_proj = null;
property.SelectedObject = null;
}
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
CloseAll();
XmlDocument doc = new XmlDocument();
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "工程文件(*.wfproj)|*.wfproj";
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
doc.Load(fd.FileName);
else
return;
main_proj = new WorkFlowsProj();
main_proj.win_main = this;
main_proj.Path = System.IO.Path.GetDirectoryName(fd.FileName);
main_proj.LoadWorkFlowProj((XmlElement)doc.SelectSingleNode("work_wlow_project"));
TreeViewItem projItem = new TreeViewItem();
StackPanel stack = new StackPanel();
stack.Orientation = System.Windows.Controls.Orientation.Horizontal;
Image im = new Image();
im.Width = 16;
im.Height = 16;
im.Source = new BitmapImage(new Uri("new_wfs.ico", UriKind.RelativeOrAbsolute));
stack.Children.Add(im);
TextBlock tb = new TextBlock();
tb.VerticalAlignment = VerticalAlignment.Center;
tb.Text = main_proj.Name;
stack.Children.Add(tb);
projItem.Header = stack;
System.Windows.Controls.ContextMenu cm = this.FindResource("proj_prop") as System.Windows.Controls.ContextMenu;
cm.PlacementTarget = sender as System.Windows.Controls.TreeViewItem;
projItem.ContextMenu = cm;
main_treeView.Items.Add(projItem);
AddFlow.IsEnabled = true;
foreach (WorkFlowMan new_wf in main_proj.GetWorkFlows())
{
TreeViewItem projItem1 = new TreeViewItem();
StackPanel stack1 = new StackPanel();
stack1.Orientation = System.Windows.Controls.Orientation.Horizontal;
Image im1 = new Image();
im1.Width = 16;
im1.Height = 16;
im1.Source = new BitmapImage(new Uri("workflow.ico", UriKind.RelativeOrAbsolute));
stack1.Children.Add(im1);
TextBlock tb1 = new TextBlock();
tb1.VerticalAlignment = VerticalAlignment.Center;
tb1.Text = new_wf.Name;
stack1.Children.Add(tb1);
projItem1.Header = stack1;
projItem1.Tag = new_wf.Name;
((TreeViewItem)main_treeView.Items[0]).Items.Add(projItem1);
projItem1.MouseDoubleClick += new_wf.OnSelected;
projItem1.MouseRightButtonUp += this.ProjectItem_menu;
new_wf.LinkToMainTab(mainTab);
}
AddNEvent.IsEnabled = true;
AddSEvent.IsEnabled = true;
AddLEvent.IsEnabled = true;
AddNewFlow.IsEnabled = true;
Save_button.IsEnabled = true;
AddNewParam.IsEnabled = true;
Complie.IsEnabled = true;
ToDb.IsEnabled = true;
}
private void Comple_Click(object sender, RoutedEventArgs e)
{
main_proj.SaveWorkFlowProj();
main_proj.Complie();
}
private void proj_menu_delete(object sender, RoutedEventArgs e)
{
//System.Windows.MessageBox.Show(sender.GetType().Name);
System.Windows.Controls.MenuItem mi = sender as System.Windows.Controls.MenuItem;
string cur_name = (mi.Parent as System.Windows.Controls.ContextMenu).Tag.ToString();
((TreeViewItem)main_treeView.Items[0]).Items.Remove((mi.Parent as System.Windows.Controls.ContextMenu).PlacementTarget);
WorkFlowMan deleted = main_proj.DeleteWorkFlowMan(cur_name);
deleted.UnLinkFromMainTab(mainTab);
}
private void param_menu_delete(object sender, RoutedEventArgs e)
{
System.Windows.Controls.MenuItem mi = sender as System.Windows.Controls.MenuItem;
string p_name = ((param)(mi.Parent as System.Windows.Controls.ContextMenu).Tag).Name;
main_proj.CurrentWF.DeleteParam(p_name);
}
public void pop_itemmenu(object sender, MouseButtonEventArgs e)
{
System.Windows.Controls.ContextMenu cm = this.FindResource("item_menu") as System.Windows.Controls.ContextMenu;
cm.PlacementTarget = (sender as ConfigItem).GetShowItem();
cm.Tag = sender;
cm.IsOpen = true;
}
private void item_menu_delete(object sender, RoutedEventArgs e)
{
System.Windows.Controls.MenuItem mi = sender as System.Windows.Controls.MenuItem;
if (property.SelectedObject == (mi.Parent as System.Windows.Controls.ContextMenu).Tag)
property.SelectedObject = null;
main_proj.CurrentWF.DeleteItem((mi.Parent as System.Windows.Controls.ContextMenu).Tag as ConfigItem);
}
private void Refresh_toDB(object sender, RoutedEventArgs e)
{
main_proj.Complie();
main_proj.SaveWorkFlowProj();
ObservableCollection<WorkFlowMan> wfs = main_proj.GetWorkFlows();
SqlConnection sql_conn = new SqlConnection(main_proj.DB_Config);
try
{
sql_conn.Open();
if (sql_conn.State == ConnectionState.Open)
{
foreach (WorkFlowMan wfm in wfs)
{
string fileName = main_proj.Path.TrimEnd('\\') + "\\workflows\\" + wfm.Name + ".wfd";
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
byte[] w_xml = Encoding.Default.GetBytes(doc.InnerXml);
SqlCommand sql_comm = new SqlCommand("select count(*) from WorkFlow_Define where W_Name='" + wfm.Name + "'", sql_conn);
SqlDataReader dr = sql_comm.ExecuteReader();
dr.Read();
if (Convert.ToInt32(dr[0].ToString()) != 0)
{
dr.Close();
sql_comm.CommandText = "update WorkFlow_Define set W_Xml = @param1, W_Attribution = @param2 where W_Name='" + wfm.Name + "'";
sql_comm.Parameters.Add("@param1", SqlDbType.VarBinary).Value = w_xml;
sql_comm.Parameters.Add("@param2", SqlDbType.NVarChar).Value = wfm.Description;
sql_comm.ExecuteNonQuery();
}
else
{
dr.Close();
sql_comm.CommandText = "insert into WorkFlow_Define(W_Attribution, W_Name, W_Xml) values (@Attr, @Name, @Xml)";
sql_comm.Parameters.Add("@Xml", SqlDbType.VarBinary).Value = w_xml;
sql_comm.Parameters.Add("@Attr", SqlDbType.NVarChar).Value = wfm.Description;
sql_comm.Parameters.Add("@Name", SqlDbType.NVarChar).Value = wfm.Name;
sql_comm.ExecuteNonQuery();
}
}
sql_conn.Close();
}
}
catch
{
System.Windows.MessageBox.Show("更新失败");
}
}
private void proj_prop_show(object sender, RoutedEventArgs e)
{
NewWorkFlowProj wfp = new NewWorkFlowProj();
wfp.Owner = this;
wfp.Title = "工程属性";
wfp.newProj_name = main_proj.Name;
wfp.newProj_path = main_proj.Path;
wfp.proj_name.IsEnabled = false;
wfp.proj_path.IsEnabled = false;
wfp.Record_Items = main_proj.Record_Items;
SqlConnection sqlConn = new SqlConnection(main_proj.DB_Config);
wfp.server.Text = sqlConn.DataSource;
wfp.SetDBConfigration(sqlConn.Database);
if (wfp.ShowDialog().Value == true)
{
main_proj.DB_Config = wfp.db_config;
main_proj.Record_Items = wfp.Record_Items;
}
}
}
}
<file_sep>using FlowEngine;
using MVCTest.Models;
using MVCTest.Models.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCTest.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult LogOn(string userName, string passWord)
{
using(var db = new UserContext())
{
UserInfo ui = db.users.Where(s => s.name == userName & s.password == <PASSWORD>).First();
if (ui == null)
return Redirect("Index");
else
{
CWFEngine.authority_params["currentuser"] = userName;
Session["User"] = ui;
return Redirect("/Main/Index");
}
}
}
}
}<file_sep>using EquipDAL.Implement;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class ZhiduManagment
{
private Zhidus Zs = new Zhidus();
public List<ZhiduFile> get_zhidu(int menuid)
{
List <ZhiduFile> E = Zs.get_zhidu(menuid);
return E;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlowEngine.Event;
using System.Xml;
using FlowEngine;
using FlowEngine.Param;
namespace XML_IO_TEST
{
class Program
{
static void Main(string[] args)
{
CWFEngine.CreateAWFEntityByName("test");
}
}
}
<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Menus : BaseDAO, IMenus
{
public EquipModel.Entities.Menu GetMenu(int id)
{
using(var db = base.NewDB())
{
return db.Sys_Menus.Where(a => a.Menu_Id == id).First();
}
}
public List<EquipModel.Entities.Menu> GetMenu(string name)
{
using (var db = base.NewDB())
{
return db.Sys_Menus.Where(a => a.Menu_Name == name).OrderBy(a => a.Menu_Name).ToList();
}
}
public List<EquipModel.Entities.Menu> GetChildMenu(int id)
{
using (var db = base.NewDB())
{
var menu = db.Sys_Menus.Where(a => a.Menu_Id == id).First();
return menu.child_menus.ToList();
}
}
public List<EquipModel.Entities.Menu> GetChildMenu(string name)
{
using (var db = base.NewDB())
{
var menu = db.Sys_Menus.Where(a => a.Menu_Name == name).First();
return menu.child_menus.ToList();
}
}
public bool AddMenu(int parentID, Menu newMenu)
{
using (var db = base.NewDB())
{
try
{
Menu parent = db.Sys_Menus.Where(a => a.Menu_Id == parentID).First();
if (parent == null)
return false;
parent.child_menus.Add(newMenu);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool DeleteMenu(int id)
{
using (var db = base.NewDB())
{
try
{
var menu = db.Sys_Menus.Where(a => a.Menu_Id == id).First();
if (menu == null)
return true;
foreach (var child in menu.child_menus)
{
DeleteMenu(child.Menu_Id);
}
db.Sys_Menus.Remove(menu);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool ModifyMenu(int id, EquipModel.Entities.Menu nVal)
{
using (var db = base.NewDB())
{
try
{
var menu = db.Sys_Menus.Where(a => a.Menu_Id == id).First();
if (menu == null)
return false;
menu.Menu_Name = nVal.Menu_Name;
menu.Menu_Icon = nVal.Menu_Icon;
menu.Link_Url = nVal.Link_Url;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
}
}
<file_sep>using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.TimerManage
{
public class CTimerNormalMission : CTimerMission
{
#region 构造函数
public CTimerNormalMission()
{
type = "Normal";
// status = TM_STATUS.TM_STATUS_STOP;
}
#endregion
/// <summary>
/// 解析运行结果
/// </summary>
/// <returns></returns>
public override object ParseRunResultToJobject()
{
throw new NotImplementedException();
}
/// <summary>
/// 解析运行结果
/// </summary>
/// <param name="strResult"></param>
public override void ParseRunResult(string strResult)
{
//throw new NotImplementedException();
}
public override void ParseRunParam(string strPars)
{
return;
}
public override object ParseRunParamsToJObject()
{
return null;
}
#region 公共方法
public override void Save(Timer_Jobs job = null)
{
Timer_Jobs job1 = new Timer_Jobs();
job1.Job_Type = TIMER_JOB_TYPE.Normal;
base.Save(job1);
}
#endregion
private void AfterCreate()
{
string custom_param = "";
base.CallCustomAction(custom_param);
}
protected override void __processing()
{
AfterCreate();
}
}
}
<file_sep>using EquipBLL.AdminManagment.MenuConfig;
using EquipBLL.AdminManagment;
using EquipModel.Entities;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
namespace WebApp.Controllers
{
public class EquipArchiController : Controller
{
private EquipArchiManagment menuconfig = new EquipArchiManagment();
// GET: SysMenu
public ActionResult Index()
{
return View();
}
[HttpPost]
public string test()
{
List<MenuListNode1> mt = menuconfig.BuildMenuList();
string str = JsonConvert.SerializeObject(mt);
return "{" +
"\"data\": " + str +
"}";
}
[HttpPost]
public JsonResult Modifyitem(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
Equip_Archi new_menu = new Equip_Archi();
new_menu.EA_Id = Convert.ToInt32(item["EA_Id"].ToString());
new_menu.EA_Name = item["EA_Name"].ToString();
new_menu.EA_Code = item["EA_Code"].ToString();
new_menu.EA_Title = item["EA_Title"].ToString();
bool res = menuconfig.ModifyEquipArchiItem(new_menu);
return Json(new { result = res });
}
[HttpPost]
public JsonResult Additem(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
Equip_Archi new_menu = new Equip_Archi();
new_menu.EA_Id = Convert.ToInt32(item["EA_Id"].ToString());
new_menu.EA_Name = item["EA_Name"].ToString();
new_menu.EA_Code = item["EA_Code"].ToString();
new_menu.EA_Title = item["EA_Title"].ToString();
bool res = menuconfig.AddEquipArchiItem(Convert.ToInt32(item["Parent_id"].ToString()), new_menu);
return Json(new { result = res });
}
[HttpPost]
public JsonResult Deleteitem(string del)
{
bool res = menuconfig.DeleteEquipArchiItem(Convert.ToInt32(del));
return Json(new { result = res });
}
}
}<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Zy : BaseDAO, ISpecialty
{
public Speciaty_Info GetSpecialty(int id)
{
using (var db = base.NewDB())
{
return db.Specialties.Where(a => a.Specialty_Id == id).First();
}
}
public List<EquipModel.Entities.Speciaty_Info> GetSpecialty(string name)
{
using (var db = base.NewDB())
{
return db.Specialties.Where(a => a.Specialty_Name == name).OrderBy(a => a.Specialty_Name).ToList();
}
}
public List<EquipModel.Entities.Speciaty_Info> GetChildSpecialty(int id)
{
using (var db = base.NewDB())
{
var zy = db.Specialties.Where(a => a.Specialty_Id == id).First();
return zy.Speciaty_Childs.ToList();
}
}
public List<EquipModel.Entities.Speciaty_Info> GetChildSpecialty(string name)
{
using (var db = base.NewDB())
{
var zy = db.Specialties.Where(a => a.Specialty_Name == name).First();
return zy.Speciaty_Childs.ToList();
}
}
public bool AddSpecialty(int parentID, Speciaty_Info newZy)
{
using (var db = base.NewDB())
{
try
{
Speciaty_Info parent = db.Specialties.Where(a => a.Specialty_Id == parentID).First();
if (parent == null)
return false;
parent.Speciaty_Childs.Add(newZy);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool DeleteSpecialty(int id)
{
using (var db = base.NewDB())
{
try
{
var Zy = db.Specialties.Where(a => a.Specialty_Id == id).First();
if (Zy == null)
return true;
foreach (var child in Zy.Speciaty_Childs)
{
DeleteSpecialty(child.Specialty_Id);
}
db.Specialties.Remove(Zy);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool ModifySpecialty(int id, Speciaty_Info nVal)
{
using (var db = base.NewDB())
{
try
{
var zy = db.Specialties.Where(a => a.Specialty_Id == id).First();
if (zy == null)
return false;
zy.Specialty_Name= nVal.Specialty_Name;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
}
}
<file_sep>using EquipBLL.AdminManagment.ZyConfig;
using EquipBLL.AdminManagment;
using EquipModel.Entities;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
namespace WebApp.Controllers
{
public class SpecialtyController : Controller
{
private SpeciatyManagment Zyconfig = new SpeciatyManagment();
// GET: Speciaty
public ActionResult Index()
{
return View();
}
[HttpPost]
public string test()
{
List<SpecialtyListNode> mt = Zyconfig.BuildSpeciatyList();
string str = JsonConvert.SerializeObject(mt);
return "{" +
"\"data\": " + str +
"}";
}
[HttpPost]
public JsonResult Modifyitem(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
Speciaty_Info new_specialty = new Speciaty_Info();
new_specialty.Specialty_Id = Convert.ToInt32(item["Specialty_Id"].ToString());
new_specialty.Specialty_Name = item["Specialty_Name"].ToString();
bool res = Zyconfig.ModifySpecialtyItem(new_specialty);
return Json(new { result = res });
}
[HttpPost]
public JsonResult Additem(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
Speciaty_Info new_specialty = new Speciaty_Info();
new_specialty.Specialty_Id = Convert.ToInt32(item["Specialty_Id"].ToString());
new_specialty.Specialty_Name = item["Specialty_Name"].ToString();
bool res = Zyconfig.AddSpecialtyItem(Convert.ToInt32(item["Parent_id"].ToString()), new_specialty);
return Json(new { result = res });
}
[HttpPost]
public JsonResult Deleteitem(string del)
{
bool res = Zyconfig.DeleteSpecialtyItem(Convert.ToInt32(del));
return Json(new { result = res });
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
namespace WebApp.Controllers
{
public class A6dot2dot1Controller : CommonController
{
public ActionResult Index()
{
return View(getIndexListRecords("A6dot2dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult Submit(string wfe_id)
{
return View(getRunhuaSubmitModel(wfe_id));
}
public ActionResult ConfirmRectified(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult PqDirectorConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
/// <summary>
/// 提报不完好润滑间
/// </summary>
/// <param name="json1"></param>
/// <returns></returns>
public string Submit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["RH_Name"] = item["Cj_Name"].ToString();
signal["ProblemDesc"] = item["Problem_Desc"].ToString();
signal["Equip_GyCode"] = "";
signal["Submit_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2dot1/Index");
}
/// <summary>
/// 润滑间确认整改提交
/// </summary>
/// <param name="json1"></param>
/// <returns></returns>
public string ConfirmRectified_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ConfirmRectified_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2dot1/Index");
}
/// <summary>
/// 片区主任核实提交
/// </summary>
/// <param name="json1"></param>
/// <returns></returns>
public string PqDirectorConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqDirectorConfirm_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2dot1/Index");
}
}
}<file_sep>///////////////////////////////////////////////////////////
// WorkFlowContext.cs
// Implementation of the Class WorkFlowContext
// Generated by Enterprise Architect
// Created on: 13-11月-2015 14:09:41
// Original author: Chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
namespace FlowEngine.Modals {
public class WorkFlowContext : DbContext
{
public WorkFlowContext()
{
}
~WorkFlowContext(){
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Mission>().HasMany(p => p.next_Mission).WithOptional(p => p.pre_Mission);
modelBuilder.Entity<CURR_Mission>().HasRequired(p => p.WFE_Parent).WithMany(p => p.Curr_Mission).HasForeignKey(p => p.WFE_ID);
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// 工作流定义表
/// </summary>
public DbSet<WorkFlow_Define> workflow_define{
get;
set;
}
/// <summary>
/// 工作流实体表
/// </summary>
public DbSet<WorkFlow_Entity> workflow_entities{
get;
set;
}
/// <summary>
/// 工作流已完成的任务
/// </summary>
public DbSet<Mission> mission{
get;
set;
}
/// <summary>
/// 过程记录的Record信息
/// </summary>
public DbSet<Process_Record> process_records{
get;
set;
}
/// <summary>
/// 过程记录的变量的值
/// </summary>
public DbSet<Mission_Param> process_parms
{
get;
set;
}
public DbSet<CURR_Mission> current_mission
{
get;
set;
}
public DbSet<Timer_Jobs> timer_jobs
{
get;
set;
}
}//end WorkFlowContext
}//end namespace FlowEngine.Modals<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A14dot1Controller : CommonController
{
//
// GET: /A14dot1/
public ActionResult Index()
{
return View(getIndexListRecords("A14dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A14dot1/可靠性工程师提报DRBPM计划
public ActionResult PqSubmitDRBPM(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A14dot1/维修单位审核,提出检修方案
public ActionResult JxdwConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A14dot1/机动处批准
public ActionResult JdcConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A14dot1/跳转到A8.2
public ActionResult JumpToA8dot2(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//GET: /A14dot1/工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string PqSubmitDRBPM_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqSubmitDRBPM_done"] = "true";
signal["PqConfirm_Result"] = "是";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Data_Src"] = item["Data_Src"].ToString();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
//string filename = Path.Combine(Request.MapPath("~/Upload"),item["Plan_DescFilePath"].ToString());
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot1/Index");
}
public string JxdwConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxdwConfirm_done"] = item["JxdwConfirm_done"].ToString();
signal["JxdwConfirm_Result"] = item["JxdwConfirm_Result"].ToString();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot1/Index");
}
public string JdcConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JdcConfirm_done"] = item["JdcConfirm_done"].ToString();
signal["JdcConfirm_Result"] = item["JdcConfirm_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot1/Index");
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System.Collections.Specialized;
using WebApp.Models.DateTables;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A14dot3dot3Controller : CommonController
{
//月度计划人工提报
public ActionResult SubmitJxPlan(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["SubmitJxPlan_Done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
signal["Plan_Name"] = item["Plan_Name"].ToString();
signal["JxCauseDesc"] = item["JxCauseDesc"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot3/Index");
}
private List<KeyValuePair<string, string>> ParsePostForm(NameValueCollection Form)
{
var list = new List<KeyValuePair<string, string>>();
if (Form != null)
{
foreach (var f in Form.AllKeys)
{
list.Add(new KeyValuePair<string, string>(f, Form[f]));
}
}
return list;
}
private DtResponse ProcessRequest(List<KeyValuePair<string, string>> data)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
var Data = http["data"] as Dictionary<string, object>;
int wfe_id = -1;
foreach (var d in Data)
{
wfe_id = Convert.ToInt32(d.Key);
}
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
foreach (var dd in d.Value as Dictionary<string, object>)
{
Dictionary<string, string> signal = new Dictionary<string, string>();
ERPInfoManagement erp = new ERPInfoManagement();
if (dd.Key == "kkconfirm1")
{
if (dd.Value.ToString() == "")
break;
string[] result = dd.Value.ToString().Split(new char[] { '$' });
signal["KkConfirm_Result"] = result[0];
if (result.Length > 1)
signal["KkConfirm_Reason"] = result[1];
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "zytdconfirm1")
{
if (dd.Value.ToString() == "")
continue;
string[] result = dd.Value.ToString().Split(new char[] { '$' });
signal["ZytdConfirm_Result"] = result[0];
if (result.Length > 1)
signal["ZytdConfirm_Reason"] = result[1];
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "notice_order1")
{
if (dd.Value.ToString() == "")
continue;
signal["NoticeOrder"] = "00" + dd.Value.ToString();
GD_InfoModal res = erp.getGD_Modal_Notice("00" + dd.Value.ToString());
if (res != null)
signal["JobOrder"] = res.GD_Id;
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "job_order1")
{
if (dd.Value.ToString() == "")
continue;
signal["JobOrder"] = "00" + dd.Value.ToString();
GD_InfoModal res = erp.getGD_Modal_GDId("00" + dd.Value.ToString());
if (res != null)
signal["NoticeOrder"] = res.GD_Notice_Id;
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
//if (dd.Key == "JumpA8dot2")
//{
// //补充跳转A8dot2的变量,Cj_Name,Zy_Type,Zy_SubType
// Dictionary<string, object> paras1 = new Dictionary<string, object>();
// paras1["Zz_Name"] = null;
// paras1["Equip_GyCode"] = null;
// paras1["Equip_Code"] = null;
// paras1["Plan_Name"] = null;
// UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(id, paras1);
// //获取设备专业类别和子类别及设备所属车间
// EquipManagment tm = new EquipManagment();
// Equip_Info getZy = tm.getEquip_ByGyCode(paras1["Equip_GyCode"].ToString());
// signal["Zy_Type"] = getZy.Equip_Specialty;
// signal["Zy_SubType"] = getZy.Equip_PhaseB;
// signal["Equip_Type"] = getZy.Equip_Type;
// //EA_Name_EA_Id= tm.getEquip(paras1["Zz_Name"].ToString()).EA_Parent.EA_Id;
// signal["Cj_Name"] = tm.getEquip(paras1["Zz_Name"].ToString());
// signal["Plan_Name"] = paras1["Plan_Name"].ToString();
// signal["JxdwAttachPlanOrder_Done"] = dd.Value.ToString();
// //record
// Dictionary<string, string> record1 = new Dictionary<string, string>();
// record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// record1["time"] = DateTime.Now.ToString();
// //submit
// CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
//}
}
}
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
paras["Equip_GyCode"] = null;
paras["Equip_Code"] = null;
paras["Equip_Type"] = null;
paras["Equip_ABCMark"] = null;
paras["Plan_Name"] = null;
paras["JxCauseDesc"] = null;
paras["KkConfirm_Result"] = null;
paras["ZytdConfirm_Result"] = null;
paras["JobOrder"] = null;
paras["NoticeOrder"] = null;
if (wfe_id != -1)
{
WorkFlows wfsd = new WorkFlows();
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(wfe_id, paras);
Dictionary<string, object> m_kv = new Dictionary<string, object>();
Mission db_miss = wfsd.GetWFEntityMissions(wfe_id).Last();//获取该实体最后一个任务
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
m_kv["index_Id"] = wfe_id;
m_kv["zz_name"] = paras["Zz_Name"].ToString();
m_kv["sb_gycode"] = paras["Equip_GyCode"].ToString();
m_kv["sb_code"] = paras["Equip_Code"].ToString();
m_kv["sb_type"] = paras["Equip_Type"].ToString();
m_kv["sb_ABCMark"] = paras["Equip_ABCMark"].ToString();
m_kv["plan_name"] = paras["Plan_Name"].ToString();
m_kv["jxreason"] = paras["JxCauseDesc"].ToString();
m_kv["kkconfirm1"] = paras["KkConfirm_Result"].ToString();
m_kv["zytdconfirm1"] = paras["ZytdConfirm_Result"].ToString();
m_kv["job_order1"] = paras["JobOrder"].ToString();
m_kv["notice_order1"] = paras["NoticeOrder"].ToString();
m_kv["missionname"] = db_miss.Miss_Desc;
m_kv["role"] = pv.Role_Names;
dt.data.Add(m_kv);
}
return dt;
}
public JsonResult PostChanges()
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = ProcessRequest(list);
return Json(dtRes);
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using FlowEngine.Modals;
using FlowEngine.DAL;
using FlowEngine.Param;
namespace WebApp.Controllers
{
public class A14dot3dot1Controller : CommonController
{
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult PlanSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult EquipFilter(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string PlanSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["WorkDetail"] = item["WorkDetail"].ToString();
signal["Equip_GyCode"] = "";
signal["PlanSubmit_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot3/Index");
}
public class EquipListModel
{
public int Equip_Id;
public string Equip_GyCode;
public string Equip_Code;
public string Equip_Type;
public string Equip_Specialty;
public string Equip_ABCMark;
}
public string get_equip_info(string wfe_id)
{
WorkFlows wfsd = new WorkFlows();
Mission db_miss = wfsd.GetWFEntityMissions(Convert.ToInt16(wfe_id)).Last();//获取该实体最后一个任务
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(Convert.ToInt16(wfe_id));
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui = new UI_MISSION();
ui.WE_Entity_Ser = wfe.WE_Ser;
ui.WE_Event_Desc = db_miss.Miss_Desc;
ui.WE_Event_Name = db_miss.Event_Name;
ui.WE_Name = db_miss.Miss_Name;
ui.Mission_Url = ""; //历史任务的页面至空
ui.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui.Miss_Params[cp.name] = cp.value;
ui.Miss_ParamsDesc[cp.name] = cp.description;
}
List<EquipListModel> EquipList = Zz_Equips(ui.Miss_Params["Zz_Name"].ToString());
List<object> miss_obj = new List<object>();
int i = 1;
foreach (var item in EquipList)
{
object m = new
{
index = i,
Equip_Id = item.Equip_Id,
Equip_GyCode = item.Equip_GyCode,
Equip_Code = item.Equip_Code,
Equip_Type = item.Equip_Type,
Equip_Specialty = item.Equip_Specialty,
Equip_ABCMark = item.Equip_ABCMark
};
miss_obj.Add(m);
i++;
}
string str = JsonConvert.SerializeObject(miss_obj);
return ("{" + "\"data\": " + str + "}");
}
public List<EquipListModel> Zz_Equips(string Zz_id)
{
EquipManagment pm = new EquipManagment();
List<Equip_Info> Equips_of_Zz = new List<Equip_Info>();
List<EquipListModel> Equip_obj = new List<EquipListModel>();
string[] Zhuangzhi_id = Zz_id.Split(',');
for (int i = 0; i < Zhuangzhi_id.Length; i++)
{
Equips_of_Zz = pm.getEquips_OfZz(Convert.ToInt32(Zhuangzhi_id[i]));
foreach (var item in Equips_of_Zz)
{
EquipListModel io = new EquipListModel();
io.Equip_Id = item.Equip_Id;
io.Equip_GyCode = item.Equip_GyCode;
io.Equip_Code = item.Equip_Code;
io.Equip_Type = item.Equip_Type;
io.Equip_Specialty = item.Equip_Specialty;
io.Equip_ABCMark = item.Equip_ABCmark;
Equip_obj.Add(io);
}
}
return Equip_obj;
}
public string EquipFilter_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["EquipFilter_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A14dot3/Index");
}
}
}<file_sep>using FlowEngine;
using FlowEngine.Modals;
using FlowEngine.UserInterface;
using MVCTest.Models;
using MVCTest.Models.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Objects;
using System.Data.Entity.Infrastructure;
using FlowEngine.DAL;
namespace MVCTest.Controllers
{
public class MainController : Controller
{
public class MainModel
{
public List<UI_WF_Define> wfs;
public List<UI_MISSION> miss;
}
// GET: Main
public ActionResult Index()
{
MainModel mm = new MainModel();
mm.wfs = CWFEngine.ListAllWFDefine();
mm.miss = CWFEngine.GetActiveMissions<UserInfo>(((IObjectContextAdapter)(new UserContext())).ObjectContext);
return View(mm);
}
[HttpPost]
public string CreateFlow(string flowname)
{
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
if (wfe != null)
{
Dictionary<string, string> record = wfe.GetRecordItems();
if (record.ContainsKey("username"))
record["username"] = "cb";
if (record.ContainsKey("time"))
record["time"] = DateTime.Now.ToString();
return wfe.Start(record);
//Json(new { url = wfe.Start(record), wfe_id = wfe.EntityID });
//"{url:'" + wfe.Start(record) + "', wfe_id:'" + wfe.EntityID + "'}";
}
else
return null;
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A7dot1Controller : CommonController
{
//
// GET: /A7dot1/
public ActionResult Index()
{
return View(getIndexListRecords("A7dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A7dot1/装置提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A7dot1/美迅平台数据筛选
public ActionResult MxptSelect(string flowname)
{
//页面权限,现场工程师能处理
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_Role = pv.Role_Names;
return View(getA7dot1MxAlarm_Model()); //2016.6.22
}
//装置筛选美迅报警设备-自动提报到A13.1进行片区分类-2016.07.27
public string Auto_MxptSelect_submitsignalToA13dot1(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string Equip_Code = item["Equip_Code"].ToString();
string AlarmState = item["AlarmState"].ToString();
string flowname = "A13dot1";
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
if (wfe != null)
{
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(Equip_Code);
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
int flow_id = wfe.EntityID;
Dictionary<string, string> signal1 = new Dictionary<string, string>();
signal1["start_done"] = "true";
CWFEngine.SubmitSignal(flow_id, signal1, record);
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = Equip_ZzBelong[1].EA_Name; //Cj_Name
signal["Zz_Name"] = Equip_ZzBelong[0].EA_Name; //Zz_Name
signal["Equip_GyCode"] = eqinfo.Equip_GyCode;
signal["Equip_Code"] = eqinfo.Equip_Code;
signal["Equip_Type"] = eqinfo.Equip_Type;
signal["Zy_Type"] = eqinfo.Equip_Specialty;
signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
signal["Data_Src"] = "A7.1.3-美迅平台报警";
signal["Problem_Desc"] = "美迅离线巡检平台显示设备报警状态等级:" + AlarmState;
signal["Problem_DescFilePath"] = "";
//record
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(flow_id, signal, record);
return ("/A7dot1/Index");
}
}
catch (Exception e)
{
return "";
}
return ("/A7dot1/Index");
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Problem_Desc"] = item["Problem_Desc"].ToString();
signal["Problem_DescFilePath"] = item["Problem_DescFilePath"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
signal["Data_Src"] = "S8000";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot1/Index");
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A7dot2Controller : CommonController
{
//
// GET: /A7dot2/
public ActionResult Index()
{
return View(getIndexListRecords("A7dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A7dot2/DRBPM系统输入(这里给一个人工提报功能;从DRBPM获取时,这步跳过)
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A7dot2/DRBMP平台数据筛选
public ActionResult DrbpmSelect(string flowname)
{
//return View(getA7dot2_Model()); //2016.7.25
string strTableName = "SbGyAnalysis";
string strWhere = "1=1";//
//页面权限,现场工程师能处理
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_Role = pv.Role_Names;
return View(getDRBPM_SbGyAnalysisList(strTableName, strWhere));//2016.7.25
}
// GET: /A7dot2/可靠性工程师确认
public ActionResult PqConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A7dot2/专业团队审核
public ActionResult ZytdConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A7dot2/车间提出改造方案
public ActionResult CjCreatePlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A7dot2/跳转到A12.2,工艺变更管理
public ActionResult JumpToA12dot2(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A7dot2/跳转到A4.1,重新选型(设计)
public ActionResult JumpToA4dot1(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//GET: /A7dot2/工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
signal["Data_Src"] = "";
signal["Problem_Desc"] = item["Problem_Desc"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
//signal["Equip_ABCMark"] = "A";//for test
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot2/Index");
}
//DRBPM平台低能效机泵-筛选-自动提报-2016.07.25
public string Auto_ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string Equip_Code = item["Equip_Code"].ToString();
//string Problem_Desc = item["gyState_PMGList"].ToString();
string flowname = "A7dot2";
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
if (wfe != null)
{
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(Equip_Code);
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
int flow_id = wfe.EntityID;
Dictionary<string, string> signal1 = new Dictionary<string, string>();
signal1["start_done"] = "true";
CWFEngine.SubmitSignal(flow_id, signal1, record);
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = Equip_ZzBelong[1].EA_Name; //Cj_Name
signal["Zz_Name"] = Equip_ZzBelong[0].EA_Name; //Zz_Name
signal["Equip_GyCode"] = eqinfo.Equip_GyCode;
signal["Equip_Code"] = eqinfo.Equip_Code;
signal["Equip_Type"] = eqinfo.Equip_Type;
signal["Zy_Type"] = eqinfo.Equip_Specialty;
signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
signal["Data_Src"] = "DRBPM平台低能效机泵";
signal["Problem_Desc"] = GetGyStateDescription(item["gyState_PMGList"].ToString(), true);
//record
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(flow_id, signal, record);
return ("/A7dot2/Index");
}
}
catch (Exception e)
{
return "";
}
return ("/A7dot2/Index");
}
public string PqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirm_Result"] = item["PqConfirm_Result"].ToString();
signal["PqConfirm_Reason"] = item["PqConfirm_Reason"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot2/Index");
}
public string ZytdConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirm_Result"] = item["ZytdConfirm_Result"].ToString();
signal["ZytdConfirm_Reason"] = item["ZytdConfirm_Reason"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot2/Index");
}
public string CjCreatePlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CjCreatePlan_done"] = "true";
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot2/Index");
}
// GET: /A7dot2/装置申请工艺变更(补充变更方案)
public ActionResult ZzAddPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string ZzAddPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzAddPlan_done"] = "true";
signal["GyChangePlan_Desc"] = item["Plan_Desc"].ToString();
signal["GyChangePlan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot2/Index");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class jingmodel
{
public double? gzqdkf { get; set; }
//设备腐蚀泄漏次数
public double ?sbfsxlcs { get; set; }
//千台冷换设备管束
public double? qtlhsbgs { get; set; }
//工业炉平均热效效率
public double? gylpjrxl { get; set; }
//换热器检修率
public double? hrqjxl { get; set; }
//压力容器定检率
public double ?ylrqdjl { get; set; }
//压力管道年度检验计划完成率
public double? ylgdndjxjhwcl { get; set; }
//安全阀年度校验计划完成率
public double ?aqfndjyjhwcl { get; set; }
//设备腐蚀检测计划完成率
public double? sbfsjcjhwcl { get; set; }
//静设备检维修一次合格率
public double? jsbjwxychgl { get; set; }
}
}
<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Person_Infos : BaseDAO, IPerson_Infos
{
public class PersonModal
{
public Person_Info P_Info;//用户基本信息
public Depart_Archi D_Info;//部门信息
public List<Equip_Archi> EA_Info;
public List<Speciaty_Info> S_Info;//专业信息
public List<Role_Info> R_Info;//角色信息
public List<Menu> M_Info;//系统菜单信息
}
public Person_Info GetPerson_info(int id)
{
try
{
using (var db = base.NewDB())
{
return db.Persons.Where(a => a.Person_Id == id).First();
}
}
catch (Exception e)
{ return null; }
}
public List<Equip_Archi> getZz_of_Person(int Person_Id, int cj_id)
{
using (var db = base.NewDB())
{
try
{
//Equip_Archi EA = new Equip_Archi();
Equip_Archi EA;
List<Equip_Archi> EA_list = new List<Equip_Archi>();
// var EA_Set = db.EArchis.Where(a => a.EA_Title == "车间" && a.EA_Childs.Where(s => s.Equips_Belong.Where(t => t.Equip_Manager.Where(b => b.Person_Id == Person_Id).Count() > 0).Count() > 0).Count() > 0);
var EA_Set = db.EArchis.Where(a => a.EA_Title == "装置" && a.EA_Parent.EA_Id == cj_id && a.Equips_Belong.Where(t => t.Equip_Manager.Where(b => b.Person_Id == Person_Id).Count() > 0).Count() > 0);
foreach (var item in EA_Set)
{
EA = new Equip_Archi();
EA.EA_Id = item.EA_Id;
EA.EA_Name = item.EA_Name;
EA.EA_Code = item.EA_Code;
EA.EA_Title = item.EA_Title;
EA_list.Add(EA);
}
return EA_list;
}
catch { return null; }
}
}
public Person_Info GetPerson_info(string Person_Name)
{
try
{
using (var db = base.NewDB())
{
return db.Persons.Where(a => a.Person_Name == Person_Name).First();
}
}
catch (Exception e)
{ return null; }
}
public PersonModal Get_PersonModal(int userId)
{
try
{
PersonModal PM = new PersonModal();
using (var db = base.NewDB())
{
PM.P_Info = db.Persons.Where(a => a.Person_Id == userId).First();
PM.D_Info = PM.P_Info.Dept_Belong;
PM.R_Info = PM.P_Info.Person_roles.ToList();
PM.S_Info = PM.P_Info.Person_specialties.ToList();
PM.EA_Info = PM.P_Info.Person_EquipEAs.ToList();
PM.M_Info = PM.P_Info.Person_Menus.ToList();
return PM;
}
}
catch (Exception e)
{ return null; }
}
public List<Person_Info> GetAllPerson_info()
{
try
{
using (var db = base.NewDB())
{
return db.Persons.ToList();
}
}
catch (Exception e)
{ return null; }
}
public List<Role_Info> GetPerson_Roles(int id)
{
using (var db = base.NewDB())
{
var P = db.Persons.Where(a => a.Person_Id == id).First();
return P.Person_roles.ToList();
}
}
public List<Equip_Archi> getEA_of_Person(int Person_Id)
{
using (var db = base.NewDB())
{
try
{
//Equip_Archi EA = new Equip_Archi();
Equip_Archi EA;
List<Equip_Archi> EA_list = new List<Equip_Archi>();
var EA_Set = db.EArchis.Where(a => a.EA_Title == "车间" && a.EA_Childs.Where(s => s.Equips_Belong.Where(t => t.Equip_Manager.Where(b => b.Person_Id == Person_Id).Count() > 0).Count() > 0).Count() > 0);
foreach (var item in EA_Set)
{
EA = new Equip_Archi();
EA.EA_Id = item.EA_Id;
EA.EA_Name = item.EA_Name;
EA.EA_Code = item.EA_Code;
EA.EA_Title = item.EA_Title;
EA_list.Add(EA);
}
return EA_list;
}
catch { return null; }
}
}
public List<Equip_Info> GetPerson_Equips(int id)
{
using (var db = base.NewDB())
{
var P = db.Persons.Where(a => a.Person_Id == id).First();
return P.Person_Equips.ToList();
}
}
public Depart_Archi GetPerson_Depart(int id)
{
using (var db = base.NewDB())
{
var P = db.Persons.Where(a => a.Person_Id == id).First();
return P.Dept_Belong;
}
}
public List<Menu> GetPerson_Menus(int id)
{
using (var db = base.NewDB())
{
var p = db.Persons.Where(a => a.Person_Id == id).First();
return p.Person_Menus.ToList();
}
}
public bool AddRole(int Person_id, int Role_id)
{
using (var db = base.NewDB())
{
try
{
var P = db.Persons.Where(a => a.Person_Id == Person_id).First();
var PR = db.Roles.Where(a => a.Role_Id == Role_id).First();
P.Person_roles.Add(PR);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool AddEquip(int Person_id, int Equip_id)
{
using (var db = base.NewDB())
{
try
{
var P = db.Persons.Where(a => a.Person_Id == Person_id).First();
var E = db.Equips.Where(a => a.Equip_Id == Equip_id).First();
P.Person_Equips.Add(E);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public int AddPerson_info(Person_Info New_Person)
{
try
{
using (var db = base.NewDB())
{
Person_Info newP = db.Persons.Add(New_Person);
db.SaveChanges();
return newP.Person_Id;
}
}
catch
{
return 0;
}
}
public bool Person_LinkRole(int Person_id, List<int> Role_ids)
{
try
{
using (var db = base.NewDB())
{
var p = db.Persons.Where(s => s.Person_Id == Person_id).First();
var pr_old = p.Person_roles.ToList();
if (pr_old.Count > 0)
{
p.Person_roles.Clear();
}
foreach (var item in Role_ids)
{
var r = db.Roles.Where(s => s.Role_Id == item).First();
p.Person_roles.Add(r);
}
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool Person_LinkDepart(int Person_id, int Depart_id)
{
try
{
using (var db = base.NewDB())
{
var p = db.Persons.Where(s => s.Person_Id == Person_id).First();
var r = db.Department.Where(s => s.Depart_Id == Depart_id).First();
p.Dept_Belong = r;
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool Person_LinkSpeciaties(int Person_id, List<int> Speciaty_IDs)
{
try
{
using (var db = base.NewDB())
{
var p = db.Persons.Where(s => s.Person_Id == Person_id).First();
var ps_old = p.Person_specialties.ToList();
if (ps_old.Count > 0)
{
p.Person_specialties.Clear();
}
foreach (var item in Speciaty_IDs)
{
Speciaty_Info r = db.Specialties.Where(s => s.Specialty_Id == item).First();
p.Person_specialties.Add(r);
}
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool Person_LinkEAs(int Person_id, List<int> EquipArchi_IDs)
{
try
{
using (var db = base.NewDB())
{
var p = db.Persons.Where(s => s.Person_Id == Person_id).First();
var ps_old = p.Person_EquipEAs.ToList();
if (ps_old.Count > 0)
{
p.Person_EquipEAs.Clear();
}
foreach (var item in EquipArchi_IDs)
{
Equip_Archi r = db.EArchis.Where(s => s.EA_Id == item).First();
p.Person_EquipEAs.Add(r);
}
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool Person_LinkEquip(int Person_id, List<int> EquipArchi_IDs, List<int> Speciaty_IDs)
{
try
{
using (var db = base.NewDB())
{
var p = db.Persons.Where(s => s.Person_Id == Person_id).First();
var pr_old = p.Person_Equips.ToList();
if (pr_old.Count > 0)
{
p.Person_Equips.Clear();
}
var r = db.Specialties.Where(s => Speciaty_IDs.Where(m => m == s.Specialty_Id).Count() > 0);
if (Person_id == 36 && Person_id == 1)
{
List<Equip_Info> e = db.Equips.Where(s => ((r.Where(rr => rr.Speciaty_Parent.Specialty_Name == s.Equip_Specialty && rr.Specialty_Name == s.Equip_PhaseB)).Count() > 0) && (EquipArchi_IDs.Where(t => (s.Equip_Location).EA_Id == t).Count() > 0)).ToList();
foreach (var eitem in e)
{ p.Person_Equips.Add(eitem); }
e = db.Equips.Where(s => ((r.Where(rr => rr.Speciaty_Parent.Specialty_Name == "root" && rr.Specialty_Name != "动" && rr.Specialty_Name == s.Equip_Specialty)).Count() > 0) && (EquipArchi_IDs.Where(t => (s.Equip_Location).EA_Id == t).Count() > 0)).ToList();
foreach (var eitem1 in e)
{ p.Person_Equips.Add(eitem1); }
}
else
{
List<Equip_Info> e = db.Equips.Where(s => (s.Equip_Specialty == "动" && (r.Where(rr => rr.Speciaty_Parent.Specialty_Name == s.Equip_Specialty && rr.Specialty_Name == s.Equip_PhaseB)).Count() > 0) && (EquipArchi_IDs.Where(t => (s.Equip_Location).EA_Id == t).Count() > 0)).ToList();
foreach (var eitem in e)
{ p.Person_Equips.Add(eitem); }
e = db.Equips.Where(s => (s.Equip_Specialty != "动" && (r.Where(rr => rr.Specialty_Name == s.Equip_Specialty)).Count() > 0) && (EquipArchi_IDs.Where(t => (s.Equip_Location).EA_Id == t).Count() > 0)).ToList();
foreach (var eitem in e)
{ p.Person_Equips.Add(eitem); }
}
db.SaveChanges();
return true;
}
}
catch (Exception e)
{
return false;
}
}
public bool Person_LinkMenus(int Person_id, List<int> Menu_IDs)
{
try
{
using (var db = base.NewDB())
{
var p = db.Persons.Where(s => s.Person_Id == Person_id).First();
var pr_old = p.Person_Menus.ToList();
if (pr_old.Count > 0)
{
p.Person_Menus.Clear();
}
foreach (var item in Menu_IDs)
{
Menu r = db.Sys_Menus.Where(s => s.Menu_Id == item).First();
p.Person_Menus.Add(r);
}
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool DeletePerson_info(int id)
{
using (var db = base.NewDB())
{
try
{
var P = db.Persons.Where(a => a.Person_Id == id).First();
if (P == null)
return false;
else
{
// P.Person_Equips.Clear();
// P.Person_Menus.Clear();
// P.Person_specialties.Clear();
// P.Person_roles.Clear();
db.Persons.Remove(P);
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
public bool ModifyPerson_info(Person_Info New_Person)
{
using (var db = base.NewDB())
{
try
{
var P = db.Persons.Where(a => a.Person_Id == New_Person.Person_Id).First();
if (P == null)
return false;
else
{
P.Person_Name = New_Person.Person_Name;
// P.Person_Pwd = New_Person.Person_Pwd;
P.Person_tel = New_Person.Person_tel;
P.Person_mail = New_Person.Person_mail;
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
public int isAdmin(string username)
{
using (var db = base.NewDB())
{
var P = db.Persons.Where(a => a.Person_Name == username && a.Person_roles.Where(r => r.Role_Name == "系统管理员").Count() > 0).Count();
if (P > 0)
return 1;
else
return 0;
}
}
public bool ModifyPerson_Pwd(string userName, byte[] userPwd)
{
using (var db = base.NewDB())
{
try
{
var P = db.Persons.Where(a => a.Person_Name == userName).First();
P.Person_Pwd = <PASSWORD>Pwd;
db.SaveChanges();
return true;
}
catch { return false; }
}
}
public Person_Info GetPerson_info(string Person_Name, byte[] Person_pwd)
{
try
{
using (var db = base.NewDB())
{
return db.Persons.Where(a => a.Person_Name == Person_Name && a.Person_Pwd == Person_pwd).First();
}
}
catch (Exception e)
{ return null; }
}
public string Get_PqnamebyCjname(string CjName)
{
try
{
using (var db = base.NewDB())
{
var p = db.Department.Where(a => a.Depart_Name == CjName).First().Depart_Parent.Depart_Name;
return p;
}
}
catch (Exception e)
{ return ""; }
}
/// <summary>
/// 16/9/8新增,获取润滑油间列表,尚未区分权限,此表为独立的表,未与人员表关联
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public List<Runhua_Info> getRunhuaCj()
{
using (var db = base.NewDB())
{
try
{
//Equip_Archi EA = new Equip_Archi();
Runhua_Info EA;
List<Runhua_Info> EA_list = new List<Runhua_Info>();
var EA_Set = db.Runhua;
foreach (var item in EA_Set)
{
EA = new Runhua_Info();
EA.Runhua_Id = item.Runhua_Id;
EA.EA_Name = item.EA_Name;
EA.RH_Name = item.RH_Name;
EA.RH_ZZ_Name = item.RH_ZZ_Name;
EA.RH_Detail = item.RH_Detail;
EA_list.Add(EA);
}
return EA_list;
}
catch { return null; }
}
}
public List<Equip_Archi> getZzByPerson(int Person_Id)
{
using (var db = base.NewDB())
{
try
{
//Equip_Archi EA = new Equip_Archi();
Equip_Archi EA;
List<Equip_Archi> EA_list = new List<Equip_Archi>();
// var EA_Set = db.EArchis.Where(a => a.EA_Title == "车间" && a.EA_Childs.Where(s => s.Equips_Belong.Where(t => t.Equip_Manager.Where(b => b.Person_Id == Person_Id).Count() > 0).Count() > 0).Count() > 0);
var EA_Set = db.EArchis.Where(a => a.EA_Title == "装置" && a.Equips_Belong.Where(t => t.Equip_Manager.Where(b => b.Person_Id == Person_Id).Count() > 0).Count() > 0);
foreach (var item in EA_Set)
{
EA = new Equip_Archi();
EA.EA_Id = item.EA_Id;
EA.EA_Name = item.EA_Name;
EA.EA_Code = item.EA_Code;
EA.EA_Title = item.EA_Title;
EA_list.Add(EA);
}
return EA_list;
}
catch { return null; }
}
}
}
}
<file_sep>using EquipBLL.AdminManagment;
using EquipBLL.AdminManagment.MenuConfig;
using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp.Controllers
{
public class RoleManagerController : Controller
{
//
// GET: /Query/
private SysMenuManagment menuconfig = new SysMenuManagment();
public ActionResult Index()
{
// RoleManagment RM = new RoleManagment();
// List<Role_Info> r = RM.get_ALl_Roles();
return View();
}
// 新增角色信息时获取权限树
public JsonResult List_MenuTree()
{
RoleManagment RM = new RoleManagment();
List<TreeListNode> Menu_obj = RM.BuildMenuList();
return Json(Menu_obj.ToArray());
}
// 修改角色信息的时候获取树
public JsonResult List_R_MenuTree(string Role_Ids)
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> Menu_obj = DM.BuildMenuList(Role_Ids);
return Json(Menu_obj.ToArray());
}
// 新加角色时向数据库提交信息信息
public string submitNewRole(string json1)
{
try
{
RoleManagment PM = new RoleManagment();
Role_Info newR = new Role_Info();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
newR.Role_Name = item["Role_Name"].ToString();
newR.Role_Desc = item["Role_Desc"].ToString();
var MenuStr = item["RoleMenus"].ToString();
List<int> MenuList = new List<int>();
if (MenuStr != "")
{
string[] s1 = MenuStr.Split(new char[] { ',' });
for (int i = 0; i < s1.Length; i++)
{ MenuList.Add(Convert.ToInt32(s1[i])); }
}
PM.Add_Role(newR, MenuList); //保存基础信息
return "保存成功!";
}
catch { return ""; };
}
// 修改后的角色向数据库提交数据
public string submitUpdateRole(string json1)
{
try
{
RoleManagment PM = new RoleManagment();
Role_Info newR = new Role_Info();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
newR.Role_Id = Convert.ToInt32(item["Role_Id"].ToString()); //将string型转换成int型
newR.Role_Name = item["Role_Name"].ToString();
newR.Role_Desc = item["Role_Desc"].ToString();
var MenuStr = item["RoleMenus"].ToString();
List<int> MenuList = new List<int>();
if (MenuStr != "")
{
string[] s1 = MenuStr.Split(new char[] { ',' });
for (int i = 0; i < s1.Length; i++)
{ MenuList.Add(Convert.ToInt32(s1[i])); }
}
PM.Update_Role(newR, MenuList); //保存基础信息
return "用户信息修改成功!";
}
catch { return ""; };
}
// 显示历史角色信息
public string Role_History()
{
// JObject item = (JObject)JsonConvert.DeserializeObject(Role_Id);
RoleManagment RM = new RoleManagment();
List<Role_Info> R = RM.get_ALl_Roles();
List<object> r = new List<object>();
for(var i=0;i<R.Count;i++)
{
string m = null;
EquipBLL.AdminManagment.RoleManagment.Role_viewModal M_info = RM.Get_RoleModal(R[i].Role_Id);
if (M_info.Menus.Count > 0)
{
m = M_info.Menu_Names;
}
object o = new
{
index = i+1,
Role_Id=R[i].Role_Id.ToString(),
Role_Name = R[i].Role_Name.ToString(),
Role_Desc=R[i].Role_Desc.ToString(),
// Role_Menus=R[i].Role_Menus.ToString(),
// Role_Menu = RM.Get_RoleModal(R[i].Role_Id).Menus,
Role_Menus=m,
mod_Role = R[i].Role_Id.ToString(),
Role_Id_del = R[i].Role_Id.ToString(),
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
// 删除角色
public string delete_Role(string json1)
{
try
{
RoleManagment RM = new RoleManagment();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
int Role_Id = Convert.ToInt32(item["Role_Id"].ToString()); //将string型转换成int型
bool del = RM.Delete_Role(Role_Id);
if (del)
return "删除成功!";
else
return "删除失败!";
}
catch
{ return ""; };
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A12dot2Controller : CommonController
{
//
// GET: /A12dot2/
public ActionResult Index()
{
return View(getIndexListRecords("A12dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A12dot2/装置提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A12dot2/可靠性工程师审核提报
public ActionResult PqConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot2/调度处判断能否调整工艺避免变更
public ActionResult DdcJudge(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot2/跳转到A11.1风险评估
public ActionResult JumpToA11dot1(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot2/专业团队审核是否执行
public ActionResult ZytdConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot2/可靠性工程师确定是否需要设计委托
public ActionResult PqConfirmDesign(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot2/跳转到A4.1设备前期管理
public ActionResult JumpToA4dot1(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot2/跳转到A12.1本体改造
public ActionResult JumpToA12dot1(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot2/跳转到A3.3文件管理
public ActionResult JumpToA3dot3(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//GET: /A12dot2/工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
//signal["Data_Src"] = item["Data_Src"].ToString();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
//string filename = Path.Combine(Request.MapPath("~/Upload"),item["Plan_DescFilePath"].ToString());
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
signal["Nature"] = item["Nature"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot2/Index");
}
public string DdcJudge_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["DdcJudge_Result"] = item["DdcJudge_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot2/Index");
}
public string PqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirm_Result"] = item["PqConfirm_Result"].ToString();
signal["PqConfirm_Reason"] = item["PqConfirm_Reason"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot2/Index");
}
public string ZytdConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirm_Result"] = item["ZytdConfirm_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot2/Index");
}
public string PqConfirmDesign_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirmDesign_Result"] = item["PqConfirmDesign_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot2/Index");
}
// GET: /A12dot2/装置申请设备本体改造(补充改造方案)
public ActionResult ZzAddPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string ZzAddPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzAddPlan_done"] = "true";
signal["ModifyPlan_Desc"] = item["Plan_Desc"].ToString();
signal["ModifyPlan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot2/Index");
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using EquipBLL.FileManagment;
using FlowEngine.DAL;
using FlowEngine.Modals;
using FlowEngine.Param;
namespace WebApp.Controllers
{
public class A6dot1Controller : CommonController
{
public ActionResult A6()
{
string WE_Status = "0";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username";
string query_condition = "E.W_Name='A6dot2dot1" + "' and E.WE_Status='" + WE_Status + "' and R.username is not null";
string record_filter = "username is not null";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
ViewBag.CompleteCount = 18 - dt.Rows.Count;
return View();
}
public ActionResult Index()
{
return View(getIndexListRecords("A6dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult SBSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult NeedWrite(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UploadOperInstruction(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ModifyAndUpload(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult SBConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult SBJudge(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult JdcConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string A6guicheng()
{
List<EQ> list = new List<EQ>();//接收结果
List<object> r = new List<object>();//输出结果
A6dot2Managment tm = new A6dot2Managment();
list = tm.caozuoguicheng();
for (int i = 0; i < list.Count; i++)
{
EquipManagment zm = new EquipManagment();
//string zzname
object o = new
{
index = i + 1,
sbGyCode = list[i].sbGyCode,
sbCode = list[i].sbCode,
sbType = list[i].sbType,
GCnewname = Path.Combine("/Upload/A3dot3", list[i].GCnewname) + "$$" + list[i].GColdname
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string SBSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["SBSubmit_Done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot1/Index");
}
public string NeedWrite_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["NeedWrite_Result"] = item["NeedWrite_Result"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A6dot1/Index");
}
public string UploadOperInstruction_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["OperInstruction"] = item["OperInstruction"].ToString();
signal["UploadOperInstruction_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A6dot1/Index");
}
public string ModifyAndUpload_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["ModifyOperInstruc"] = item["ModifyOperaInstruc"].ToString();
signal["ModifyAndUpload_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A6dot1/Index");
}
public string SBConfirm_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
A6dot2Managment WM = new A6dot2Managment();
FileItem file = new FileItem();
int Equip_Id = 0;
//new input paras
signal["SBConfirm_Result"] = item["SBConfirm_Result"].ToString();
signal["SBSupplement"] = item["SBSupplement"].ToString();
if (signal["SBConfirm_Result"] == "通过")
{
//向File_Info里写文件信息
WorkFlows wfsd = new WorkFlows();
List<Mission> db_miss = wfsd.GetWFEntityMissions(Convert.ToInt32(flowname));//获取该实体的所有任务
for (int k = 0; k < db_miss.Count; k++)
{
if (db_miss[k].Miss_Desc == "设备主任判定是否为重要设备")
{
UI_MISSION ui_mi1 = new UI_MISSION();
List<Mission_Param> mis_pars1 = wfsd.GetMissParams(db_miss[k].Miss_Id);//获取当前任务参数
foreach (var par in mis_pars1)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi1.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi1.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
if (ui_mi1.Miss_Params["SBJudge_Result"].ToString() == "否")
{
for (int i = 0; i < db_miss.Count; i++)
{
if (db_miss[i].Miss_Desc == "可靠性工程师修改再上传")
{
UI_MISSION ui_mi = new UI_MISSION();
ui_mi.WE_Entity_Id = Convert.ToInt32(flowname);
ui_mi.WE_Event_Desc = db_miss[i].Miss_Desc;
ui_mi.WE_Event_Name = db_miss[i].Event_Name;
ui_mi.WE_Name = db_miss[i].Miss_Name;
ui_mi.Mission_Url = ""; //历史任务的页面至空
ui_mi.Miss_Id = db_miss[i].Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss[i].Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
Equip_Id = WM.GetEquipIdBySbCode(ui_mi.Miss_Params["Equip_Code"].ToString());
string[] File_AllName = ui_mi.Miss_Params["ModifyOperInstruc"].ToString().Split(new char[] { '$' });
file.fileName = File_AllName[0];
file.fileNamePresent = File_AllName[1];
file.ext = Path.GetExtension(ui_mi.Miss_Params["ModifyOperInstruc"].ToString());
file.updateTime = DateTime.Now.ToString();
file.Mission_Id = db_miss[i].Miss_Id;
file.WfEntity_Id = Convert.ToInt32(flowname);
//file.Self_Catalog_Catalog_Id = 28;
file.path = @"/Upload/A3dot3";
bool res = WM.AddNewFile(28, file);
break;
}
}
//通过上传时间找到刚才上传到File_Info的文件的File_Id
int File_Id = WM.GetFileIdByUpdateTime(Convert.ToDateTime(file.updateTime));
//调用File.cs里的AttachtoEuip使连接表产生数据,让设备与操作规程勾连,需要用到Equip_Id和File_Id
bool les = WM.AttachtoEuipAndFile(File_Id, Equip_Id);
}
}
}
}
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A6dot1/Index");
}
public string SBJudge_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["SBJudge_Result"] = item["SBJudge_Result"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A6dot1/Index");
}
public string JdcConfirm_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
A6dot2Managment WM = new A6dot2Managment();
FileItem file = new FileItem();
int Equip_Id = 0;
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["JdcConfirm_Result"] = item["JdcConfirm_Result"].ToString();
signal["JdcSupplement"] = item["JdcSupplement"].ToString();
//上传到File_Info
if (signal["JdcConfirm_Result"] == "通过")
{
//向File_Info里写文件信息
WorkFlows wfsd = new WorkFlows();
List<Mission> db_miss = wfsd.GetWFEntityMissions(Convert.ToInt32(flowname));//获取该实体的所有任务
for (int i = 0; i < db_miss.Count; i++)
{
if (db_miss[i].Miss_Desc == "可靠性工程师修改再上传")
{
UI_MISSION ui_mi = new UI_MISSION();
ui_mi.WE_Entity_Id = Convert.ToInt32(flowname);
ui_mi.WE_Event_Desc = db_miss[i].Miss_Desc;
ui_mi.WE_Event_Name = db_miss[i].Event_Name;
ui_mi.WE_Name = db_miss[i].Miss_Name;
ui_mi.Mission_Url = ""; //历史任务的页面至空
ui_mi.Miss_Id = db_miss[i].Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss[i].Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
Equip_Id = WM.GetEquipIdBySbCode(ui_mi.Miss_Params["Equip_Code"].ToString());
string[] File_AllName = ui_mi.Miss_Params["ModifyOperInstruc"].ToString().Split(new char[] { '$' });
file.fileName = File_AllName[0];
file.fileNamePresent = File_AllName[1];
file.ext = Path.GetExtension(ui_mi.Miss_Params["ModifyOperInstruc"].ToString());
file.updateTime = DateTime.Now.ToString();
file.Mission_Id = db_miss[i].Miss_Id;
file.WfEntity_Id = Convert.ToInt32(flowname);
//file.Self_Catalog_Catalog_Id = 28;
file.path = @"/Upload/A3dot3";
bool res = WM.AddNewFile(28, file);
break;
}
}
//通过上传时间找到刚才上传到File_Info的文件的File_Id
int File_Id = WM.GetFileIdByUpdateTime(Convert.ToDateTime(file.updateTime));
//调用File.cs里的AttachtoEuip使连接表产生数据,让设备与操作规程勾连,需要用到Equip_Id和File_Id
bool les = WM.AttachtoEuipAndFile(File_Id, Equip_Id);
}
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A6dot1/Index");
}
}
}<file_sep>using FlowEngine.Modals;
using FlowEngine.TimerManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FlowEngine.Event
{
public class CTimeOutProperty : IXMLEntity
{
#region 构造函数
public CTimeOutProperty(CEvent parent)
{
Parent = parent;
}
#endregion
#region 相对时间起始点类型
public enum TIME_START { TIME_WF_CREATE, TIME_EVENT_ENTER } ;
#endregion
#region 属性
/// 说明: m_timeOffset与m_startTime成对使用
/// m_ExactTime单独使用
/// 一般情况下,上面两组时间指定方式选一组, 如果两组都指定则以具体时间为标准
/// <summary>
/// 相对时间起始点
/// </summary>
private TIME_START? m_startTime = null;
public TIME_START? StartTime
{
get
{
return m_startTime;
}
set
{
m_startTime = value;
}
}
/// <summary>
/// 相对于起点的时间偏移量
/// </summary>
private TimeSpan? m_timeOffset = null;
public TimeSpan? TimeOffset
{
get
{
return m_timeOffset;
}
set
{
m_timeOffset = value;
}
}
/// <summary>
/// 具体时间
/// </summary>
private DateTime? m_ExactTime = null;
public DateTime? ExactTime
{
get
{
return m_ExactTime;
}
set
{
m_ExactTime = value;
}
}
/// <summary>
/// Timeout的动作
/// </summary>
private string m_action = "";
public string Action
{
get
{
return m_action;
}
set
{
m_action = value;
}
}
/// <summary>
/// 所属的Event
/// </summary>
public CEvent Parent
{
get;
set;
}
/// <summary>
/// 回调函数的url地址
/// </summary>
public string CallbackUrl { get; set; }
/// <summary>
/// 该超时任务在定时任务管理器中的ID号
/// </summary>
private int m_timerMissionID = -1;
#endregion
#region IXMLEntity 接口
public void InstFromXmlNode(XmlNode xmlNode)
{
XmlElement xe = (XmlElement)xmlNode;
//1. 判断该节点是否为 "timeout", 并读取相关属性
if (xmlNode.Name.ToLower() != "timeout_setting")
return;
m_action = xmlNode.Attributes["action"].Value;
if (xmlNode.Attributes["linkTimerID"] == null || xmlNode.Attributes["linkTimerID"].Value == "")
m_timerMissionID = -1;
else
m_timerMissionID = Convert.ToInt32(xmlNode.Attributes["linkTimerID"].Value);
//2. 读取具体时间
XmlNode eTime = xmlNode.SelectSingleNode("exact_time");
if (eTime == null || eTime.InnerText.Trim() == "")
m_ExactTime = null;
else
{
m_ExactTime = DateTime.Parse(eTime.InnerText);
}
//3. 读取偏移时间
XmlNode oTime = xmlNode.SelectSingleNode("offset_time");
if (oTime == null)
{
m_startTime = null;
m_timeOffset = null;
}
else
{
string startType = oTime.Attributes["time_start"].Value;
string offset = oTime.Attributes["time_offset"].Value;
if (offset.Trim() == "")
{
m_startTime = null;
m_timeOffset = null;
}
else
{
m_timeOffset = TimeSpan.Parse(offset);
switch (startType.ToLower())
{
case "wf_create":
m_startTime = TIME_START.TIME_WF_CREATE;
break;
case "ev_enter":
m_startTime = TIME_START.TIME_EVENT_ENTER;
break;
default:
m_startTime = null;
m_timeOffset = null;
break;
}
}
}
//4. 读取callback的地址
XmlNode urlNode = xmlNode.SelectSingleNode("call_back");
if (urlNode != null)
CallbackUrl = urlNode.InnerText;
else
CallbackUrl = "";
}
public XmlNode WriteToXmlNode()
{
XmlDocument doc = new XmlDocument();
XmlElement toNode = doc.CreateElement("timeout_setting");
toNode.SetAttribute("action", m_action);
toNode.SetAttribute("linkTimerID", Convert.ToString(m_timerMissionID));
//1. 构建具体时间节点
if (m_ExactTime != null)
{
XmlElement et = doc.CreateElement("exact_time");
et.InnerText = m_ExactTime.Value.ToString();
toNode.AppendChild(et);
}
//2. 构建偏移时间节点
if (m_startTime != null && m_timeOffset != null)
{
XmlElement ot = doc.CreateElement("offset_time");
string time_start = "";
switch (m_startTime)
{
case TIME_START.TIME_WF_CREATE:
time_start = "wf_create";
break;
case TIME_START.TIME_EVENT_ENTER:
time_start = "ev_enter";
break;
}
ot.SetAttribute("time_start", time_start);
ot.SetAttribute("time_offset", m_timeOffset.Value.ToString());
toNode.AppendChild(ot);
}
//3. 构建callback节点
XmlElement cb = doc.CreateElement("call_back");
cb.AppendChild(doc.CreateCDataSection(CallbackUrl));
toNode.AppendChild(cb);
return toNode;
}
#endregion
#region 公共方法
/// <summary>
/// 设置属性
/// </summary>
/// <param name="attr_name">属性名,可选值 exact_time, offset_time, time_start</param>
/// <param name="val">属性的值,
/// 当attr_name = "exact_time", val为datetime
/// attr_name = "offset_time", val为timespan
/// attr_name = "time_start", val为string, 可选值wf_create, ev_enter</param>
/// <returns></returns>
public bool SetAttribute(string attr_name, object val)
{
try
{
switch (attr_name)
{
case "exact_time":
m_ExactTime = (val as DateTime?);
break;
case "offset_time":
m_timeOffset = (val as TimeSpan?);
break;
case "time_start":
if ((val as string) == "wf_create")
m_startTime = TIME_START.TIME_WF_CREATE;
else if ((val as string) == "ev_enter")
m_startTime = TIME_START.TIME_EVENT_ENTER;
else
return false;
break;
case "action":
m_action = (val as string);
break;
case "call_back":
CallbackUrl = (val as string);
break;
default:
return false;
}
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 该Timeout属性表示的含义是否有效
/// </summary>
/// <returns></returns>
public bool IsEnable()
{
if (m_ExactTime != null) //具体时间指定——有效
return true;
else if (m_startTime != null && m_timeOffset != null) //具体时间未指定, starttime与timeoffset指定——有效
return true;
else
return false;
}
/// <summary>
/// 注册到Timer管理器
/// </summary>
/// <param name="bCreateWF">是否为创建工作流时刻</param>
public void RegTimeoutTimer(bool bCreateWF)
{
//如果含义无效,直接返回
if (!IsEnable())
return;
CTimerTimeout timeout_job = new CTimerTimeout();
timeout_job.CreateTime = DateTime.Now;
timeout_job.for_using = TIMER_USING.FOR_SYSTEM;
timeout_job.mission_name = string.Format("{0}:{1}", Parent.Parent.name, Parent.name);
timeout_job.status = TM_STATUS.TM_STATUS_ACTIVE;
timeout_job.SetActionForWF(m_action);
timeout_job.AttachWFEntityID = Parent.Parent.EntityID;
timeout_job.CustomAction = CallbackUrl;
timeout_job.EventName = Parent.name;
string strCorn = "";
//如果该函数是调用于工作流创建时刻,但是偏移时间的起始不是TIME_START.TIME_WF_CREATE 则注册失败, 直接返回
if (bCreateWF)
{
if ((m_ExactTime == null) && (m_startTime != TIME_START.TIME_WF_CREATE))
return;
}
else //如果该函数是调用于进入Event时刻,但是偏移时间的起始不是TIME_START.TIME_WF_CREATE 则注册失败, 直接返回
{
if (m_ExactTime != null || m_startTime != TIME_START.TIME_EVENT_ENTER)
return;
}
if (m_ExactTime != null)
{
strCorn = string.Format("{0} {1} {2} {3} {4} {5} {6}",
m_ExactTime.Value.Second,
m_ExactTime.Value.Minute,
m_ExactTime.Value.Hour,
m_ExactTime.Value.Day,
m_ExactTime.Value.Month,
"?",
m_ExactTime.Value.Year);
timeout_job.SetTriggerTiming(strCorn);
}
else
{
DateTime run_time = DateTime.Now + m_timeOffset.Value;
strCorn = string.Format("{0} {1} {2} {3} {4} {5} {6}",
run_time.Second,
run_time.Minute,
run_time.Hour,
run_time.Day,
run_time.Month,
"?",
run_time.Year);
timeout_job.SetTriggerTiming(strCorn);
}
//保存该定时任务,并将其添加到激活任务列表
timeout_job.Save();
m_timerMissionID = timeout_job.ID;
CTimerManage.AppendMissionToActiveList(timeout_job);
}
/// <summary>
/// 取消该超时任务在定时任务管理器中的注册
/// </summary>
public void UnregTimeoutTimer()
{
var t = CTimerManage.LoadTimerMission(m_timerMissionID);
if (t != null)
{
t.status = TM_STATUS.TM_FINISH;
t.Save();
CTimerManage.RemoveFromActiveList(t.ID);
}
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class GongDan
{
public string GD_Id { get; set; }
public string GD_Notice_Id { get; set; }
public string GD_Desc { get; set; }
public string GD_State { get; set; }
public string GD_CRDate { get; set; }
public string GD_OrderDate { get; set; } //下达日期
public string GD_Order_Type { get; set; }
public string GD_WorkingCenter { get; set; }
public string GD_PlanGroup { get; set; }
public string GD_Version { get; set; }
public Decimal GD_PlanCost { get; set; } //计划成本
public string GD_Inputer { get; set; } //输入者
public string GD_Condition { get; set; }
public string GD_EquipCode { get; set; }
public string GD_Equip_ABCmark { get; set; }
public string GD_EndDate { get; set; }
public string GD_JobType { get; set; }
public string GD_Fun_Location { get; set; }
public string GD_Fun_Desc { get; set; }
public string GD_PriorityTxt { get; set; }
public string GD_WBS_Title { get; set; }
public Decimal GD_Cost { get; set; } //实绩成本
public string GD_PreCG { get; set; } //预留采购
public string GD_Real_StartDate { get; set; }//实绩开始时间
public string GD_Equip_Catalog { get; set; }
}
public class Notice
{
public string Notice_ID { get; set; }
public string Notice_Type { get; set; }
public string Notice_Desc { get; set; }
public string Notice_Yx { get; set; }
public string Notice_EquipCode { get; set; }
public string Notice_Equip_ABCmark { get; set; }
public string Notice_OverCondition { get; set; }
public string Notice_State { get; set; }
public string Notice_Order_ID { get; set; }
public string Notice_FaultStart { get; set; }
public string Notice_FaultEnd { get; set; }
public string Notice_FaultStartTime { get; set; }
public string Notice_FaultEndTime { get; set; }
public string Notice_PlanGroup { get; set; }
public string Notice_CR_Person { get; set; }
public string Notice_CR_Date { get; set; }
public double Notice_Stop { get; set; }
public string Notice_Commit_Time { get; set; }
public string Notice_FunLoc { get; set; }
public string Notice_FunLocDesc { get; set; }
public string Notice_Catalog { get; set; }
public string Notice_TechDesc { get; set; }
public string Notice_Priority { get; set; }
public string Notice_Commit_Date { get; set; }
public string Notice_QMcode { get; set; }
public string Notice_FaultXX { get; set; }
public string Notice_FaultLoc { get; set; }
public string Notice_FaultLoss { get; set; }
public string Notice_FaultReason { get; set; }
public string Notice_FaultMethod { get; set; }
public string Notice_FaultYx { get; set; }
public string Notice_AUSP { get; set; }
}
public class OilInfo
{
public string oil_EquipCode { get; set; }
public string oil_EquipDesc { get; set; }
public string oil_Fun_Loc { get; set; }
public string oil_Fun_LocDesc { get; set; }
public string oil_Loc { get; set; }
public string oil_Loc_Desc { get; set; }
public string oil_Interval { get; set; }
public string oil_Unit { get; set; }
public string oil_Unit2 { get; set; }
public string oil_LastDate{get;set;}
public Decimal oil_LastNum { get; set; }
public DateTime oil_NextDate{get;set;}
public Decimal oil_NextNum{get;set;}
public string oil_Code{get;set;}
public string oil_Desc{get;set;}
}
}
<file_sep>///////////////////////////////////////////////////////////
// CAuthority.cs
// Implementation of the Class CCombEvent
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
namespace FlowEngine.Authority
{
/// <summary>
/// 权限认证
/// </summary>
public class CAuthority : IXMLEntity
{
//权限认证串——EntitySql
public string auth_string { get; set; }
/// <summary>
/// 将参数值填充到查询语句中,使其不含参数
/// </summary>
/// <param name="inter_params"></param>
/// <param name="outer_params"></param>
/// <returns>返回填充后的字符串</returns>
public string FillParams(IDictionary<string, object> inter_params,
IDictionary<string, object> outer_params)
{
string ret_string = "";
ret_string = auth_string;
Dictionary<string, List<string>> pars_sql = GetParams();
//设置内部变量
if (inter_params != null)
{
foreach (var intps in pars_sql["inter"])
{
//内部变量为CParam, 其值的类型只有string, int, float, boolean等
switch (inter_params[intps].GetType().Name)
{
case "String":
ret_string = ret_string.Replace(@"@IP_" + intps, "'" + Convert.ToString(inter_params[intps]) + "'");
break;
default:
ret_string = ret_string.Replace(@"@IP_" + intps, Convert.ToString(inter_params[intps]));
break;
}
}
}
if (outer_params != null)
{
//设置外部变量
foreach (var outps in pars_sql["outer"])
{
//外部变量可能比较复杂,暂时仅考虑字符串
switch (outer_params[outps].GetType().Name)
{
case "String":
ret_string = ret_string.Replace(@"@OP_" + outps, "'" + Convert.ToString(outer_params[outps]) + "'");
break;
default:
ret_string = ret_string.Replace(@"@OP_" + outps, Convert.ToString(outer_params[outps]));
break;
}
}
}
return ret_string;
}
/// <summary>
///
/// </summary>
/// <param name="inter_params">内部参数,指以auth_string中@IP_name格式的名字为name的参数</param>
/// <param name="outer_params">外部参数,指以auth_string中@OP_name格式的名字为name的参数</param>
/// <returns>是否通过权限认证, 若查询记录集的个数不为0则为真, 否则为假</returns>
public bool CheckAuth<T>(IDictionary<string, object> inter_params,
IDictionary<string, object> outer_params,
ObjectContext Context)
{
try
{
if (auth_string == null || auth_string.Trim() == "")
return true;
Dictionary<string, List<string>> pars_sql = GetParams();
//
ObjectQuery<T> contextQuery = new ObjectQuery<T>(auth_string, Context);
//设置内部变量
foreach (var intps in pars_sql["inter"])
{
contextQuery.Parameters.Add(new ObjectParameter("IP_" + intps, inter_params[intps]));
}
//设置外部变量
foreach (var outps in pars_sql["outer"])
{
contextQuery.Parameters.Add(new ObjectParameter("OP_" + outps, outer_params[outps]));
}
if (contextQuery.ToList().Count == 0)
return false;
}
catch (Exception e)
{
return false;
}
return true;
}
/// <summary>
/// 返回权限认证串中的参数名称
/// </summary>
/// <returns>
/// Key = "inter" 或 "outer"
/// Value = inter_params 或 outer_params
/// </returns>
private Dictionary<string, List<string>> GetParams()
{
Dictionary<string, List<string>> pars = new Dictionary<string, List<string>>();
pars["inter"] = new List<string>();
pars["outer"] = new List<string>();
//利用正则表达式提取sql语句中的变量名
Regex paramReg = new Regex(@"[^@@](?<p>@\w+)");
MatchCollection matches = paramReg.Matches(String.Concat(auth_string, " "));
foreach (Match m in matches)
{
string par_sql = m.Groups["p"].Value;
if (par_sql.IndexOf("@IP_") == 0) //含有内部变量前缀
{
if (!pars["inter"].Contains(par_sql.Substring(4)))
pars["inter"].Add(par_sql.Substring(4));
}
else if (par_sql.IndexOf("@OP_") == 0)
{
if (!pars["outer"].Contains(par_sql.Substring(4)))
pars["outer"].Add(par_sql.Substring(4));
}
else
throw new Exception("Authority Checking String Is Error!");
}
return pars;
}
public void InstFromXmlNode(System.Xml.XmlNode xmlNode)
{
if (xmlNode == null)
{
auth_string = "";
return;
}
if (xmlNode.Name != "authority")
return;
auth_string = xmlNode.InnerText;
}
public System.Xml.XmlNode WriteToXmlNode()
{
XmlDocument doc = new XmlDocument();
XmlElement xe = doc.CreateElement("authority");
xe.AppendChild(doc.CreateCDataSection(auth_string));
return xe;
}
}
}
<file_sep>using FlowDesigner.Management;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowDesigner.PropertyEditor
{
public class Param_APPRes
{
public string p_name { get; set; }
public string app_res { get; set; }
}
/// <summary>
/// LinkParamsWin.xaml 的交互逻辑
/// </summary>
public partial class LinkParamsWin : Window
{
public Dictionary<string, string> _newValue;
public Dictionary<string, string> newValue
{
get {
return _newValue;
}
set
{
_newValue = value;
//Dest.ItemsSource = _newValue;
foreach(var s in _newValue)
{
Dest.Items.Add(new Param_APPRes() { p_name = s.Key, app_res = s.Value});
}
MainWindow mw = (MainWindow)Application.Current.MainWindow;
foreach(param pa in mw.main_proj.CurrentWF.params_table)
{
if (!_newValue.ContainsKey(pa.Name))
Source.Items.Add(pa);
}
}
}
public LinkParamsWin()
{
InitializeComponent();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
_newValue.Clear();
//newValue.Add("aaaa");
foreach(var i in Dest.Items)
{
Param_APPRes pl = (i as Param_APPRes);
_newValue[pl.p_name] = pl.app_res;
}
this.DialogResult = true;
this.Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
(sender as ComboBox).ItemsSource = ((MainWindow)Application.Current.MainWindow).main_proj.Param_AppRes;
}
private void Add_Click(object sender, RoutedEventArgs e)
{
param pa = (Source.SelectedItem as param);
Source.Items.Remove(pa);
Dest.Items.Add(new Param_APPRes() { p_name = pa.Name, app_res = "" });
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
Param_APPRes pl = (Dest.SelectedItem as Param_APPRes);
Dest.Items.Remove(pl);
MainWindow mw = (MainWindow)Application.Current.MainWindow;
foreach (param pa in mw.main_proj.CurrentWF.params_table)
{
if (pa.Name == pl.p_name)
Source.Items.Add(pa);
}
}
}
}
<file_sep>using EquipDAL.Implement;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class EquipManagment
{
private Equip_Archis EAs = new Equip_Archis();
private Equips Es=new Equips();
private Depart_Archis Ds = new Depart_Archis();
//功能:获取所有的车间信息
//参数:空
//返回值:List<Equip_Archi>
public List<Equip_Archi> getAllCj()
{
List<Equip_Archi> r=EAs.getEAs_isCj();
return r;
}
//功能:查询设备列表
//参数:设备工艺编号,位置id,设备子类
//返回值:List<Equip_Archi>
public List<Equip_Info> getAllEquips_byinfo(string Equip_gycode, int Equip_archi, string Equip_specialty)
{
List<Equip_Info> r = Es.getEquips_byinfo(Equip_gycode, Equip_archi, Equip_specialty);
return r;
}
//开始0801
public string getCjnamebyEa_id(int id)
{
return EAs.getEA_Parent(id).EA_Name;
}
//结束
public string getPq(string Cjname)
{
return Ds.getDepart_Pq(Cjname);
}
public int getE_id_byGybh(string equip_Gy)
{
int r = Es.getE_id_byGybh(equip_Gy);
return r;
}
public int getEA_id_byCode(string equip_code)
{
int r = Es.getEA_id_byCode(equip_code);
return r;
}
//功能:获取某车间的所有装置信息
//参数:Cj_id 整型 车间Id
//返回值:List<Equip_Archi>
public List<Equip_Archi> getZzs_ofCj(int Cj_id)
{
List<Equip_Archi> r = EAs.getEA_Childs(Cj_id);
return r;
}
//功能:获取某装置的所有设备信息
//参数:Zz_Id 整型 装置Id
//返回值:List<Equip_Info>
public List<Equip_Info> getEquips_OfZz(int Zz_Id, string username = null)
{
List<Equip_Info> r = EAs.getEA_Equips(Zz_Id, username);
return r;
}
public List<Equip_Info> getThEquips_OfZz(int Zz_Id)
{
List<Equip_Info> r = EAs.getThEA_Equips(Zz_Id);
return r;
}
//功能:获取某设备的详细信息
//参数: Equip_Id 整型 设备Id
//返回值:Equip_Info
public Equip_Info getEquip_Info(int Equip_Id)
{
Equip_Info e=Es.getEquip_Info(Equip_Id);
return e;
}
//功能:获取某设备的详细信息 --xwm add
//参数: Equip_Code, string 设备编码
//返回值:Equip_Info
public Equip_Info getEquip_Info(string Equip_Code)
{
Equip_Info e = Es.getEquip_Info(Equip_Code);
return e;
}
public Equip_Info getEquip_ByGyCode(string Equip_GyCode)
{
Equip_Info e = Es.getEquip_byGyCode(Equip_GyCode);
return e;
}
public List<Equip_Archi> getEquip_ZzBelong(int Equip_Id)
{
List<Equip_Archi> E_ZzCjInfo = new List<Equip_Archi>();
Equip_Archi m = Es.getEquip_EA(Equip_Id);
E_ZzCjInfo.Add(m);
E_ZzCjInfo.Add(EAs.getEA_Parent(m.EA_Id));
return E_ZzCjInfo;
}
//功能:添加设备信息
//参数: new_Equip 新添加设备相关信息
// Zz_Id 新添加设备所属装置Id
// Person_Ids 新添加设备所属管理者集合,该参数默认为null,当不将设备添加给用户时,取默认值
//返回值:bool
public bool addEquip(Equip_Info new_Equip,int Zz_Id,List<int> Person_Ids=null)
{
try
{
Es.AddEquip(new_Equip, Zz_Id);
if (Person_Ids!=null) Es.Equip_LinkPersons(new_Equip.Equip_Id,Person_Ids);
return true;
}
catch{return false;}
}
//功能:修改设备信息
//参数: new_Equip 设备的修改信息
// Zz_Id 设备新的所属装置Id
// Person_Ids 设备所属的新管理者集合,该参数默认为null,当不改变设备所属用户时,该参数取默认值
//返回值:bool
public bool modifyEquip(Equip_Info new_Equip,int Zz_Id,List<int> Person_Ids=null)
{
try
{
Es.ModifyEquip(new_Equip,Zz_Id);
if (Person_Ids != null) Es.Equip_LinkPersons(new_Equip.Equip_Id, Person_Ids);
return true;
}
catch { return false; }
}
//功能:删除设备信息,会自动删除该设备链接的其他信息
//参数:E_Id 设备Id
//返回值:bool
public bool deleteEquip(int E_Id)
{
try
{
Es.DeleteEquip(E_Id );
return true;
}
catch { return false; }
}
public List<EANummodel> getequipnum_byarchi()
{
try
{
List<EANummodel> E = Es.getequipnum_byarchi();
return E;
}
catch { return null; }
}
public int getEA_parentid(int Ea_id)
{
try
{
int E = Es.getEA_parentid(Ea_id);
return E;
}
catch { return 0; }
}
public int getEa_idbyname(string Ea_name)
{
try
{
int E = EAs.getEa_idbyname(Ea_name);
return E;
}
catch { return 0; }
}
public string getEa_namebyid(int Ea_id)
{
try
{
string E = EAs.getEa_namebyId(Ea_id);
return E;
}
catch { return null; }
}
public string getZzName(int Equip_location_EA_Id)
{
List<Equip_Archi> E_Zz = new List<Equip_Archi>();
string ZzName = EAs.getEA_Name(Equip_location_EA_Id);
return ZzName;
}
/// <summary>
/// 0917xs
/// </summary>
/// <param name="EA_Name"></param>
/// <returns></returns>
public string getEquip(string EA_Name)
{
return EAs.getEA_NameByZzNAme(EA_Name);
}
public List<Equip_Info> getAllThEquips()
{
return Es.getAllThEquips();
}
public List<Equip_Archi> GetAllCj()
{
return Es.GetAllCj();
}
public List<Pq_Zz_map> GetZzsofPq(string Pqname)
{
return Es.GetZzsofPq(Pqname);
}
public Pq_Zz_map GetPqofZz(string Zzname)
{
return Es.GetPqofZz(Zzname);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Security.AccessControl;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Collections;
using EquipBLL.FileManagment;
using Newtonsoft.Json;
namespace WebApp.Controllers
{
public class A3dot1Controller : Controller
{
public ActionResult Index()
{
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
/// <summary>
/// 组织结构
/// </summary>
public class Depart_Archi
{
/// <summary>
/// 主键
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Depart_Id { get; set; }
public string Depart_Name { get; set; }
/// <summary>
/// 父节点
/// </summary>
public virtual Depart_Archi Depart_Parent { get; set; }
/// <summary>
/// 子节点
/// </summary>
public virtual ICollection<Depart_Archi> Depart_child { get; set; }
/// <summary>
/// 部门职员
/// </summary>
public virtual ICollection<Person_Info> Depart_Persons { get; set; }
}
}
<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class JxpgManagment
{
private Jxpg db_Jxpg = new Jxpg();
public bool AddJxItem( A15dot1Tab add)
{
return db_Jxpg.AddJxRecord(add);
}
public bool ModifyJxItem(A15dot1Tab add)
{
return db_Jxpg.ModifyJxRecord(add);
}
//时机动处修改
public bool JdcModifyJxItem(A15dot1Tab add)
{
return db_Jxpg.JdcModifyJxRecord(add);
}
public List<A15dot1Tab> GetJxItem(string roles, string dep, string name)
{
return db_Jxpg.GetJxRecord(roles,dep,name);
}
public List<A15dot1Tab> GetJxItem_detail(int id)
{
return db_Jxpg.GetJxRecord_detail(id);
}
public List<A15dot1Tab> GetHisJxItem(string roles, string dep, string name)
{
return db_Jxpg.GetHisJxRecord(roles, dep, name);
}
public List<A15dot1Tab> GetHisJxItem_detail(int id)
{
return db_Jxpg.GetHisJxRecord_detail(id);
}
public List<object> qst(string grahpic_name, string pianqu)
{
return db_Jxpg.qstdata(grahpic_name, pianqu);
}
public List<A15dot1Tab> GetJxItemforA2(DateTime time, DateTime time2)
{
return db_Jxpg.GetJxItemforA2Tab(time,time2);
}
public List<A15dot1Tab> newGetJxItemforA2(DateTime time, DateTime time2, string pianqu)
{
return db_Jxpg.newGetJxItemforA2Tab(time, time2, pianqu);
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using WebApp.Models.DateTables;
using System.Collections.Specialized;
using EquipBLL.AdminManagment.MenuConfig;
using FlowEngine.TimerManage;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class DSA5dot2Controller : CommonController
{
//
// GET: /LSA5dot2/
PersonManagment pm = new PersonManagment();
TablesManagment tm = new TablesManagment();
EquipManagment Em = new EquipManagment();
EquipArchiManagment Eam = new EquipArchiManagment();
private SxglManagment Sx = new SxglManagment();
public ActionResult ZzSubmit(string wfe_id)
{
UI_MISSION mi = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
Dictionary<string, object> mi_params = mi.Miss_Params;
int Zz_id = Eam.getEa_idbyname(mi.Miss_Params["Zz_Name"].ToString());
ViewBag.Zz_id = Zz_id;
ViewBag.Zz_name = mi.Miss_Params["Zz_Name"].ToString();
ViewBag.wfe_id = wfe_id;
return View();
}
public string ZzSubmit_Bcsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
CTimerTimeout timeout_job = new CTimerTimeout();
timeout_job.CreateTime = DateTime.Now;
timeout_job.for_using = TIMER_USING.FOR_SYSTEM;
timeout_job.mission_name = "";
timeout_job.status = TM_STATUS.TM_STATUS_ACTIVE;
timeout_job.SetActionForWF("INVILID");
timeout_job.AttachWFEntityID = Convert.ToInt32(item["wfe_id"]);
timeout_job.CustomAction = "http://localhost/CallBack/testCallBack";
timeout_job.EventName = "PqAessess";
timeout_job.SetTriggerTiming("0 0 0 20 * ?");
//保存该定时任务,并将其添加到激活任务列表
timeout_job.Save();
int m_timerMissionID = timeout_job.ID;
CTimerManage.AppendMissionToActiveList(timeout_job);
// A5dot1Tab1 a5dot1Tab1 = new A5dot1Tab1();
DateTime my = DateTime.Now;
int cjid = Em.getEA_parentid(Convert.ToInt32(item["Zz_Id"]));
string cjname = Eam.getEa_namebyId(cjid);
A5dot2Tab1 new_5dot2 = new A5dot2Tab1();
new_5dot2.cjName = cjname;
new_5dot2.zzName = item["Zz_Name"].ToString();
new_5dot2.sbGyCode = item["Equip_GyCode"].ToString();
new_5dot2.sbCode = item["Equip_Code"].ToString();
new_5dot2.sbType = item["Equip_Type"].ToString();
new_5dot2.zyType = item["Zy_Type"].ToString();
new_5dot2.problemDescription = item["problemDescription"].ToString();
new_5dot2.jxSubmitTime = DateTime.Now;
new_5dot2.jxUserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_5dot2.isRectified = 0;
new_5dot2.state = 0;
new_5dot2.temp2 = item["wfe_id"].ToString();
new_5dot2.temp3 = m_timerMissionID.ToString();
bool res = Sx.AddSxItem(new_5dot2);
string wfe_id = item["wfe_id"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(wfe_id), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A5dot2/Index");
}
}
}<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class A6dot2LsTaskTabs : BaseDAO
{
public List<A6dot2LsTaskTab> getAllLsTaskTabs(string wfe_id)
{
using (var db = base.NewDB())
{
return db.A6dot2LsTaskTab.Where(a => a.wfd_id==wfe_id).ToList();
}
}
public A6dot2LsTaskTab AddA6dot2LsTask(A6dot2LsTaskTab new_A6dot2LsTask)
{
try
{
using (var db = base.NewDB())
{
A6dot2LsTaskTab newP = db.A6dot2LsTaskTab.Add(new_A6dot2LsTask);
db.SaveChanges();
return newP;
}
}
catch
{
return null;
}
}
public bool remove(int id)
{
try
{
using (var db = base.NewDB())
{
var P = db.A6dot2LsTaskTab.Where(a => a.Id == id).First();
if (P == null)
return false;
else
{
db.A6dot2LsTaskTab.Remove(P);
db.SaveChanges();
return true;
}
}
}
catch
{
return false;
}
}
public A6dot2LsTaskTab UpdateA6dot2LsTask(int id, List<string> propertis, List<object> vals)
{
try
{
using (var db = base.NewDB())
{
var LsTask = db.A6dot2LsTaskTab.Where(a => a.Id == id).First();
if (propertis.Count == 0)
return LsTask;
for (int i = 0; i < propertis.Count; i++)
{
string property = propertis[i];
object val = vals[i];
switch (property)
{
case "Zz_Name":
LsTask.Zz_Name = val as string;
break;
case "Equip_Gybh":
LsTask.Equip_Gybh = val as string ;
break;
case "Equip_Code":
LsTask.Equip_Code = val as string;
break;
case "Last_HY":
LsTask.lastOilTime = val as string;
break;
case "HY_ZQ":
LsTask.oilInterval = (int)val;
break;
case "Problem_Cur":
LsTask.cur_problem = val as string;
break;
case "ZG_status":
LsTask.cur_status = val as string;
LsTask.cur_problem = "1";
break;
default: //其他字段
break;
}
}
if (db.SaveChanges() != 1)
return null;
return LsTask;
}
}
catch (Exception e)
{
return null;
}
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using FlowEngine.Param;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A8dot2Controller : CommonController
{
//
// GET: /A8dot2/
public ActionResult A8()
{
return View();
}
public ActionResult Index()
{
return View(getIndexListRecords("A8dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A8dot2/检修单位提报(直接从DRBPM当月计划中提取后确认提交!)
public ActionResult JxSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult JxdwCreateOrder (string wfe_id)
{
Dictionary<string, object> paras1 = new Dictionary<string, object>();
paras1["Job_Name"] = null;
paras1["Job_Order"] = null;
paras1["Data_Src"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(Convert.ToInt32(wfe_id), paras1);
ViewBag.GD_Id = paras1["Job_Order"].ToString();
ViewBag.Plan_Name = paras1["Job_Name"].ToString();
ViewBag.Data_Src = paras1["Data_Src"].ToString();
ERPInfoManagement erp = new ERPInfoManagement();
GD_InfoModal res = erp.getGD_Modal_GDId(paras1["Job_Order"].ToString());
if (res != null)
ViewBag.GD_State = res.GD_State;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZzConfirmJobOrder(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdConfirm1(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult PqConfirm1(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult JhkConfirm2(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult CaiGouConfirm(string wfe_id)
{
Dictionary<string, object> paras1 = new Dictionary<string, object>();
paras1["Job_OrderState"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(Convert.ToInt32(wfe_id), paras1);
ViewBag.Job_OrderState = paras1["Job_OrderState"].ToString();
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_Role = pv.Role_Names;
ViewBag.user_Depart = pv.Department_Name;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WzcCaiGou(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WzcNoticeJxdw(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UploadJxPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WriteJxContent(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdConfirmPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult PqConfirmContent(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZzConfirmPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZzConfirmCondition(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UploadZjRecord(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UploadBCdot17(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZzPqZytdConfirm(string wfe_id)
{
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_Role = pv.Role_Names;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UploadTryRunRecord(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZzPqConfirm(string wfe_id)
{
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_Role = pv.Role_Names;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult JxdwConfirmEnd(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string JxSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Jx_Reason"] = item["Jx_Reason"].ToString();
//signal["Data_Src"] = item["Data_Src"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
signal["Job_Name"] = "";
signal["Job_Order"] = "";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string JxdwCreateOrder_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
//JObject item2 = (JObject)JsonConvert.DeserializeObject(item["plan_data"].ToString());
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["Job_Order"] = item2["Plan_num"].ToString();
signal["Job_Name"] = item["Job_Name"].ToString();
signal["Job_Order"] = item["Job_Order"].ToString();
ERPInfoManagement erp = new ERPInfoManagement();
GD_InfoModal res = erp.getGD_Modal_GDId("00"+item["Job_Order"].ToString());
signal["Job_OrderState"] = res.GD_State;
//signal["Job_OrderState"] = item["Job_OrderState"].ToString();
//signal["job_Name"] = item2["Plan_name"].ToString();
signal["ZjGxIsOK"] = "是";
//signal["Equip_GyCode"] = "8";
//signal["Equip_Code"] = "7";
//signal["Equip_ABCMark"] = "A";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string ZzConfirmJobOrder_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzConfirmJobOrder_done"] = "是";
signal["Job_OrderState"] = "待审";//for test
//signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string ZytdConfirm1_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirm1_done"] = "是";
// signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string PqConfirm1_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirm1_done"] = "是";
// signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string JhkConfirm2_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JhkConfirm2_done"] = "是";
signal["Job_OrderState"] = "下达";
// signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string CaiGouConfirm_submitsignal(string json1)//否否走不通
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["IsCaiGou_Wzc"] = item["IsCaiGou_Wzc"].ToString();
signal["IsCaiGou_Jxdw"] = item["IsCaiGou_Jxdw"].ToString();
// signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string WzcCaiGou_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Daohuo_Time"] = item["Daohuo_Time"].ToString();
signal["IsDaohuo_All"] = "Unconfirmed";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string WzcNoticeJxdw_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["IsDaohuo_All"] = "是";
// signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string UploadJxPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
signal["UploadJxPlan_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string WriteJxContent_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Jx_Content"] = item["Jx_Content"].ToString();
signal["Job_Guidebook"] = item["Job_Guidebook"].ToString();
signal["WriteJxContent_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string ZytdConfirmPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirmPlan_Result"] = item["ZytdConfirmPlan_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string PqConfirmContent_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirmContent_Result"] = item["PqConfirmContent_Result"].ToString();
// signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string ZzConfirmPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzConfirmPlan_Result"] = item["ZzConfirmPlan_Result"].ToString(); ;
signal["Delay_Reason"] = item["Delay_Reason"].ToString();
// signal["faulty_intensity"] = item["faulty_intensity"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string ZzConfirmCondition_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzConfirmCondition_Result"] = item["ZzConfirmCondition_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string UploadZjRecord_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZjRecord_File"] = item["ZjRecord_File"].ToString();
signal["UploadZjRecord_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string ZzPqZytdConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzConfirmZjRecord_Result"] = item["ZzConfirmZjRecord_Result"].ToString();
signal["PqConfirmZjRecord_Result"] = item["PqConfirmZjRecord_Result"].ToString();
signal["ZytdConfirmZjRecord_Result"] = item["ZytdConfirmZjRecord_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string ZzPqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzConfirmZjRecord_Result"] = item["ZzConfirmZjRecord_Result"].ToString();
signal["PqConfirmZjRecord_Result"] = item["PqConfirmZjRecord_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string UploadTryRunRecord_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["TryRunRecord_ConfirmResult"] = "是";
signal["TryRunRecord_File"] = item["TryRunRecord_File"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public string JxdwConfirmEnd_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxdwConfirmEnd_done"] = "true";
signal["JobFinish_File"] = item["JobFinish_File"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A8dot2/Index");
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WorkFolw_DetailforA8 (string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public class Gxqmodel
{
public string WE_Ser;
public int WE_Id;
}
public string A8ActiveList(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string WE_Status = "0";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "' and R.username is not null";
string record_filter = "username is not null";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<A8Model> Hm = new List<A8Model>();
ERPInfoManagement erp = new ERPInfoManagement();
foreach (var item in Gmlist)
{
A8Model h = new A8Model();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
paras["Job_Order"] = null;//通过工单找通知单号
paras["Zz_Name"] = null;
paras["Job_Name"] = null;//计划名称
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
h.zz_name = paras["Zz_Name"].ToString();
h.sb_gycode = paras["Equip_GyCode"].ToString();
h.job_order = paras["Job_Order"].ToString();
h.plan_name = paras["Job_Name"].ToString();
GD_InfoModal res = erp.getGD_Modal_GDId(paras["Job_Order"].ToString());
if (res != null)
h.notice_order = res.GD_Notice_Id;
h.gd_state = "检修中";
WorkFlows wfsd = new WorkFlows();
Mission db_missA8dot2 = wfsd.GetWFEntityMissions(item.WE_Id).Last();
//写if而不写else if是因为13.1和8.2是断开的,跳转8.2仍满足db_miss.Miss_Desc == "专业团队审核"
if (db_missA8dot2.Miss_Desc == "检修单位按计划建立工单,完善工序、组件")
{
if(res!=null)
h.gd_state = res.GD_State;
}
else if (db_missA8dot2.Miss_Desc == "检修计划提报")
{
if (res != null)
h.gd_state = res.GD_State;
}
else if (db_missA8dot2.Miss_Desc == "现场工程师审核工单")
{
if (res != null)
h.gd_state = res.GD_State;
}
else if (db_missA8dot2.Miss_Desc == "专业团队审1")
{
if (res != null)
h.gd_state = res.GD_State;
}
else if (db_missA8dot2.Miss_Desc == "可靠性工程师审1")
{
if (res != null)
h.gd_state = res.GD_State;
}
else if (db_missA8dot2.Miss_Desc == "机动处计划科审2")
{
if (res != null)
h.gd_state = res.GD_State;
}
else if (db_missA8dot2.Miss_Desc == "物资处采购,填写到货时间")
{
h.gd_state = "物资采购中";
}
else if (db_missA8dot2.Miss_Desc == "物资处确认到货并通知检修单位")
{
h.gd_state = "物资已到货";
}
else if (db_missA8dot2.Miss_Desc == "检修单位上传检修方案" || db_missA8dot2.Miss_Desc == "专业团队审批" || db_missA8dot2.Miss_Desc == "检修单位填写检修内容及关键工序,关联作业指导书" || db_missA8dot2.Miss_Desc == "可靠性工程师审批")
{
h.gd_state = "检修方案制定与审判";
}
else if (db_missA8dot2.Miss_Desc == "现场工程师确认是否可实施计划")
{
UI_MISSION ui = new UI_MISSION();
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_missA8dot2.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
ui.Miss_Params[cp.name] = cp.value;
}
if (ui.Miss_Params["ZzConfirmPlan_Result"].ToString() == "是")
{
h.gd_state = "检修计划实施中";
}
else if (ui.Miss_Params["ZzConfirmPlan_Result"].ToString() == "否")
{
h.gd_state = "检修计划延期";
}
}
else if (db_missA8dot2.Miss_Desc == "检修单位确认施工完毕,上传交工资料")
{
h.gd_state = "处理完成";
}
h.Data_Src = "待定";
h.detail = "待定";
Hm.Add(h);
}
List<object> or = new List<object>();
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
index = i + 1,
equip_gycode = Hm[i].sb_gycode,
job_order = Hm[i].job_order,
notice_order = Hm[i].notice_order,
gd_state = Hm[i].gd_state,
datasrc = Hm[i].Data_Src,
detail = Hm[i].detail,
zzname = Hm[i].zz_name,
planname = Hm[i].plan_name
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
//public string A8ActiveList(string WorkFlow_Name)
//{
// string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// string WE_Status = "0";
// string query_list = "distinct E.WE_Ser, E.WE_Id, R.username";
// string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "' and R.username is not null";
// string record_filter = "username is not null";
// DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
// List<Gxqmodel> Gmlist = new List<Gxqmodel>();
// for (int i = 0; i < dt.Rows.Count; i++)
// {
// Gxqmodel Gm = new Gxqmodel();
// Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
// Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
// Gmlist.Add(Gm);
// }
// List<A8Model> Hm = new List<A8Model>();
// ERPInfoManagement erp = new ERPInfoManagement();
// foreach (var item in Gmlist)
// {
// A8Model h = new A8Model();
// Dictionary<string, object> paras = new Dictionary<string, object>();
// paras["Equip_GyCode"] = null;
// paras["Job_Order"] = null;//通过工单找通知单号
// paras["Zz_Name"] = null;
// paras["Job_Name"] = null;//计划名称
// UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
// h.zz_name = paras["Zz_Name"].ToString();
// h.sb_gycode = paras["Equip_GyCode"].ToString();
// h.job_order = paras["Job_Order"].ToString();
// h.plan_name = paras["Job_Name"].ToString();
// GD_InfoModal res = erp.getGD_Modal_GDId(paras["Job_Order"].ToString());
// if (res != null)
// {
// h.notice_order = res.GD_Notice_Id;
// //h.gd_state = res.GD_UserState;
// h.gd_state = res.GD_State;
// }
// h.Data_Src = "待定";
// h.detail = "待定";
// Hm.Add(h);
// }
// List<object> or = new List<object>();
// for (int i = 0; i < Hm.Count; i++)
// {
// object o = new
// {
// index=i+1,
// equip_gycode = Hm[i].sb_gycode,
// job_order = Hm[i].job_order,
// notice_order = Hm[i].notice_order,
// gd_state=Hm[i].gd_state,
// datasrc = Hm[i].Data_Src,
// detail=Hm[i].detail,
// zzname=Hm[i].zz_name,
// planname=Hm[i].plan_name
// };
// or.Add(o);
// }
// string str = JsonConvert.SerializeObject(or);
// return ("{" + "\"data\": " + str + "}");
//}
public string A8HistoryList(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string WE_Status = "3";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "' and R.username is not null";
string record_filter = "username is not null";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in Gmlist)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.WE_Id);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.WE_Ser;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item.WE_Id;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
List<object> or = new List<object>();
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
//与工作流相关的表(在EquipWeb数据库中)
public class A15dot1Tab //设备绩效管理,片区或检修单位提报,机动处给出建议及改进措施
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//非计划停工次数
public int timesNonPlanStop { get; set; }
//非计划停工次数***参与统计台数
public int Count_timesNonPlanStop { get; set; }
//四类以上故障强度扣分
public int scoreDeductFaultIntensity { get; set; }
//四类以上故障强度扣分***参与统计台数
public int Count_scoreDeductFaultIntensity { get; set; }
//大机组故障率K
public double rateBigUnitFault { get; set; }
//大机组故障率K ***参与统计台数
public int Count_rateBigUnitFault { get; set; }
//故障维修率F
public double rateFaultMaintenance { get; set; }
//故障维修率F***参与统计台数
public int Count_rateFaultMaintenance { get; set; }
//一般机泵设备平均无故障间隔期MTBF
public double MTBF { get; set; }
//一般机泵设备平均无故障间隔期MTBF***参与统计台数
public int Count_MTBF { get; set; }
//设备投用率R(反映MTTR)
public double rateEquipUse { get; set; }
//设备投用率R(反映MTTR)***参与统计台数
public int Count_rateEquipUse { get; set; }
//紧急抢修工时率C--成本能效指标
public double rateUrgentRepairWorkHour { get; set; }
//维修工单有效完成时间T -小时--成本能效指标
public double hourWorkOrderFinish { get; set; }
//机械密封平均寿命s -小时
public int avgLifeSpanSeal { get; set; }
//机械密封平均寿命s -小时***参与统计台数
public int Count_avgLifeSpanSeal { get; set; }
//轴承平均寿命B -小时
public int avgLifeSpanAxle { get; set; }
//轴承平均寿命B -小时***参与统计台数
public int Count_avgLifeSpanAxle { get; set; }
//设备完好率W
public double percentEquipAvailability { get; set; }
//设备完好率W***参与统计台数
public int Count_percentEquipAvailability { get; set; }
//检修一次合格率
public double percentPassOnetimeRepair { get; set; }
//检修一次合格率***参与统计台数
public int Count_percentPassOnetimeRepair { get; set; }
//机泵平均效率n1--统计指标
public double avgEfficiencyPump { get; set; }
//机组平均效率n2--统计指标
public double avgEfficiencyUnit { get; set; }
//隐患排查情况
public string hiddenDangerInvestigation { get; set; }
//负荷率
public string rateLoad { get; set; }
//工艺变更
public string gyChange { get; set; }
//设备变更
public string equipChange { get; set; }
//其他说明
public string otherDescription { get; set; }
//装置设备运行情况基本评估
public string evaluateEquipRunStaeDesc { get; set; }
//装置设备运行情况基本评估附图
public string evaluateEquipRunStaeImgPath { get; set; }
//可靠性结论
public string reliabilityConclusion { get; set; }
//机动处建议及改进措施
public string jdcAdviseImproveMeasures { get; set; }
//提交单位: XX片区或检修单位
public string submitDepartment { get; set; }
//单位提交人
public string submitUser { get; set; }
//单位提交时间
public DateTime? submitTime { get; set; }
//机动处操作人
public string jdcOperator { get; set; }
//机动处操作时间
public DateTime? jdcOperateTime { get; set; }
//进度状态: 0-单位保存,1-单位提交完成,2-机动处保存,3-机动处提交
public int state { get; set; }
//报告类型: 月报或年报
public string reportType { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A5dot1Tab1 //用于提报不完好内容
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
public string pqName { get; set; }
//车间
public string cjName { get; set; }
//装置
public string zzName { get; set; }
//设备位号
public string sbGyCode { get; set; }
//设备编号
[Required()]
public string sbCode { get; set; }
//设备型号
public string sbType { get; set; }
//不完好内容
public string notGoodContent { get; set; }
//是否整改 0-未整改 1-已整改
public int isRectified { get; set; }
//专业分类
public string zyType { get; set; }
//现场工程师
public string zzUserName { get; set; }
//现场工程师提报时间
public DateTime? zzSubmitTime { get; set; }
//可靠性工程师
public string pqUserName { get; set; }
//可靠性工程师检查时间
public DateTime? pqCheckTime { get; set; }
//统计年月
public string yearMonthForStatistic { get; set; }
//数据来源: A5dot1现场工程师提报;A5dot1检修单位新增;A13dot1
public string dataSource { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A5dot1Tab2 //用于统计不完好内容,以及筛选最差5台和10台
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
public string pqName { get; set; }
//车间
public string cjName { get; set; }
//装置
public string zzName { get; set; }
//设备位号
public string sbGyCode { get; set; }
//设备编号
[Required()]
public string sbCode { get; set; }
//设备型号
public string sbType { get; set; }
//不完好内容及整改情况
public string notGoodContents { get; set; }
//当月不完好次数
public int timesNotGood { get; set; }
//当前累计未整改不完好项数
public int countAllNoRectifed { get; set; }
//专业分类
public string zyType { get; set; }
//问题描述
public string problemDescription { get; set; }
//问题分析与处理建议
public string problemAnalysisAdvise { get; set; }
//处理手段与方法
public string processMeansMethods { get; set; }
//处理结果 勾选-待处理、处理中、已处理
public string processReuslt { get; set; }
//是否列入最差5台机泵 0-否(默认),1-是
public int isSetAsTop5Worst { get; set; }
//是否列入最差10台机泵 0-否(默认),1-是
public int isSetAsTop10Worst { get; set; }
//可靠性工程师
public string pqUserName { get; set; }
//检修单位人员
public string jxdwUserName { get; set; }
//机动处
public string jdcUserName { get; set; }
//统计年月
public string yearMonthForStatistic { get; set; }
//进度状态 0-默认;1-片区挑选完成;2-检修单位修改完成;3-机动处汇总完成
public int state { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A5dot2Tab1 //用于提报竖向问题
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
public string pqName { get; set; }
//车间
public string cjName { get; set; }
//装置
public string zzName { get; set; }
//设备位号
public string sbGyCode { get; set; }
//设备编号
[Required()]
public string sbCode { get; set; }
//设备型号
public string sbType { get; set; }
//竖向问题描述
public string problemDescription { get; set; }
//是否整改 0-未整改 1-已整改
public int isRectified { get; set; }
//专业分类
public string zyType { get; set; }
//检修人员
public string jxUserName { get; set; }
//检修人员提报时间
public DateTime? jxSubmitTime { get; set; }
//可靠性工程师
public string pqUserName { get; set; }
//可靠性工程师检查时间
public DateTime? pqCheckTime { get; set; }
//统计年月
public string yearMonthForStatistic { get; set; }
//进度状态 0-默认;1-片区操作完成
public int state { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A5dot2Tab2 //用于统计竖向问题,以及筛选最脏10台
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
public string pqName { get; set; }
//车间
public string cjName { get; set; }
//装置
public string zzName { get; set; }
//设备位号
public string sbGyCode { get; set; }
//设备编号
[Required()]
public string sbCode { get; set; }
//设备型号
public string sbType { get; set; }
//本月竖向问题次数
public int nProblemsInCurMonth { get; set; }
//全年竖向问题次数
public int nProblemsInCurYear { get; set; }
//专业分类
public string zyType { get; set; }
//问题描述
public string problemDescription { get; set; }
//是否列入最脏10台机泵 0-否(默认),1-是
public int isSetAsTop10Worst { get; set; }
//机动处
public string jdcUserName { get; set; }
//机动处操作时间
public DateTime? jdcOperateTime { get; set; }
//统计年月
public string yearMonthForStatistic { get; set; }
//进度状态 0-默认;1-机动处操作完成
public int state { get; set; }
//预留字段1
public string temp1 { get; set; }
//预留字段2
public string temp2 { get; set; }
//预留字段3
public string temp3 { get; set; }
}
public class A6dot2Tab1 //用于记录上传五定表的日志信息
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string userName { get; set; }
public string pqName { get; set; }
public string uploadtime { get; set; }
public string uuploadFileName { get; set; }
public string uploadDesc { get; set; }
public virtual ICollection<A6dot2Tab2> WDTable_details { get; set; }
}
public class A6dot2Tab2 //用于记录上传五定表的详细数据
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string equipCode { get; set; }
public string equipDesc { get; set; }
public string funLoc { get; set; }
public string funLoc_desc { get; set; }
public string oilLoc { get; set; }
public string oilLoc_desc { get; set; }
public int oilInterval { get; set; }
public string unit { get; set; }
public string lastOilTime { get; set; }
public double lastOilNumber { get; set; }
public string lastOilUnit { get; set; }
public string NextOilTime { get; set; }
public double NextOilNumber { get; set; }
public string NextOilUnit { get; set; }
public string oilCode { get; set; }
public string oilCode_desc { get; set; }
public string substiOilCode { get; set; }
public string substiOilCode_desc { get; set; }
public string equip_PqName { get; set; }
public string equip_CjName { get; set; }
public string equip_ZzName { get; set; }
public int isExceed { get; set; }
public int isOilType { get; set; }
public int isValid { get; set; }
public int Tab1_Id { get; set; }
public virtual A6dot2Tab1 Tab1_Belong { get; set; }
}
public class A6dot2LsTaskTab
{
/// <summary>
/// 主键
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Zz_Name { get; set; }
public string Equip_Gybh { get; set; }
public string Equip_Code { get; set; }
public string lastOilTime { get; set; }
public int oilInterval { get; set; }
public string NextOilTime { get; set; }
public string cur_problem { get; set; }
public string cur_status { get; set; }
public string wfd_id { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using iTextSharp.text.pdf;
using iTextSharp.text;
using EquipBLL.AdminManagment.MenuConfig;
namespace WebApp.Controllers
{
public class A15dot1jingController: CommonController
{
private KpiManagement Jx = new KpiManagement();
public class submitmodel
{
public string troubleKoufen;//故障强度扣分
public string equipFushil;//设备腐蚀泄漏次数(有毒有害易燃易爆介质)
public string thousandColdChangeRate;//千台冷换设备管束(含整台)更换率
public string gongyelu;//工业炉(>=10MW)平均热效率
public string huanreqiRate;//换热器检修率
public string pressureRate;//压力容器定检率
public string yaliguandao;//压力管道年度检验计划完成率
public string safeRate;//安全阀年度校验计划完成率
public string equipFushiRate;//设备腐蚀监测计划完成率
public string jingEquipRate;//静设备检维修一次合格率
public List<Equip_Archi> UserHasEquips;
}
public ActionResult Submit()
{
submitmodel sm = new submitmodel();
ViewBag.curtime = DateTime.Now;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
sm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(sm);
}
public bool Submit_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabJing new_15dot1Jing = new A15dot1TabJing();
new_15dot1Jing.gzqdkf = Convert.ToInt32(item["gzqdkf"].ToString());
new_15dot1Jing.sbfsxlcs = Convert.ToInt32(item["sbfsxlcs"].ToString());
new_15dot1Jing.qtlhsbgs = Convert.ToInt32(item["qtlhsbgs"].ToString());
new_15dot1Jing.gylpjrxl = Convert.ToDouble(item["gylpjrxl"].ToString());
new_15dot1Jing.hrqjxl = Convert.ToDouble(item["hrqjxl"].ToString());
new_15dot1Jing.ylrqdjl = Convert.ToDouble(item["ylrqdjl"].ToString());
new_15dot1Jing.ylgdndjxjhwcl = Convert.ToInt32(item["ylgdndjxjhwcl"].ToString());
new_15dot1Jing.aqfndjyjhwcl = Convert.ToInt32(item["aqfndjyjhwcl"].ToString());
new_15dot1Jing.sbfsjcjhwcl = Convert.ToDouble(item["sbfsjcjhwcl"].ToString());
new_15dot1Jing.jsbjwxychgl = Convert.ToDouble(item["jsbjwxychgl"].ToString());
new_15dot1Jing.temp3 = item["cjname"].ToString();
new_15dot1Jing.submitDepartment = item["submitDepartment"].ToString();
new_15dot1Jing.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1Jing.submitTime = DateTime.Now;
new_15dot1Jing.state = 0;
new_15dot1Jing.reportType = item["reportType"].ToString();
new_15dot1Jing.temp2 = "静设备专业";
bool res = Jx.AddJingItem(new_15dot1Jing);
return res;
}
}
}<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
/// <summary>
/// 对表File_Catalog的访问接口
/// </summary>
public class WorkSummaryCatalog : BaseDAO
{
//根据分类号查找分类
public WorkSumCatalog GetCatalog(int cat_ID)
{
using (var db = base.NewDB())
{
var fc = db.WCatalogs.Where(s => s.Catalog_Id == cat_ID).First();
return fc;
}
}
//根据分类名称查找分类
public List<WorkSumCatalog> GetCatalog(string cat_name)
{
using (var db = base.NewDB())
{
return db.WCatalogs.Where(s => s.Catalog_Name == cat_name).ToList();
}
}
//查找分类的子分类
public List<WorkSumCatalog> GetChildCatalogs(int cat_ID)
{
using (var db = base.NewDB())
{
var fc = db.WCatalogs.Where(s => s.Catalog_Id == cat_ID).First();
if (fc == null)
return null;
return fc.Child_Catalogs.ToList();
}
}
//查找分类的父类
public WorkSumCatalog GetParentCatalog(int cat_ID)
{
using (var db = base.NewDB())
{
var fc = db.WCatalogs.Where(s => s.Catalog_Id == cat_ID).First();
if (fc == null)
return null;
return fc.parent_Catalog;
}
}
public DbSet<WorkSumCatalog> GetCatalogsSet()
{
return base.NewDB().WCatalogs;
}
/// <summary>
/// 添加一个新分类
/// </summary>
/// <param name="p_ID">父节点ID</param>
/// <param name="n_Name">新节点名称</param>
/// <returns></returns>
public bool AddNewCatalog(int p_ID, string n_Name)
{
using (var db = base.NewDB())
{
WorkSumCatalog nfc = new WorkSumCatalog();
nfc.Catalog_Name = n_Name;
if (p_ID != -1)
{
var fc = db.WCatalogs.Where(s => s.Catalog_Id == p_ID).First();
if (fc == null)
return false;
fc.Child_Catalogs.Add(nfc);
}
else
{
db.WCatalogs.Add(nfc);
}
db.SaveChanges();
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="ID"></param>
/// <returns></returns>
public bool DeleteCatalog(int ID)
{
bool bResult = false;
try
{
using (var db = base.NewDB())
{
db.WCatalogs.Remove(db.WCatalogs.Where(s => s.Catalog_Id == ID).First());
db.SaveChanges();
}
bResult = true;
}
catch
{
bResult = false;
}
return bResult;
}
public bool ModifyCatalog(int ID, string name)
{
bool bResult = false;
try
{
using (var db = base.NewDB())
{
db.WCatalogs.Where(s => s.Catalog_Id == ID).First().Catalog_Name = name;
db.SaveChanges();
}
}
catch
{
bResult = false;
}
return bResult;
}
public List<WorkSummary> GetFiles(int ID)
{
List<WorkSummary> files = null;
try
{
using (var db = base.NewDB())
{
files = db.WCatalogs.Where(s => s.Catalog_Id == ID).First().Files_Included.ToList();
foreach (var item in files)
{
item.Mission_Id = item.File_Submiter.Person_Id;
}
}
}
catch
{
files = null;
}
return files;
}
public bool AddFiletoCatalog(int pID, WorkSummary nf)
{
try
{
using (var db = base.NewDB())
{
db.WCatalogs.Where(s => s.Catalog_Id == pID).First().Files_Included.Add(nf);
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class GetNWorkSer : BaseDAO
{
private static object insert_lock = new object();
public NWorkFlowSer AddNWorkEntity(string wfName, string WE_Ser = "")
{
NWorkFlowSer NW = new NWorkFlowSer();
NWorkFlowSer n = new NWorkFlowSer();
lock (insert_lock)
{ //locked
using (var db = base.NewDB())
{
if (WE_Ser == "") //保证子工作流串号与父工作流相同
{
//对WorkFlow_Entity编号的处理
string perFix = DateTime.Now.ToString("yyyyMM");
IQueryable<NWorkFlowSer> we_Ser = db.NWorkFlowSer.Where(s => s.WE_Ser.StartsWith("N" + perFix)).OrderBy(s => s.WE_Ser);
if (we_Ser.ToList().Count == 0)
WE_Ser = "N" + perFix + "00001";
else
{
string last_ser = we_Ser.ToList().Last().WE_Ser;
string[] b = last_ser.Split(new Char[] { 'N' });
string num_ser = b[1];
WE_Ser = "N" + (Convert.ToInt64(b[1]) + 1).ToString();
}
NW.time = DateTime.Now;
NW.WE_Ser = WE_Ser;
NW.WF_Name = wfName;
n = db.NWorkFlowSer.Add(NW);
if (db.SaveChanges() != 1)
return null;
}
else
{
NW.time = DateTime.Now;
NW.WE_Ser = WE_Ser;
NW.WF_Name = wfName;
n = db.NWorkFlowSer.Add(NW);
if (db.SaveChanges() != 1)
return null;
}
}
}//unlocked
return n;
}
}
}
<file_sep>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MVCTest.Models.User
{
public class UserInfo
{
[Key]
public string name { get; set; }
public string password { get; set; }
public virtual Role my_role { get; set; }
public virtual Depart my_depart { get; set; }
}
}<file_sep>///////////////////////////////////////////////////////////
// CEndEvent.cs
// Implementation of the Class CEndEvent
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine.Event;
using FlowEngine;
using System.Xml;
using System.Net;
using System.Diagnostics;
namespace FlowEngine.Event {
public class CEndEvent : CEvent {
public CEndEvent(CWorkFlow parent) : base(parent){
}
~CEndEvent(){
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public override void InstFromXmlNode(XmlNode xmlNode){
//1. 解析基类CEvent的成员
base.InstFromXmlNode(xmlNode);
//2. 解析EndEvent的成员
}
/// <summary>
/// 反解析到XML元素
/// </summary>
public override XmlNode WriteToXmlNode(){
//1. 反解析基类部分成员
XmlNode xn = base.WriteToXmlNode();
//2. 反解析CombEvent的成员
XmlElement xe = (XmlElement)xn;
xe.SetAttribute("type", "endevent");
return xn;
}
/// <summary>
/// 进入该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void EnterEvent(string strjson){
if (beforeaction != "")
{
string strjson1 = "{param:'{";
foreach (var par in m_beforeActionParams)
{
string tmp = string.Format("{0}:\"{1}\",", par.Key, parselEventActionParams(par.Value));
strjson1 += tmp;
}
strjson1.TrimEnd(new char[] { ',' });
strjson1 += "}'}";
try
{
byte[] bytes = Encoding.UTF8.GetBytes(strjson1);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(beforeaction);
request.ContentType = @"application/json";
request.Accept = "application/xml";
request.Method = "POST";
request.ContentLength = bytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Dispose();
//结束动作函数返回值
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//对返回结果进行处理
OpResutsfromAction(sr.ReadToEnd());
}
catch (Exception e)
{
Trace.WriteLine("EnterEvent error:" + e.Message);
//return;
}
}
base.UpdateCurrentEvent(true);
m_timeout.RegTimeoutTimer(false);
}
/// <summary>
/// 离开该事件(Event)
/// </summary>
/// <param name="strjson"></param>
public override void LeaveEvent(string strjson){
if (beforeaction != "")
{
string strjson1 = "{param:'{";
foreach (var par in m_afterActionParams)
{
string tmp = string.Format("{0}:\"{1}\",", par.Key, parselEventActionParams(par.Value));
strjson1 += tmp;
}
strjson1.TrimEnd(new char[] { ',' });
strjson1 += "}'}";
try
{
byte[] bytes = Encoding.UTF8.GetBytes(strjson1);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(afteraction);
request.ContentType = @"application/json";
request.Accept = "application/xml";
request.Method = "POST";
request.ContentLength = bytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Dispose();
//结束动作函数返回值
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//对返回结果进行处理
OpResutsfromAction(sr.ReadToEnd());
}
catch (Exception e)
{
Trace.WriteLine("EnterEvent error:" + e.Message);
//return;
}
}
//2016.1.3 添加子事件返回
base.InsertMissionToDB();
//清空工作流的当前任务
base.UpdateCurrentEvent(true);
m_timeout.UnregTimeoutTimer();
}
}//end CEndEvent
}//end namespace Event<file_sep>using FlowDesigner.ConfigItems;
using System;
using System.Activities.Presentation.Converters;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.PropertyEditing;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
namespace FlowDesigner.PropertyEditor
{
class ParamTransferEditor : DialogPropertyValueEditor
{
public ParamTransferEditor()
{
string template = @"
<DataTemplate
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:pe='clr-namespace:System.Activities.Presentation.PropertyEditing;assembly=System.Activities.Presentation'>
<DockPanel LastChildFill='True'>
<pe:EditModeSwitchButton TargetEditMode='Dialog' Name='EditButton'
DockPanel.Dock='Right'>...</pe:EditModeSwitchButton>
<TextBlock Text='集合' Margin='2,0,0,0' VerticalAlignment='Center'/>
</DockPanel>
</DataTemplate>";
using (var sr = new MemoryStream(Encoding.UTF8.GetBytes(template)))
{
this.InlineEditorTemplate = XamlReader.Load(sr) as DataTemplate;
}
}
public override void ShowDialog(PropertyValue propertyValue, System.Windows.IInputElement commandSource)
{
ParamTransferWin wn = new ParamTransferWin(propertyValue.Value as List<paramtransfer_item>);
//wn.newValue = propertyValue.Value as List<string>;
if (wn.ShowDialog().Equals(true))
{
var ownerActivityConverter = new ModelPropertyEntryToOwnerActivityConverter();
ModelItem activityItem = ownerActivityConverter.Convert(propertyValue.ParentProperty, typeof(ModelItem), false, null) as ModelItem;
using(ModelEditingScope editingScope = activityItem.BeginEdit())
{
propertyValue.Value = wn.params_transfer;
editingScope.Complete();
var control = commandSource as Control;
var oldData = control.DataContext;
control.DataContext = null;
control.DataContext = oldData;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Runhua_Info
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Runhua_Id { get; set; }
/// <summary>
/// 生产车间名称
/// </summary>
public string EA_Name { get; set; }
/// <summary>
/// 润滑油间名称
/// </summary>
public string RH_Name { get; set; }
/// <summary>
/// 润滑油间负责的生产装置
/// </summary>
public string RH_ZZ_Name { get; set; }
/// <summary>
/// 润滑油间情况
/// </summary>
public string RH_Detail { get; set; }
/// <summary>
/// 预留字段1
/// </summary>
public string res1 { get; set; }
/// <summary>
/// 预留字段2
/// </summary>
public string res2 { get; set; }
/// <summary>
/// 预留字段3
/// </summary>
public string res3 { get; set; }
public string Equip_GyCode { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.Modals;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Xml;
using FlowEngine.Event;
using FlowEngine.DAL;
using FlowEngine.Param;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace WebApp.Controllers
{
public class A13dot1Controller : CommonController
{
public class MissHisLinkModal
{
public int Miss_Id;
public string Miss_Name;
public string Miss_Time;
public int Miss_Type; //0:一般任务 1:子流程任务
public string Miss_LinkFlowType;//"Normal" ,"paradel","Serial"
public int Miss_LinkFlowId;//跳转的工作流Id
}
public class ListMissHisLInkModal
{
public int Flow_Id;
public string Flow_Name;
public List<MissHisLinkModal> Miss;
}
public ActionResult A13()
{
NoticeManagement NM = new NoticeManagement();
List<Notice_A13dot1> list = NM.getNoticeForA13dot1Uncomp();
ViewBag.NoticeCount = list.Count();
return View();
}
public ActionResult Index1(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
//
// GET: /A13dot1/
public ActionResult Index()
{
return View(getIndexListRecords("A13dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A13dot1/装置提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A13dot1/可靠性工程师分类
public ActionResult PqCatalog(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A13dot1/专业团队审核
public ActionResult ZytdConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WorkFlow_HisDetailParallel(int Entity_Id)
{
List<UI_MISSION> miss;
ListMissHisLInkModal missModals = new ListMissHisLInkModal();
missModals.Miss = new List<MissHisLinkModal>();
UI_WFEntity_Info wfe = CWFEngine.GetWorkFlowEntiy(Entity_Id, true);
missModals.Flow_Id = Entity_Id;
missModals.Flow_Name = wfe.name;
miss = CWFEngine.GetHistoryMissions(wfe.EntityID);
if (wfe.Status == WE_STATUS.ACTIVE)
{
miss.Add(CWFEngine.GetActiveMission<Person_Info>(wfe.EntityID, null, false));
}
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe2 = wfs.GetWorkFlowEntity(wfe.EntityID);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe2.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wf.EntityID = wfe.EntityID;
IDictionary<string, IEvent> allEvents = wf.events;
foreach (var item in miss)
{
MissHisLinkModal m = new MissHisLinkModal();
m.Miss_Id = item.Miss_Id;
m.Miss_Name = item.WE_Event_Desc;
if (item.Miss_Id > 0)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
m.Miss_Time = r["time"];
}
else
{
m.Miss_Time = "";
}
}
else
{
m.Miss_Time = "";
}
if (allEvents[item.WE_Event_Name].GetType().Name == "CSubProcessEvent")
{
m.Miss_Type = 1;
m.Miss_LinkFlowType = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WorkingMode;
m.Miss_LinkFlowId = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WfEntityId;
}
else
{
m.Miss_Type = 0;
m.Miss_LinkFlowType = "Normal";
m.Miss_LinkFlowId = -1;
}
missModals.Miss.Add(m);
}
return View(missModals);
}
public ActionResult WorkFlow_HisDetail()
{
List<UI_MISSION> miss;
ListMissHisLInkModal missModals = new ListMissHisLInkModal();
missModals.Miss = new List<MissHisLinkModal>();
UI_WFEntity_Info wfe=CWFEngine.GetMainWorkFlowEntity("20160200010");
missModals.Flow_Id = wfe.EntityID;
missModals.Flow_Name = wfe.name;
miss = CWFEngine.GetHistoryMissions(wfe.EntityID);
if (wfe.Status == WE_STATUS.ACTIVE)
{
miss.Add(CWFEngine.GetActiveMission<Person_Info>(wfe.EntityID, null, false));
}
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe2 = wfs.GetWorkFlowEntity(wfe.EntityID);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe2.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wf.EntityID = wfe.EntityID;
IDictionary<string,IEvent> allEvents=wf.events;
foreach (var item in miss)
{
MissHisLinkModal m = new MissHisLinkModal();
m.Miss_Id = item.Miss_Id;
m.Miss_Name = item.WE_Event_Desc;
if (item.Miss_Id>0)
{ IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0 )
{
m.Miss_Time = r["time"];
}
else
{
m.Miss_Time = "";
}
}
else{
m.Miss_Time = "";
}
if(allEvents[item.WE_Event_Name].GetType().Name=="CSubProcessEvent")
{
m.Miss_Type = 1;
m.Miss_LinkFlowType = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WorkingMode;
m.Miss_LinkFlowId = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WfEntityId;
}else
{ m.Miss_Type = 0;
m.Miss_LinkFlowType = "Normal";
m.Miss_LinkFlowId = -1;
}
missModals.Miss.Add(m);
}
return View(missModals);
}
public JsonResult WorkFlow_SubProcess( int FlowId)
{
List<UI_MISSION> miss;
ListMissHisLInkModal missModals = new ListMissHisLInkModal();
missModals.Miss = new List<MissHisLinkModal>();
UI_WFEntity_Info wfe = CWFEngine.GetWorkFlowEntiy(FlowId,true);
missModals.Flow_Id = FlowId;
missModals.Flow_Name = wfe.name;
miss = CWFEngine.GetHistoryMissions(wfe.EntityID);
if (wfe.Status == WE_STATUS.ACTIVE)
{
miss.Add(CWFEngine.GetActiveMission<Person_Info>(wfe.EntityID, null, false));
}
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe2 = wfs.GetWorkFlowEntity(wfe.EntityID);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe2.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wf.EntityID = wfe.EntityID;
IDictionary<string, IEvent> allEvents = wf.events;
foreach (var item in miss)
{
MissHisLinkModal m = new MissHisLinkModal();
m.Miss_Id = item.Miss_Id;
m.Miss_Name = item.WE_Event_Desc;
if (item.Miss_Id > 0)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
m.Miss_Time = r["time"];
}
else
{
m.Miss_Time = "";
}
}
else
{
m.Miss_Time = "";
}
if (allEvents[item.WE_Event_Name].GetType().Name == "CSubProcessEvent")
{
m.Miss_Type = 1;
m.Miss_LinkFlowType = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WorkingMode;
m.Miss_LinkFlowId = ((CSubProcessEvent)allEvents[item.WE_Event_Name]).WfEntityId;
}
else
{
m.Miss_Type = 0;
m.Miss_LinkFlowType = "Normal";
m.Miss_LinkFlowId = -1;
}
missModals.Miss.Add(m);
}
return Json(missModals);
}
public JsonResult WorkFlow_ListParam(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
int Flow_Id = Convert.ToInt32(item["Entity_Id"].ToString());
int Mission_Id = Convert.ToInt32(item["Mission_Id"].ToString());
List<UI_MissParam> MissParams = CWFEngine.GetMissionParams(Flow_Id,Mission_Id);
return Json(MissParams.ToArray());
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Problem_Desc"] = item["Problem_Desc"].ToString();
signal["Problem_DescFilePath"] = item["Problem_DescFilePath"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
//signal["Equip_ABCMark"] = "A";//for test
signal["Data_Src"] ="人工提报"; //格式统一
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A13dot1/Index");
}
public string PqCatalog_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
Dictionary<string, string> signal = new Dictionary<string, string>();
var flowname = Convert.ToInt32(item["Flow_Name"].ToString());
signal["catlog_type"] = item["catlog_type"].ToString();
if (item["catlog_type"].ToString() == "完好类" )
{
string[] notgood = item["Incomplete_content"].ToString().Split('|');
WorkFlows wfsd = new WorkFlows();
WorkFlows wfs = new WorkFlows();
Mission db_miss = wfsd.GetWFEntityMissions(flowname).Last();//获取该实体最后一个任务
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(flowname);
UI_MISSION ui_mi = new UI_MISSION();
ui_mi.WE_Entity_Id = flowname;
ui_mi.WE_Event_Desc = db_miss.Miss_Desc;
ui_mi.WE_Event_Name = db_miss.Event_Name;
ui_mi.WE_Name = db_miss.Miss_Name;
ui_mi.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
List<Mission> gettime = wfs.GetWFEntityMissions(flowname);//获取实体的所有任务找到第二个任务获取提报时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(gettime[1].Miss_Id);
if (timeanduser.Count > 0)
{
ui_mi.Mission_Url = timeanduser["username"];
ui_mi.WE_Entity_Ser = timeanduser["time"];
}
else
{
ui_mi.Mission_Url = "";
ui_mi.WE_Entity_Ser = "";
}
A5dot1Tab1 a5dot1Tab1 = new A5dot1Tab1();
DateTime my = DateTime.Now;
string yearmonth = "";
if (my.Day >= 15)
{
yearmonth = my.Year.ToString() + my.AddMonths(1).Month.ToString();
}
else
{
yearmonth = my.Year.ToString() + my.Month.ToString();
}
if (notgood[notgood.Count() - 1] == "")
{
for (int i = 0; i < notgood.Count() - 1; i++)
{
a5dot1Tab1.cjName = ui_mi.Miss_Params["Cj_Name"].ToString();
a5dot1Tab1.zzName = ui_mi.Miss_Params["Zz_Name"].ToString();
a5dot1Tab1.sbGyCode = ui_mi.Miss_Params["Equip_GyCode"].ToString();
a5dot1Tab1.sbCode = ui_mi.Miss_Params["Equip_Code"].ToString();
a5dot1Tab1.sbType = ui_mi.Miss_Params["Equip_Type"].ToString();
a5dot1Tab1.zyType = ui_mi.Miss_Params["Zy_Type"].ToString();
a5dot1Tab1.notGoodContent = notgood[i];
a5dot1Tab1.isRectified = 0;
a5dot1Tab1.zzSubmitTime = Convert.ToDateTime(ui_mi.WE_Entity_Ser);
a5dot1Tab1.zzUserName = ui_mi.Mission_Url;
a5dot1Tab1.yearMonthForStatistic = yearmonth;
a5dot1Tab1.temp2 = Convert.ToString(flowname);
TablesManagment tm = new TablesManagment();
tm.Zzsubmit(a5dot1Tab1);
}
}
else
{
for (int i = 0; i < notgood.Count(); i++)
{
a5dot1Tab1.cjName = ui_mi.Miss_Params["Cj_Name"].ToString();
a5dot1Tab1.zzName = ui_mi.Miss_Params["Zz_Name"].ToString();
a5dot1Tab1.sbGyCode = ui_mi.Miss_Params["Equip_GyCode"].ToString();
a5dot1Tab1.sbCode = ui_mi.Miss_Params["Equip_Code"].ToString();
a5dot1Tab1.sbType = ui_mi.Miss_Params["Equip_Type"].ToString();
a5dot1Tab1.zyType = ui_mi.Miss_Params["Zy_Type"].ToString();
a5dot1Tab1.notGoodContent = notgood[i];
a5dot1Tab1.isRectified = 0;
a5dot1Tab1.zzSubmitTime = Convert.ToDateTime(ui_mi.WE_Entity_Ser);
a5dot1Tab1.zzUserName = ui_mi.Mission_Url;
a5dot1Tab1.yearMonthForStatistic = yearmonth;
a5dot1Tab1.temp2 = Convert.ToString(flowname);
TablesManagment tm = new TablesManagment();
tm.Zzsubmit(a5dot1Tab1);
}
}
}
else if (item["catlog_type"].ToString() == "隐患")
{
signal["defect_level"] = item["defect_level"].ToString();
}
else if (item["catlog_type"].ToString() == "故障")
{
signal["defect_level"] = item["defect_level"].ToString();
signal["fault_intensity"] = item["fault_intensity"].ToString();
}
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{ return ""; }
return ("/A13dot1/Index");
}
public string ZytdConfirm_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
string ser = CWFEngine.GetWorkFlowEntiy(Convert.ToInt32(flowname), false).serial;
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["fault_intensity"] = item["fault_intensity"].ToString();
signal["ZytdConfirm_Result"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
//======================================2016.6.22================================================
//DRBPM紧急检修计划 : writeDRBPM(string sbcode,string reason, bool isUrgent)
string Equip_Code = item["Equip_Code"].ToString();
writeDRBPM(Equip_Code, "一级缺陷", true,ser); // write to drbpm
//======================================================================================
return ("/A13dot1/Index");
}
public string defectmanagement(string json1)
{
List<object> r = new List<object>();//存放返回结果
TablesManagment tm = new TablesManagment();
List<UI_WFEntity_Info> miss_done;
miss_done = CWFEngine.GetWFEntityByHistoryDone(t => t.Miss_WFentity.WE_Wref.W_Name == "A13dot1");
List<UI_MISSION> his_missdone = new List<UI_MISSION>();//最后一步均为跳转,因此最后一步关联了所需的所有参数,可直接获得最后一步的任务参数即可
WorkFlows wfsd = new WorkFlows();
foreach (var item in miss_done)//获得entity_id
{
Mission db_miss = wfsd.GetWFEntityMissions(item.EntityID).Last();//获取该实体最后一个任务
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.EntityID);
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui_mi = new UI_MISSION();
ui_mi.WE_Entity_Id = item.EntityID;
ui_mi.WE_Entity_Ser = wfe.WE_Ser;
ui_mi.WE_Event_Desc = db_miss.Miss_Desc;
ui_mi.WE_Event_Name = db_miss.Event_Name;
ui_mi.WE_Name = db_miss.Miss_Name;
ui_mi.Mission_Url = ""; //历史任务的页面至空
ui_mi.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
List<Mission> gettime = wfs.GetWFEntityMissions(item.EntityID);//获取实体的所有任务找到第二个任务获取提报时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(gettime[1].Miss_Id);
if (timeanduser.Count > 0)
{
ui_mi.Mission_Url = timeanduser["username"];
ui_mi.WE_Event_Desc = timeanduser["time"];
}
else
{
ui_mi.Mission_Url = "";
ui_mi.WE_Event_Desc = "";
}
his_missdone.Add(ui_mi);
}
for (int i = 0; i < his_missdone.Count; i++)
{
string chulijindu = "处理中";
string[] total_time = new string[4];//最多4个完好问题,因此4个时间
string completetime = "2010/7/7";
if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "隐患")
continue;
if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "不需处理")//不需处理
{
chulijindu = "处理完成";
Mission db_miss = wfsd.GetWFEntityMissions(his_missdone[i].WE_Entity_Id).Last();
//获取当前任务的完成时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_miss.Miss_Id);
if (timeanduser.Count > 0)
{
completetime = timeanduser["time"];
}
else
{
completetime = "";
}
if (completetime == "2010/7/7")
{
completetime = "";
}
if (chulijindu == "处理中")
{
completetime = "";
}
}
if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "完好类")//完好跳转A5dot1跟踪
{
chulijindu = "处理完成";
List<A5dot1Tab1> mission = tm.get_recordbyentity(his_missdone[i].WE_Entity_Id.ToString());
for (int k = 0; k < mission.Count; k++)
{
if (mission[k].isRectified == 0)
{
chulijindu = "处理中";
}
total_time[k] = mission[k].pqCheckTime.ToString();
if (total_time[k] != null)
{
if (total_time[k] != "")
{
if (Convert.ToDateTime(total_time[k]) > Convert.ToDateTime(completetime))
{
completetime = total_time[k];
}
}
}
}
if (completetime == "2010/7/7")
{
completetime = "";
}
if (chulijindu == "处理中")
{
completetime = "";
}
}
//else if(his_missdone[i].Miss_Params["catlog_type"].ToString()=="隐患")//隐患跳转A11dot2跟踪
//{
// //由于跳转到11dot2会产生新实体号,因此通过串号找到该实体号,此方法得到串号对应的所有实体号
// List<WorkFlow_Entity> getentity = wfsd.GetWorkFlowEntitiesbySer(his_missdone[i].WE_Entity_Ser);
// foreach (var item in getentity)
// {
// WorkFlow_Define getentity_name = wfsd.GetWorkFlowDefine(item.WE_Id);//通过每个实体号找到该实体号的名字,就可以确定每个实体号的内容
// if(getentity_name.W_Name=="A11dot2")
// {
// Mission db_miss = wfsd.GetWFEntityMissions(item.WE_Id).Last();
// if (db_miss.Miss_Desc == "现场工程师提报隐患")
// {
// chulijindu = "提报";
// }
// else if (db_miss.Miss_Desc == "可靠性工程师风险矩阵评估" )
// {
// chulijindu = "危害识别中";
// }
// else if(db_miss.Miss_Desc == "专业团队审核")
// {
// WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.WE_Id);
// //CWorkFlow wf = new CWorkFlow();
// WorkFlows wfs = new WorkFlows();
// UI_MISSION ui = new UI_MISSION();
// ui.WE_Entity_Id = item.WE_Id;
// ui.WE_Entity_Ser = wfe.WE_Ser;
// ui.WE_Event_Desc = db_miss.Miss_Desc;
// ui.WE_Event_Name = db_miss.Event_Name;
// ui.WE_Name = db_miss.Miss_Name;
// ui.Mission_Url = ""; //历史任务的页面至空
// ui.Miss_Id = db_miss.Miss_Id;
// List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
// foreach (var par in mis_pars)
// {
// CParam cp = new CParam();
// cp.type = par.Param_Type;
// cp.name = par.Param_Name;
// cp.value = par.Param_Value;
// cp.description = par.Param_Desc;
// ui.Miss_Params[cp.name] = cp.value;
// ui.Miss_ParamsDesc[cp.name] = cp.description;
// }
// //判断风险评估结果所在区域的颜色
// if(ui.Miss_Params["RiskMatrix_Color"].ToString()=="green")
// {
// chulijindu="完成危害识别,结果为绿色";
// }
// else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "red")
// {
// chulijindu = "完成危害识别,结果为红色";
// }
// else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "yellow")
// {
// chulijindu = "完成危害识别,结果为黄色";
// }
// if(ui.Miss_Params["ZytdConfirm_Result"].ToString()=="False")
// {
// chulijindu = "审核未通过,重新评估";
// }
// }
// else if (db_miss.Miss_Desc == "车间确立应急预案")
// {
// chulijindu = "应急预案制定与实施中";
// }
// else if (db_miss.Miss_Desc == "片区监督执行")
// {
// chulijindu = "处理完成";
// WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.WE_Id);
// //CWorkFlow wf = new CWorkFlow();
// WorkFlows wfs = new WorkFlows();
// UI_MISSION ui = new UI_MISSION();
// ui.WE_Entity_Id = item.WE_Id;
// ui.WE_Entity_Ser = wfe.WE_Ser;
// ui.WE_Event_Desc = db_miss.Miss_Desc;
// ui.WE_Event_Name = db_miss.Event_Name;
// ui.WE_Name = db_miss.Miss_Name;
// ui.Mission_Url = ""; //历史任务的页面至空
// ui.Miss_Id = db_miss.Miss_Id;
// List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
// foreach (var par in mis_pars)
// {
// CParam cp = new CParam();
// cp.type = par.Param_Type;
// cp.name = par.Param_Name;
// cp.value = par.Param_Value;
// cp.description = par.Param_Desc;
// ui.Miss_Params[cp.name] = cp.value;
// ui.Miss_ParamsDesc[cp.name] = cp.description;
// }
// if(ui.Miss_Params["Supervise_done"].ToString()=="False")
// {
// chulijindu = "应急预案制定与实施中";
// }
// //获取当前任务的完成时间
// IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_miss.Miss_Id);
// if (timeanduser.Count > 0)
// {
// completetime = timeanduser["time"];
// }
// else
// {
// completetime = "";
// }
// }
// else if (db_miss.Miss_Desc == "跳转到【A11.3】风险管控模块")
// {
// chulijindu = "风险管控";
// }
// }
// //此处写风险管控if(getentity_name.W_Name=="A11dot3")
// }
// if (completetime == "2010/7/7")
// {
// completetime = "";
// }
// if (chulijindu == "处理中")
// {
// completetime = "";
// }
//}
else if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "故障")
{
Mission db_miss = wfsd.GetWFEntityMissions(his_missdone[i].WE_Entity_Id).Last();
if (db_miss.Miss_Desc == "可靠性工程师缺陷分类")
{
chulijindu = "提报";
}
else if (db_miss.Miss_Desc == "专业团队审核")
{
chulijindu = "机动处已确认";
}
//按时间和设备编号在workflow中查询A8.2的实体号
string query_list = "E.W_Name,E.WE_Id,M.Event_Name, R.time";
string query_condition = string.Format("P.Equip_Code in ({0}) and E.W_Name = 'A8dot2'", his_missdone[i].Miss_Params["Equip_Code"]);
//时间为当月
DateTime dtime = DateTime.Now;
dtime = dtime.AddDays(-dtime.Day + 1);
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
string record_filter = string.Format("time >= '{0}' ", dtime.ToString()); //"1 <> 1";
System.Data.DataTable dtA8dot2 = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
DataRow[] NNullRows = dtA8dot2.Select("WE_Id is not Null");
if (NNullRows.Length > 0)
{
//由于当月一台设备只有一个流程,实体号唯一,任取NNullRows中一行,再取其中ItemArray中第二个数据(按query_list查询条件)即为实体号
var entityid = NNullRows[0].ItemArray[1];
//获取对应实体号的最后一个任务追踪进度
Mission db_missA8dot2 = wfsd.GetWFEntityMissions(Convert.ToInt32(entityid)).Last();
//写if而不写else if是因为13.1和8.2是断开的,跳转8.2仍满足db_miss.Miss_Desc == "专业团队审核"
if (db_missA8dot2.Miss_Desc == "检修单位按计划建立工单,完善工序、组件")
{
UI_MISSION ui = new UI_MISSION();
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_missA8dot2.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui.Miss_Params[cp.name] = cp.value;
ui.Miss_ParamsDesc[cp.name] = cp.description;
}
chulijindu = "工单已建立并完善,工单号为:" + ui.Miss_Params["Job_Order"].ToString();
}
else if (db_missA8dot2.Miss_Desc == "机动处计划科审2")
{
chulijindu = "检修工单已下达";
}
else if (db_missA8dot2.Miss_Desc == "物资处采购,填写到货时间")
{
chulijindu = "物资采购中";
}
else if (db_missA8dot2.Miss_Desc == "物资处确认到货并通知检修单位")
{
chulijindu = "物资已到货";
}
else if (db_missA8dot2.Miss_Desc == "检修单位上传检修方案" || db_missA8dot2.Miss_Desc == "专业团队审批" || db_missA8dot2.Miss_Desc == "检修单位填写检修内容及关键工序,关联作业指导书" || db_missA8dot2.Miss_Desc == "可靠性工程师审批")
{
chulijindu = "检修方案制定与审判";
}
else if (db_missA8dot2.Miss_Desc == "现场工程师确认是否可实施计划")
{
UI_MISSION ui = new UI_MISSION();
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_missA8dot2.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
ui.Miss_Params[cp.name] = cp.value;
}
if (ui.Miss_Params["ZzConfirmPlan_Result"].ToString() == "是")
{
chulijindu = "检修计划实施中";
}
else if (ui.Miss_Params["ZzConfirmPlan_Result"].ToString() == "否")
{
chulijindu = "检修计划延期";
}
}
else if (db_missA8dot2.Miss_Desc == "检修单位确认施工完毕,上传交工资料")
{
chulijindu = "处理完成";
//获取当前任务的完成时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_missA8dot2.Miss_Id);
if (timeanduser.Count > 0)
{
completetime = timeanduser["time"];
}
else
{
completetime = "";
}
}
}
else
{
chulijindu = "正在DRBPM中处理!";
completetime = "";
}
if (completetime == "2010/7/7")
{
completetime = "";
}
if (chulijindu == "处理中")
{
completetime = "";
}
}
//旧的工作流中没有这两个字段,因此需判断是否存在这两个字段
string NoticeNum = "无";
string userstate = "无";
if (his_missdone[i].Miss_Params.ContainsKey("NoticeNum"))
NoticeNum = his_missdone[i].Miss_Params["NoticeNum"].ToString();
if (his_missdone[i].Miss_Params.ContainsKey("User_State"))
userstate = his_missdone[i].Miss_Params["User_State"].ToString();
object o = new
{
index = i + 1,
noticenum = NoticeNum,
userstate = userstate,
//第一步提报参数
cjnamae = his_missdone[i].Miss_Params["Cj_Name"].ToString(),
zzname = his_missdone[i].Miss_Params["Zz_Name"].ToString(),
equip_gycode = his_missdone[i].Miss_Params["Equip_GyCode"].ToString(),
equip_code = his_missdone[i].Miss_Params["Equip_Code"].ToString(),
equip_type = his_missdone[i].Miss_Params["Equip_Type"].ToString(),
problemdetail = his_missdone[i].Miss_Params["Problem_Desc"].ToString() + '$' + his_missdone[i].Miss_Params["Problem_DescFilePath"].ToString(),
pro_specialty = his_missdone[i].Miss_Params["Zy_Type"].ToString(),
time = his_missdone[i].WE_Event_Desc,//WE_Event_Desc字段暂存时间
pqtype = his_missdone[i].Miss_Params["catlog_type"].ToString(),
jindu = chulijindu,
endtime = completetime,
};
r.Add(o);
}
int count = r.Count;
List<A5dot1Tab1> Allmission = tm.get_All();
for (int te = 0; te < Allmission.Count; te++)
{
if (Allmission[te].temp2 == null)
{
string jindu = "处理中";
string edtime = "";
if (Allmission[te].isRectified == 1)
{
jindu = "处理完成";
edtime = Allmission[te].pqCheckTime.ToString();
}
object x = new
{
index = count + 1,
noticenum = "无",
userstate = "无",
//第一步提报参数
cjnamae = Allmission[te].cjName,
zzname = Allmission[te].zzName,
equip_gycode = Allmission[te].sbGyCode,
equip_code = Allmission[te].sbCode,
equip_type = Allmission[te].sbType,
problemdetail = Allmission[te].notGoodContent + '$' + '$',
pro_specialty = Allmission[te].zyType,
time = Allmission[te].zzSubmitTime.ToString(),
pqtype = "完好类",
jindu = jindu,
endtime = edtime,
};
count++;
r.Add(x);
}
}
//11dot2状态监测
List<UI_MISSION> miss;
//有权限
miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, "A11dot2", true);
List<UI_MISSION> his_missdoneA11dot2 = new List<UI_MISSION>();//最后一步均为跳转,因此最后一步关联了所需的所有参数,可直接获得最后一步的任务参数即可
foreach (var item in miss)//获得entity_id
{
Mission db_miss = wfsd.GetWFEntityMissions(item.WE_Entity_Id).Last();//获取该实体最后一个任务
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.WE_Entity_Id);
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui_mi = new UI_MISSION();
ui_mi.WE_Entity_Id = item.WE_Entity_Id;
ui_mi.WE_Entity_Ser = wfe.WE_Ser;
ui_mi.WE_Event_Desc = db_miss.Miss_Desc;
ui_mi.WE_Event_Name = db_miss.Event_Name;
ui_mi.WE_Name = db_miss.Miss_Name;
ui_mi.Mission_Url = ""; //历史任务的页面至空
ui_mi.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
ui_mi.Mission_Url = "";
ui_mi.WE_Event_Desc = "";
List<Mission> gettime = wfs.GetWFEntityMissions(item.WE_Entity_Id);//获取实体的所有任务找到第二个任务获取提报时间
if (gettime.Count > 1)
{
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(gettime[1].Miss_Id);
if (timeanduser.Count > 0)
{
ui_mi.Mission_Url = timeanduser["username"];
ui_mi.WE_Event_Desc = timeanduser["time"];
}
else
{
ui_mi.Mission_Url = "";
ui_mi.WE_Event_Desc = "";
}
}
his_missdoneA11dot2.Add(ui_mi);
}
foreach (var re in his_missdoneA11dot2)
{
string chulijindu = "处理中";
string completetime = "2010/7/7";
Mission db_miss = wfsd.GetWFEntityMissions(re.WE_Entity_Id).Last();
if (db_miss.Miss_Desc == "Start")
{
chulijindu = "提报尚未完成";
}
if (db_miss.Miss_Desc == "现场工程师提报隐患")
{
chulijindu = "提报";
}
else if (db_miss.Miss_Desc == "可靠性工程师风险矩阵评估")
{
chulijindu = "危害识别中";
}
else if (db_miss.Miss_Desc == "专业团队审核")
{
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(re.WE_Entity_Id);
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui = new UI_MISSION();
ui.WE_Entity_Id = re.WE_Entity_Id;
ui.WE_Entity_Ser = wfe.WE_Ser;
ui.WE_Event_Desc = db_miss.Miss_Desc;
ui.WE_Event_Name = db_miss.Event_Name;
ui.WE_Name = db_miss.Miss_Name;
ui.Mission_Url = ""; //历史任务的页面至空
ui.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui.Miss_Params[cp.name] = cp.value;
ui.Miss_ParamsDesc[cp.name] = cp.description;
}
//判断风险评估结果所在区域的颜色
if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "green")
{
chulijindu = "完成危害识别,结果为绿色";
}
else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "red")
{
chulijindu = "完成危害识别,结果为红色";
}
else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "yellow")
{
chulijindu = "完成危害识别,结果为黄色";
}
if (ui.Miss_Params["ZytdConfirm_Result"].ToString() == "False")
{
chulijindu = "审核未通过,重新评估";
}
}
else if (db_miss.Miss_Desc == "车间确立应急预案")
{
chulijindu = "应急预案制定与实施中";
}
else if (db_miss.Miss_Desc == "片区监督执行")
{
chulijindu = "处理完成";
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(re.WE_Entity_Id);
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui = new UI_MISSION();
ui.WE_Entity_Id = re.WE_Entity_Id;
ui.WE_Entity_Ser = wfe.WE_Ser;
ui.WE_Event_Desc = db_miss.Miss_Desc;
ui.WE_Event_Name = db_miss.Event_Name;
ui.WE_Name = db_miss.Miss_Name;
ui.Mission_Url = ""; //历史任务的页面至空
ui.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui.Miss_Params[cp.name] = cp.value;
ui.Miss_ParamsDesc[cp.name] = cp.description;
}
if (ui.Miss_Params["Supervise_done"].ToString() == "False")
{
chulijindu = "应急预案制定与实施中";
}
//获取当前任务的完成时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_miss.Miss_Id);
if (timeanduser.Count > 0)
{
completetime = timeanduser["time"];
}
else
{
completetime = "";
}
}
else if (db_miss.Miss_Desc == "跳转到【A11.3】风险管控模块")
{
chulijindu = "风险管控";
}
else if (db_miss.Miss_Desc == "专业团队确立管控措施")
{
chulijindu = "专业团队确立管控措施";
}
else if (db_miss.Miss_Desc == "机动处组织监督实施")
{
chulijindu = "机动处组织监督实施";
}
else if (db_miss.Miss_Desc == "管控措施实施后确认风险是否可接受,并进行风险登记")
{
chulijindu = "管控措施实施后确认风险是否可接受,并进行风险登记";
}
else if (db_miss.Miss_Desc == "车间确立管控措施")
{
chulijindu = "车间确立管控措施";
}
else if (db_miss.Miss_Desc == "可靠性工程师审核")
{
chulijindu = "可靠性工程师审核";
}
else if (db_miss.Miss_Desc == "车间组织监督实施")
{
chulijindu = "车间组织监督实施";
}
else if (db_miss.Miss_Desc == "管控措施实施后确认风险是否消除,并进行风险登记")
{
chulijindu = "管控措施实施后确认风险是否消除,并进行风险登记";
}
if (completetime == "2010/7/7")
{
completetime = "";
}
if (chulijindu == "处理中")
{
completetime = "";
}
//旧的工作流中没有这两个字段,因此需判断是否存在这两个字段
string NoticeNum="无";
string userstate="无";
if(re.Miss_Params.ContainsKey("NoticeNum"))
NoticeNum=re.Miss_Params["NoticeNum"].ToString();
if(re.Miss_Params.ContainsKey("User_State"))
userstate=re.Miss_Params["User_State"].ToString();
object o = new
{
index = count + 1,
//第一步提报参数
cjnamae = re.Miss_Params["Cj_Name"].ToString(),
zzname = re.Miss_Params["Zz_Name"].ToString(),
equip_gycode = re.Miss_Params["Equip_GyCode"].ToString(),
equip_code = re.Miss_Params["Equip_Code"].ToString(),
equip_type = re.Miss_Params["Equip_Type"].ToString(),
problemdetail = re.Miss_Params["Problem_Desc"].ToString() + '$' + re.Miss_Params["Problem_DescFilePath"].ToString(),
pro_specialty = re.Miss_Params["Zy_Type"].ToString(),
time = re.WE_Event_Desc,//WE_Event_Desc字段暂存时间
pqtype = "隐患类",
jindu = chulijindu,
endtime = completetime,
noticenum = NoticeNum,
userstate = userstate
};
r.Add(o);
count++;
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string tongji()
{
List<object> r = new List<object>();//存放返回结果
int Count_WH_Done = 0;//完好类已封闭
int Count_YH_Done = 0;//隐患类已封闭
int Count_GZ_Done = 0;//故障类已封闭
int Count_WH = 0;//完好类未封闭
int Count_YH = 0;//隐患类未封闭
int Count_GZ = 0;//故障类未封闭
List<UI_WFEntity_Info> miss_done;
miss_done = CWFEngine.GetWFEntityByHistoryDone(t => t.Miss_WFentity.WE_Wref.W_Name == "A13dot1");
List<UI_MISSION> his_missdone = new List<UI_MISSION>();//最后一步均为跳转,因此最后一步关联了所需的所有参数,可直接获得最后一步的任务参数即可
WorkFlows wfsd = new WorkFlows();
TablesManagment tm = new TablesManagment();
foreach (var item in miss_done)//获得entity_id
{
Mission db_miss = wfsd.GetWFEntityMissions(item.EntityID).Last();//获取该实体最后一个任务
WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.EntityID);
//CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
UI_MISSION ui_mi = new UI_MISSION();
ui_mi.WE_Entity_Id = item.EntityID;
ui_mi.WE_Entity_Ser = wfe.WE_Ser;
ui_mi.WE_Event_Desc = db_miss.Miss_Desc;
ui_mi.WE_Event_Name = db_miss.Event_Name;
ui_mi.WE_Name = db_miss.Miss_Name;
ui_mi.Mission_Url = ""; //历史任务的页面至空
ui_mi.Miss_Id = db_miss.Miss_Id;
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
// ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
}
List<Mission> gettime = wfs.GetWFEntityMissions(item.EntityID);//获取实体的所有任务找到第二个任务获取提报时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(gettime[1].Miss_Id);
if (timeanduser.Count > 0)
{
ui_mi.Mission_Url = timeanduser["username"];
ui_mi.WE_Event_Desc = timeanduser["time"];
}
else
{
ui_mi.Mission_Url = "";
ui_mi.WE_Event_Desc = "";
}
his_missdone.Add(ui_mi);
}
for (int i = 0; i < his_missdone.Count; i++)
{
string chulijindu = "处理中";
string[] total_time = new string[4];
string completetime = "2010/7/7";
if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "不需处理")//不需处理
{
chulijindu = "处理完成";
Mission db_miss = wfsd.GetWFEntityMissions(his_missdone[i].WE_Entity_Id).Last();
//获取当前任务的完成时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_miss.Miss_Id);
if (timeanduser.Count > 0)
{
completetime = timeanduser["time"];
}
else
{
completetime = "";
}
if (completetime == "2010/7/7")
{
completetime = "";
}
if (chulijindu == "处理中")
{
completetime = "";
}
}
if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "完好类")//完好跳转A5dot1跟踪
{
chulijindu = "处理完成";
List<A5dot1Tab1> mission = tm.get_recordbyentity(his_missdone[i].WE_Entity_Id.ToString());
for (int k = 0; k < mission.Count; k++)
{
if (mission[k].isRectified == 0)
{
chulijindu = "处理中";
}
total_time[k] = mission[k].pqCheckTime.ToString();
if (total_time[k] != null)
{
if (total_time[k] != "")
{
if (Convert.ToDateTime(total_time[k]) > Convert.ToDateTime(completetime))
{
completetime = total_time[k];
}
}
}
}
if (completetime == "2010/7/7")
{
completetime = "";
}
if (chulijindu == "处理中")
{
completetime = "";
}
//统计完好类封闭正在处理的数量
if (chulijindu == "处理完成")
{
Count_WH_Done++;
}
if (chulijindu == "处理中")
{
Count_WH++;
}
}
//else if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "隐患")//隐患跳转A11dot2跟踪
//{
// //由于跳转到11dot2会产生新实体号,因此通过串号找到该实体号,此方法得到串号对应的所有实体号
// List<WorkFlow_Entity> getentity = wfsd.GetWorkFlowEntitiesbySer(his_missdone[i].WE_Entity_Ser);
// foreach (var item in getentity)
// {
// WorkFlow_Define getentity_name = wfsd.GetWorkFlowDefine(item.WE_Id);//通过每个实体号找到该实体号的名字,就可以确定每个实体号的内容
// if (getentity_name.W_Name == "A11dot2")
// {
// Mission db_miss = wfsd.GetWFEntityMissions(item.WE_Id).Last();
// if (db_miss.Miss_Desc == "现场工程师提报隐患")
// {
// chulijindu = "提报";
// }
// else if (db_miss.Miss_Desc == "可靠性工程师风险矩阵评估")
// {
// chulijindu = "危害识别中";
// }
// else if (db_miss.Miss_Desc == "专业团队审核")
// {
// WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.WE_Id);
// //CWorkFlow wf = new CWorkFlow();
// WorkFlows wfs = new WorkFlows();
// UI_MISSION ui = new UI_MISSION();
// ui.WE_Entity_Id = item.WE_Id;
// ui.WE_Entity_Ser = wfe.WE_Ser;
// ui.WE_Event_Desc = db_miss.Miss_Desc;
// ui.WE_Event_Name = db_miss.Event_Name;
// ui.WE_Name = db_miss.Miss_Name;
// ui.Mission_Url = ""; //历史任务的页面至空
// ui.Miss_Id = db_miss.Miss_Id;
// List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
// foreach (var par in mis_pars)
// {
// CParam cp = new CParam();
// cp.type = par.Param_Type;
// cp.name = par.Param_Name;
// cp.value = par.Param_Value;
// cp.description = par.Param_Desc;
// ui.Miss_Params[cp.name] = cp.value;
// ui.Miss_ParamsDesc[cp.name] = cp.description;
// }
// //判断风险评估结果所在区域的颜色
// if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "green")
// {
// chulijindu = "完成危害识别,结果为绿色";
// }
// else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "red")
// {
// chulijindu = "完成危害识别,结果为红色";
// }
// else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "yellow")
// {
// chulijindu = "完成危害识别,结果为黄色";
// }
// if (ui.Miss_Params["ZytdConfirm_Result"].ToString() == "False")
// {
// chulijindu = "审核未通过,重新评估";
// }
// }
// else if (db_miss.Miss_Desc == "车间确立应急预案")
// {
// chulijindu = "应急预案制定与实施中";
// }
// else if (db_miss.Miss_Desc == "片区监督执行")
// {
// chulijindu = "处理完成";
// WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.WE_Id);
// //CWorkFlow wf = new CWorkFlow();
// WorkFlows wfs = new WorkFlows();
// UI_MISSION ui = new UI_MISSION();
// ui.WE_Entity_Id = item.WE_Id;
// ui.WE_Entity_Ser = wfe.WE_Ser;
// ui.WE_Event_Desc = db_miss.Miss_Desc;
// ui.WE_Event_Name = db_miss.Event_Name;
// ui.WE_Name = db_miss.Miss_Name;
// ui.Mission_Url = ""; //历史任务的页面至空
// ui.Miss_Id = db_miss.Miss_Id;
// List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
// foreach (var par in mis_pars)
// {
// CParam cp = new CParam();
// cp.type = par.Param_Type;
// cp.name = par.Param_Name;
// cp.value = par.Param_Value;
// cp.description = par.Param_Desc;
// ui.Miss_Params[cp.name] = cp.value;
// ui.Miss_ParamsDesc[cp.name] = cp.description;
// }
// if (ui.Miss_Params["Supervise_done"].ToString() == "False")
// {
// chulijindu = "应急预案制定与实施中";
// }
// //获取当前任务的完成时间
// IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_miss.Miss_Id);
// if (timeanduser.Count > 0)
// {
// completetime = timeanduser["time"];
// }
// else
// {
// completetime = "";
// }
// }
// else if (db_miss.Miss_Desc == "跳转到【A11.3】风险管控模块")
// {
// chulijindu = "风险管控";
// }
// }
// //此处写风险管控if(getentity_name.W_Name=="A11dot3")
// }
// if (completetime == "2010/7/7")
// {
// completetime = "";
// }
// if (chulijindu == "处理中")
// {
// completetime = "";
// }
// //统计完好类封闭正在处理的数量
// if (chulijindu == "处理完成")
// {
// Count_YH_Done++;
// }
// if (chulijindu != "处理完成")
// {
// Count_YH++;
// }
//}
else if (his_missdone[i].Miss_Params["catlog_type"].ToString() == "故障")
{
Mission db_miss = wfsd.GetWFEntityMissions(his_missdone[i].WE_Entity_Id).Last();
if (db_miss.Miss_Desc == "可靠性工程师缺陷分类")
{
chulijindu = "提报";
}
else if (db_miss.Miss_Desc == "专业团队审核")
{
chulijindu = "机动处已确认";
}
//按时间和设备编号在workflow中查询A8.2的实体号
string query_list = "E.W_Name,E.WE_Id,M.Event_Name, R.time";
string query_condition = string.Format("P.Equip_Code in ({0}) and E.W_Name = 'A8dot2'", his_missdone[i].Miss_Params["Equip_Code"]);
//时间为当月
DateTime dtime = DateTime.Now;
dtime = dtime.AddDays(-dtime.Day + 1);
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
string record_filter = string.Format("time >= '{0}' ", dtime.ToString()); //"1 <> 1";
System.Data.DataTable dtA8dot2 = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
DataRow[] NNullRows = dtA8dot2.Select("WE_Id is not Null");
if (NNullRows.Length > 0)
{
//由于当月一台设备只有一个流程,实体号唯一,任取NNullRows中一行,再取其中ItemArray中第二个数据(按query_list查询条件)即为实体号
var entityid = NNullRows[0].ItemArray[1];
//获取对应实体号的最后一个任务追踪进度
Mission db_missA8dot2 = wfsd.GetWFEntityMissions(Convert.ToInt32(entityid)).Last();
//写if而不写else if是因为13.1和8.2是断开的,跳转8.2仍满足db_miss.Miss_Desc == "专业团队审核"
if (db_missA8dot2.Miss_Desc == "检修单位按计划建立工单,完善工序、组件")
{
UI_MISSION ui = new UI_MISSION();
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_missA8dot2.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui.Miss_Params[cp.name] = cp.value;
ui.Miss_ParamsDesc[cp.name] = cp.description;
}
chulijindu = "工单已建立并完善,工单号为:" + ui.Miss_Params["Job_Order"].ToString();
}
else if (db_missA8dot2.Miss_Desc == "机动处计划科审2")
{
chulijindu = "检修工单已下达";
}
else if (db_missA8dot2.Miss_Desc == "物资处采购,填写到货时间")
{
chulijindu = "物资采购中";
}
else if (db_missA8dot2.Miss_Desc == "物资处确认到货并通知检修单位")
{
chulijindu = "物资已到货";
}
else if (db_missA8dot2.Miss_Desc == "检修单位上传检修方案" || db_missA8dot2.Miss_Desc == "专业团队审批" || db_missA8dot2.Miss_Desc == "检修单位填写检修内容及关键工序,关联作业指导书" || db_missA8dot2.Miss_Desc == "可靠性工程师审批")
{
chulijindu = "检修方案制定与审判";
}
else if (db_missA8dot2.Miss_Desc == "现场工程师确认是否可实施计划")
{
UI_MISSION ui = new UI_MISSION();
List<Mission_Param> mis_pars = wfsd.GetMissParams(db_missA8dot2.Miss_Id);//获取当前任务参数
foreach (var par in mis_pars)
{
CParam cp = new CParam();
ui.Miss_Params[cp.name] = cp.value;
}
if (ui.Miss_Params["ZzConfirmPlan_Result"].ToString() == "是")
{
chulijindu = "检修计划实施中";
}
else if (ui.Miss_Params["ZzConfirmPlan_Result"].ToString() == "否")
{
chulijindu = "检修计划延期";
}
}
else if (db_missA8dot2.Miss_Desc == "检修单位确认施工完毕,上传交工资料")
{
chulijindu = "处理完成";
//获取当前任务的完成时间
IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_missA8dot2.Miss_Id);
if (timeanduser.Count > 0)
{
completetime = timeanduser["time"];
}
else
{
completetime = "";
}
}
}
else
{
chulijindu = "正在DRBPM中处理!";
}
completetime = "";
if (completetime == "2010/7/7")
{
completetime = "";
}
if (chulijindu == "处理中")
{
completetime = "";
}
if (chulijindu == "处理完成")
{
Count_GZ_Done++;
}
if (chulijindu != "处理完成")
{
Count_GZ++;
}
}
}
List<A5dot1Tab1> Allmission = tm.get_All();
for (int te = 0; te < Allmission.Count; te++)
{
if (Allmission[te].temp2 == null)
{
string jindu = "处理中";
string edtime = "";
if (Allmission[te].isRectified == 1)
{
jindu = "处理完成";
edtime = Allmission[te].pqCheckTime.ToString();
}
if (jindu == "处理中")
{
Count_WH++;
}
else if (jindu == "处理完成")
Count_WH_Done++;
}
}
//舍弃下面注释内容,以前是通过A13dot1找A11dot2的工作流,现在A11dot2全部内容归入缺陷管理表后直接找A11dot2
////11dot2状态监测
//List<UI_MISSION> miss;
////有权限
//miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, "A11dot2", true);
//List<UI_MISSION> his_missdoneA11dot2 = new List<UI_MISSION>();//最后一步均为跳转,因此最后一步关联了所需的所有参数,可直接获得最后一步的任务参数即可
//foreach (var item in miss)//获得entity_id
//{
// Mission db_miss = wfsd.GetWFEntityMissions(item.WE_Entity_Id).Last();//获取该实体最后一个任务
// WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(item.WE_Entity_Id);
// //CWorkFlow wf = new CWorkFlow();
// WorkFlows wfs = new WorkFlows();
// UI_MISSION ui_mi = new UI_MISSION();
// ui_mi.WE_Entity_Id = item.WE_Entity_Id;
// ui_mi.WE_Entity_Ser = wfe.WE_Ser;
// ui_mi.WE_Event_Desc = db_miss.Miss_Desc;
// ui_mi.WE_Event_Name = db_miss.Event_Name;
// ui_mi.WE_Name = db_miss.Miss_Name;
// ui_mi.Mission_Url = ""; //历史任务的页面至空
// ui_mi.Miss_Id = db_miss.Miss_Id;
// List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
// foreach (var par in mis_pars)
// {
// CParam cp = new CParam();
// cp.type = par.Param_Type;
// cp.name = par.Param_Name;
// cp.value = par.Param_Value;
// cp.description = par.Param_Desc;
// ui_mi.Miss_Params[cp.name] = cp.value;
// // ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
// ui_mi.Miss_ParamsDesc[cp.name] = cp.description;//xwm modified
// }
// ui_mi.Mission_Url = "";
// ui_mi.WE_Event_Desc = "";
// List<Mission> gettime = wfs.GetWFEntityMissions(item.WE_Entity_Id);//获取实体的所有任务找到第二个任务获取提报时间
// if (gettime.Count > 1)
// {
// IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(gettime[1].Miss_Id);
// if (timeanduser.Count > 0)
// {
// ui_mi.Mission_Url = timeanduser["username"];
// ui_mi.WE_Event_Desc = timeanduser["time"];
// }
// else
// {
// ui_mi.Mission_Url = "";
// ui_mi.WE_Event_Desc = "";
// }
// }
// his_missdoneA11dot2.Add(ui_mi);
//}
//foreach (var re in his_missdoneA11dot2)
//{
// string chulijindu = "处理中";
// string completetime = "2010/7/7";
// Mission db_miss = wfsd.GetWFEntityMissions(re.WE_Entity_Id).Last();
// if (db_miss.Miss_Desc == "Start")
// {
// chulijindu = "提报尚未完成";
// }
// if (db_miss.Miss_Desc == "现场工程师提报隐患")
// {
// chulijindu = "提报";
// }
// else if (db_miss.Miss_Desc == "可靠性工程师风险矩阵评估")
// {
// chulijindu = "危害识别中";
// }
// else if (db_miss.Miss_Desc == "专业团队审核")
// {
// WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(re.WE_Entity_Id);
// //CWorkFlow wf = new CWorkFlow();
// WorkFlows wfs = new WorkFlows();
// UI_MISSION ui = new UI_MISSION();
// ui.WE_Entity_Id = re.WE_Entity_Id;
// ui.WE_Entity_Ser = wfe.WE_Ser;
// ui.WE_Event_Desc = db_miss.Miss_Desc;
// ui.WE_Event_Name = db_miss.Event_Name;
// ui.WE_Name = db_miss.Miss_Name;
// ui.Mission_Url = ""; //历史任务的页面至空
// ui.Miss_Id = db_miss.Miss_Id;
// List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
// foreach (var par in mis_pars)
// {
// CParam cp = new CParam();
// cp.type = par.Param_Type;
// cp.name = par.Param_Name;
// cp.value = par.Param_Value;
// cp.description = par.Param_Desc;
// ui.Miss_Params[cp.name] = cp.value;
// ui.Miss_ParamsDesc[cp.name] = cp.description;
// }
// //判断风险评估结果所在区域的颜色
// if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "green")
// {
// chulijindu = "完成危害识别,结果为绿色";
// }
// else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "red")
// {
// chulijindu = "完成危害识别,结果为红色";
// }
// else if (ui.Miss_Params["RiskMatrix_Color"].ToString() == "yellow")
// {
// chulijindu = "完成危害识别,结果为黄色";
// }
// if (ui.Miss_Params["ZytdConfirm_Result"].ToString() == "False")
// {
// chulijindu = "审核未通过,重新评估";
// }
// }
// else if (db_miss.Miss_Desc == "车间确立应急预案")
// {
// chulijindu = "应急预案制定与实施中";
// }
// else if (db_miss.Miss_Desc == "片区监督执行")
// {
// chulijindu = "处理完成";
// WorkFlow_Entity wfe = wfsd.GetWorkFlowEntity(re.WE_Entity_Id);
// //CWorkFlow wf = new CWorkFlow();
// WorkFlows wfs = new WorkFlows();
// UI_MISSION ui = new UI_MISSION();
// ui.WE_Entity_Id = re.WE_Entity_Id;
// ui.WE_Entity_Ser = wfe.WE_Ser;
// ui.WE_Event_Desc = db_miss.Miss_Desc;
// ui.WE_Event_Name = db_miss.Event_Name;
// ui.WE_Name = db_miss.Miss_Name;
// ui.Mission_Url = ""; //历史任务的页面至空
// ui.Miss_Id = db_miss.Miss_Id;
// List<Mission_Param> mis_pars = wfsd.GetMissParams(db_miss.Miss_Id);//获取当前任务参数
// foreach (var par in mis_pars)
// {
// CParam cp = new CParam();
// cp.type = par.Param_Type;
// cp.name = par.Param_Name;
// cp.value = par.Param_Value;
// cp.description = par.Param_Desc;
// ui.Miss_Params[cp.name] = cp.value;
// ui.Miss_ParamsDesc[cp.name] = cp.description;
// }
// if (ui.Miss_Params["Supervise_done"].ToString() == "False")
// {
// chulijindu = "应急预案制定与实施中";
// }
// //获取当前任务的完成时间
// IDictionary<string, string> timeanduser = CWFEngine.GetMissionRecordInfo(db_miss.Miss_Id);
// if (timeanduser.Count > 0)
// {
// completetime = timeanduser["time"];
// }
// else
// {
// completetime = "";
// }
// }
// else if (db_miss.Miss_Desc == "跳转到【A11.3】风险管控模块")
// {
// chulijindu = "风险管控";
// }
// else if (db_miss.Miss_Desc == "专业团队确立管控措施")
// {
// chulijindu = "专业团队确立管控措施";
// }
// else if (db_miss.Miss_Desc == "机动处组织监督实施")
// {
// chulijindu = "机动处组织监督实施";
// }
// else if (db_miss.Miss_Desc == "管控措施实施后确认风险是否可接受,并进行风险登记")
// {
// chulijindu = "管控措施实施后确认风险是否可接受,并进行风险登记";
// }
// else if (db_miss.Miss_Desc == "车间确立管控措施")
// {
// chulijindu = "车间确立管控措施";
// }
// else if (db_miss.Miss_Desc == "可靠性工程师审核")
// {
// chulijindu = "可靠性工程师审核";
// }
// else if (db_miss.Miss_Desc == "车间组织监督实施")
// {
// chulijindu = "车间组织监督实施";
// }
// else if (db_miss.Miss_Desc == "管控措施实施后确认风险是否消除,并进行风险登记")
// {
// chulijindu = "管控措施实施后确认风险是否消除,并进行风险登记";
// }
// if (completetime == "2010/7/7")
// {
// completetime = "";
// }
// if (chulijindu == "处理中")
// {
// completetime = "";
// }
// //统计隐患类封闭正在处理的数量
// // if (chulijindu == "处理完成")
// // {
// // Count_YH_Done++;
// // }
// // if (chulijindu != "处理完成")
// // {
// // Count_YH++;
// // }
//}
WorkFlows getmission = new WorkFlows();
Count_YH = getmission.GetActiveMissionsOfEntity("A11dot2").Count;
string WE_Status = "3";
string query_list1 = "distinct E.WE_Ser, E.WE_Id, R.username";
string query_condition1 = "E.W_Name='A11dot2' and E.WE_Status='" + WE_Status + "' and R.username is not null";
string record_filter1 = "username is not null";
DataTable dt = CWFEngine.QueryAllInformation(query_list1, query_condition1, record_filter1);
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
Count_YH_Done = Gmlist.Count;
string databack = Count_WH + "$" + Count_WH_Done + "$" + Count_YH + "$" + Count_YH_Done + "$" + Count_GZ + "$" + Count_GZ_Done;
return (databack);
}
/// <summary>
/// 2017-1-18新增,获取待处理通知单
/// </summary>
/// <returns></returns>
public string getNotice_list()
{
NoticeManagement NM=new NoticeManagement();
PersonManagment PM = new PersonManagment();
List<Equip_Archi> Zz_Name = new List<Equip_Archi>();
Zz_Name = PM.Get_Person_Zz((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
List<Object> result = new List<object>();
List<Notice_A13dot1> list = NM.getNoticeForA13dot1();
List<object> temp = new List<object>();
PersonManagment.P_viewModal pv = PM.Get_PersonModal((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
if(pv.Role_Names.Contains("现场工程师"))
{
foreach(var tt in Zz_Name)
{
object k = tt.EA_Name;
temp.Add(k);
}
string aa = JsonConvert.SerializeObject(temp);
foreach(var item in list)
{
if(aa.Contains(item.Zz_Name))
{
object o = new
{
isSubmit=1,
Notice_ID=item.Notice_ID,
Notice_EquipCode = item.Notice_EquipCode,
Notice_EquipType = item.Notice_EquipType,
Notice_State = item.Notice_State,
Pq_Name = item.Pq_Name,
Zz_Name = item.Zz_Name,
Notice_Desc = item.Notice_Desc,
Notice_CR_Person = item.Notice_CR_Person,
Notice_CR_Date = item.Notice_CR_Date,
Notice_EquipSpeciality = item.Notice_Speciality
};
result.Add(o);
}
}
}
else
{
foreach (var item in list)
{
object o = new
{
isSubmit = 0,
Notice_ID = item.Notice_ID,
Notice_EquipCode = item.Notice_EquipCode,
Notice_EquipType = item.Notice_EquipType,
Notice_State = item.Notice_State,
Pq_Name = item.Pq_Name,
Zz_Name = item.Zz_Name,
Notice_Desc = item.Notice_Desc,
Notice_CR_Person = item.Notice_CR_Person,
Notice_CR_Date = item.Notice_CR_Date,
Notice_EquipSpeciality = item.Notice_Speciality
};
result.Add(o);
}
}
string str = JsonConvert.SerializeObject(result);
return ("{" + "\"data\": " + str + "}");
}
/// <summary>
/// 通过通知单号生成A13dot1的工作流
/// </summary>
/// <returns></returns>
public string CreateA13dot1ByNotice(string Notice_Id)
{
NoticeManagement NM=new NoticeManagement();
Notice_A13dot1 a_notice=NM.getNoticeForA13dot1ByNI(Notice_Id);
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(a_notice.Notice_EquipCode);
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName("A13dot1");
NM.modifyNoticeForA13dot1((Session["User"] as EquipModel.Entities.Person_Info).Person_Name, DateTime.Now.ToString(), Notice_Id);
if (wfe != null)
{
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
int flow_id = wfe.EntityID;
Dictionary<string, string> signal1 = new Dictionary<string, string>();
signal1["start_done"] = "true";
CWFEngine.SubmitSignal(flow_id, signal1, record);
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = Equip_ZzBelong[1].EA_Name;
signal["Zz_Name"] = a_notice.Zz_Name;
signal["Equip_GyCode"] =eqinfo.Equip_GyCode;
signal["Equip_Code"] = a_notice.Notice_EquipCode;
signal["Equip_Type"] =a_notice.Notice_EquipType;
signal["Problem_Desc"] = a_notice.Notice_Desc;
signal["Problem_DescFilePath"] = "";
signal["Zy_Type"] = eqinfo.Equip_Specialty;
signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
signal["Data_Src"] = "由现场工程师通过ERP转入";
signal["NoticeNum"] = Notice_Id;
signal["User_State"] = a_notice.Notice_State;
//submit
//record
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(flow_id, signal, record);
}
return ("/A13dot1/Index");
}
/// <summary>
/// 删除通知单
/// </summary>
/// <param name="Notice_Id"></param>
/// <returns></returns>
public string RemoveA13dot1ByNotice(string Notice_Id)
{
NoticeManagement NM = new NoticeManagement();
NM.removeNoticeForA13dot1(Notice_Id);
return ("/A13dot1/Index");
}
/// <summary>
/// 用于获取现场工程师已提交的通知单中的未完成通知单
/// </summary>
/// <returns></returns>
public string NoticeUncomp()
{
NoticeManagement NM = new NoticeManagement();
PersonManagment PM = new PersonManagment();
List<Object> result = new List<object>();
List<Notice_A13dot1> list = NM.getNoticeForA13dot1Uncomp();
foreach (var item in list)
{
if(item.Notice_State!="删除"&&item.Notice_State!="完成")
{
object o = new
{
Notice_ID = item.Notice_ID,
Notice_EquipCode = item.Notice_EquipCode,
Notice_EquipType = item.Notice_EquipType,
Notice_State = item.Notice_State,
Pq_Name = item.Pq_Name,
Zz_Name = item.Zz_Name,
Notice_Desc = item.Notice_Desc,
Notice_CR_Person = item.Notice_CR_Person,
Notice_CR_Date = item.Notice_CR_Date,
Notice_EquipSpeciality = item.Notice_Speciality
};
result.Add(o);
}
}
string str = JsonConvert.SerializeObject(result);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Equips:BaseDAO
{
public Equip_Info getEquip_Info(int Equip_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.Equip_Id == Equip_id).First();
return E;
}
catch
{ return null; }
}
}
//根据设备编号获取设备信息-xwm add
public Equip_Info getEquip_byGyCode(string Equip_GyCode)
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.Equip_GyCode == Equip_GyCode).First();
return E;
}
catch
{ return null; }
}
}
public int getE_id_byGybh(string equip_Gy)
{
using (var db = base.NewDB())
{
try
{
var E = Convert.ToInt16(db.Equips.Where(a => a.Equip_Code == equip_Gy).First().Equip_Id);
return E;
}
catch
{ return 0; }
}
}
public int getEA_id_byCode(string equip_code)
{
using (var db = base.NewDB())
{
try
{
var E = Convert.ToInt16(db.Equips.Where(a => a.Equip_Code == equip_code).First().Equip_Location.EA_Id);
return E;
}
catch
{ return 0; }
}
}
//查询设备
public List<Equip_Info> getEquips_byinfo(string Equip_gycode, int Equip_archi, string Equip_specialty)
{
using (var db = base.NewDB())
{
try
{
if (Equip_gycode != "" && Equip_archi != 0 && Equip_specialty != "")
{
var E = db.Equips.Where(a => a.Equip_PhaseB.Contains(Equip_specialty) && a.Equip_GyCode.Contains(Equip_gycode) && a.Equip_Location.EA_Id == Equip_archi).ToList();
return E;
}
else if (Equip_gycode == "" && Equip_archi != 0 && Equip_specialty != "")
{
var E = db.Equips.Where(a => a.Equip_PhaseB.Contains(Equip_specialty) && a.Equip_Location.EA_Id == Equip_archi).ToList();
return E;
}
else if (Equip_archi == 0 && Equip_specialty != "" && Equip_gycode != "")
{
var E = db.Equips.Where(a => a.Equip_PhaseB.Contains(Equip_specialty) && a.Equip_GyCode.Contains(Equip_gycode)).ToList();
return E;
}
else if (Equip_specialty == "" && Equip_archi != 0 && Equip_gycode != "")
{
var E = db.Equips.Where(a => a.Equip_Location.EA_Id == Equip_archi && a.Equip_GyCode.Contains(Equip_gycode)).ToList();
return E;
}
else if (Equip_specialty == "" && Equip_archi == 0 && Equip_gycode != "")
{
var E = db.Equips.Where(a => a.Equip_GyCode.Contains(Equip_gycode)).ToList();
return E;
}
else if (Equip_specialty == "" && Equip_archi != 0 && Equip_gycode == "")
{
var E = db.Equips.Where(a => a.Equip_Location.EA_Id == Equip_archi).ToList();
return E;
}
else
{
var E = db.Equips.Where(a => a.Equip_PhaseB.Contains(Equip_specialty)).ToList();
return E;
}
}
catch
{ return null; }
}
}
public Equip_Info getEquip_Info(string Equip_Code)
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.Equip_Code == Equip_Code).First();
return E;
}
catch
{ return null; }
}
}
//获取某设备所在的装置信息
public Equip_Archi getEquip_EA(int Equip_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.Equip_Id == Equip_id).First();
return E.Equip_Location;
}
catch
{ return null; }
}
}
//获取某设备的所有负责人信息
public List<Person_Info> getEquipManagers(int Equip_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.Equip_Id == Equip_id).First();
return E.Equip_Manager.ToList();
}
catch
{ return null; }
}
}
//添加设备的管理员,链接Equip表和Person_info表
public bool Equip_LinkPersons(int Equip_id,List<int> Person_Ids)
{
try
{
using (var db = base.NewDB())
{
var E = db.Equips.Where(a => a.Equip_Id == Equip_id).First();
if ( Person_Ids!=null && Person_Ids.Count>0 )
{ var Ep_old = E.Equip_Manager.ToList();
if (Ep_old.Count > 0)
{
E.Equip_Manager.Clear();
}
foreach (var item in Person_Ids)
{
var P = db.Persons.Where(a => a.Person_Id == item).First();
E.Equip_Manager.Add(P);
}
db.SaveChanges();
}
return true;
}
}
catch
{
return false;
}
}
//添加设备,并将其和装置建立链接
public bool AddEquip(Equip_Info New_Equip_Info,int ZzId)
{
try
{
using (var db = base.NewDB())
{
Equip_Info e=db.Equips.Add(New_Equip_Info);
Equip_Archi eItem = db.EArchis.Where(a => a.EA_Id == ZzId).First();
e.Equip_Location = eItem;
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
//删除设备信息
public bool DeleteEquip(int Equip_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.Equip_Id == Equip_id).First();
if (E == null)
return false;
else
{ db.Equips.Remove(E);
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
//修改设备信息相关信息
//参数:New_Equip_Info 新的设备信息
//装置 EA_Id 新的设备所属装置Id
public bool ModifyEquip(Equip_Info New_Equip_Info,int EA_Id)
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.Equip_Code== New_Equip_Info.Equip_Code).First();
Equip_Archi eItem = db.EArchis.Where(a => a.EA_Id == EA_Id && a.EA_Title=="装置").First();
if (E == null || eItem==null)
return false;
else
{
E.Equip_ABCmark = New_Equip_Info.Equip_ABCmark;
E.Equip_Code = New_Equip_Info.Equip_Code;
E.Equip_ManufactureDate = New_Equip_Info.Equip_ManufactureDate;
E.Equip_Manufacturer = New_Equip_Info.Equip_Manufacturer;
E.Equip_PhaseB = New_Equip_Info.Equip_PhaseB;
E.Equip_Specialty = New_Equip_Info.Equip_Specialty;
E.Equip_Type = New_Equip_Info.Equip_Type;
E.Equip_GyCode = New_Equip_Info.Equip_GyCode;
E.Equip_Location = New_Equip_Info.Equip_Location;
E.Equip_PerformanceParasJson=New_Equip_Info.Equip_PerformanceParasJson;
E.Equip_Location = eItem;
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
public List<EANummodel> getequipnum_byarchi()
{
using (var db = base.NewDB())
{
try
{
List<EANummodel> Em = new List<EANummodel>();
var E = db.Equips.Select(a => new { EA_Id = a.Equip_Location.EA_Id}).GroupBy(a => a.EA_Id).ToList();
foreach (var i in E)
{
EANummodel temp = new EANummodel();
temp.Equip_Num = i.Count();
temp.EA_Id = i.Key;
Em.Add(temp);
}
return Em;
}
catch(Exception e)
{ return null; }
}
}
public int getEA_parentid(int Ea_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.EArchis.Where(a => a.EA_Id == Ea_id).First().EA_Parent.EA_Id;
return E;
}
catch
{ return 0; }
}
}
public List<Equip_Info> getAllThEquips()
{
using (var db = base.NewDB())
{
try
{
var E = db.Equips.Where(a => a.thRecordTable== "1").ToList();
return E;
}
catch
{ return null; }
}
}
public List<Equip_Archi> GetAllCj()
{
using (var db = base.NewDB())
{
try
{
var E = db.EArchis.Where(a => a.EA_Parent.EA_Id == 1).ToList();
return E;
}
catch
{ return null; }
}
}
public List<Pq_Zz_map> GetZzsofPq(string Pqname)
{
using (var db = base.NewDB())
{
try
{
var E = db.Pq_Zz_maps.Where(a => a.Pq_Name == Pqname).ToList();
return E;
}
catch
{ return null; }
}
}
public Pq_Zz_map GetPqofZz(string Zzname)
{
using (var db = base.NewDB())
{
try
{
var E = db.Pq_Zz_maps.Where(a => a.Zz_Name == Zzname).First();
return E;
}
catch
{ return null; }
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/////////////////////////////////////////////////////////
//2016/5/17--chenbin
//添加CURR_Mission表用以记录工作流事件的当前任务,避免频繁从XML重构工作流,提高效率
////////////////////////////////////////////////////////
namespace FlowEngine.Modals
{
public class CURR_Mission
{
//主键
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Miss_Id
{
get;
set;
}
/// <summary>
/// 任务名称
/// </summary>
public string Miss_Name
{
get;
set;
}
/// <summary>
/// 任务描述
/// </summary>
public string Miss_Desc
{
get;
set;
}
/// <summary>
/// 进入事件
/// </summary>
public string Before_Action
{
get;
set;
}
/// <summary>
/// 当前事件
/// </summary>
public string Current_Action
{
get;
set;
}
/// <summary>
/// 离开事件
/// </summary>
public string After_Action
{
get;
set;
}
/// <summary>
/// 权限
/// </summary>
public string Str_Authority
{
get;
set;
}
public int WFE_ID
{
get;
set;
}
public virtual WorkFlow_Entity WFE_Parent
{
get;
set;
}
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Zhidus : BaseDAO
{
public List<ZhiduFile> get_zhidu(int menuid)
{
using (var db = base.NewDB())
{
try
{
var E = db.ZhiduFile.Where(a => a.Menu.Menu_Id == menuid).ToList();
return E;
}
catch
{ return null; }
}
}
}
}
<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Q_Entrance : BaseDAO
{
public bool AddQ_Entrance(int p_id, int m_id, int q_id)
{
//Menus ms = new Menus();
//Menu m = ms.GetMenu(m_id);
//Person_Infos pis = new Person_Infos();
//Person_Info p = pis.GetPerson_info(p_id);
using (var db = base.NewDB())
{
try
{
//Quick_Entrance q_e = db.Quick_Entrance.Where(a => a.Quick_Entrance_id== q_id&&a.Person_Info.Person_Id==p_id).First();
var q_e = db.Quick_Entrance.Where(a => a.xuhao == q_id && a.Person_Info.Person_Id == p_id).ToList();
if (q_e.Count() != 0)
{
q_e.First().Menu = db.Sys_Menus.Where(a => a.Menu_Id == m_id).First();
db.SaveChanges();
return true;
}
else
{
Quick_Entrance QE = new Quick_Entrance();
db.Quick_Entrance.Add(QE);
QE.Menu = db.Sys_Menus.Where(a => a.Menu_Id == m_id).First();
QE.Person_Info = db.Persons.Where(a => a.Person_Id == p_id).First();
QE.xuhao = q_id;
db.SaveChanges();
return true;
}
}
catch (Exception e)
{
return false;
}
}
}
public List<Quick_Entrance> GetQ_EbyP_Id(int p_id)
{
//List<Quick_Entrance> QE = new List<Quick_Entrance>();
//using (var db = base.NewDB())
//{
// try
// {
// QE = db.Quick_Entrance.Where(a => a.Person_Info.Person_Id == p_id).ToList();
// }
// catch
// { return null; }
//}
//return QE;
List<Quick_Entrance> QE = new List<Quick_Entrance>();
try
{
var db = base.NewDB();
QE = db.Quick_Entrance.Where(a => a.Person_Info.Person_Id == p_id).ToList();
}
catch
{ return null; }
return QE;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Pq_EC_map
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Pq_EC_mapId { get; set; }
public string Pq_Name { get; set; }
public string Equip_Code { get; set; }
}
}
<file_sep>///////////////////////////////////////////////////////////
// CWorkFlow.cs
// Implementation of the Class CWorkFlow
// Generated by Enterprise Architect
// Created on: 26-10月-2015 9:46:30
// Original author: Ailibuli
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FlowEngine;
using FlowEngine.Param;
using FlowEngine.Event;
using System.Xml;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using FlowEngine.UserInterface;
using FlowEngine.Modals;
using FlowEngine.DAL;
namespace FlowEngine {
/// <summary>
/// 工作流管理类
/// </summary>
public class CWorkFlow : IXMLEntity, UI_WorkFlow_Entity
{
/// <summary>
/// 该工作流定义的ID号
/// </summary>
private int m_defineID = -1;
/// <summary>
/// 工作流实体的ID,表示依据该工作模型建立的一个具体工作流,该ID在整个系统中唯一
/// </summary>
private int m_entityID = -1;
/// <summary>
/// 工作流状态迁移流程,列表的最后一个元素表示当前事件(状态)
/// </summary>
private List<string> m_eventProc = new List<string>();
/// <summary>
/// 工作流(WorkFlow)中事件(Event)集合,其中Key为事件名称
/// </summary>
private Dictionary<string, Event.IEvent> m_events = new Dictionary<string, Event.IEvent>();
/// <summary>
/// 工作流的名称
/// </summary>
private string m_name = "";
/// <summary>
/// 工作流包括的用户数据
/// </summary>
private FlowEngine.Param.CParamTable m_paramtable = new FlowEngine.Param.CParamTable();
/// <summary>
/// 事件(CEvent)与变量(CParam)之间的联系 该字典的Key为CEvent名称, Value为与该事件对应的变量名组成的字符串数组
/// </summary>
private Dictionary<string, List<string>> m_relationEP = new Dictionary<string,List<string>>();
/// <summary>
/// 工作流(WorkFlow)的描述
/// </summary>
private string m_description = "";
/// <summary>
/// 流程(Flow)集合
/// Key为Flow的源事件(Event)的名称
/// </summary>
private Dictionary<string, List<Flow.IFlow>> m_flows = new Dictionary<string, List<Flow.IFlow>>();
/// <summary>
/// 工作流当前事件(Event)
/// </summary>
private string m_courrentEvent = "";
/// <summary>
/// 工作流当前事件(Event)
/// </summary>
private List<string> m_recordItems = new List<string>();
/// <summary>
/// 工作流串号
/// </summary>
private string m_entitySerial = "";
/// <summary>
/// 父工作流的EntityID, 如果该工作流不是子工作流则m_parentEntity = -1
/// </summary>
private int m_parentEntity = -1;
/// <summary>
/// 工作流最后一次状态迁移时间
/// </summary>
public DateTime? Last_TransTime
{
get;
set;
}
public CWorkFlow(){
}
~CWorkFlow(){
}
public CParamTable paramstable
{
get
{
return m_paramtable;
}
}
/// <summary>
/// 工作流的事件
/// </summary>
public IDictionary<string, IEvent> events
{
get
{
return m_events;
}
}
/// <summary>
/// 设置获取工作流的父工作流
/// </summary>
public int ParentEntityID
{
get
{
return m_parentEntity;
}
set
{
m_parentEntity = value;
}
}
public int DefineID
{
get
{
return m_defineID;
}
set
{
m_defineID = value;
}
}
/// <summary>
/// 工作流实体的ID,表示依据该工作模型建立的一个具体工作流,该ID在整个系统中唯一
/// </summary>
public int EntityID{
get{
return m_entityID;
}
set
{
m_entityID = value;
}
}
/// <summary>
/// 设置、获取工作流的串号
/// </summary>
public string EntitySerial
{
get
{
return m_entitySerial;
}
set
{
m_entitySerial = value;
}
}
/// <summary>
/// 工作流需要记录的信息
/// </summary>
public List<string> RecordItems
{
get
{
return m_recordItems;
}
}
//更新工作流实体,(修改数据相应的项)
public void UpdateEntity(WE_STATUS status)
{
try
{
WorkFlow_Entity wfe = new WorkFlow_Entity
{
WE_Id = m_entityID,
WE_Status = status,
Last_Trans_Time = this.Last_TransTime
};
wfe.WE_Binary = Encoding.Default.GetBytes(WriteToXmlNode().OuterXml);
WorkFlows wfs = new WorkFlows();
if (!wfs.SaveWorkFlowEntity(wfe))
throw new Exception("Save WorkFlow Entity failed!");
}
catch(Exception e)
{
return;
}
}
public Dictionary<string, string> GetRecordItems()
{
Dictionary<string, string> re = new Dictionary<string, string>();
foreach(string s in m_recordItems)
{
re.Add(s, null);
}
return re;
}
/// <summary>
/// 检查SubProcess的状态
/// </summary>
private void CheckSubEventStatus()
{
//如果当前状态是SubProcess, 则要检测子时间是否已经执行完毕,
//若已经执行完毕,则需要将返回值从子事件中取回
if (m_events[m_courrentEvent].GetType().Name == "CSubProcessEvent")
{
CSubProcessEvent subE = (CSubProcessEvent)(m_events[m_courrentEvent]);
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe = wfs.GetWorkFlowEntity(subE.WfEntityId);
//自流程已执行完成
if (wfe.WE_Status == WE_STATUS.DONE)
{
CWorkFlow subWf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfs.GetWorkFlowEntity(subE.WfEntityId).WE_Binary));
subWf.InstFromXmlNode(doc.DocumentElement);
subWf.EntityID = subE.WfEntityId;
IEvent subEnd = subWf.GetCurrentEvent();
//将变量返回回来
foreach (var p in subE.m_paramsFrom)
{
subE.paramlist[p.Key].value = subEnd.paramlist[p.Value].value;
}
//若子工作流的工作方式为串行, 则父工作流在子流程完成后继续向下执行
if (subE.WorkingMode == "serial")
{
StateTransfer("");
if (m_events[m_courrentEvent].GetType().Name == "CEndEvent")
{
//将该工作流置为已完成(结束)
UpdateEntity(WE_STATUS.DONE);
//2016.1.3 添加子事件返回
}
else
//更新工作流到数据库,不改变状态
UpdateEntity(WE_STATUS.INVALID);
}
}
}
}
/// <summary>
/// 返回工作流的当前事件(状态)的名称
/// </summary>
public string GetCurrentState(){
CheckSubEventStatus();
return m_courrentEvent;
}
/// <summary>
/// 返回工作流的当前事件(状态)
/// </summary>
public IEvent GetCurrentEvent()
{
CheckSubEventStatus();
return m_events[m_courrentEvent];
}
/// <summary>
/// 解析工作流基础信息
/// </summary>
/// <param name="xmlNode"></param>
public void ParaseBaseInfo(XmlNode xmlNode)
{
//1. 判断xmlNode的类型
if (xmlNode.Name != "workflow")
return;
//2. 解析workflow的属性
m_name = xmlNode.Attributes["name"].Value;
m_description = xmlNode.Attributes["desc"].Value;
m_courrentEvent = xmlNode.Attributes["current_event"].Value;
if (xmlNode.Attributes["entity_serial"] != null)
m_entitySerial = xmlNode.Attributes["entity_serial"].Value;
else
m_entitySerial = "";
if (xmlNode.Attributes["parent_entityid"] != null)
m_parentEntity = Convert.ToInt32(xmlNode.Attributes["parent_entityid"].Value);
else
m_parentEntity = -1;
}
/// <summary>
/// 解析参数列表
/// </summary>
/// <param name="xmlNode"></param>
public void ParseParams(XmlNode xmlNode)
{
m_paramtable.InstFromXmlNode(xmlNode);
}
/// <summary>
/// 解析XML元素
/// </summary>
/// <param name="xmlNode"></param>
public void InstFromXmlNode(XmlNode xmlNode){
//1. 判断xmlNode的类型
if (xmlNode.Name != "workflow")
return;
//2. 解析workflow的属性
m_name = xmlNode.Attributes["name"].Value;
m_description = xmlNode.Attributes["desc"].Value;
m_courrentEvent = xmlNode.Attributes["current_event"].Value;
if (xmlNode.Attributes["entity_serial"] != null)
m_entitySerial = xmlNode.Attributes["entity_serial"].Value;
else
m_entitySerial = "";
if (xmlNode.Attributes["parent_entityid"] != null)
m_parentEntity = Convert.ToInt32(xmlNode.Attributes["parent_entityid"].Value);
else
m_parentEntity = -1;
//3. 反解析参数表
XmlNode paramstable = xmlNode.SelectSingleNode("paramtable");
m_paramtable.InstFromXmlNode(paramstable);
//4. 解析事件
XmlNode events = xmlNode.SelectSingleNode("events");
ParseEvents(events);
//5. 建立参数与事件之间的联系
LinkParamEvent();
//6. 解析流
XmlNode flows = xmlNode.SelectSingleNode("flows");
ParseFlows(flows);
//7. 解析RecordItems
XmlNode rItems = xmlNode.SelectSingleNode("recorditems");
ParseRecordItems(rItems);
}
/// <summary>
/// 解析RecordItems
/// </summary>
private void ParseRecordItems(XmlNode items)
{
if (items.Name != "recorditems")
return;
foreach(XmlNode xn in items.ChildNodes)
{
if (xn.Name.ToLower() != "item")
continue;
m_recordItems.Add(xn.InnerText);
}
}
/// <summary>
/// 工作流的名称
/// </summary>
public string name{
get{
return m_name;
}
set{
m_name = value;
}
}
/// <summary>
/// 工作流状态迁移
/// </summary>
protected bool StateTransfer(string pars_json)
{
bool bTransfered = false;
if (!m_flows.ContainsKey(m_courrentEvent))
return bTransfered;
foreach (Flow.IFlow flow in m_flows[m_courrentEvent])
{
if (flow.Evaluate()) {
//离开当前事件
m_events[flow.source_event].LeaveEvent(pars_json);
//设置当前事件
m_courrentEvent = flow.destination_event;
//进入下一个事件
m_events[flow.destination_event].EnterEvent(pars_json);
bTransfered = true;
break;
}
}
return bTransfered;
}
/// <summary>
/// 向工作流提交信号(Signal:工作流外部的推动动力),即将用户的处理结果(Param参数)提交给工作流。
/// 用户提交的数据(Param参数)合法则返回true
/// 用户提交的数据(Param参数)不合法则返回false(不合法的情况:1. 变量类型与CParamTable对应变量类型不符; 2.
/// 提交的变量不属于当前事件(Event); 3. 提交的变量值不合法)
/// </summary>
/// <param name="json">用户提供的用户处理结果,即参数表(CParamTable)里包含变量的新值</param>
public bool SubmitSignal(string json){
//1. 更新当前事件所关联的变量的值
m_events[m_courrentEvent].UpdateParams(json);
//2. 状态迁移
bool bTrans = StateTransfer("");
if (bTrans)
{
Last_TransTime = DateTime.Now;
}
if (m_events[m_courrentEvent].GetType().Name == "CEndEvent")
{
//将该工作流置为已完成(结束)
UpdateEntity(WE_STATUS.DONE);
//2016.1.3 添加子事件返回
}
else
UpdateEntity(WE_STATUS.INVALID);
return true;
}
/// <summary>
/// 反解析到XML元素
/// </summary>
public XmlNode WriteToXmlNode(){
XmlDocument doc = new XmlDocument();
//1.创建WorkFlow节点
XmlElement workflow = doc.CreateElement("workflow");
workflow.SetAttribute("name", m_name);
workflow.SetAttribute("desc", m_description);
workflow.SetAttribute("current_event", m_courrentEvent);
workflow.SetAttribute("entity_serial", m_entitySerial);
if (m_parentEntity != -1)
workflow.SetAttribute("parent_entityid", m_parentEntity.ToString());
//2. 反解析参数列表
XmlNode paramstable = m_paramtable.WriteToXmlNode();
workflow.AppendChild(doc.ImportNode(paramstable, true));
//3. 反解析事件
XmlElement events = doc.CreateElement("events");
foreach(Event.IEvent ev in m_events.Values){
XmlNode xn = ((IXMLEntity)((Event.CEvent)ev)).WriteToXmlNode();
if (xn != null)
events.AppendChild(doc.ImportNode(xn, true));
}
workflow.AppendChild(events);
//4. 反解析流程
XmlElement flows = doc.CreateElement("flows");
foreach(List<Flow.IFlow> fls in m_flows.Values)
{
foreach (Flow.IFlow fl in fls)
{
XmlNode xn = ((IXMLEntity)((Flow.IFlow)fl)).WriteToXmlNode();
if (xn != null)
flows.AppendChild(doc.ImportNode(xn, true));
}
}
workflow.AppendChild(flows);
//5. 反解析RecordItems
XmlElement rItems = doc.CreateElement("recorditems");
foreach(string item in m_recordItems)
{
XmlNode xn = doc.CreateElement("item");
xn.InnerText = item;
rItems.AppendChild(xn);
}
workflow.AppendChild(rItems);
return workflow;
}
/// <summary>
/// 工作流(WorkFlow)的描述
/// </summary>
public string description{
get{
return m_description;
}
set
{
m_description = value;
}
}
/// <summary>
/// 从XML中解析出事件列表(Events)
/// </summary>
/// <param name="xmlNode"></param>
private void ParseEvents(XmlNode xmlNode){
if (xmlNode.Name != "events")
return;
foreach (XmlNode ev in xmlNode.ChildNodes)
{
if (ev.Name != "event")
continue;
switch (ev.Attributes["type"].Value)
{
case "combevent":
CCombEvent ce = new CCombEvent(this);
ce.InstFromXmlNode(ev);
m_events.Add(ce.name, ce);
break;
case "endevent":
CEndEvent ee = new CEndEvent(this);
ee.InstFromXmlNode(ev);
m_events.Add(ee.name, ee);
break;
case "startevent":
CStartEvent se = new CStartEvent(this);
se.InstFromXmlNode(ev);
m_events.Add(se.name, se);
break;
case "normlevent":
case "normalevent":
CNormlEvent ne = new CNormlEvent(this);
ne.InstFromXmlNode(ev);
m_events.Add(ne.name, ne);
break;
case "subprocess":
CSubProcessEvent sp = new CSubProcessEvent(this);
sp.InstFromXmlNode(ev);
m_events.Add(sp.name, sp);
break;
case "loopevent":
CLoopEvent le = new CLoopEvent(this);
le.InstFromXmlNode(ev);
m_events.Add(le.name, le);
break;
default:
break;
}
}
}
/// <summary>
/// 建立变量(Param)与事件(Event)间的联系
/// </summary>
private void LinkParamEvent(){
try
{
int paNum = m_paramtable.ParamsNum;
for (int i = 0; i < paNum; i++)
{
CParam pa = m_paramtable[i];
foreach (string strEv in pa.linkEvents)
{
//如果CParam关联的Event不存在,则异常
if (!m_events.ContainsKey(strEv))
throw new Exception("Event " + strEv + " is not exist");
//如果pa关联的Event暂时未添加到m_relationEP中
if (!m_relationEP.ContainsKey(strEv))
{
m_relationEP.Add(strEv, new List<string>());
}
//建立事件(strEv)与变量(pa)之间的联系
m_relationEP[strEv].Add(pa.name);
m_events[strEv].paramlist[pa.name] = pa;
m_events[strEv].paramsApp_res[pa.name] = pa.linkEventsApp_res[strEv];
}
}
}
catch(Exception e)
{
Trace.WriteLine(e.Message);
}
}
/// <summary>
/// 添加一个变量
/// </summary>
/// <param name="par">添加的新变量</param>
public void AppendParam(CParam par){
try
{
//1. 添加变量到变量列表
m_paramtable.AppendParam(par);
//2. 建立变量与事件之间的联系
foreach(string strev in par.linkEvents)
{
//2.1 判断包含变量的事件是否存在
if (!m_events.ContainsKey(strev))
throw new Exception("Event " + strev + " is not exist");
//2.2 如果par关联的事件还未添加到m_relationEP
if (!m_relationEP.ContainsKey(strev))
{
m_relationEP.Add(strev, new List<string>());
}
//2.3 建立par与事件之间的关联
m_relationEP[strev].Add(par.name);
}
}
catch(Exception e)
{
Trace.WriteLine(e.Message);
}
}
/// <summary>
/// 添加一个事件(Event)
/// </summary>
/// <param name="ev">添加的新时间(Event)</param>
public void AppendEvent(IEvent ev){
try
{
//1. 判断ev是否已存在
if (m_events.ContainsKey(ev.name))
throw new Exception("Event " + ev.name + " is already exist");
//2. 添加ev到事件列表中
m_events.Add(ev.name, ev);
}
catch(Exception e)
{
Trace.WriteLine(e.Message);
}
}
/// <summary>
/// 添加流程
/// </summary>
/// <param name="flow"></param>
public void AppendFlow(Flow.IFlow flow){
try
{
//1 如果已存在以flow.source_event为key的项
if (m_flows.ContainsKey(flow.source_event))
{
List<Flow.IFlow> eFlows = m_flows[flow.source_event];
foreach (Flow.IFlow eFlow in eFlows)
{
//1.1 判断flow是否已存在
//如果两个流的源事件、目的事件相同,且两个流的类型相同,并且表达式相同
//则认为这两个流相同
if ((eFlow.GetType() == flow.GetType())
&& (eFlow.destination_event == flow.destination_event)
&& (eFlow.expression == flow.expression))
throw new Exception("Flow is already exist");
//1.2 添加流到工作流中
eFlows.Add(flow);
}
}
else //2 如果已存在以flow.source_event为key的项
{
List<Flow.IFlow> flows = new List<Flow.IFlow>();
flows.Add(flow);
m_flows.Add(flow.source_event, flows);
}
}
catch(Exception e)
{
Trace.WriteLine(e.Message);
}
}
/// <summary>
/// 解析流程(Flow)
/// </summary>
/// <param name="xmlNode"></param>
private void ParseFlows(XmlNode xmlNode){
//1. 检查xmlNode节点的合法性
if (xmlNode.Name != "flows")
return;
//2. 解析每个flow
foreach(XmlNode fn in xmlNode.ChildNodes)
{
/////////////////////////////////////对Flow种类的处理???
Flow.CFlow flow = new Flow.CFlow(m_paramtable);
flow.InstFromXmlNode(fn);
if (m_flows.ContainsKey(flow.source_event))
m_flows[flow.source_event].Add(flow);
else
{
List<Flow.IFlow> flows = new List<Flow.IFlow>();
flows.Add(flow);
m_flows.Add(flow.source_event, flows);
}
}
}
//保存事件实体创建时的Record Item
private List<Process_Record> SaveCreateRecord(Dictionary<string, string> records)
{
List<Process_Record> record_items = new List<Process_Record>();
foreach(var item in records)
{
Process_Record pr = new Process_Record();
pr.Re_Name = item.Key;
pr.Re_Value = item.Value;
record_items.Add(pr);
}
return record_items;
}
//根据自身信息创建工作流
//该函数调用要确保自身信息构建完善
public bool CreateEntityBySelf(string Ser_Num = null)
{
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe = new WorkFlow_Entity();
wfe.WE_Status = WE_STATUS.CREATED;
wfe.WE_Binary = Encoding.Default.GetBytes(WriteToXmlNode().OuterXml);
//2016/2/12 --保证子工作流串号与父工作流相同
if (Ser_Num == null)
wfe.WE_Ser = "";
else
wfe.WE_Ser = Ser_Num;
if (!wfs.AddWorkEntity(name, wfe))
return false;
m_entityID = wfe.WE_Id;
m_entitySerial = wfe.WE_Ser;
//m_defineID = define.W_ID;
RegEventsTimeOut(true);
return true;
}
public bool CreateEntity(string wf_name, string Ser_Num = null/*2016/2/12--保证子工作流串号与父工作流相同*/)
{
WorkFlows wfs = new WorkFlows();
XmlDocument doc = new XmlDocument();
WorkFlow_Define define = wfs.GetWorkFlowDefine(wf_name);
doc.LoadXml(Encoding.Default.GetString(define.W_Xml));
InstFromXmlNode((XmlNode)doc.DocumentElement);
WorkFlow_Entity wfe = new WorkFlow_Entity();
wfe.WE_Status = WE_STATUS.CREATED;
wfe.WE_Binary = Encoding.Default.GetBytes(WriteToXmlNode().OuterXml);
//wfe.Create_Info = SaveCreateRecord();
//2016/2/12 --保证子工作流串号与父工作流相同
if (Ser_Num == null)
wfe.WE_Ser = "";
else
wfe.WE_Ser = Ser_Num;
if (!wfs.AddWorkEntity(wf_name, wfe))
return false;
m_entityID = wfe.WE_Id;
m_entitySerial = wfe.WE_Ser;
m_defineID = define.W_ID;
RegEventsTimeOut(true);
return true;
}
public void RegEventsTimeOut(bool bCreated = true)
{
foreach(var e in m_events)
{
e.Value.RegTimeOut(bCreated);
}
}
//工作流开始运行
public string Start(IDictionary<string, string> record)
{
IEvent startE = null;
foreach(var item in m_events)
{
if (item.Value.GetType().Name == "CStartEvent")
{
startE = item.Value;
break;
}
}
if (startE == null)
return null;
m_courrentEvent = startE.name;
startE.EnterEvent("");
UpdateEntity(WE_STATUS.ACTIVE);
SubmitSignal("[]");
//状态发生了迁移
if (GetCurrentState() != startE.name)
{
if (record != null)
{
WorkFlows wfs = new WorkFlows();
Mission ms = wfs.GetWFEntityLastMission(EntityID);
List<Process_Record> res = new List<Process_Record>();
foreach (var re in record)
{
if (GetRecordItems().ContainsKey(re.Key))
{
Process_Record pre = new Process_Record();
pre.Re_Name = re.Key;
pre.Re_Value = re.Value;
res.Add(pre);
}
}
wfs.LinkRecordInfoToMiss(ms.Miss_Id, res);
}
}
return m_events[m_courrentEvent].currentaction + @"/?wfe_id=" + m_entityID;
}
//获取当前事件的处理页面
public string CurrentEventLink()
{
if (m_events[m_courrentEvent] == null || m_events[m_courrentEvent].currentaction.Trim() == "")
return "";
else
return m_events[m_courrentEvent].currentaction + @"/?wfe_id=" + m_entityID;
}
}//end CWorkFlow
}//end namespace FlowEngine<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Interface
{
public interface IEquipArchis
{
Equip_Archi GetEquipArchi(int id);
List<Equip_Archi> GetEquipArchi(string name);
List<Equip_Archi> GetChildMenu(int id);
bool AddEquipArchi(int parentID, Equip_Archi newMenu);
bool ModifyEquipArchi(int parentID, Equip_Archi nVal);
bool DeleteEquipArchi(int id);
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class PersonAndWorkflowsController : CommonController
{
public ActionResult Index()
{
return View();
}
public string submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
PersonManagment pm = new PersonManagment();
string workflow = item["WorkFlow"].ToString();
string[] member = item["Member"].ToString().Split(new char[] { ',' });
for (int i = 0; i < member.Length; i++)
{
int pid = pm.GetPersonId(member[i]);
int mid = pm.GetMenuId(workflow);
bool res = pm.AddPW(pid, mid);
}
//bool ress = pm.AddPW(Convert.ToInt32(item["personid"].ToString()), Convert.ToInt32(item["menuid"].ToString()));
}
catch (Exception e)
{
return "";
}
return ("/PersonAndWorkflows/Index");
}
}
}
<file_sep>using FlowEngine.Authority;
using FlowEngine.DAL;
using FlowEngine.Event;
using FlowEngine.Modals;
using FlowEngine.Param;
using FlowEngine.UserInterface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Web;
using System.Web.Security;
namespace FlowEngine
{
public class CWFEngine
{
//public static Dictionary<string, Dictionary<string, object>> authority_params = new Dictionary<string, Dictionary<string, object>>();
public static string authority_params = "";
//获得系统所有的工作流定义
public static List<UI_MissParam> GetMissionParams(int entity_id, int missId)
{
UI_MISSION miss = null;
List<UI_MISSION> m;
List<UI_MissParam> Listmp = new List<UI_MissParam>();
m = CWFEngine.GetHistoryMissions(entity_id);
foreach(var item in m)
{
if (item.Miss_Id != missId) continue;
else
{
miss = item; break;
}
}
foreach(var item in miss.Miss_ParamsAppRes)
{
if(miss.Miss_ParamsAppRes[item.Key]!="App_hidden")
{ UI_MissParam mp = new UI_MissParam();
mp.Param_Desc = miss.Miss_ParamsDesc[item.Key].ToString();
mp.Param_Value = miss.Miss_Params[item.Key].ToString();
if (mp.Param_Desc.IndexOf("附件") > -1)
{
mp.Param_isFile = 1;
if (mp.Param_Desc.IndexOf("附件") > -1 && mp.Param_Value != "")
{
string[] savedFileName = mp.Param_Value.Split(new char[] { '$' });
string saveExistFilename = Path.Combine("/Upload", savedFileName[1]);
mp.Param_SavedFilePath = savedFileName[0];
mp.Param_UploadFilePath = saveExistFilename;
}
}
else
{
mp.Param_isFile = 0;
mp.Param_SavedFilePath = "";
mp.Param_UploadFilePath = "";
}
Listmp.Add(mp);
}
}
return Listmp;
/* m=wfs.GetMissParams(missId);
foreach(var item in m)
{
UI_MissParam m1 = new UI_MissParam();
m1.Param_Name=item.Param_Name;
m1.Param_Value=item.Param_Value;
m1.Param_Type=item.Param_Type;
m1.Param_Desc=item.Param_Desc;
m1.Param_AppRes = wf.paramstable[item.Param_Name].linkEventsApp_res[event_Name];
missParams.Add(m1);
}
return missParams;*/
}
public static List<UI_WF_Define> ListAllWFDefine()
{
WorkFlows wfs = new WorkFlows();
List<UI_WF_Define> ui_wfs = new List<UI_WF_Define>();
List<WorkFlow_Define> wds = wfs.GetAllWorkFlows();
wds.ForEach(s => ui_wfs.Add(new UI_WF_Define { wf_id = s.W_ID, wf_name = s.W_Name, wf_description = s.W_Attribution }));
return ui_wfs;
}
//创建一个工作流
public static UI_WorkFlow_Entity CreateAWFEntityByName(string wf_name, string Ser_Num = null)
{
CWorkFlow wf = new CWorkFlow();
if (!wf.CreateEntity(wf_name, Ser_Num))
return null;
return wf;
}
public static CWorkFlow CreateWFEntityModifiedTimeOut(string wf_name, string event_name, CTimeOutProperty property, string Ser_Num = null /*2016/2/12--保证子工作流串号与父工作流相同*/)
{
CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
XmlDocument doc = new XmlDocument();
WorkFlow_Define define = wfs.GetWorkFlowDefine(wf_name);
doc.LoadXml(Encoding.Default.GetString(define.W_Xml));
wf.InstFromXmlNode((XmlNode)doc.DocumentElement);
//修改wf
IEvent ev_target = wf.events[event_name];
CTimeOutProperty timeout_pro = ev_target.GetTimeOutProperty();
timeout_pro.ExactTime = property.ExactTime;
timeout_pro.StartTime = property.StartTime;
timeout_pro.TimeOffset = property.TimeOffset;
WorkFlow_Entity wfe = new WorkFlow_Entity();
wfe.WE_Status = WE_STATUS.CREATED;
wfe.WE_Binary = Encoding.Default.GetBytes(wf.WriteToXmlNode().OuterXml);
if (Ser_Num == null)
wfe.WE_Ser = "";
else
wfe.WE_Ser = Ser_Num;
if (!wfs.AddWorkEntity(wf_name, wfe))
return null;
wf.EntityID = wfe.WE_Id;
wf.EntitySerial = wfe.WE_Ser;
wf.DefineID = define.W_ID;
wf.RegEventsTimeOut(true);
return wf;
}
//返回一个工作流定义
public static UI_WF_Define GetWorkFlowDefine(string wf_name)
{
WorkFlows wfs = new WorkFlows();
WorkFlow_Define wfd = wfs.GetWorkFlowDefine(wf_name);
UI_WF_Define ui_wfd = new UI_WF_Define { wf_name = wfd.W_Name, wf_description = wfd.W_Attribution };
return ui_wfd;
}
/// <summary>
/// 将Record添加到subprocess
/// </summary>
private static void Post_processSubprocess(IEvent ev, IDictionary<string, string> record)
{
if (record == null)
return;
CSubProcessEvent sp = (CSubProcessEvent)ev;
List<UI_MISSION> miss = GetHistoryMissions(sp.WfEntityId);
WorkFlows wfs = new WorkFlows();
foreach (UI_MISSION mi in miss)
{
List<Process_Record> prs = new List<Process_Record>();
foreach (var re in record)
{
Process_Record pr = new Process_Record();
pr.Re_Name = re.Key;
pr.Re_Value = re.Value;
prs.Add(pr);
}
wfs.LinkRecordInfoToMiss(mi.Miss_Id, prs);
}
//SubmitSignal(sp.WfEntityId, new Dictionary<string, string>(), record);
}
//fhp添加方法开始----
public static UI_WFEntity_Info GetMainWorkFlowEntity(string wfe_ser)
{
UI_WFEntity_Info wfe = new UI_WFEntity_Info();
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe1 = wfs.GetMainWorkFlowEntity(wfe_ser);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe1.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wfe.description = wf.description;
wfe.name = wf.name;
wfe.EntityID = wfe1.WE_Id;
wfe.serial = wfe1.WE_Ser;
wfe.Status = wfe1.WE_Status;
return wfe;
}
//fhp添加方法结束-----
/// <summary>
/// 或的工作流的信息以及指定变量的值
/// </summary>
/// <param name="wfe_id">工作流实体ID</param>
/// <param name="paras">变量列表
/// 例如: 要获得工作流(ID 为 4)的Equip_GyCode的当前值,则:
/// Dictionary paras = new Dictionary();
/// paras["Equip_GyCode"] = null;
/// UI_WFEntity_Info wfei = GetWorkFlowEntityWithParams(4, paras);
///
/// 调用完成后, wfei返回了 name, description, EntityID, serial, Status
/// 而paras["Equip_GyCode"] 将会被设置为正确值
/// </param>
/// <returns></returns>
public static UI_WFEntity_Info GetWorkFlowEntityWithParams(int wfe_id, IDictionary<string, object> paras)
{
UI_WFEntity_Info wfe = new UI_WFEntity_Info();
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe1 = wfs.GetWorkFlowEntity(wfe_id);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe1.WE_Binary));
XmlNode xml = doc.DocumentElement;
wf.ParaseBaseInfo(xml);
wf.ParseParams(xml.SelectSingleNode("paramtable"));
Dictionary<string, object> _tmp = new Dictionary<string, object>(paras);
foreach (var par in _tmp)
{
paras[par.Key] = wf.paramstable[par.Key].value;
}
wfe.name = wf.name;
wfe.description = wf.description;
wfe.EntityID = wf.EntityID;
wfe.serial = wf.EntitySerial;
wfe.Status = wfe1.WE_Status;
return wfe;
}
/// <summary>
/// 通过工作流实体的id获得工作流实体
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public static UI_WFEntity_Info GetWorkFlowEntiy(int wfe_id, bool FullInfo = false)
{
UI_WFEntity_Info wfe = new UI_WFEntity_Info();
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe1 = wfs.GetWorkFlowEntity(wfe_id);
if (FullInfo)
{
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe1.WE_Binary));
XmlNode xml = doc.DocumentElement;
wf.ParaseBaseInfo(xml);
WorkFlow_Define wfd = wfs.GetWorkFlowDefine(wfe_id);
//wfe.name = wfd.W_Name;
//wfe.description = wfd.W_Attribution;
wfe.Binary = Encoding.Default.GetString(wfe1.WE_Binary);
wfe.name = wf.name;
wfe.description = wf.description;
}
wfe.EntityID = wfe1.WE_Id;
wfe.serial = wfe1.WE_Ser;
wfe.Status = wfe1.WE_Status;
wfe.Last_TransTime = wfe1.Last_Trans_Time;
return wfe;
}
//发送消息到工作流
public static void SubmitSignal(int wfe_id, IDictionary<string, string> signal, IDictionary<string, string> record = null)
{
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe = wfs.GetWorkFlowEntity(wfe_id);
//如果该工作流处于非激活状态,则不能向其发送信息
if (wfe.WE_Status != WE_STATUS.ACTIVE)
return;
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wf.EntityID = wfe.WE_Id;
string preState = wf.GetCurrentState();
JArray ja = new JArray();
foreach(var s in signal)
{
JObject jo = new JObject();
jo.Add("name", s.Key);
jo.Add("value", s.Value);
ja.Add(jo);
}
wf.SubmitSignal(JsonConvert.SerializeObject(ja));
//如果preEvent为subprocess
IEvent preEvent = wf.GetCurrentEvent();
if (preEvent.GetType().Name == "CSubProcessEvent")
{
Post_processSubprocess(preEvent, record);
//wf.SubmitSignal("[]");
}
//状态发生了迁移
if (wf.GetCurrentState() != preState)
{
if (record != null)
{
Mission ms = wfs.GetWFEntityLastMission(wf.EntityID);
List<Process_Record> res = new List<Process_Record>();
foreach(var re in record)
{
//如果record中包含事件定义的需要记录的record item则记录到数据库中
if (wf.GetRecordItems().ContainsKey(re.Key))
{
Process_Record pre = new Process_Record();
pre.Re_Name = re.Key;
pre.Re_Value = re.Value;
res.Add(pre);
}
}
wfs.LinkRecordInfoToMiss(ms.Miss_Id, res);
}
//如果当前工作流是子流程,且已执行到End
if (wf.GetCurrentEvent().GetType().Name == "CEndEvent" && wf.ParentEntityID != -1)
{
WorkFlow_Entity P_wfe = wfs.GetWorkFlowEntity(wf.ParentEntityID);
CWorkFlow P_wf = new CWorkFlow();
XmlDocument P_doc = new XmlDocument();
P_doc.LoadXml(Encoding.Default.GetString(P_wfe.WE_Binary));
P_wf.InstFromXmlNode(P_doc.DocumentElement);
P_wf.EntityID = P_wfe.WE_Id;
P_wf.GetCurrentState();
}
}
//如果当前时间为subprocess
if (preEvent.GetType().Name == "CSubProcessEvent")
{
//如果该子事件的工作模式为并行的, 则需要发送一个信号,激励其自动运行一次
if (((CSubProcessEvent)preEvent).WorkingMode == "parallel")
SubmitSignal(wfe_id, new Dictionary<string, string>(), record);
}
}
private static void UpdateEntity(CWorkFlow wf, WE_STATUS status)
{
try
{
WorkFlow_Entity wfe = new WorkFlow_Entity
{
WE_Id = wf.EntityID,
WE_Status = status
};
wfe.WE_Binary = Encoding.Default.GetBytes(wf.WriteToXmlNode().OuterXml);
WorkFlows wfs = new WorkFlows();
if (!wfs.SaveWorkFlowEntity(wfe))
throw new Exception("Save WorkFlow Entity failed!");
}
catch (Exception e)
{
return;
}
}
//获取当前任务列表
/*public static List<UI_MISSION> GetActiveMissions<T>(ObjectContext oc, string Entity_name="ALL", bool bAuthCheck = true)
{
List<UI_MISSION> missions = new List<UI_MISSION>();
WorkFlows wfs = new WorkFlows();
List<WorkFlow_Entity> wfes = wfs.GetActiveWorkFlowEntities(Entity_name);
foreach(WorkFlow_Entity wfe in wfes)
{
UI_MISSION mi = new UI_MISSION();
mi.WE_Entity_Id = wfe.WE_Id;
mi.WE_Name = wfs.GetWorkFlowEntityName(wfe.WE_Id);
//恢复工作流实体
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wf.EntityID = wfe.WE_Id;
wf.EntitySerial = wfe.WE_Ser;
//if (wf.CurrentEventLink() == "")
// continue;
//权限验证
if (bAuthCheck)
{
IEvent ev = wf.GetCurrentEvent();
if (!ev.CheckAuthority<T>(authority_params, oc))
continue;
}
mi.WE_Event_Name = wf.GetCurrentEvent().name;
mi.WE_Event_Desc = wf.GetCurrentEvent().description;
mi.Mission_Url = wf.CurrentEventLink();
//读取参数的值
foreach(var pa in wf.GetCurrentEvent().paramlist)
{
mi.Miss_Params[pa.Key] = pa.Value.value;
}
missions.Add(mi);
}
return missions;
}*/
public static List<UI_MISSION> GetActiveMissions<T>(ObjectContext oc, string Entity_name = "ALL", bool bAuthCheck = true)
{
List<UI_MISSION> missions = new List<UI_MISSION>();
WorkFlows wfs = new WorkFlows();
List<CURR_Mission> cMis = wfs.GetActiveMissionsOfEntity(Entity_name);
foreach (CURR_Mission cm in cMis)
{
UI_MISSION mi = new UI_MISSION();
mi.WE_Entity_Id = cm.WFE_ID;
//if (wf.CurrentEventLink() == "")
// continue;
//权限验证
if (bAuthCheck)
{
CAuthority author = new CAuthority();
author.auth_string = cm.Str_Authority;
//if (!author.CheckAuth<T>(new Dictionary<string, object>(), authority_params[HttpContext.Current.Session.SessionID], oc))
// continue;
if (!author.CheckAuth<T>(new Dictionary<string, object>(), (Dictionary<string, object>)HttpContext.Current.Session[authority_params], oc))
continue;
}
mi.WE_Event_Name = cm.Miss_Name;
mi.WE_Event_Desc = cm.Miss_Desc;
mi.Mission_Url = cm.Current_Action + @"/?wfe_id=" + mi.WE_Entity_Id;
mi.WE_Event_Desc = cm.Miss_Desc;
missions.Add(mi);
}
return missions;
}
//获得工作流实体的当前任务
public static UI_MISSION GetActiveMission<T>(int entity_id, ObjectContext oc, bool bAuthCheck = true)
{
UI_MISSION miss = new UI_MISSION();
WorkFlows wfs = new WorkFlows();
WorkFlow_Entity wfe = wfs.GetWorkFlowEntity(entity_id);
miss.WE_Entity_Id = wfe.WE_Id;
miss.WE_Name = wfs.GetWorkFlowEntityName(wfe.WE_Id);
miss.WE_Entity_Ser = wfe.WE_Ser;
//恢复工作流实体
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe.WE_Binary));
wf.InstFromXmlNode(doc.DocumentElement);
wf.EntityID = wfe.WE_Id;
//权限验证
if (bAuthCheck)
{
IEvent ev = wf.GetCurrentEvent();
if (!ev.CheckAuthority<T>((Dictionary<string, object>)HttpContext.Current.Session[authority_params], oc))
return null;
}
miss.WE_Event_Name = wf.GetCurrentEvent().name;
miss.WE_Event_Desc = wf.GetCurrentEvent().description;
miss.Mission_Url = wf.CurrentEventLink();
//读取参数的值
foreach (var pa in wf.GetCurrentEvent().paramlist)
{
miss.Miss_Params[pa.Key] = pa.Value.value;
miss.Miss_ParamsAppRes[pa.Key] = wf.GetCurrentEvent().paramsApp_res[pa.Key];
}
return miss;
}
/// <summary>
/// 获取某一工作流实体的历史任务
/// </summary>
/// <param name="entity_id">工作流实体ID</param>
/// <returns></returns>
public static List<UI_MISSION> GetHistoryMissions(int entity_id)
{
List<UI_MISSION> his_miss = new List<UI_MISSION>();
WorkFlows wfs = new WorkFlows();
List<Mission> db_miss = wfs.GetWFEntityMissions(entity_id);
WorkFlow_Entity wfe = wfs.GetWorkFlowEntity(entity_id);
//恢复工作流实体
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfe.WE_Binary));
wf.EntityID = wfe.WE_Id;
wf.InstFromXmlNode(doc.DocumentElement);
foreach(var mi in db_miss)
{
UI_MISSION ui_mi = new UI_MISSION();
ui_mi.WE_Entity_Id = entity_id;
ui_mi.WE_Entity_Ser = wfe.WE_Ser;
ui_mi.WE_Event_Desc = mi.Miss_Desc;
ui_mi.WE_Event_Name = mi.Event_Name;
ui_mi.WE_Name = mi.Miss_Name;
ui_mi.Mission_Url = ""; //历史任务的页面至空
ui_mi.Miss_Id = mi.Miss_Id;
List<Mission_Param> mis_pars = wfs.GetMissParams(mi.Miss_Id);
foreach(var par in mis_pars)
{
CParam cp = new CParam();
cp.type = par.Param_Type;
cp.name = par.Param_Name;
cp.value = par.Param_Value;
cp.description = par.Param_Desc;
ui_mi.Miss_Params[cp.name] = cp.value;
ui_mi.Miss_ParamsAppRes[cp.name] = wf.paramstable[cp.name].linkEventsApp_res[ui_mi.WE_Event_Name];
ui_mi.Miss_ParamsDesc[cp.name]=cp.description;//xwm modified
}
his_miss.Add(ui_mi);
}
return his_miss;
}
/// <summary>
/// 根据历史任务状态选择符合条件的工作流
/// </summary>
/// <param name="condition">查询条件的lambda表达式如: s => (s.Params_Info.Count(t => t.name = "approve_user" && t.value = "cb1") > 0)</param>
/// <returns></returns>
public static List<UI_WFEntity_Info> GetWFEntityByHistoryStatus(System.Linq.Expressions.Expression<Func<Mission, bool>> condition)
{
List<UI_WFEntity_Info> wfe_info = new List<UI_WFEntity_Info>();
WorkFlows wfs = new WorkFlows();
List<WorkFlow_Entity> wfes = null;
//List<WorkFlow_Entity> wfes = wfs.GetWFEntityByConditon(s => s.Process_Info.wh );
try
{
using (var db = new WorkFlowContext())
{
wfes = db.mission.Where(condition).Select(a => a.Miss_WFentity).Distinct().Where(s => s.WE_Status != WE_STATUS.DELETED).ToList();
}
}
catch(Exception e)
{
return null;
}
foreach(WorkFlow_Entity fe in wfes)
{
UI_WFEntity_Info fe_info = new UI_WFEntity_Info();
fe_info.name = wfs.GetWorkFlowEntityName(fe.WE_Id);
fe_info.Status = fe.WE_Status;
fe_info.EntityID = fe.WE_Id;
fe_info.description = wfs.GetWorkFlowEntityDesc(fe.WE_Id);
fe_info.serial = fe.WE_Ser;
wfe_info.Add(fe_info);
}
return wfe_info;
}
public static List<UI_WFEntity_Info> GetWFEntityByHistoryDone(System.Linq.Expressions.Expression<Func<Mission, bool>> condition)
{
List<UI_WFEntity_Info> wfe_info = new List<UI_WFEntity_Info>();
WorkFlows wfs = new WorkFlows();
List<WorkFlow_Entity> wfes = null;
//List<WorkFlow_Entity> wfes = wfs.GetWFEntityByConditon(s => s.Process_Info.wh );
try
{
using (var db = new WorkFlowContext())
{
wfes = db.mission.Where(condition).Select(a => a.Miss_WFentity).Distinct().Where(s => s.WE_Status == WE_STATUS.DONE).ToList();
}
}
catch (Exception e)
{
return null;
}
foreach (WorkFlow_Entity fe in wfes)
{
UI_WFEntity_Info fe_info = new UI_WFEntity_Info();
fe_info.name = wfs.GetWorkFlowEntityName(fe.WE_Id);
fe_info.Status = fe.WE_Status;
fe_info.EntityID = fe.WE_Id;
fe_info.description = wfs.GetWorkFlowEntityDesc(fe.WE_Id);
fe_info.serial = fe.WE_Ser;
wfe_info.Add(fe_info);
}
return wfe_info;
}
/// <summary>
/// 获得某一工作流历史平均需要的步骤数量
/// </summary>
/// <param name="wf_name">工作流的名称</param>
/// <returns></returns>
public static int GetWorkFlowAvgSteps(string wf_name)
{
WorkFlows wfs = new WorkFlows();
return wfs.GetWFAvgSteps(wf_name);
}
/// <summary>
/// 获得某一工作流实体目前完成的步骤数量
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public static int GetWFEntityFinishSteps(int wfe_id)
{
WorkFlows wfs = new WorkFlows();
return wfs.GetWFEntityFinishSteps(wfe_id);
}
public static IDictionary<string, string> GetMissionRecordInfo(int wfe_id)
{
WorkFlows wfs = new WorkFlows();
List<Process_Record> Pre = wfs.GetMissionRecordInfo(wfe_id);
Dictionary<string, string> res = new Dictionary<string, string>();
foreach(var p in Pre)
{
res[p.Re_Name] = p.Re_Value;
}
return res;
}
/// <summary>
/// 从数据库中删除一个工作流实体
/// 建议:在用户取消人工提报时调用
/// </summary>
/// <param name="wfe_id"></param>
public static void RemoveWFEntity(int wfe_id)
{
WorkFlows wfs = new WorkFlows();
wfs.DeleteWFEntity(wfe_id);
}
/// <summary>
/// 将一个工作流实体置为已删除
/// 建议: 若该工作流已执行数步, 需要将其删除,为了保证系统后期可追溯,建议调用该函数
/// </summary>
/// <param name="wfe_id"></param>
public static void DeleteWFEntity(int wfe_id)
{
WorkFlows wfs = new WorkFlows();
wfs.SetWFEntityDeleted(wfe_id);
}
/// <summary>
/// 对工作流信息进行查询(low level)
/// </summary>
/// <param name="query_list">
/// 需要查询的属性列——空字符串表示查询所有属性列, 慎用!!!!!
/// 由于变量名的量比较大,强烈建议该参数不使用空串
/// M 代表 Missions
/// R 代表 Record
/// P 代表 Params
/// E 代表 WorkFlow_Entity
/// 如 "M.Event_Name, M.Miss_Name, R.time, R.username, P.Proble_DataSrc, E.WE_Ser, E.W_Attribtuion, ..."
/// </param>
/// <param name="query_condition">查询条件,如: "R.username = 'fhp' and E.W_Name = 'A11dot1'"</param>
/// <param name="record_filter">
/// Record过滤器——空字符串表示不过滤
/// 因为Process_Record表与Mission_Param是工作流数据库中最大的两张表,故而非常有必要再连接之前对两者进行预先筛选以提高效率
/// 考虑到参数表(Mission_Param)的筛选条件可能比较复杂,因此在这个函数中只提供在连接前对Record进行预筛选
/// 如: time >= '2015/12/25 0:00:00' and username = 'fhp'
/// 特别需要提醒的是: 如果查询不需要record信息,请务必将该参数设置为 "1 <> 1"
/// </param>
public static System.Data.DataTable QueryAllInformation(string query_list, string query_condition, string record_filter)
{
WorkFlows wfs = new WorkFlows();
return wfs.QueryAllInformation(query_list, query_condition, record_filter);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.UserInterface
{
/// <summary>
/// 用户用以返回任务的类
/// </summary>
public class UI_MISSION
{
public int Miss_Id {get; set;}
//任务所属工作流实体的ID
public int WE_Entity_Id { get; set; }
public string WE_Entity_Ser { get; set; }
//任务所属工作流名称
public string WE_Name { get; set; }
//任务所对应的事件(Event)名称
public string WE_Event_Name { get; set; }
//任务所对应事件(Event)描述
public string WE_Event_Desc { get; set; }
//处理任务的页面地址
public string Mission_Url { get; set; }
//任务关联的参数列表-(参数名称,参数值)
public Dictionary<string, object> Miss_Params = new Dictionary<string, object>();
//任务关联参数对应的描述-(参数名称,参数描述)用于显示-xwm modify
public Dictionary<string, object> Miss_ParamsDesc = new Dictionary<string, object>();
//任务关联参数对应的App_Res (参数名称, 参数的App_res)
public Dictionary<string, string> Miss_ParamsAppRes = new Dictionary<string, string>();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp.Controllers
{
public class CacheController : Controller
{
//
// GET: /Cache/
public ActionResult Index()
{
FileStream fs = new FileStream("D:\\web\\ZJtestCache.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs); // 创建写入流
sw.WriteLine("Cache" + " " + DateTime.Now.ToString()); // 写入
sw.Close(); //关闭文件
return View();
}
}
}<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class MyDsWorks:BaseDAO
{
/// <summary>
/// 检查是否本月已经存过定时信息
/// </summary>
/// <param name="work_name"></param>
/// <param name="event_name"></param>
/// <param name="year"></param>
/// <param name="month"></param>
/// <returns></returns>
//public bool IsAlreadySave(string work_name,string event_name,string year,string month)
//{
// using (var db = base.NewDB())
// {
// var R = db.DSEventDetail.Where(a => a.work_name == work_name & a.event_name == event_name&a.year==year&a.month==month);
// if (R.Count() != 0)
// return true;
// else
// return false;
// }
//}
public string getDstime(string work_name, string event_name)
{
using (var db = base.NewDB())
{
var R = db.DsTimeOfWork.Where(a => a.work_name == work_name & a.event_name == event_name);
if (R.Count() != 0)
return R.First().time;
else
return "";
}
}
public int AddDsEvent(DSEventDetail ds)
{
try
{
using (var db = base.NewDB())
{
DSEventDetail newds = db.DSEventDetail.Add(ds);
db.SaveChanges();
return 1;
}
}
catch(Exception e)
{
return 0;
}
}
public DSEventDetail getdetailbyE_id(int entity_id)
{
using (var db = base.NewDB())
{
try
{
var E = db.DSEventDetail.Where(a => a.entity_id == entity_id).First();
return E;
}
catch
{ return null; }
}
}
public bool modifystate(int entity_id,string event_name)
{
using (var db = base.NewDB())
{
try
{
var E = db.DSEventDetail.Where(a => a.entity_id == entity_id&&a.event_name==event_name).First();
if (E != null)
{
E.state = 1;
E.done_time = DateTime.Now;
db.SaveChanges();
return true;
}
else
return true;
}
catch
{ return false; }
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class A15dot1TabJing_Weight //静
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//设备腐蚀泄漏次数
public double sbfsxlcs_weight { get; set; }
//千台冷换设备管束
public double qtlhsbgs_weight { get; set; }
//工业炉平均热效效率
public double gylpjrxl_weight { get; set; }
//换热器检修率
public double hrqjxl_weight { get; set; }
//压力容器定检率
public double ylrqdjl_weight { get; set; }
//压力管道年度检验计划完成率
public double ylgdndjxjhwcl_weight { get; set; }
//安全阀年度校验计划完成率
public double aqfndjyjhwcl_weight { get; set; }
//设备腐蚀检测计划完成率
public double sbfsjcjhwcl_weight { get; set; }
//静设备检维修一次合格率
public double jsbjwxychgl_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class A15dot1TabDian_Weight //电
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//电气误操作次数
public double dqwczcs_weight { get; set; }
//继电保护正确动作率
public double jdbhzqdzl_weight { get; set; }
//设备故障率
public double sbgzl_weight { get; set; }
// 电机MTBF
public double djMTBF_weight { get; set; }
//电力电子设备MTBF
public double dzdlsbMTBF_weight { get; set; }
//主变功率因素
public double zbglys_weight { get; set; }
//电能计量平衡率
public double dnjlphl_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class A15dot1TabYi_Weight //仪
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//联锁系统正确动作率
public double lsxtzqdzl_weight { get; set; }
// 控制系统故障次数
public double kzxtgzcs_weight { get; set; }
//仪表控制率
public double ybkzl_weight { get; set; }
//仪表实际控制率
public double ybsjkzl_weight { get; set; }
//联锁系统投用率
public double lsxttyl_weight { get; set; }
//关键控制阀门故障次数
public double gjkzfmgzcs_weight { get; set; }
//控制系统故障报警次数
public double kzxtgzbjcs_weight { get; set; }
// 常规仪表故障率
public double cgybgzl_weight { get; set; }
//调节阀门MTBF
public double tjfMDBF_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class A15dot1TabQiYe_Weight //企业级KPI
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//装置可靠性指数
public double zzkkxzs_weight { get; set; }
//维修费用指数
public double wxfyzs_weight { get; set; }
//千台离心泵(机泵)密封消耗率
public double qtlxbmfxhl_weight { get; set; }
//千台冷换设备管束(含整台)更换率
public double qtlhsbgsghl_weight { get; set; }
//仪表实际控制率
public double ybsjkzl_weight { get; set; }
//事件数
public double sjs_weight { get; set; }
//故障强度扣分
public double gzqdkf_weight { get; set; }
//项目逾期率
public double xmyql_weight { get; set; }
//培训及能力
public double pxjnl_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class A15dot1TabDong_Weight //动
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//大机组故障率
public double djzgzl_weight { get; set; }
//故障维修率
public double gzwxl_weight { get; set; }
//千台离心泵密封消耗率
public double qtlxbmfxhl_weight { get; set; }
//紧急抢修工时率
public double jjqxgsl_weight { get; set; }
//工单平均完成时间
public double gdpjwcsj_weight { get; set; }
//机械密封检修率
public double jxmfpjsm_weight { get; set; }
//轴承平均寿命
public double zcpjsm_weight { get; set; }
//设备完好率
public double sbwhl_weight { get; set; }
//检修一次合格率
public double jxychgl_weight { get; set; }
//主要机泵平均效率
public double zyjbpjxl_weight { get; set; }
//机组平均效率
public double jzpjxl_weight { get; set; }
//往复机组故障率
public double wfjzgzl_weight { get; set; }
//年度百台机泵重复维修率
public double ndbtjbcfjxtc_weight { get; set; }
//机泵平均无故障间隔时间MTBF
public double jbpjwgzjgsjMTBF_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class Pq_A15dot1TabJing_Weight //静
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//设备腐蚀泄漏次数
public double sbfsxlcs_weight { get; set; }
//千台冷换设备管束
public double qtlhsbgs_weight { get; set; }
//工业炉平均热效效率
public double gylpjrxl_weight { get; set; }
//换热器检修率
public double hrqjxl_weight { get; set; }
//压力容器定检率
public double ylrqdjl_weight { get; set; }
//压力管道年度检验计划完成率
public double ylgdndjxjhwcl_weight { get; set; }
//安全阀年度校验计划完成率
public double aqfndjyjhwcl_weight { get; set; }
//设备腐蚀检测计划完成率
public double sbfsjcjhwcl_weight { get; set; }
//静设备检维修一次合格率
public double jsbjwxychgl_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class Pq_A15dot1TabDian_Weight //电
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//电气误操作次数
public double dqwczcs_weight { get; set; }
//继电保护正确动作率
public double jdbhzqdzl_weight { get; set; }
//设备故障率
public double sbgzl_weight { get; set; }
// 电机MTBF
public double djMTBF_weight { get; set; }
//电力电子设备MTBF
public double dzdlsbMTBF_weight { get; set; }
//主变功率因素
public double zbglys_weight { get; set; }
//电能计量平衡率
public double dnjlphl_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class Pq_A15dot1TabYi_Weight //仪
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//联锁系统正确动作率
public double lsxtzqdzl_weight { get; set; }
// 控制系统故障次数
public double kzxtgzcs_weight { get; set; }
//仪表控制率
public double ybkzl_weight { get; set; }
//仪表实际控制率
public double ybsjkzl_weight { get; set; }
//联锁系统投用率
public double lsxttyl_weight { get; set; }
//关键控制阀门故障次数
public double gjkzfmgzcs_weight { get; set; }
//控制系统故障报警次数
public double kzxtgzbjcs_weight { get; set; }
// 常规仪表故障率
public double cgybgzl_weight { get; set; }
//调节阀门MTBF
public double tjfMDBF_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class Pq_A15dot1TabQiYe_Weight //企业级KPI
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//装置可靠性指数
public double zzkkxzs_weight { get; set; }
//维修费用指数
public double wxfyzs_weight { get; set; }
//千台离心泵(机泵)密封消耗率
public double qtlxbmfxhl_weight { get; set; }
//千台冷换设备管束(含整台)更换率
public double qtlhsbgsghl_weight { get; set; }
//仪表实际控制率
public double ybsjkzl_weight { get; set; }
//事件数
public double sjs_weight { get; set; }
//故障强度扣分
public double gzqdkf_weight { get; set; }
//项目逾期率
public double xmyql_weight { get; set; }
//培训及能力
public double pxjnl_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
public class Pq_A15dot1TabDong_Weight //动
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//[Required()]
//故障强度扣分
public double gzqdkf_weight { get; set; }
//大机组故障率
public double djzgzl_weight { get; set; }
//故障维修率
public double gzwxl_weight { get; set; }
//千台离心泵密封消耗率
public double qtlxbmfxhl_weight { get; set; }
//紧急抢修工时率
public double jjqxgsl_weight { get; set; }
//工单平均完成时间
public double gdpjwcsj_weight { get; set; }
//机械密封检修率
public double jxmfpjsm_weight { get; set; }
//轴承平均寿命
public double zcpjsm_weight { get; set; }
//设备完好率
public double sbwhl_weight { get; set; }
//检修一次合格率
public double jxychgl_weight { get; set; }
//主要机泵平均效率
public double zyjbpjxl_weight { get; set; }
//机组平均效率
public double jzpjxl_weight { get; set; }
//往复机组故障率
public double wfjzgzl_weight { get; set; }
//年度百台机泵重复维修率
public double ndbtjbcfjxtc_weight { get; set; }
//机泵平均无故障间隔时间MTBF
public double jbpjwgzjgsjMTBF_weight { get; set; }
//片区名称
public string Pq_Name { get; set; }
//装置计划元组
public string Zz_Code { get; set; }
//装置名称
public string Zz_Name { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A11dot1Controller : CommonController
{
//
// GET: /A11dot1/
public ActionResult Index()
{
return View(getIndexListRecords("A11dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A11dot1/提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A11dot1/成立风险评估小组
public ActionResult CreateAssessGroup(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/危害识别
public ActionResult RiskRecognition(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/车间确立管控措施
public ActionResult CjMngCtlPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/机动处(专业团队)审核下达
public ActionResult ZytdConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/可靠性工程师审核车间管控措施
public ActionResult PqConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/车间组织监督实施
public ActionResult CjSupervise(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/评估小组确立管控措施
public ActionResult PgxzMngCtlPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/机动处组织监督实施
public ActionResult JdcSupervise(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot1/确认风险是否可控,并进行风险登记
public ActionResult RiskAcceptRecord(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A8dot2/跳转到[A11.3]风险管控模块
public ActionResult JumpToA11dot3(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Submit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string CreateAssessGroup_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CreateAssessGroup_done"] = item["CreateAssessGroup_done"].ToString();
signal["Group_Header"] = item["Group_Header"].ToString();
signal["Group_Member"] = item["Group_Member"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string RiskRecognition_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Risk_Type"] = item["Risk_Type"].ToString();
signal["RiskRecognition_done"] = item["RiskRecognition_done"].ToString();
signal["Severity"] = item["Severity"].ToString();
signal["Probability"] = item["Probability"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string CjMngCtlPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CreatePlan_done"] = item["CreatePlan_done"].ToString();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string PqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirm_done"] = item["PqConfirm_done"].ToString();
signal["PqConfirm_Result"] = item["PqConfirm_Result"].ToString();
signal["PqConfirm_Reason"] = item["PqConfirm_Reason"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string CjSupervise_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ImplementPlan_done"] = item["ImplementPlan_done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string PgxzMngCtlPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CreatePlan_done"] = item["CreatePlan_done"].ToString();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string JdcSupervise_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ImplementPlan_done"] = item["ImplementPlan_done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
public string RiskAcceptRecord_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["RiskAcceptRecord_done"] = item["RiskAcceptRecord_done"].ToString();
signal["Risk_IsAcceptable"] = item["Risk_IsAcceptable"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot1/Index");
}
}
}<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment.MenuConfig
{
public class EquipArchiManagment
{
private IEquipArchis db_equip_archi = new Equip_Archis();
private Equip_Archis EAs = new Equip_Archis();
public string getEa_namebyId(int Ea_id)
{
return EAs.getEa_namebyId(Ea_id);
}
public int getEa_idbyname(string Ea_name)
{
return EAs.getEa_idbyname(Ea_name);
}
public string getEa_codebyname(string Ea_name)
{
return EAs.getcodebyname(Ea_name);
}
//添加一个菜单
//parentID == -1 ,添加到根节点
public bool AddEquipArchiItem(int parent_Id, Equip_Archi add)
{
if (parent_Id == -1)
{
Equip_Archi root = GetRootItem();
return db_equip_archi.AddEquipArchi(root.EA_Id, add);
}
else
return db_equip_archi.AddEquipArchi(parent_Id, add);
}
//修改一个菜单
public bool ModifyEquipArchiItem(Equip_Archi modify)
{
return db_equip_archi.ModifyEquipArchi(modify.EA_Id, modify);
}
//删除一个菜单
public bool DeleteEquipArchiItem(int del)
{
return db_equip_archi.DeleteEquipArchi(del);
}
//获得菜单的根节点
public Equip_Archi GetRootItem()
{
try
{
List<Equip_Archi> res = db_equip_archi.GetEquipArchi("root");
if (res.Count > 1)
throw new Exception("DB has not only one root item");
return res[0];
}
catch (Exception e)
{
return null;
}
}
//public Equip_Archi GetItemById(int id)
//{
// return db_equip_archi.GetEA_Archi(id);
//}
//获得某一个菜单项的子节点
public List<Equip_Archi> GetChildsMenu(int EA_Id)
{
List<Equip_Archi> childs = new List<Equip_Archi>();
childs = db_equip_archi.GetChildMenu(EA_Id);
return childs;
}
//private MenuTree BuildChildTree(int parentId)
//{
// MenuTree cRoot = new MenuTree();
// Menu cRootM = GetItemById(parentId);
// cRoot.Menu_Id = cRootM.Menu_Id;
// cRoot.Menu_Name = cRootM.Menu_Name;
// cRoot.Menu_Icon = cRootM.Menu_Icon;
// cRoot.Link_Url = cRootM.Link_Url;
// List<Menu> childs = GetChildsMenu(parentId);
// foreach(Menu m in childs)
// {
// MenuTree mt = BuildChildTree(m.Menu_Id);
// cRoot.childs.Add(mt);
// }
// return cRoot;
//}
//public MenuTree BuildMenuTree()
//{
// Menu root = GetRootItem();
// return BuildChildTree(root.Menu_Id);
//}
private void BuildMenuList_inter(MenuListNode1 parent, List<MenuListNode1> list)
{
List<Equip_Archi> childs = GetChildsMenu(parent.EA_Id);
foreach (Equip_Archi m in childs)
{
MenuListNode1 mn = new MenuListNode1();
mn.EA_Id = m.EA_Id;
mn.EA_Name = m.EA_Name;
mn.EA_Code = m.EA_Code;
mn.EA_Title = m.EA_Title;
mn.Parent_id = parent.EA_Id;
mn.level = parent.level + 1;
parent.Childs.Add(mn.EA_Id);
list.Add(mn);
BuildMenuList_inter(mn, list);
mn.Childs.ForEach(i => parent.Childs.Add(i));
}
}
public List<MenuListNode1> BuildMenuList()
{
Equip_Archi root = GetRootItem();
MenuListNode1 rmn = new MenuListNode1();
rmn.EA_Id = root.EA_Id;
rmn.EA_Name = root.EA_Name;
rmn.EA_Code = root.EA_Code;
rmn.EA_Title = root.EA_Title;
rmn.level = -1;
List<MenuListNode1> list = new List<MenuListNode1>();
BuildMenuList_inter(rmn, list);
foreach (MenuListNode1 mn in list)
{
if (mn.Parent_id == root.EA_Id)
mn.Parent_id = 0;
}
return list;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Notice_Info
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string Notice_ID { get; set; }
public string Notice_Type { get; set; }
public string Notice_Desc { get; set; }
public string Notice_Yx { get; set; }
public string Notice_EquipCode { get; set; }
public string Notice_Equip_ABCmark { get; set; }
public string Notice_OverCondition { get; set; }
public string Notice_State { get; set; }
public string Notice_Order_ID { get; set; }
public string Notice_FaultStart { get; set; }
public string Notice_FaultEnd { get; set; }
public string Notice_FaultStartTime { get; set; }
public string Notice_FaultEndTime { get; set; }
public string Notice_PlanGroup { get; set; }
public string Notice_CR_Person { get; set; }
public string Notice_CR_Date { get; set; }
public string Notice_Stop { get; set; }
public string Notice_Commit_Time { get; set; }
public string Notice_FunLoc { get; set; }
public string Notice_Catalog { get; set; }
public string Notice_Priority { get; set; }
public string Notice_Commit_Date { get; set; }
public string Notice_QMcode { get; set; }
public string Notice_FaultYx { get; set; }
public string Notice_LongTxt { get; set; }
public string Notice_EquipSpeciality{ get; set; }
public int Notice_A13dot1State { get; set; }//被A13dot1处理状态 "0:待处理","1:已处理"
public string Notice_A13dot1_DoDateTime { get; set; }//在A13dot1处理的日期时间 ”yyy-mm-dd HH:SS:mm"
public string Notice_A13dot1_DoUserName { get; set; }//在A13dot1处理的用户名
public string Notice_LoadinDateTime { get; set; }//导入完整性系统的日期时间
public string Notice_Speciality { get; set; }
public string Notice_UpdateDate { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using WebApp.Models.DateTables;
using System.Collections.Specialized;
using EquipBLL.AdminManagment.MenuConfig;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class LSA5dot2Controller : CommonController
{
//
// GET: /LSA5dot2/
PersonManagment pm = new PersonManagment();
TablesManagment tm = new TablesManagment();
EquipManagment Em = new EquipManagment();
EquipArchiManagment Eam = new EquipArchiManagment();
private SxglManagment Sx = new SxglManagment();
public ActionResult Index(int job_id)
{
Jobs js = new Jobs();
Timer_Jobs tj = js.GetTimerJob(job_id);
string qeendtime = tj.STR_RES_3;
if (DateTime.Now < DateTime.Parse(qeendtime))
ViewBag.zgenable = 1;
else
ViewBag.zgenable = 0;
ViewBag.jobName = tj.job_name;
ViewBag.time = tj.STR_RES_2;
ViewBag.depts = tj.STR_RES_1;
ViewBag.wfe_ids = tj.run_result;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
{
ViewBag.isKkxgcs = "1";
}
else
{
ViewBag.isKkxgcs = "0";
}
return View();
}
public class LSA5Model
{
public string userName;
public string missTime;
public int missIndex;
public string miss_desc;
public string miss_url;
public string wfe_serial;
public string zz_name;
public string workFlowName;
}
public string getdcllist(string jobName, string time, string depts, string wfe_ids)
{
string run_results = wfe_ids.TrimStart('[').TrimEnd(']');
List<string> run_enity_id = new List<string>();
List<int> wfe_id = new List<int>();
if (run_results.Contains(','))
{
run_enity_id = run_results.Split(new char[] { ',' }).ToList();
}
else
{
run_enity_id.Add(run_results);
}
for (int i = 0; i < run_enity_id.Count(); i++)
{
wfe_id.Add(Convert.ToInt16(run_enity_id[i]));
}
// string WorkFlow_Name = "A5dot1";
List<LSA5Model> Am = new List<LSA5Model>();
// List<UI_MISSION> miss;
List<object> or = new List<object>();
//miss = CWFEngine.GetActiveMissions<Person_Info>(((IObjectContextAdapter)(new EquipWebContext())).ObjectContext, WorkFlow_Name, true);
foreach (var item in wfe_id)
{
LSA5Model o = new LSA5Model();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item, paras);
UI_MISSION lastMi = CWFEngine.GetHistoryMissions(item).Last();
int Miss_Id = lastMi.Miss_Id;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
//o.userName = r["username"];
o.missTime = r["time"];
}
else
{
// o.userName = "";
o.missTime = "";
}
//if (item.Mission_Url.Contains("dot"))
// o.miss_url = item.Mission_Url;
//else
// o.miss_url = "";
o.wfe_serial = wfei.serial;
o.zz_name = paras["Zz_Name"].ToString();
o.miss_url = "/LSA5dot2/ZzSubmit/?wfe_id=" + item.ToString();
Am.Add(o);
}
for (int i = 0; i < Am.Count; i++)
{
object o = new
{
wfe_serial = Am[i].wfe_serial,
zz_Name = Am[i].zz_name,
job_name = jobName,
time = time,
missTime = Am[i].missTime,
depts = depts,
miss_url = Am[i].miss_url
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public string dcl_list(string wfe_ids)
{
string run_results = wfe_ids.TrimStart('[').TrimEnd(']');
List<string> run_enity_id = new List<string>();
List<int> wfe_id = new List<int>();
if (run_results.Contains(','))
{
run_enity_id = run_results.Split(new char[] { ',' }).ToList();
}
else
{
run_enity_id.Add(run_results);
}
for (int i = 0; i < run_enity_id.Count(); i++)
{
wfe_id.Add(Convert.ToInt16(run_enity_id[i]));
}
List<A5dot2Tab1> E = Sx.GetLS_listbywfe_id(wfe_id);
List<object> r = new List<object>();
string isRectified = "";
for (int i = 0; i < E.Count; i++)
{
if (E[i].isRectified == 0)
isRectified = "未整改";
else
isRectified = "已整改";
object o = new
{
index = i + 1,
zzname = E[i].zzName.ToString(),
sbgybh = E[i].sbGyCode.ToString(),
sbcode = E[i].sbCode.ToString(),
notgood = E[i].problemDescription.ToString(),
iszg = isRectified,
a_id = E[i].Id
};
r.Add(o);
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public ActionResult ZzSubmit(string wfe_id)
{
UI_MISSION mi = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
Dictionary<string, object> mi_params = mi.Miss_Params;
int Zz_id = Eam.getEa_idbyname(mi.Miss_Params["Zz_Name"].ToString());
ViewBag.Zz_id = Zz_id;
ViewBag.Zz_name = mi.Miss_Params["Zz_Name"].ToString();
ViewBag.wfe_id = wfe_id;
return View();
}
public string Pqcheck_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string pqname = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// int a_id = Convert.ToInt32(item["a_id"]);
string a_ids = item["a_id"].ToString();
List<string> a_id = a_ids.Split(new char[] { ',' }).ToList();
DateTime time = DateTime.Now;
TablesManagment tm = new TablesManagment();
for (int i = 0; i < a_id.Count(); i++)
{
tm.Pqcheck_byid(Convert.ToInt32(a_id[i]), pqname, time);
A5dot2Tab1 new_5dot21 = new A5dot2Tab1();
new_5dot21.pqCheckTime = DateTime.Now;
new_5dot21.pqUserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_5dot21.isRectified = 1;
new_5dot21.state = 1;
new_5dot21.Id = Convert.ToInt32(a_id[i]);
string res = Sx.ModifySxItem1(new_5dot21);
}
}
catch (Exception e)
{
return "";
}
return ("/A5dot2/Index");
}
public string ZzSubmit_Bcsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A5dot1Tab1 a5dot1Tab1 = new A5dot1Tab1();
DateTime my = DateTime.Now;
int cjid = Em.getEA_parentid(Convert.ToInt32(item["Zz_Id"]));
string cjname = Eam.getEa_namebyId(cjid);
A5dot2Tab1 new_5dot2 = new A5dot2Tab1();
new_5dot2.cjName = cjname;
new_5dot2.zzName = item["Zz_Name"].ToString();
new_5dot2.sbGyCode = item["Equip_GyCode"].ToString();
new_5dot2.sbCode = item["Equip_Code"].ToString();
new_5dot2.sbType = item["Equip_Type"].ToString();
new_5dot2.zyType = item["Zy_Type"].ToString();
new_5dot2.problemDescription = item["problemDescription"].ToString();
new_5dot2.jxSubmitTime = DateTime.Now;
new_5dot2.jxUserName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_5dot2.isRectified = 0;
new_5dot2.state = 0;
new_5dot2.temp2 = item["wfe_id"].ToString();
bool res = Sx.AddSxItem(new_5dot2);
string wfe_id = item["wfe_id"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(wfe_id), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A5dot2/Index");
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Collections;
namespace WebApp.Controllers
{
public class A14dot1Controller : CommonController
{
//
// GET: /A14dot1/
public ActionResult Index()
{
return View(getA14dot1_Model());
}
public ActionResult A14()
{
return View();
}
public ActionResult WorkFolw_DetailforA14(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string click_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string Equip_Code = item["Equip_Code"].ToString();
string Jx_Reason = item["Jx_Reason"].ToString();
string flowname = "A8dot2";
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
if (wfe != null)
{
EquipManagment em = new EquipManagment();
Equip_Info eqinfo = em.getEquip_Info(Equip_Code);
List<Equip_Archi> Equip_ZzBelong = em.getEquip_ZzBelong(eqinfo.Equip_Id);
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
int flow_id = wfe.EntityID;
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxSubmit_done"] = "true";
signal["Cj_Name"] = Equip_ZzBelong[1].EA_Name; //Cj_Name
signal["Zz_Name"] = Equip_ZzBelong[0].EA_Name; //Zz_Name
signal["Equip_GyCode"] = eqinfo.Equip_GyCode;
signal["Equip_Code"] = eqinfo.Equip_Code;
signal["Equip_Type"] = eqinfo.Equip_Type;
signal["Zy_Type"] = eqinfo.Equip_Specialty;
signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
signal["Jx_Reason"] = Jx_Reason;//计划检修原因 PM?
signal["Data_Src"] = "A14dot1";
//record
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(flow_id, signal, record);
return ("/A8dot2/Index");
}
else
return "/A14dot1/Index";
}
catch (Exception e)
{
return "";
}
//return ("/A14dot1/Index");
}
public class Gxqmodel
{
public string WE_Ser;
public int WE_Id;
}
//=========================2016.8.7by XuS===========================================================
/// <summary>
/// 删除重复行,若查询条件有时间,则会将一个流水号的所有事件查询出来,下面两个函数可将流水号筛选一遍剔除重复
/// </summary>
/// <param name="indexList"></param>
/// <param name="index"></param>
/// <returns></returns>
public static bool IsContain(ArrayList indexList, int index)
{
for (int i = 0; i < indexList.Count; i++)
{
int tempIndex = Convert.ToInt32(indexList[i]);
if (tempIndex == index)
{
return true;
}
}
return false;
}
public static DataTable DeleteSameRow(DataTable dt, string Field)
{
ArrayList indexList = new ArrayList();
// 找出待删除的行索引
if (dt.Rows.Count>1)
{
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
if (!IsContain(indexList, i))
{
for (int j = i + 1; j < dt.Rows.Count; j++)
{
if (dt.Rows[i][Field].ToString() == dt.Rows[j][Field].ToString())
{
indexList.Add(j);
}
}
}
}
// 根据待删除索引列表删除行
for (int i = indexList.Count - 1; i >= 0; i--)
{
int index = Convert.ToInt32(indexList[i]);
dt.Rows.RemoveAt(index);
}
}
return dt;
}
//========================================================================================================
public string A14ActiveList(string WorkFlow_Name,string yearandmonth)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string WE_Status = "0";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username,R.time";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "' and R.username is not null";
string record_filter;
string nexttimepoint;
string[] month = yearandmonth.Split('/');
nexttimepoint=month[0]+"/"+(Convert.ToInt16(month[1])+1).ToString();
record_filter = "time >= '" + yearandmonth + "/" + "1" + " 00:00:00'" + "and time <= '" + nexttimepoint + "/" + "1" + " 00:00:00'";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
DataTable dt2 = DeleteSameRow(dt, "WE_Ser");
string str = "";//存返回结果
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < dt2.Rows.Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in Gmlist)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.WE_Id);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.WE_Ser;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item.WE_Id;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
List<object> or = new List<object>();
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public string A14HistoryList(string WorkFlow_Name, string yearandmonth)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
string WE_Status = "3";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username,R.time";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and E.WE_Status='" + WE_Status + "' and R.username is not null";
string record_filter;
string nexttimepoint;
string[] month = yearandmonth.Split('/');
nexttimepoint = month[0] + "/" + (Convert.ToInt16(month[1]) + 1).ToString();
record_filter = "time >= '" + yearandmonth + "/" + "1" + " 00:00:00'" + "and time <= '" + nexttimepoint + "/" + "1" + " 00:00:00'";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
DataTable dt2 = DeleteSameRow(dt, "WE_Ser");
string str="";//存返回结果
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < dt2.Rows.Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in Gmlist)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.WE_Id);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.WE_Ser;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item.WE_Id;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
List<object> or = new List<object>();
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using System;
using EquipDAL.Implement;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EquipModel.Context;
using EquipModel.Entities;
namespace EquipBLL.AdminManagment
{
public class RoleManagment
{
// 角色model........THL
public class Role_viewModal
{
public int Role_Ids;
public string Role_Names;
public string Role_Descs;
public string Menu_Ids;
public string Menu_Names;
public List<Menu> Menus;
}
private Roles RR = new Roles();
public bool AddPersons(int Role_Id,List<int> PersonIdSet)
{
try
{
foreach(var i in PersonIdSet)
{
RR.AddPerson(Role_Id, i);
}
return true;
}
catch { return false; }
}
public bool Add_Role(Role_Info R, List<int> Menu_IDs)
{
try
{
int NewpR_id = RR.AddRole(R);
RR.Roles_LinkMenus(NewpR_id, Menu_IDs);
return true;
}
catch { return false; }
}
public List<Person_Info> getRole_Persons(int Role_Id)
{
return RR.getRole_Persons(Role_Id);
}
public List<Role_Info> get_ALl_Roles()
{
try { return RR.getRoles(); }
catch { return null; }
}
public Role_viewModal Get_RoleModal(int Role_Id)
{
int i;
var r = RR.Get_RoleModal(Role_Id);
Role_viewModal r_item = new Role_viewModal();
r_item.Role_Ids = r.RInfo.Role_Id;
r_item.Role_Names = r.RInfo.Role_Name;
r_item.Role_Descs = r.RInfo.Role_Desc;
r_item.Menu_Names = "";
r_item.Menu_Ids = "";
if (r.M_Info.Count > 0)
{
for (i = 0; i < r.M_Info.Count - 1; i++)
{
r_item.Menu_Ids = r_item.Menu_Ids + (r.M_Info[i]).Menu_Id + ",";
r_item.Menu_Names = r_item.Menu_Names + (r.M_Info[i]).Menu_Name + "\r\n";
}
r_item.Menu_Ids = r_item.Menu_Ids + (r.M_Info[i]).Menu_Id;
r_item.Menu_Names = r_item.Menu_Names + (r.M_Info[i]).Menu_Name;
}
r_item.Menus = r.M_Info;
return r_item;
}
//public Role_viewModal G_M_Model(int Role_Id)
//{
// int i;
// var r = RR.Get_RoleModal(Role_Id);
// Role_viewModal r_item = new Role_viewModal();
// if (r.M_Info.Count > 0)
// {
// for (i = 0; i < r.M_Info.Count - 1; i++)
// {
// }
// }
//}
public bool Update_Role(Role_Info r, List<int> Menu_IDs)
{
try
{
RR.ModifyRole(r);
RR.Roles_LinkMenus(r.Role_Id, Menu_IDs);
return true;
}
catch { return false; }
}
public bool Delete_Role(int id)
{
return RR.DeleteRole(id);
}
// 新增角色信息时获取权限树
// ......专为添加角色菜单时显示使用.....新增加thl
public List<TreeListNode> BuildMenuList()
{
TreeListNode rnode = new TreeListNode();
rnode.text = "root";
rnode.selectable = false;
List<TreeListNode> list = new List<TreeListNode>();
BuildMenuList_inter(rnode, list);
return list;
}
// 添加角色时系统菜单显示时使用.....新增加thl
private void BuildMenuList_inter(TreeListNode parent, List<TreeListNode> list)
{
Menus M_D=new Menus();
List<Menu> Childs = M_D.GetChildMenu(parent.text);
foreach (Menu item in Childs)
{
TreeListNode mn = new TreeListNode();
mn.text = item.Menu_Name;
mn.id = item.Menu_Id;
if (M_D.GetChildMenu(item.Menu_Id).Count == 0) mn.selectable = true;
parent.nodes.Add(mn);
if (parent.text == "root") list.Add(mn);
BuildMenuList_inter(mn, list);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FlowDesigner.ConfigItems
{
class ConfigLoopEvent : ConfigEvent
{
public ConfigLoopEvent(string eType) : base(eType)
{
}
[CategoryAttribute("循环设置")]
public string LoopCondition { get; set; }
[CategoryAttribute("循环设置")]
public string TimeWaiting { get; set; }
public override XmlElement SaveConfigItem(XmlDocument Owner)
{
XmlElement base_xml = base.SaveConfigItem(Owner);
XmlElement loopSetting = Owner.CreateElement("LoopSetting");
XmlElement loopcondition = Owner.CreateElement("condition");
loopcondition.AppendChild(Owner.CreateCDataSection(LoopCondition));
loopSetting.AppendChild(loopcondition);
XmlElement waitingtime = Owner.CreateElement("waiting_time");
waitingtime.AppendChild(Owner.CreateCDataSection(TimeWaiting));
loopSetting.AppendChild(waitingtime);
base_xml.AppendChild(loopSetting);
return base_xml;
}
}
}
<file_sep>///////////////////////////////////////////////////////////
// CSymbol.cs
// Implementation of the Class CSymbol
// Generated by Enterprise Architect
// Created on: 28-10月-2015 14:59:32
// Original author: chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace FlowEngine.Flow {
/// <summary>
/// 标识符
/// </summary>
public class CSymbol {
/// <summary>
/// 名称
/// </summary>
private string m_name;
/// <summary>
/// 类型
/// </summary>
private CSymbol.Type m_type;
/// <summary>
/// 值
/// </summary>
private object m_value;
public enum Type : int
{
Param,
Value,
Operator,
Function,
Result,
OpenBracket,
CloseBracket,
Invalid //未知,非法
};
public CSymbol(){
}
~CSymbol(){
}
public string name{
get{
return m_name;
}
set{
m_name = value;
}
}
/// <summary>
/// 类型
/// </summary>
public Type type{
get{
return m_type;
}
set{
m_type = value;
}
}
/// <summary>
/// 值
/// </summary>
public object value{
get{
return m_value;
}
set{
m_value = value;
}
}
public override string ToString(){
return name;
}
}
}//end namespace Flow<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class QEntranceManagment
{
Q_Entrance qe = new Q_Entrance();
public bool AddQ_Entrance(int p_id, int m_id, int q_id)
{
try
{
qe.AddQ_Entrance(p_id,m_id,q_id);
return true;
}
catch
{
return false;
}
}
public List<Quick_Entrance> GetQ_EbyP_Id(int p_id)
{
List<Quick_Entrance> QE = new List<Quick_Entrance>();
QE = qe.GetQ_EbyP_Id(p_id);
return QE;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class TreeListNode
{
public class stateModel
{
public stateModel()
{ selected = false; }
public bool selected { get; set; }
}
public string text{get;set;}
public int id { get; set; }
public bool selectable{get;set;}
public stateModel state { get; set; }
public List<TreeListNode> nodes{get;set;}
public TreeListNode()
{
nodes=new List<TreeListNode>();
state = new stateModel();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Notice_A13dot1
{
public string Notice_ID { get; set; }
public string Notice_Desc { get; set; }
public string Notice_EquipCode { get; set; }
public string Notice_EquipType { get; set; }
public string Notice_State { get; set; }
public string Pq_Name { get; set; }
public string Zz_Name { get; set; }
public string Notice_LongTxt { get; set; }
public string Notice_CR_Person { get; set; }
public string Notice_CR_Date { get; set; }
public string Notice_EquipSpeciality { get; set; }
public int Notice_A13dot1State { get; set; }//被A13dot1处理状态 "0:待处理","1:已处理"
public string Notice_A13dot1_DoDateTime { get; set; }//在A13dot1处理的日期时间 ”yyy-mm-dd HH:SS:mm"
public string Notice_A13dot1_DoUserName { get; set; }//在A13dot1处理的用户名
public string Notice_LoadinDateTime { get; set; }//导入完整性系统的日期时间
public string Notice_Speciality { get; set; }
public string Notice_UpdateDate { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Speciaties:BaseDAO
{
//得到某个专业的孩子节点
public List<Speciaty_Info> getSepciaty_Childs(int Speciaty_Id)
{
using(var db=base.NewDB())
{
return db.Specialties.Where(a => a.Speciaty_Parent.Specialty_Id == Speciaty_Id).ToList();
}
}
public List<Speciaty_Info> getSepciaty_Parent()
{
using (var db = base.NewDB())
{
return db.Specialties.Where(a => a.Speciaty_Parent.Specialty_Name == "root").ToList();
}
}
public List<Speciaty_Info> getSepciaty_Childs(string Speciaty_name)
{
using (var db = base.NewDB())
{
return db.Specialties.Where(a => a.Speciaty_Parent.Specialty_Name == Speciaty_name).ToList();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MVCTest.Models.User
{
public class Role
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int r_id {get;set;}
public string r_name { get; set; }
public virtual ICollection<UserInfo> conn_users {get; set;}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
/// <summary>
/// 片区信息
/// </summary>
public class PqInfo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int PqId { get; set; }
[Required()]
//片区名称
public string PqName { get; set; }
//片区代码
public string PqCode { get; set; }
// public virtual ICollection<CjInfo> Cjs;
}
//车间信息
public class CjInfo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int CjId { get; set; }
[Required()]
//车间名称
public string CjName { get; set; }
//车间代码
public string CjCode { get; set; }
//===所属片区
public virtual PqInfo Pg_belong { get; set; }
}
//装置信息
public class ZzInfo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int ZzId { get; set; }
[Required()]
//装置名称
public string ZzName { get; set; }
//装置代码
public string ZzCode { get; set; }
//所属片区
public int PqId { get; set; }
//===所属车间
public int CjId { get; set; }
}
//设备信息
public class SbInfo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int SbId { get; set; }
//装置编号(数字字符串,唯一标识)
public string SbCode { get; set; }
//设备工艺编号
public string SbGybh { get; set; }
//设备位号
public string SbWh { get; set; }
//计划人员组 =ZzCode
public string PlannerGroup { get; set; }
//设备ABC分类
public string SbABC { get; set; }
//设备B相分类
public string SbPhaseB { get; set; }
//设备类型
public string SbType { get; set; }
//制造日期
public string ManufactureDate { get; set; }
//制造厂家
public string Manufacturer { get; set; }
//===所属装置
public int ZzId { get; set; }
}
//角色信息
public class RoleInfo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int RoleId { get; set; }
[Required()]
//角色名称:装置设备员,检维修单位,机动处,XX处室,系统管理员
public string RoleName { get; set; }
//角色代码:对应上面给一个代码?
public string RoleCode { get; set; }
//角色职位:经理,主任
public string RolePost { get; set; }
}
//用户信息
public class UserInfo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int UserId { get; set; }
[Required()]
//用户名
public string UserName { get; set; }
//用户密码
public string Password { get; set; }
//部门
public string Department { get; set; }
//===所拥有的权限
public int RoleId { get; set; }
}
//用户设备对应
public class User2Sb
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//
public int UserId { get; set; }
public int SbId { get; set; }
}
//用户装置对应
public class User2Zz
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//
public int UserId { get; set; }
public int ZzId { get; set; }
}
//角色权限对应
public class Role2Authority
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//
public int RoleId { get; set; }
public int AuthorityId { get; set; }
}
//用户权限对应
public class User2Authority
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//主键
public int Id { get; set; }
//
public int UserId { get; set; }
public int AuthorityId { get; set; }
}
}
<file_sep>using EquipDAL.Implement;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.FileManagment
{
public class WorkSum_Cat_Manager
{
private WSCatalogTreeNode BuildCatNodes(WorkSumCatalog parent)
{
WSCatalogTreeNode pd = new WSCatalogTreeNode();
pd.text = parent.Catalog_Name;
pd.tags.Add(parent.Catalog_Id.ToString());
pd.selectable = true;
foreach (var cd in parent.Child_Catalogs.ToList())
{
pd.nodes.Add(BuildCatNodes(cd));
}
return pd;
}
//构建文件种类树
public List<WSCatalogTreeNode> BuildCatTree()
{
List<WSCatalogTreeNode> nodes = new List<WSCatalogTreeNode>();
WorkSummaryCatalog fcs = new WorkSummaryCatalog();
DbSet<WorkSumCatalog> ta = fcs.GetCatalogsSet();
var roots = ta.Where(s => s.parent_Catalog == null).ToList();
foreach (var root in roots)
{
nodes.Add(BuildCatNodes(root));
}
return nodes;
}
/// <summary>
/// 增加一个文件分类
/// </summary>
/// <param name="parentID"></param>
/// <param name="newCatalog"></param>
/// <returns></returns>
public bool AddNewCatalog(int parentID, string newCatalog)
{
WorkSummaryCatalog fcs = new WorkSummaryCatalog();
return fcs.AddNewCatalog(parentID, newCatalog);
}
public bool DeleteCatalog(int ID)
{
return (new WorkSummaryCatalog()).DeleteCatalog(ID);
}
public bool ModifyFileCatalog(int ID, string name)
{
return (new WorkSummaryCatalog()).ModifyCatalog(ID, name);
}
public List<WSFileItem> GetFilesInCatalog(int ID)
{
List<WorkSummary> files = (new WorkSummaryCatalog()).GetFiles(ID);
List<WSFileItem> fs = new List<WSFileItem>();
foreach (var f in files)
{
Person_Infos submiter = new Person_Infos();
WSFileItem fi = new WSFileItem();
fi.id = Convert.ToString(f.File_Id);
//fi.uploader = f.File_Submiter.Person_Name.ToString();
fi.uploader = submiter.GetPerson_info(f.Mission_Id).Person_Name;
fi.fileName = f.File_OldName;
fi.updateTime = f.File_UploadTime.ToString();
fi.ext = f.File_ExtType;
fi.path = f.File_SavePath;
fi.fileNamePresent = f.File_NewName;
fs.Add(fi);
}
return fs;
}
public bool AddNewFile(int pID, WSFileItem fi, int uID)
{
WorkSummary nf = new WorkSummary();
nf.File_NewName = fi.fileNamePresent;
nf.File_OldName = fi.fileName;
nf.File_UploadTime = Convert.ToDateTime(fi.updateTime);
nf.File_Submiter = (new Person_Infos()).GetPerson_info(uID);
nf.File_SavePath = fi.path;
nf.File_ExtType = fi.ext;
return (new WorkSummaryCatalog()).AddFiletoCatalog(pID, nf);
}
public bool DeleteFile(int fID)
{
return (new WorkSum()).delete(fID);
}
}
}
<file_sep>using EquipBLL.AdminManagment;
using EquipBLL.AdminManagment.ZyConfig;
using EquipBLL.AdminManagment.MenuConfig;
using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp.Controllers
{
public class EquipQueryController : Controller
{
//
// GET: /EquipQuery/
public class QueryModal
{
public List<UI_WF_Define> wf;
public List<Equip_Archi> UserHasEquips;
public List<Speciaty_Info> sps;
}
public ActionResult AddEquip()
{
QueryModal qm = new QueryModal();
SpeciatyManagment spm = new SpeciatyManagment();
qm.sps = spm.getsps();
return View(qm);
}
//返回设备专业子类
public JsonResult EquipSp_Info(int sp_id)
{
SpeciatyManagment sm = new SpeciatyManagment();
List<Speciaty_Info> sp = sm.getsps_child(sp_id);
List<object> sp_obj = new List<object>();
foreach (var item in sp)
{
object o = new
{
sp_Id = item.Specialty_Id,
sp_Name = item.Specialty_Name
};
sp_obj.Add(o);
}
return Json(sp_obj.ToArray());
}
public ActionResult EquipQuery()
{
QueryModal qm = new QueryModal();
qm.wf = CWFEngine.ListAllWFDefine();
PersonManagment pm = new PersonManagment();
qm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(qm);
}
public JsonResult List_EquipArchi()
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> EquipArchi_obj = DM.BuildEquipArchiList();
return Json(EquipArchi_obj.ToArray());
}
public JsonResult List_Speciaties()
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> Speciaty_obj = DM.BuildSpeciatyList();
return Json(Speciaty_obj.ToArray());
}
//功能:根据查询信息查询设备
//参数:设备工艺编号,设备位置,设备专业分类
//返回:数据拼接string
public string Query_Equip(string equip_gycode, int equiparchi_id, string equip_specialty)//string json1)//,)
{
List<object> r = new List<object>();
List<Equip_Info> e = new List<Equip_Info>();
if (equip_gycode != "" || equiparchi_id != 0 || equip_specialty != "")
{
EquipManagment EM = new EquipManagment();
e = EM.getAllEquips_byinfo(equip_gycode, equiparchi_id, equip_specialty);
for (var i = 0; i < e.Count; i++)
{
//数据库中可能为空这些数据做些处理在赋值给o
string ecode;
string manuf;
if (e[i].Equip_Code == null)
ecode = "无";
else
{
ecode = e[i].Equip_Code;
}
if (e[i].Equip_Manufacturer == null)
manuf = "无";
else
{
manuf = e[i].Equip_Manufacturer;
}
//返回前台显示的数据
object o = new
{
index = i+1,
equip_gycode = e[i].Equip_GyCode.ToString(),
equip_code = ecode,
equip_specialty = e[i].Equip_Specialty.ToString(),
equip_phaseB = e[i].Equip_PhaseB.ToString(),
equip_manufacturer = manuf
};
r.Add(o);
}
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
//获得点击修改的设备的具体信息
public JsonResult List_Equipinfo(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
//取得设备编号
string e_code = item["equip_code"].ToString();
EquipManagment EM = new EquipManagment();
int EA_id = EM.getEA_id_byCode(e_code);
EquipArchiManagment EAM=new EquipArchiManagment();
Equip_Info mod_equip = new Equip_Info();
mod_equip = EM.getEquip_Info(e_code);
object mod = new
{
e_abc=mod_equip.Equip_ABCmark,
e_code=mod_equip.Equip_Code,
e_gycode=mod_equip.Equip_GyCode,
e_man=mod_equip.Equip_Manufacturer,
e_phaseB=mod_equip.Equip_PhaseB,
e_sp=mod_equip.Equip_Specialty,
e_type=mod_equip.Equip_Type,
e_Achi=EAM.getEa_namebyId(EA_id)
};
return Json(mod);
}
//添加新设备
public string submitNewEquip(string json1)
{
try
{
EquipManagment EM = new EquipManagment();
Equip_Info new_equip = new Equip_Info();
int Zz_Id;
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
Zz_Id = Convert.ToInt16(item["Equip_Archi_Id"]);
new_equip.Equip_ABCmark = item["EquipABCMark"].ToString();
new_equip.Equip_GyCode = item["EquipName"].ToString();
new_equip.Equip_Code = item["EquipCode"].ToString();
new_equip.Equip_Type = item["EquipType"].ToString();
new_equip.Equip_Specialty = item["EquipSpecialty"].ToString();
new_equip.Equip_PhaseB = item["EquipPhaseB"].ToString();
new_equip.Equip_Manufacturer = item["EquipManufacturer"].ToString();
EM.addEquip(new_equip,Zz_Id);
return "保存成功!";
}
catch { return ""; };
}
//删除设备
public string delete_equip(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
EquipManagment EM = new EquipManagment();
string equip_id =item["equip_id"].ToString();
int E_id = EM.getE_id_byGybh(equip_id);
bool del= EM.deleteEquip(E_id);
if(del)
return "删除成功!";
else
return "删除失败!";
}
catch { return "error"; }
}
//修改设备
public string modifyEquip(string json1)
{
try
{
EquipManagment EM = new EquipManagment();
Equip_Info new_equip = new Equip_Info();
string Ea_name;
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
Ea_name = item["Equip_Archi"].ToString();
EquipArchiManagment EAM = new EquipArchiManagment();
int Zz_Id = EAM.getEa_idbyname(Ea_name);
new_equip.Equip_ABCmark = item["EquipABCMark"].ToString();
new_equip.Equip_GyCode = item["EquipName"].ToString();
new_equip.Equip_Code = item["EquipCode"].ToString();
new_equip.Equip_Type = item["EquipType"].ToString();
new_equip.Equip_Specialty = item["EquipSpecialty"].ToString();
new_equip.Equip_PhaseB = item["EquipPhaseB"].ToString();
new_equip.Equip_Manufacturer = item["EquipManufacturer"].ToString();
if(EM.modifyEquip(new_equip,Zz_Id))
return "保存成功!";
else
return "保存失败!";
}
catch { return ""; };
}
}
}<file_sep>using EquipBLL.AdminManagment;
using EquipBLL.AdminManagment.MenuConfig;
using EquipModel.Context;
using EquipModel.Entities;
using FlowEngine;
using FlowEngine.Modals;
using FlowEngine.TimerManage;
using FlowEngine.UserInterface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Models.DateTables;
namespace WebApp.Controllers
{
public class A6dot2dot2Controller : CommonController
{
//
// GET: /A6dot2dot2/
public class A6dot2dot2InfoModal
{
public string cj_name;
public string wfe_id;
public string tempjob_name;
public List<Equip_Archi> All_Zz;
}
public class LsTaskInfo
{
public string workflow_ser;
public string workflow_name;
public string cj_name;
public string Zt_unit;
public int status;
}
public ActionResult Index()
{
return View( getIndexListRecords("A6dot2dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name ) );
}
public ActionResult Submit(string wfe_id)
{
EquipManagment EM = new EquipManagment();
UI_MISSION mi = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
Dictionary<string ,object> mi_params=mi.Miss_Params;
string cj_name=mi.Miss_Params["Cj_Name"].ToString();
string tempjob_name=mi.Miss_Params["Job_Name"].ToString();
A6dot2Managment AM = new A6dot2Managment();
int i = 1;
List<A6dot2LsTaskTab> rList = AM.getLsTask(wfe_id);
//string cj_name = "2";
//string tempjob_name = "test";
ViewBag.wfe_id = wfe_id;
A6dot2dot2InfoModal infoModal = new A6dot2dot2InfoModal();
infoModal.tempjob_name = tempjob_name;
infoModal.cj_name = cj_name;
infoModal.wfe_id = wfe_id;
infoModal.All_Zz=EM.getZzs_ofCj(Convert.ToInt32(cj_name));
return View(infoModal);
}
public ActionResult LsTaskHistoryDetail(string wfe_id)
{
EquipArchiManagment Em = new EquipArchiManagment();
UI_MISSION mi=new UI_MISSION();
List<UI_MISSION> t=CWFEngine.GetHistoryMissions(int.Parse(wfe_id));
mi=(UI_MISSION)t.ElementAt(1);
Dictionary<string ,object> mi_params=mi.Miss_Params;
string cj_name=mi.Miss_Params["Cj_Name"].ToString();
string tempjob_name=mi.Miss_Params["Job_Name"].ToString();
ViewBag.wfe_id = wfe_id;
A6dot2dot2InfoModal infoModal = new A6dot2dot2InfoModal();
infoModal.tempjob_name = tempjob_name;
infoModal.cj_name = cj_name;
infoModal.wfe_id = wfe_id;
EquipManagment EM = new EquipManagment();
infoModal.All_Zz = EM.getZzs_ofCj(Convert.ToInt32(cj_name));
return View(infoModal);
}
public string getA6dot2dot2Tab(string wfe_id)
{
List<object> or = new List<object>();
A6dot2Managment AM=new A6dot2Managment();
int i=1;
List<A6dot2LsTaskTab> rList= AM.getLsTask(wfe_id);
foreach(var r in rList)
{
object o = new
{ ID=r.Id,
Zz_Name = r.Zz_Name,
Equip_Gybh = r.Equip_Gybh,
Equip_Code = r.Equip_Code,
Last_HY = r.lastOilTime,
HY_ZQ = r.oilInterval,
Next_HY = r.NextOilTime,
Problem_Cur = r.cur_problem,
ZG_status=r.cur_status,
Wfe_id=r.wfd_id
};
i=i+1;
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
public JsonResult List_Equips(string Zz_Id)
{
EquipManagment EM = new EquipManagment();
List<Equip_Info> e_obj = EM.getEquips_OfZz(Convert.ToInt32(Zz_Id));
List<object> r = new List<object>();
foreach (Equip_Info item in e_obj)
{
object o = new
{
Equip_Id = item.Equip_Id,
Equip_GyCode = item.Equip_GyCode,
};
r.Add(o);
}
return Json(r.ToArray());
}
/// <summary>
/// 解析datatables 请求的Form数据
/// </summary>
/// <param name="Form"></param>
/// <returns></returns>
private List<KeyValuePair<string, string>> ParsePostForm(NameValueCollection Form)
{
var list = new List<KeyValuePair<string, string>>();
if (Form != null)
{
foreach (var f in Form.AllKeys)
{
list.Add(new KeyValuePair<string, string>(f, Form[f]));
}
}
return list;
}
/// <summary>
/// 处理datatables请求
/// </summary>
/// <param name="data"></param>
private DtResponse ProcessRequest(List<KeyValuePair<string, string>> data,string wfe_id)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
if (http.ContainsKey("action"))
{
string action = http["action"] as string;
if (action == "edit")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
List<string> pros = new List<string>();
List<object> vals = new List<object>();
Dictionary<string, object> m_kv = new Dictionary<string, object>();
foreach (var dd in d.Value as Dictionary<string, object>)
{
pros.Add(dd.Key);
vals.Add(dd.Value);
}
A6dot2Managment AM = new A6dot2Managment();
A6dot2LsTaskTab m = AM.UpdateA6dot2LsTask(id, pros, vals);
m_kv["ID"] = m.Id;
m_kv["Zz_Name"] = m.Zz_Name;
m_kv["Equip_Gybh"] = m.Equip_Gybh;
m_kv["Equip_Code"] = m.Equip_Code;
m_kv["Last_HY"] = m.lastOilTime;
m_kv["HY_ZQ"] = m.oilInterval;
m_kv["Next_HY"] = m.NextOilTime;
m_kv["Problem_Cur"] = m.cur_problem;
m_kv["ZG_status"] = m.cur_status;
m_kv["Wfe_id"] = m.wfd_id;
dt.data.Add(m_kv);
}
}
else if (action == "create") //新建工作流
{
A6dot2Managment AM = new A6dot2Managment();
A6dot2LsTaskTab rt = new A6dot2LsTaskTab();
rt.wfd_id = wfe_id;
A6dot2LsTaskTab m = AM.AddA6dot2LsTask(rt);
Dictionary<string, object> m_kv = new Dictionary<string, object>();
m_kv["ID"] = m.Id;
m_kv["Zz_Name"] = m.Zz_Name;
m_kv["Equip_Gybh"] = m.Equip_Gybh;
m_kv["Equip_Code"] = m.Equip_Code;
m_kv["Last_HY"] = m.lastOilTime;
m_kv["HY_ZQ"] = m.oilInterval;
m_kv["Next_HY"] = m.NextOilTime;
m_kv["Problem_Cur"] = m.cur_problem;
m_kv["ZG_status"] = m.cur_status;
m_kv["Wfe_id"] = m.wfd_id;
dt.data.Add(m_kv);
}
else if (action == "remove")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
A6dot2Managment AM = new A6dot2Managment();
AM.RemoveA6dot2LsTask(id);
}
}
}
return dt;
}
//提交定时任务修改
[HttpPost]
public JsonResult PostChanges(string wfe_id)
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = ProcessRequest(list,wfe_id);
return Json(dtRes);
}
public string LsTaskSubmit(string wfe_id)
{
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Submit_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(wfe_id), signal, record);
return ("/TempJob/Index");
}
public string LsTaskList(string wfe_id)
{ //string wfe_id="[1,2]";
EquipArchiManagment Em = new EquipArchiManagment();
List<Object> r = new List<Object>();
JArray item = (JArray)JsonConvert.DeserializeObject(wfe_id);
int ii = 1;
foreach (var i in item)
{
string workflow_entity;
workflow_entity = i.ToString();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Cj_Name"] = null;
paras["Job_Name"] = null;
paras["Submit_Done"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(Convert.ToInt32(workflow_entity), paras);
object o = new
{ ID=ii,
workflow_ser = wfei.serial,
workflow_name = wfei.name,
cj_name = Em.getEa_namebyId(Convert.ToInt16(paras["Cj_Name"])),
Zt_unit = "",
status = (int)wfei.Status,
workflow_id = workflow_entity
};
r.Add(o);
ii = ii + 1;
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public ActionResult LsTaskManager(string job_name,string run_result)
{
ViewBag.job_name= job_name;
ViewBag.wfe_id = run_result;
return View();
}
}
}<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Jxpg : BaseDAO
{
public List<A15dot1Tab> GetJxRecord(string roles,string dep, string name)
{ List<A15dot1Tab> e=new List<A15dot1Tab>();
using (var db = base.NewDB())
{
if (dep.Contains("机动处"))
{
if (roles.Contains("可靠性工程师") || roles.Contains("检维修人员"))
{
return db.A15dot1Tab.Where(a => (a.state == 1 || a.state == 2 ||a.state == 0) && a.submitUser == name).ToList();
}
else
return db.A15dot1Tab.Where(a => a.state == 1 || a.state == 2).ToList();
}
else if (roles.Contains("可靠性工程师") || roles.Contains("检维修人员"))
{
return db.A15dot1Tab.Where(a => a.state == 0&&a.submitUser==name).ToList();
}
else
return e;
}
}
public List<A15dot1Tab> GetJxRecord_detail(int id)
{
using (var db = base.NewDB())
{
return db.A15dot1Tab.Where(a => a.Id == id).ToList();
}
}
public List<A15dot1Tab> GetHisJxRecord(string roles, string dep, string name)
{
List<A15dot1Tab> e = new List<A15dot1Tab>();
using (var db = base.NewDB())
{
if (dep.Contains("机动处"))
{
return db.A15dot1Tab.Where(a => a.state == 3).ToList();
}
else if (roles.Contains("可靠性工程师") || roles.Contains("检维修人员"))
{
return db.A15dot1Tab.Where(a => a.state == 3 && a.submitUser == name).ToList();
}
else
return e;
}
}
public List<A15dot1Tab> GetHisJxRecord_detail(int id)
{
using (var db = base.NewDB())
{
return db.A15dot1Tab.Where(a => a.Id == id).ToList();
}
}
public bool AddJxRecord(A15dot1Tab nVal)
{
using (var db = base.NewDB())
{
try
{
db.A15dot1Tab.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool ModifyJxRecord(A15dot1Tab nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA15 = db.A15dot1Tab.Where(a => a.Id == nVal.Id).First();
modifyA15.timesNonPlanStop = nVal.timesNonPlanStop;
modifyA15.scoreDeductFaultIntensity = nVal.scoreDeductFaultIntensity;
modifyA15.rateBigUnitFault = nVal.rateBigUnitFault;
modifyA15.rateFaultMaintenance = nVal.rateFaultMaintenance;
modifyA15.MTBF = nVal.MTBF;
modifyA15.rateEquipUse = nVal.rateEquipUse;
modifyA15.rateUrgentRepairWorkHour = nVal.rateUrgentRepairWorkHour;
modifyA15.hourWorkOrderFinish = nVal.hourWorkOrderFinish;
modifyA15.avgLifeSpanSeal = nVal.avgLifeSpanSeal;
modifyA15.avgLifeSpanAxle = nVal.avgLifeSpanAxle;
modifyA15.percentEquipAvailability = nVal.percentEquipAvailability;
modifyA15.percentPassOnetimeRepair = nVal.percentPassOnetimeRepair;
modifyA15.avgEfficiencyPump = nVal.avgEfficiencyPump;
modifyA15.avgEfficiencyUnit = nVal.avgEfficiencyUnit;
modifyA15.hiddenDangerInvestigation = nVal.hiddenDangerInvestigation;
modifyA15.rateLoad = nVal.rateLoad;
modifyA15.gyChange = nVal.gyChange;
modifyA15.equipChange = nVal.equipChange;
modifyA15.otherDescription = nVal.otherDescription;
modifyA15.evaluateEquipRunStaeDesc = nVal.evaluateEquipRunStaeDesc;
modifyA15.evaluateEquipRunStaeImgPath = nVal.evaluateEquipRunStaeImgPath;
modifyA15.reliabilityConclusion = nVal.reliabilityConclusion;
modifyA15.jdcAdviseImproveMeasures = nVal.jdcAdviseImproveMeasures;
modifyA15.submitDepartment = nVal.submitDepartment;
modifyA15.submitUser = nVal.submitUser;
modifyA15.submitTime = nVal.submitTime;
modifyA15.reportType = nVal.reportType;
modifyA15.submitUser = nVal.submitUser;
modifyA15.submitTime = nVal.submitTime;
modifyA15.state = nVal.state;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool JdcModifyJxRecord(A15dot1Tab nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA15 = db.A15dot1Tab.Where(a => a.Id == nVal.Id).First();
modifyA15.jdcAdviseImproveMeasures = nVal.jdcAdviseImproveMeasures;
modifyA15.jdcOperateTime = nVal.jdcOperateTime;
modifyA15.jdcOperator = nVal.jdcOperator;
modifyA15.state = nVal.state;
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
//查询表中一列的数据,列名不定
public List<object> qstdata(string grahpic_name, string pianqu)
{
using (var db = base.NewDB())
{
var i = db.Database.SqlQuery<A15dot1Tab>("select * from A15dot1Tab where submitDepartment='" + pianqu + "'").ToList();
List<object> a = new List<object>();
foreach (var item in i)
{
var t = item.GetType().GetProperty(grahpic_name);
var result = t.GetValue(item, null);
a.Add(result);
}
object cut = new object();
cut = "$$";
a.Add(cut);
foreach (var ex in i)
{
var t = ex.GetType().GetProperty("jdcOperateTime");
var result = t.GetValue(ex, null);
a.Add(result);
}
return a;
}
}
public List<A15dot1Tab> GetJxItemforA2Tab(DateTime time,DateTime time2)
{
using (var db = base.NewDB())
{
return db.A15dot1Tab.Where(a => a.state == 3 && a.jdcOperateTime < time &&a.jdcOperateTime>time2).ToList();
}
}
public List<A15dot1Tab> newGetJxItemforA2Tab(DateTime time, DateTime time2, string pianqu)
{
using (var db = base.NewDB())
{
return db.A15dot1Tab.Where(a => a.state == 3 && a.jdcOperateTime < time && a.jdcOperateTime > time2 && a.submitDepartment == pianqu).ToList();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class Equip_Info
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Equip_Id { get; set; }
/// <summary>
/// 工艺编号(代表名称)
/// </summary>
public string Equip_GyCode { get; set; }
/// <summary>
/// 设备编号
/// </summary>
public string Equip_Code { get; set; }
/// <summary>
/// 设备专业分类(动M 静电仪)
/// </summary>
public string Equip_Specialty { get; set; }
/// <summary>
/// 设备ABC标志
/// </summary>
public string Equip_ABCmark { get; set; }
/// <summary>
/// 设备型号
/// </summary>
public string Equip_Type { get; set; }
/// <summary>
/// 设备制造商
/// </summary>
public string Equip_Manufacturer { get; set; }
/// <summary>
/// 设备生产日期
/// </summary>
public string Equip_ManufactureDate { get; set; }
/// <summary>
/// 设备B相分类:动设备分为 - 特护机组,非特护机组,机泵,特种设备,专用设备
/// </summary>
public string Equip_PhaseB { get; set; }
/// <summary>
/// 设备主要性能参数(Json ??)
/// </summary>
public string Equip_PerformanceParasJson { get; set; }
public string thRecordTable { get; set; }
/// <summary>
/// 所属装置
/// </summary>
public virtual Equip_Archi Equip_Location { get; set; }
/// <summary>
/// 设备管理人员
/// </summary>
public virtual ICollection<Person_Info> Equip_Manager { get; set; }
public virtual ICollection<File_Info> Equip_Files { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.UserInterface
{
public class UI_MissParam
{
/// <summary>
/// 变量的值
/// </summary>
public string Param_Value { get; set; }
/// <summary>
/// 变量的类型
/// </summary>
public int Param_isFile { get; set; }
/// <summary>
/// 变量的描述
/// </summary>
public string Param_Desc { get; set; }
public string Param_SavedFilePath { get; set; }
public string Param_UploadFilePath { get; set; }
}
}
<file_sep>///////////////////////////////////////////////////////////
// WorkFlows.cs
// Implementation of the Class WorkFlows
// Generated by Enterprise Architect
// Created on: 13-11月-2015 14:52:16
// Original author: Chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.IO;
using FlowEngine.Modals;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace FlowEngine.DAL {
public class WorkFlows : BaseDAO
{
public WorkFlows()
{
}
~WorkFlows()
{
}
/// <summary>
/// 获得数据库中所以的工作流定义
/// </summary>
public List<WorkFlow_Define> GetAllWorkFlows()
{
using (var db = base.NewDB())
{
return db.workflow_define.ToList();
}
}
/// <summary>
/// 获得wf_name的工作流的所有实例
/// </summary>
/// <param name="wf_id"></param>
public List<WorkFlow_Entity> GetWorkFlowEntities(int wf_id)
{
using (var db = base.NewDB())
{
return db.workflow_entities.Where(a => a.WE_Wref.W_ID == wf_id).ToList();
}
}
public List<WorkFlow_Entity> GetWorkFlowEntitiesbySer(string serial)
{
using (var db = base.NewDB())
{
return db.workflow_entities.Where(s => s.WE_Ser == serial).ToList();
}
}
//fhp添加的方法开始-----
public WorkFlow_Entity GetMainWorkFlowEntity(string wfe_ser)
{
using (var db = base.NewDB())
{
return db.workflow_entities.Where(a => a.WE_Ser == wfe_ser).OrderBy(a => a.WE_Id).First();
}
}
//fhp添加方法结束---
/// <summary>
/// 获得处于Active状态的工作流实体
/// </summary>
/// <param name="wf_id"></param>
public List<WorkFlow_Entity> GetActiveWorkFlowEntities(string Entity_name)
{
//&& a.WE_Wref.W_Name == "A13dot1"
using (var db = base.NewDB())
{
if (Entity_name == "ALL")
return db.workflow_entities.Where(a => a.WE_Status == WE_STATUS.ACTIVE).ToList();
else
return db.workflow_entities.Where(a => a.WE_Status == WE_STATUS.ACTIVE && a.WE_Wref.W_Name == Entity_name).ToList();
}
}
/// <summary>
/// 获得工作流实体的名称
/// </summary>
/// <param name="wf_id"></param>
public string GetWorkFlowEntityName(int wfe_id)
{
using (var db = base.NewDB())
{
WorkFlow_Entity we = db.workflow_entities.Where(a => a.WE_Id == wfe_id).First();
if (we == null)
return "";
return we.WE_Wref.W_Name;
}
}
/// <summary>
/// 获得工作流实体的描述信息
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public string GetWorkFlowEntityDesc(int wfe_id)
{
using (var db = base.NewDB())
{
WorkFlow_Entity we = db.workflow_entities.Where(a => a.WE_Id == wfe_id).First();
if (we == null)
return "";
return we.WE_Wref.W_Attribution;
}
}
/// <summary>
/// 依据工作流实体id查找工作流实体
/// </summary>
/// <param name="we_id"></param>
public WorkFlow_Entity GetWorkFlowEntity(int we_id)
{
using (var db = base.NewDB())
{
return db.workflow_entities.Where(a => a.WE_Id == we_id).First();
}
}
public WorkFlow_Define GetWorkFlowDefine(string wf_name)
{
using (var db = base.NewDB())
{
WorkFlow_Define wd = db.workflow_define.Where(s => s.W_Name == wf_name).First();
return wd;
}
}
//通过工作流定义ID获得工作流的定义
public WorkFlow_Define GetWorkFlowDefineByID(int defineID)
{
try
{
using (var db = base.NewDB())
{
return db.workflow_define.Where(a => a.W_ID == defineID).First();
}
}
catch(Exception e)
{
return null;
}
}
//获得工作流实体 wfe_id 的define
public WorkFlow_Define GetWorkFlowDefine(int wfe_id)
{
try
{
using (var db = base.NewDB())
{
WorkFlow_Define wd = db.workflow_entities.Where(s => s.WE_Id == wfe_id).First().WE_Wref;
return wd;
}
}
catch
{
return null;
}
}
/// <summary>
/// 更新工作流实体的属性
/// </summary>
/// <param name="wfe_id">工作流实体ID</param>
/// <param name="property_name">属性名</param>
/// <param name="value">值</param>
/// <returns></returns>
public bool UpdateWorkFlowEntity(int wfe_id, string property_name, object value)
{
try
{
using (var db = base.NewDB())
{
var wfe = db.workflow_entities.Where(a => a.WE_Id == wfe_id).First();
switch(property_name)
{
case "WE_Ser":
if (value.GetType().Name != "string")
throw new Exception("Error type");
wfe.WE_Ser = (string)value;
break;
case "WE_Status":
if (value.GetType().Name != "WE_STATUS")
throw new Exception("Error type");
wfe.WE_Status = (WE_STATUS)value;
break;
case "WE_Binary":
if (value.GetType().Name != "byte[]")
throw new Exception("Error type");
wfe.WE_Binary = (byte[])value;
break;
default:
throw new Exception("Unkown property or Error property or unchangeable property");
}
if (db.SaveChanges() >= 1)
return true;
else
return false;
}
}
catch
{
return false;
}
}
public bool SaveWorkFlowEntity(WorkFlow_Entity we)
{
using (var db = base.NewDB())
{
var wfe = db.workflow_entities.Where(a => a.WE_Id == we.WE_Id).First();
if (we.WE_Status != WE_STATUS.INVALID) //不更新状态
wfe.WE_Status = we.WE_Status;
wfe.WE_Binary = we.WE_Binary;
wfe.Last_Trans_Time = we.Last_Trans_Time;
if (db.SaveChanges() >= 1)
return true;
}
return false;
}
/// <summary>
/// 针对同时添加实体会导致串号异常,因此定义insert lock 对象
/// </summary>
private static object insert_lock = new object();
public bool AddWorkEntity(string wfName, WorkFlow_Entity we)
{
int num = 0;
lock (insert_lock)
{ //locked
using (var db = base.NewDB())
{
WorkFlow_Define wd = db.workflow_define.Where(s => s.W_Name == wfName).First();
if (we.WE_Ser == "") //2012/2/12--保证子工作流串号与父工作流相同
{
//对WorkFlow_Entity编号的处理
string perFix = DateTime.Now.ToString("yyyyMM");
IQueryable<WorkFlow_Entity> we_Ser = db.workflow_entities.Where(s => s.WE_Ser.StartsWith(perFix)).OrderBy(s => s.WE_Ser);
if (we_Ser.ToList().Count == 0)
we.WE_Ser = perFix + "00001";
else
{
we.WE_Ser = (Convert.ToInt64(we_Ser.ToList().Last().WE_Ser) + 1).ToString();
}
}
if (wd == null)
return false;
wd.W_Wentities.Add(we);
//System.Threading.Thread.Sleep(2000);
num = db.SaveChanges();
//return (db.SaveChanges() != 0);
}
}//unlocked
return (num != 0);
}
/// <summary>
/// 获得任务实体的第一任务
/// </summary>
/// <param name="wfEntityId"></param>
/// <returns></returns>
public Mission GetWFEntityFirstMission(int wfEntityId)
{
using (var db = base.NewDB())
{
WorkFlow_Entity wfe = db.workflow_entities.Where(s => s.WE_Id == wfEntityId).First();
if (wfe == null)
return null;
return wfe.Process_Info.Where(s => s.pre_Mission == null).First();
}
}
/// <summary>
/// 删除工作流实体
/// </summary>
/// <param name="wfEntityId"></param>
public void DeleteWFEntity(int wfEntityId)
{
using (var db = base.NewDB())
{
WorkFlow_Entity wfe = db.workflow_entities.Where(s => s.WE_Id == wfEntityId).First();
if (wfe != null)
{
wfe.Process_Info.Clear();
db.workflow_entities.Remove(wfe);
}
db.SaveChanges();
}
}
/// <summary>
/// 置工作流实体为删除状态——注意对比与DeleteWFEntity的区别
/// </summary>
/// <param name="wfEntityId"></param>
public void SetWFEntityDeleted(int wfEntityId)
{
using (var db = base.NewDB())
{
WorkFlow_Entity wfe = db.workflow_entities.Where(s => s.WE_Id == wfEntityId).First();
if (wfe != null)
{
wfe.WE_Status = WE_STATUS.DELETED;
}
db.SaveChanges();
}
}
/// <summary>
/// 获得任务实体的最后一个任务
/// </summary>
/// <param name="wfEntityId"></param>
/// <returns></returns>
public Mission GetWFEntityLastMission(int wfEntityId)
{
using (var db = base.NewDB())
{
WorkFlow_Entity wfe = db.workflow_entities.Where(s => s.WE_Id == wfEntityId).First();
if (wfe == null)
return null;
return wfe.Process_Info.Where(s => s.next_Mission.Count == 0).First();
}
}
/// <summary>
/// 获得任务实体的所有已执行完的任务,以任务的顺序排列
/// </summary>
/// <param name="wfEntityId"></param>
/// <returns></returns>
public List<Mission> GetWFEntityMissions(int wfEntityId)
{
using (var db = base.NewDB())
{
List<Mission> missions = new List<Mission>();
WorkFlow_Entity wfe = db.workflow_entities.Where(s => s.WE_Id == wfEntityId).First();
if (wfe != null)
{
Mission miss = wfe.Process_Info.Where(s => s.pre_Mission == null).First();
if (miss != null)
{
missions.Add(miss);
while (miss.next_Mission.Count != 0)
{
missions.Add(miss.next_Mission.First());
miss = (Mission)miss.next_Mission.First();
}
}
}
return missions;
}
}
/// <summary>
/// 添加一条任务记录到数据库
/// </summary>
/// <param name="wfEntityId">工作流实体的ID</param>
/// <param name="miss">新任务</param>
/// <returns>操作成功返回true,否则返回false</returns>
public bool AddMissionRecord(int wfEntityId, Mission miss)
{
using (var db = base.NewDB())
{
//查找wfEntityId的工作流实体
WorkFlow_Entity wfe = db.workflow_entities.Where(s => s.WE_Id == wfEntityId).First();
if (wfe == null)
return false;
if (wfe.Process_Info.Count == 0)
{
miss.next_Mission = null;
miss.pre_Mission = null;
wfe.Process_Info.Add(miss);
}
else
{
Mission last = wfe.Process_Info.Where(s => s.next_Mission.Count == 0).First();
miss.pre_Mission = last;
miss.Miss_WFentity = wfe;
last.next_Mission.Add(miss);
}
return (db.SaveChanges() != 0);
}
}
/// <summary>
/// 为一个任务添加参数
/// </summary>
/// <param name="missId">任务的ID</param>
/// <param name="pars">参数列表</param>
/// <returns>操作成功返回true, 否则返回false</returns>
public bool LinkParamsToMiss(int missId, List<Mission_Param> pars)
{
using (var db = base.NewDB())
{
Mission miss = db.mission.Where(s => s.Miss_Id == missId).First();
if (miss == null)
return false;
foreach (Mission_Param mpar in pars)
{
miss.Params_Info.Add(mpar);
}
return (db.SaveChanges() != 0);
}
}
/// <summary>
/// 为一个任务添加Record信息
/// </summary>
/// <param name="missId">任务的ID</param>
/// <param name="pRecords">Record信息</param>
/// <returns>操作成功返回true, 否则返回false</returns>
public bool LinkRecordInfoToMiss(int missId, List<Process_Record> pRecords)
{
using (var db = base.NewDB())
{
Mission miss = db.mission.Where(s => s.Miss_Id == missId).First();
if (miss == null)
return false;
foreach (Process_Record pr in pRecords)
{
miss.Record_Info.Add(pr);
}
return (db.SaveChanges() != 0);
}
}
/// <summary>
/// 获取某一任务的Record信息
/// </summary>
/// <param name="missId">任务的ID</param>
/// <returns>Mission的Record列表</returns>
public List<Process_Record> GetMissionRecordInfo(int missId)
{
using (var db = base.NewDB())
{
Mission miss = db.mission.Where(s => s.Miss_Id == missId).First();
if (miss == null)
return null;
return miss.Record_Info.ToList();
}
}
/// <summary>
/// 获取某一任务的参数
/// </summary>
/// <param name="missId"></param>
/// <returns>Mission的参数列表</returns>
public List<Mission_Param> GetMissParams(int missId)
{
using (var db = base.NewDB())
{
Mission miss = db.mission.Where(s => s.Miss_Id == missId).First();
if (miss == null)
return null;
return miss.Params_Info.ToList();
}
}
/// <summary>
/// 获取某一个任务的前一个任务
/// </summary>
/// <param name="missId"></param>
/// <returns></returns>
public Mission GetPreMission(int missId)
{
using (var db = base.NewDB())
{
Mission miss = db.mission.Where(s => s.Miss_Id == missId).First();
if (miss == null)
return null;
return miss.pre_Mission;
}
}
/// <summary>
/// 获取某一个任务的前一个任务
/// </summary>
/// <param name="missId"></param>
/// <returns></returns>
public Mission GetNextMission(int missId)
{
using (var db = base.NewDB())
{
Mission miss = db.mission.Where(s => s.Miss_Id == missId).First();
if (miss == null)
return null;
return miss.next_Mission.First();
}
}
public List<WorkFlow_Entity> GetWFEntityByConditon(Func<WorkFlow_Entity, bool> condition)
{
using (var db = base.NewDB())
{
try
{
db.workflow_entities.Where(s => s.Process_Info.Count(t => t.Miss_Id == 1) == 0);
return db.workflow_entities.Where(condition).ToList();
}
catch (Exception e)
{
return null;
}
}
}
/// <summary>
/// 获得某个工作流完成需要的步骤
/// </summary>
/// <param name="wf_name"></param>
/// <returns></returns>
public int GetWFAvgSteps(string wf_name)
{
using (var db = base.NewDB())
{
var workflow = db.workflow_define.Where(s => s.W_Name == wf_name).First();
var wfEntities = workflow.W_Wentities.Where(s => s.WE_Status == WE_STATUS.DONE);
if (wfEntities.ToList().Count == 0)
return 0;
double steps = wfEntities.Average(s => s.Process_Info.Count);
return (int)steps;
}
}
/// <summary>
/// 获得某一工作流实体已执行了多少步
/// </summary>
/// <param name="wfe_id"></param>
/// <returns></returns>
public int GetWFEntityFinishSteps(int wfe_id)
{
using (var db = base.NewDB())
{
var wfe = db.workflow_entities.Where(s => s.WE_Id == wfe_id).First();
if (wfe != null)
return wfe.Process_Info.Count;
else
return 0;
}
}
/// <summary>
/// 对工作流信息进行查询(low level)
/// </summary>
/// <param name="query_list">
/// 需要查询的属性列——空字符串表示查询所有属性列, 慎用!!!!!
/// 由于变量名的量比较大,强烈建议该参数不使用空串
/// M 代表 Missions
/// R 代表 Record
/// P 代表 Params
/// E 代表 WorkFlow_Entity
/// 如 "M.Event_Name, M.Miss_Name, R.time, R.username, P.Proble_DataSrc, E.WE_Ser, E.W_Attribtuion, ..."
/// </param>
/// <param name="query_condition">查询条件,如: "R.username = 'fhp' and E.W_Name = 'A11dot1'"</param>
/// <param name="record_filter">
/// Record过滤器——空字符串表示不过滤
/// 因为Process_Record表与Mission_Param是工作流数据库中最大的两张表,故而非常有必要再连接之前对两者进行预先筛选以提高效率
/// 考虑到参数表(Mission_Param)的筛选条件可能比较复杂,因此在这个函数中只提供在连接前对Record进行预筛选
/// 如: time >= '2015/12/25 0:00:00' and username = 'fhp'
/// 特别需要提醒的是: 如果查询不需要record信息,请务必将该参数设置为 "1 <> 1"
/// </param>
public System.Data.DataTable QueryAllInformation(string query_list, string query_condition, string record_filter)
{
//分析需要查询的 属性列, P与R
Regex paramReg = new Regex(@"(?<p>(P.|R.)\w+)");
string str = String.Concat(query_list, " " + query_condition + " ");
MatchCollection matches = paramReg.Matches(str);
string p_str = "(";
string r_str = "(";
int f_par = 0, f_rec = 0;
foreach (Match m in matches)
{
string par_sql = m.Groups["p"].Value;
if (par_sql.IndexOf("P.") == 0)
{
if (f_par == 0)
p_str += ("select '" + par_sql.Substring(2) + "' ");
else
p_str += ("union select '" + par_sql.Substring(2) + "' ");
f_par = 1;
}
else if (par_sql.IndexOf("R.") == 0)
{
if (f_rec == 0)
r_str += ("select '" + par_sql.Substring(2) + "' ");
else
r_str += ("union select '" + par_sql.Substring(2) + "' ");
f_rec = 1;
}
}
//p_str = p_str.TrimEnd(new char[] { ',' });
//r_str = r_str.TrimEnd(new char[] { ',' });
p_str = p_str + ")";
r_str = r_str + ")";
query_condition = query_condition.Replace(@"'", @"''");
record_filter = record_filter.Replace(@"'", @"''");
string str_sql;
str_sql = "declare @sql varchar(8000)\n" +
"set @sql = 'select Re_Mission_Miss_Id '\n";
if (r_str != "()")
{
str_sql +=
"select @sql = @sql + ',max(case Re_Name when ''' + Re_Name + ''' then Re_Value else null end)[' + Re_Name+'] '\n" +
"from (select distinct Re_Name from " + r_str + "t(Re_Name)) as a1\n";
}
str_sql += "set @sql = @sql + 'from Process_Record group by Re_Mission_Miss_Id'\n" +
"declare @sql1 varchar(8000)\n" +
"set @sql1 = 'select Miss_Belong_Miss_Id '\n";
if (p_str != "()")
{
str_sql +=
"select @sql1 = @sql1 + ',max(case Param_Name when ''' + Param_Name + ''' then Param_Value else null end)[' + Param_Name+'] '\n" +
"from (select distinct Param_Name from " + p_str + "k(Param_Name)) as a2\n";
}
str_sql += "set @sql1 = @sql1 + 'from Mission_Param group by Miss_Belong_Miss_Id'\n" +
"declare @sql2 varchar(8000)\n" +
"set @sql2 = 'select WE_Id, W_Name, W_Attribution, WE_Ser, WE_Status from WorkFlow_Define, WorkFlow_Entity where WorkFlow_Define.W_ID = WorkFlow_Entity.WE_Wref_W_ID'\n" +
"declare @sql_t varchar(8000)\n";
//对查询属性列进行处理
if (query_list == "" || query_list == null)
str_sql += "set @sql_t = 'select * from ' +\n";
else
str_sql += "set @sql_t = 'select " + query_list + " from ' +\n";
str_sql += " 'Missions as M ' +\n" +
" 'inner join (' + @sql2 +') as E on M.Miss_WFentity_WE_Id = E.WE_Id ' + \n" +
" 'left join (' + @sql1 + ') as P on M.Miss_Id = P.Miss_Belong_Miss_Id ' +\n";
//对Record进行筛选
if (record_filter == "" || record_filter == null)
str_sql += " 'left join (' + @sql + ')as R on M.Miss_Id = R.Re_Mission_Miss_Id'\n";
else
str_sql += " 'left join (select * from (' + @sql + ') as a3 where " + record_filter + ")as R on M.Miss_Id = R.Re_Mission_Miss_Id ";
//对查询条件进行处理
if (query_condition == "" || query_condition == null)
str_sql += "'\n exec(@sql_t)";
else
str_sql += " where " + query_condition + "'\n exec(@sql_t)";
System.Data.DataTable dt = new System.Data.DataTable();
using (var db = base.NewDB())
{
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = str_sql;
try
{
db.Database.Connection.Open();
var re = cmd.ExecuteReader();
dt.Load(re);
re.Close();
}
catch (Exception e)
{
dt = null;
}
finally
{
db.Database.Connection.Close();
}
return dt;
}
}
//2016/5/17--chenbin
/// <summary>
/// 更新工作流实体的当前任务
/// </summary>
/// <param name="wfEntity_ID">工作流实体ID</param>
/// <returns></returns>
public bool UpdateCurrentMission(int wfEntity_ID, CURR_Mission cMiss)
{
try
{
using (var db = base.NewDB())
{
var wfe = db.workflow_entities.Where(s => s.WE_Id == wfEntity_ID).First();
//没有当前任务
if (wfe.Curr_Mission.Count == 0)
wfe.Curr_Mission.Add(cMiss);
else
{
CURR_Mission cur_miss = wfe.Curr_Mission.First();
if (cMiss != null)
{
cur_miss.After_Action = cMiss.After_Action;
cur_miss.Before_Action = cMiss.Before_Action;
cur_miss.Current_Action = cMiss.Current_Action;
cur_miss.Miss_Desc = cMiss.Miss_Desc;
cur_miss.Miss_Name = cMiss.Miss_Name;
cur_miss.Str_Authority = cMiss.Str_Authority;
}
else
{
db.current_mission.Remove(cur_miss);
//cMiss = null, 清除当前任务, 在end事件时调用
//wfe.Curr_Mission.Clear();
}
}
db.SaveChanges();
}
}
catch(Exception e)
{
Trace.WriteLine(e.Message);
return false;
}
return true;
}
/// <summary>
/// 获得某一工作流的当前任务列表
/// </summary>
/// <param name="entityName"></param>
/// <returns></returns>
public List<CURR_Mission> GetActiveMissionsOfEntity(string entityName)
{
using (var db = base.NewDB())
{
if (entityName == "ALL")
return db.current_mission.Where(a => a.WFE_Parent.WE_Status == WE_STATUS.ACTIVE).ToList();
else
return db.current_mission.Where(a => a.WFE_Parent.WE_Status == WE_STATUS.ACTIVE && a.WFE_Parent.WE_Wref.W_Name == entityName).ToList();
}
}
//end 2016/5/17
}
//end WorkFlows
}//end namespace FlowEngine.DAL<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class DSEventDetail
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
public int week { get; set; }
public int entity_id { get; set; }
public string event_name { get; set; }
public string DSTime_Desc { get; set; }
/// <summary>
/// state:0代表超时完成,1代表按时完成
/// </summary>
public int state { get; set; }
public DateTime? done_time { get; set; }
}
}
<file_sep>using EquipDAL.Implement;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.guidelinesmanagment
{
public class guide_Cat_manager
{
private CatalogTreeNode BuildCatNodes(guidelines_catalog parent)
{
CatalogTreeNode pd = new CatalogTreeNode();
pd.text = parent.Catalog_Name;
pd.tags.Add(parent.Catalog_Id.ToString());
pd.selectable = true;
foreach (var cd in parent.Child_Catalogs.ToList())
{
pd.nodes.Add(BuildCatNodes(cd));
}
return pd;
}
//构建文件种类树
public List<CatalogTreeNode> BuildCatTree()
{
List<CatalogTreeNode> nodes = new List<CatalogTreeNode>();
guidelinescatalogs fcs = new guidelinescatalogs();
DbSet<guidelines_catalog> ta = fcs.GetCatalogsSet();
var roots = ta.Where(s => s.parent_Catalog == null).ToList();
foreach (var root in roots)
{
nodes.Add(BuildCatNodes(root));
}
return nodes;
}
/// <summary>
/// 增加一个文件分类
/// </summary>
/// <param name="parentID"></param>
/// <param name="newCatalog"></param>
/// <returns></returns>
public bool AddNewCatalog(int parentID, string newCatalog)
{
guidelinescatalogs fcs = new guidelinescatalogs();
return fcs.AddNewCatalog(parentID, newCatalog);
}
public bool DeleteCatalog(int ID)
{
return (new guidelinescatalogs()).DeleteCatalog(ID);
}
public bool ModifyFileCatalog(int ID, string name)
{
return (new guidelinescatalogs()).ModifyCatalog(ID, name);
}
public List<guiditem> GetFilesInCatalog(int ID)
{
List<guidelines_info> files = (new guidelinescatalogs()).GetFiles(ID);
List<guiditem> fs = new List<guiditem>();
foreach (var f in files)
{
guiditem fi = new guiditem();
fi.id = Convert.ToString(f.File_Id);
fi.fileName = f.File_OldName;
fi.updateTime = f.File_UploadTime.ToString();
fi.ext = f.File_ExtType;
fi.path = f.File_SavePath;
fi.fileNamePresent = f.File_NewName;
fs.Add(fi);
}
return fs;
}
public bool AddNewFile(int pID, guiditem fi, int uID)
{
guidelines_info nf = new guidelines_info();
nf.File_NewName = fi.fileNamePresent;
nf.File_OldName = fi.fileName;
nf.File_UploadTime = Convert.ToDateTime(fi.updateTime);
nf.File_Submiter = (new Person_Infos()).GetPerson_info(uID);
nf.File_SavePath = fi.path;
nf.File_ExtType = fi.ext;
return (new guidelinescatalogs()).AddFiletoCatalog(pID, nf);
}
public bool DeleteFile(int fID)
{
return (new guidelines()).delete(fID);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment.ZyConfig
{
public class SpecialtyListNode
{
public SpecialtyListNode()
{
Childs = new List<int>();
}
public int Specialty_Id { get; set; }
//专业名称
public string Specialty_Name { get; set; }
public int Parent_id { get; set; }
public List<int> Childs { get; set; }
public int level { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Roles : BaseDAO
{
//获取拥有指定角色的用户信息列表
public class RoleModal
{
public Role_Info RInfo;//用户基本信
public List<Menu> M_Info;//系统菜单信息
}
public List<Person_Info> getRole_Persons(int Role_id)
{
using (var db = base.NewDB())
{
var R = db.Roles.Where(a => a.Role_Id==Role_id).First();
return R.Role_Persons.ToList();
}
}
//获取所有的角色
public List<Role_Info> getRoles()
{
using (var db = base.NewDB())
{
var R = db.Roles.ToList();
return R;
}
}
//获取某制定角色对应的系统菜单
public List<Menu> getRole_Menus(int Role_id)
{
using (var db = base.NewDB())
{
var R = db.Roles.Where(a=>a.Role_Id==Role_id).First().Role_Menus.ToList();
return R;
}
}
//给特定的角色添加用户
public List<Menu> getPerson_Role_Menus(string PersonRoles)
{
using (var db = base.NewDB())
{
int i; int ids;
List<Menu> rm = new List<Menu>();
string[] s1 = PersonRoles.Split(new char[] { ',' });
for (i = 0; i < s1.Length;i++)
{
ids = (Convert.ToInt32(s1[i]));
var R = db.Roles.Where(a => a.Role_Id == ids).First().Role_Menus.ToList();
foreach(var item in R)
rm.Add(item);
}
rm = rm.Distinct().ToList();
return rm;
}
}
//修改某一个已定义的角色
public bool ModifyRole(Role_Info New_Role)
{
int id = New_Role.Role_Id;
using (var db = base.NewDB())
{
try
{
var r = db.Roles.Where(a => a.Role_Id==id).First();
if (r == null)
return false;
else
{
r.Role_Name = New_Role.Role_Name;
r.Role_Desc = New_Role.Role_Desc;
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
public bool AddPerson(int Role_id,int Person_id )
{
using (var db = base.NewDB())
{
try
{
var PR = db.Roles.Where(a => a.Role_Id == Role_id).First();
var P = db.Persons.Where(a => a.Person_Id == Person_id).First();
PR.Role_Persons.Add(P);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
//添加一个新的角色
public int AddRole(Role_Info New_Role)
{
using (var db = base.NewDB())
{
try
{
Role_Info newR = db.Roles.Add(New_Role);
db.SaveChanges();
return newR.Role_Id;
// return true;
}
catch
{
return 0;
}
}
}
//删除某一个已定义的角色
public bool DeleteRole(int roleId)
{
using (var db = base.NewDB())
{
try
{
var r = db.Roles.Where(a => a.Role_Id == roleId).First();
if (r == null)
return false;
else
{ //foreach(var p in r.Role_Persons )
// { var person = db.Persons.Where(a => a.Person_Id == p.Person_Id).First();
// person.Person_roles.Remove(person.Person_roles.Where(s => s.Role_Id == r.Role_Id).First());
// }
r.Role_Persons.Clear();
db.Roles.Remove(r);
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
//修改某一个已定义的角色
public bool ModifyRole(int roleId, Role_Info New_Role)
{
using (var db = base.NewDB())
{
try
{
var r = db.Roles.Where(a => a.Role_Id == roleId).First();
if (r == null)
return false;
else
{
r.Role_Name = New_Role.Role_Name;
r.Role_Desc = New_Role.Role_Desc;
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
public bool Roles_LinkMenus(int Role_id, List<int> Menu_IDs)
{
try
{
using (var db = base.NewDB())
{
var r = db.Roles.Where(s => s.Role_Id == Role_id).First();
var r_old = r.Role_Menus.ToList();
if (r_old.Count > 0)
{
r.Role_Menus.Clear();
}
foreach (var item in Menu_IDs)
{
Menu rm = db.Sys_Menus.Where(s => s.Menu_Id == item).First();
r.Role_Menus.Add(rm);
}
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public RoleModal Get_RoleModal(int Role_Id)
{
try
{
RoleModal RM = new RoleModal();
using (var db = base.NewDB())
{
RM.RInfo = db.Roles.Where(a => a.Role_Id == Role_Id).First();
RM.M_Info = RM.RInfo.Role_Menus.ToList();
return RM;
}
}
catch (Exception e)
{ return null; }
}
}
}
<file_sep>using EquipDAL.Interface;
using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Sxgl : BaseDAO
{
public bool AddSxRecord(A5dot2Tab1 nVal)
{
using (var db = base.NewDB())
{
try
{
db.A5dot2Tab1.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public List<A5dot2Tab1> GetSxRecord(List<string> cjname)
{
using (var db = base.NewDB())
{
List<A5dot2Tab1> E = new List<A5dot2Tab1>();
foreach (var cn in cjname)
{
var e = db.A5dot2Tab1.Where(a => a.state == 0 && a.cjName == cn).ToList();
E.AddRange(e);
}
return E;
}
}
public List<A5dot2Tab1> GetSxRecord_detail(int id)
{
using (var db = base.NewDB())
{
return db.A5dot2Tab1.Where(a => a.Id == id).ToList();
}
}
public A5dot2Tab1 getAllbyid(int a_id)
{
using (var db = base.NewDB())
{
return db.A5dot2Tab1.Where(a => a.Id ==a_id).First();
}
}
public string ModifySxRecord(A5dot2Tab1 nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA5dot2Tab1 = db.A5dot2Tab1.Where(a => a.Id == nVal.Id).First();
modifyA5dot2Tab1.pqCheckTime = nVal.pqCheckTime;
modifyA5dot2Tab1.pqUserName = nVal.pqUserName;
modifyA5dot2Tab1.isRectified = nVal.isRectified;
modifyA5dot2Tab1.state = nVal.state;
modifyA5dot2Tab1.problemDescription = nVal.problemDescription;
db.SaveChanges();
return modifyA5dot2Tab1.sbCode;
}
catch
{
return "出错!";
}
}
}
public string ModifySxRecord1(A5dot2Tab1 nVal)
{
using (var db = base.NewDB())
{
try
{
var modifyA5dot2Tab1 = db.A5dot2Tab1.Where(a => a.Id == nVal.Id).First();
modifyA5dot2Tab1.pqCheckTime = nVal.pqCheckTime;
modifyA5dot2Tab1.pqUserName = nVal.pqUserName;
modifyA5dot2Tab1.isRectified = nVal.isRectified;
modifyA5dot2Tab1.state = nVal.state;
db.SaveChanges();
return modifyA5dot2Tab1.sbCode;
}
catch
{
return "出错!";
}
}
}
public List<A5dot2Tab2> GetA5dot2Tab2(string res)
{
try
{
using (var db = base.NewDB())
{
return db.A5dot2Tab2.Where(a => a.sbCode == res).ToList();
}
}
catch(Exception e)
{
return null;
}
}
public bool AddA5dot2Tab2(A5dot2Tab2 nVal)
{
using (var db = base.NewDB())
{
try
{
db.A5dot2Tab2.Add(nVal);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool ModifyA5dot2Tab2(A5dot2Tab2 nVal)
{
using (var db = base.NewDB())
{
try
{
List<A5dot2Tab2> modifyA5dot2Tab2 = db.A5dot2Tab2.Where(a => a.sbCode == nVal.sbCode).ToList();
string[] yearandmonth = (nVal.yearMonthForStatistic).Split(new char[] { '年' });
int key = 0;
for (int k = 0; k < modifyA5dot2Tab2.Count;k++ )
{
string[] YandMfromDB = (modifyA5dot2Tab2[k].yearMonthForStatistic).Split(new char[] { '年' });
if (YandMfromDB[1] == yearandmonth[1] && YandMfromDB[0] == yearandmonth[0])//年月一样
{
modifyA5dot2Tab2[k].problemDescription = modifyA5dot2Tab2[k].problemDescription + "$" + nVal.problemDescription;
modifyA5dot2Tab2[k].zyType = modifyA5dot2Tab2[k].zyType + "$" + nVal.zyType;
modifyA5dot2Tab2[k].nProblemsInCurMonth++;
modifyA5dot2Tab2[k].nProblemsInCurYear++;
key = 1;
}
}
if(key==0)
{
db.A5dot2Tab2.Add(nVal);//年一样月不一样或年不一样月一样或年月不一样
}
//string[] YandMfromDB = (modifyA5dot2Tab2.yearMonthForStatistic).Split(new char[] { '年' });
//if (YandMfromDB[1] == yearandmonth[1] && YandMfromDB[0] == yearandmonth[0])
//{
// modifyA5dot2Tab2.problemDescription = modifyA5dot2Tab2.problemDescription + "$" + nVal.problemDescription;
// modifyA5dot2Tab2.zyType = modifyA5dot2Tab2.zyType + "$" + nVal.zyType;
// modifyA5dot2Tab2.nProblemsInCurMonth++;
// modifyA5dot2Tab2.nProblemsInCurYear++;
//}
//else if (YandMfromDB[1] != yearandmonth[1] && YandMfromDB[0] == yearandmonth[0])
//{
// db.A5dot2Tab2.Add(nVal);
//}
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
//片区汇总筛选10台最脏设备
public List<A5dot2Tab2> GetA5dot2Tab2ForPq(string yearandmonth)
{
try
{
using (var db = base.NewDB())
{
return db.A5dot2Tab2.Where(a => a.yearMonthForStatistic == yearandmonth).ToList();
}
}
catch (Exception e)
{
return null;
}
}
//单台设备全年问题次数
public int GetnProblemsInYear(string sbCode)
{
try
{
using (var db=base.NewDB())
{
int nprobleminyear = 0;
List<A5dot2Tab2> c = db.A5dot2Tab2.Where(a => a.sbCode == sbCode).ToList();
foreach(var item in c)
{
nprobleminyear = nprobleminyear + item.nProblemsInCurMonth;
}
return nprobleminyear;
}
}
catch(Exception e )
{
return 0;
}
}
//将选中的最脏设备更新到库
public bool SetWorse(int id,string user)
{
try
{
using (var db = base.NewDB())
{
var setworse = db.A5dot2Tab2.Where(a => a.Id == id).First();
setworse.isSetAsTop10Worst = 1;
setworse.jdcOperateTime = DateTime.Now;
setworse.jdcUserName = user;
db.SaveChanges();
}
return true;
}
catch(Exception e)
{
return false;
}
}
//查出本月最脏十台
public List<A5dot2Tab2> jdcsummy(string yearandmonth)
{
try
{
using (var db = base.NewDB())
{
return db.A5dot2Tab2.Where(a => a.yearMonthForStatistic == yearandmonth && a.isSetAsTop10Worst==1).ToList();
}
}
catch (Exception e)
{
return null;
}
}
//查出最脏设备未整改问题
public List<A5dot2Tab1> uncomp(string sbCode ,DateTime time)
{
try
{
using (var db = base.NewDB())
{
return db.A5dot2Tab1.Where(a => a.sbCode == sbCode && a.isRectified == 0 && a.pqCheckTime<time).ToList();
}
}
catch (Exception e)
{
return null;
}
}
public string forlastmonthproblem(string lastmonth, string sbCode)
{
try
{
using (var db = base.NewDB())
{
var i= db.A5dot2Tab2.Where(a => a.yearMonthForStatistic == lastmonth && a.sbCode == sbCode).First();
string lastmonthproblem = i.problemDescription;
return lastmonthproblem;
}
}
catch (Exception e)
{
return null;
}
}
public List<A5dot2Tab1> GetLS_listbywfe_id(List<int> wfe_id)
{
using (var db = base.NewDB())
{
List<A5dot2Tab1> E = new List<A5dot2Tab1>();
try
{
foreach (var w in wfe_id)
{
var e = db.A5dot2Tab1.Where(a => a.temp2 == w.ToString()).ToList();
E.AddRange(e);
}
return E;
}
catch (Exception e)
{
return null;
}
}
}
}
}
<file_sep>using FlowDesigner.PropertyEditor;
using System;
using System.Activities.Presentation.PropertyEditing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Xml;
namespace FlowDesigner.ConfigItems
{
public class EventActionDefine
{
public string url { get; set; }
private Dictionary<string, string> _params = new Dictionary<string, string>();
public Dictionary<string, string> action_params
{
get
{
return _params;
}
set
{
_params = value;
}
}
public Dictionary<string, string> event_params;
}
/// <summary>
/// 事件的定制元素
/// </summary>
public class ConfigEvent : ConfigItem
{
/// <summary>
/// 宽度
/// </summary>
private int nWidth;
/// <summary>
/// 高度
/// </summary>
private int nHeight;
/// <summary>
/// 事件的类型
/// </summary>
private string eventType;
private EventActionDefine _beforeaction = new EventActionDefine();
private EventActionDefine _aftereaction = new EventActionDefine();
//事件
[CategoryAttribute("事件")]
[Editor(typeof(EventActionEditor), typeof(PropertyValueEditor))]
public EventActionDefine BeforeAction {
get
{
return _beforeaction;
}
set {
_beforeaction = value;
}
}
[CategoryAttribute("事件")]
public string CurrentAction { get; set; }
[CategoryAttribute("事件")]
[Editor(typeof(EventActionEditor), typeof(PropertyValueEditor))]
public EventActionDefine AfterAction {
get {
return _aftereaction;
}
set
{
_aftereaction = value;
}
}
[CategoryAttribute("权限")]
public string authority { get; set; }
//关联变量
private Dictionary<string, string> _LinkParams = new Dictionary<string, string>();
[Category("参数")]
[Editor(typeof(LinkParamsEditor), typeof(PropertyValueEditor))]
public object Link_Params
{
get
{
return _LinkParams;
}
set
{
_LinkParams = (value as Dictionary<string, string>);
}
}
//timeout
private Dictionary<string, object> _TimeOut = new Dictionary<string, object>();
[Category("超时")]
[Editor(typeof(TimeoutEditor), typeof(PropertyValueEditor))]
public object Time_Out
{
get
{
return _TimeOut;
}
set
{
_TimeOut = (value as Dictionary<string, object>);
}
}
public Dictionary<string, string> LinkParams
{
get{
return _LinkParams;
}
set {
_LinkParams = value;
}
}
public string GetEventType()
{
return eventType;
}
/// <summary>
/// 构造函数
/// </summary>
public ConfigEvent(string eType)
{
nWidth = 150;
nHeight = 70;
Color bkColor = Color.FromRgb(255, 255, 255) ;
Color storkColor = Color.FromRgb(255, 255, 255);
eventType = eType;
switch(eventType)
{
case "NormalEvent":
bkColor = Color.FromRgb(51, 144, 208);
storkColor = Color.FromRgb(17, 50, 72);
break;
case "StartEvent":
bkColor = Color.FromRgb(4, 181, 13);
storkColor = Color.FromRgb(2, 113, 7);
break;
case "EndEvent":
bkColor = Color.FromRgb(255, 0, 128);
storkColor = Color.FromRgb(162, 0, 81);
break;
case "SubProcess":
bkColor = Color.FromRgb(255, 255, 0);
storkColor = Color.FromRgb(128, 128, 0);
break;
case "LoopEvent":
bkColor = Color.FromRgb(163, 73, 164);
storkColor = Color.FromRgb(88, 39, 88);
break;
}
VisualBrush myVisualBrush = new VisualBrush();
StackPanel myStackPanel = new StackPanel();
myStackPanel.Background = new SolidColorBrush(bkColor);
TextBlock somtext = new TextBlock();
FontSizeConverter myFontSizeConverter = new FontSizeConverter();
somtext.FontSize = 0.7F;//(double)myFontSizeConverter.ConvertFrom("6px");
somtext.FontFamily = new FontFamily("Arial");
somtext.Text = name + "\r\n" + description;
somtext.Margin = new Thickness(2);
myStackPanel.Children.Add(somtext);
myVisualBrush.Visual = myStackPanel;
Show_item = new Rectangle()
{
Width = nWidth,
Height = nHeight,
Fill = myVisualBrush,//new SolidColorBrush(Color.FromRgb(51, 144, 208)),
Stroke = new SolidColorBrush(storkColor),
StrokeThickness = 2,
Cursor = Cursors.Cross,
Opacity = 0.6,
RadiusX = 5,
RadiusY = 5
};
builidEventLink();
_beforeaction.event_params = this.LinkParams;
_aftereaction.event_params = this.LinkParams;
}
public override void UnSelect()
{
m_selected = false;
Canvas.SetZIndex(this.Show_item, 1);
Show_item.Opacity = 0.6;
}
public override void Selected()
{
m_selected = true;
Canvas.SetZIndex(this.Show_item, Int16.MaxValue - 1 );
}
/// <summary>
/// 重载设置位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public override void SetPos(int x, int y)
{
((Rectangle)Show_item).Margin = new Thickness(x, y, 0, 0);
}
protected override void NameChanged()
{
((TextBlock)((StackPanel)((VisualBrush)Show_item.Fill).Visual).Children[0]).Text = name + "\r\n" + description;
}
protected override void DescChanged()
{
((TextBlock)((StackPanel)((VisualBrush)Show_item.Fill).Visual).Children[0]).Text = name + "\r\n" + description;
}
protected override void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed && m_selected)
{
Point ptCur = e.GetPosition(Show_item);
double dx = ptCur.X - pt.X;
double dy = ptCur.Y - pt.Y;
Thickness tk = ((Rectangle)Show_item).Margin;
tk.Left += (int)dx;
tk.Top += (int)dy;
((Rectangle)Show_item).Margin = tk;
//pt = ptCur;
//Trace.WriteLine("X = " + ptCur.X + "; Y = " + ptCur.Y);
foreach (ConfigFlow cf in attach_flows)
cf.Connect();
}
}
public override XmlElement SaveConfigItem(XmlDocument Owner)
{
//base
XmlElement base_xml = base.SaveConfigItem(Owner);
base_xml.SetAttribute("item_type", "event");
base_xml.SetAttribute("event_type", eventType);
base_xml.SetAttribute("authority", authority);
//shape
XmlElement shape_xml = Owner.CreateElement("shape");
shape_xml.SetAttribute("type", Show_item.ToString());
shape_xml.SetAttribute("margin", Show_item.Margin.ToString());
base_xml.AppendChild(shape_xml);
//actions
XmlElement actions_xml = Owner.CreateElement("actions");
//beforeaction
XmlElement ba = Owner.CreateElement("beforeaction");
ba.SetAttribute("url", BeforeAction.url);
XmlElement ba_pars = Owner.CreateElement("action_params");
foreach(var pa in BeforeAction.action_params)
{
XmlElement xpa = Owner.CreateElement("param");
xpa.SetAttribute("name", pa.Key);
xpa.InnerText = pa.Value;
ba_pars.AppendChild(xpa);
}
ba.AppendChild(ba_pars);
actions_xml.AppendChild(ba);
//afteraction
XmlElement aa = Owner.CreateElement("afteraction");
aa.SetAttribute("url", AfterAction.url);
XmlElement aa_pars = Owner.CreateElement("action_params");
foreach (var pa in AfterAction.action_params)
{
XmlElement xpa = Owner.CreateElement("param");
xpa.SetAttribute("name", pa.Key);
xpa.InnerText = pa.Value;
aa_pars.AppendChild(xpa);
}
aa.AppendChild(aa_pars);
actions_xml.AppendChild(aa);
//currentaction
actions_xml.SetAttribute("currentaction", CurrentAction);
base_xml.AppendChild(actions_xml);
//link_params
XmlElement pas_xml = Owner.CreateElement("link_params");
foreach(var pa in _LinkParams)
{
XmlElement pa_xml = Owner.CreateElement("param");
pa_xml.SetAttribute("name", pa.Key);
pa_xml.SetAttribute("app_reserve", pa.Value);
pas_xml.AppendChild(pa_xml);
}
base_xml.AppendChild(pas_xml);
//TimeOut
XmlElement time_xml = Owner.CreateElement("time_out");
XmlElement time_start = Owner.CreateElement("start");
if ( _TimeOut.ContainsKey("start") == false || _TimeOut["start"] == null)
time_start.InnerText = "";
else
time_start.InnerText = (_TimeOut["start"] as string);
time_xml.AppendChild(time_start);
XmlElement time_offset = Owner.CreateElement("offset");
if (_TimeOut.ContainsKey("offset") == false || _TimeOut["offset"] == null)
time_offset.InnerText = "";
else
{
TimeSpan? ts = (_TimeOut["offset"] as TimeSpan?);
time_offset.AppendChild(Owner.CreateCDataSection(ts.Value.ToString()));
}
time_xml.AppendChild(time_offset);
XmlElement time_exact = Owner.CreateElement("exact");
if (_TimeOut.ContainsKey("exact") == false || _TimeOut["exact"] == null)
time_exact.InnerText = "";
else
{
time_exact.AppendChild(Owner.CreateCDataSection((_TimeOut["exact"] as DateTime?).Value.ToString()));
}
time_xml.AppendChild(time_exact);
XmlElement time_action = Owner.CreateElement("action");
if (_TimeOut.ContainsKey("action") == false || _TimeOut["action"] == null)
{
time_action.InnerText = "";
}
else
{
time_action.InnerText = (_TimeOut["action"] as string);
}
time_xml.AppendChild(time_action);
XmlElement time_callback = Owner.CreateElement("callback");
if (_TimeOut.ContainsKey("callback") == false || _TimeOut["callback"] == null)
time_callback.InnerText = "";
else
time_callback.AppendChild(Owner.CreateCDataSection(_TimeOut["callback"] as string));
time_xml.AppendChild(time_callback);
base_xml.AppendChild(time_xml);
return base_xml;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class guidelines_info
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int File_Id { get; set; }
/// <summary>
/// 文件名(保存)
/// </summary>
public string File_NewName { get; set; }
/// <summary>
/// 文件名(用户上传时的文件名)
/// </summary>
public string File_OldName { get; set; }
/// <summary>
/// 保存路径
/// </summary>
public string File_SavePath { get; set; }
/// <summary>
/// 文件类型
/// </summary>
public string File_ExtType { get; set; }
/// <summary>
/// 上传日期
/// </summary>
public DateTime File_UploadTime { get; set; }
/// <summary>
/// 上传人
/// </summary>
public virtual Person_Info File_Submiter { get; set; }
/// <summary>
/// 工作流实体ID
/// </summary>
public int WfEntity_Id { get; set; }
/// <summary>
/// Mission ID
/// </summary>
public int Mission_Id { get; set; }
/// <summary>
/// 文件的类别
/// </summary>
virtual public guidelines_catalog Self_Catalog { get; set; }
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Threading;
namespace WebApp.Controllers
{
public class A12dot1Controller : CommonController
{
//
// GET: /A12dot1/
public ActionResult Index()
{
return View(getIndexListRecords("A12dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A12dot1/装置提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A12dot1/维修单位给出具体建议
public ActionResult JxdwAdvise(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot1/可靠性工程师审核提报
public ActionResult PqConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot1/跳转到A11.1风险评估
public ActionResult JumpToA11dot1(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot1/专业团队审核是否执行
public ActionResult ZytdConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot1/专业团队确认是否上报厂部领导
public ActionResult ZytdConfirmToLeader(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A12dot1/厂部领导审核是否执行
public ActionResult LeaderConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//GET: /A12dot1/工作流详情
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Data_Src"] = "设备本体改造";
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
//string filename = Path.Combine(Request.MapPath("~/Upload"),item["Plan_DescFilePath"].ToString());
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot1/Index");
}
public string JxdwAdvise_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JxdwAdvise_done"] = item["JxdwAdvise_done"].ToString();
signal["JxdwAdvise_Desc"] = item["JxdwAdvise_Desc"].ToString();
signal["JxdwAdvise_File"] = item["JxdwAdvise_File"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot1/Index");
}
public string PqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirm_Result"] = item["PqConfirm_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot1/Index");
}
public string ZytdConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirm_Result"] = item["ZytdConfirm_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot1/Index");
}
public string ZytdConfirmToLeader_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirmToLeader_Result"] = item["ZytdConfirmToLeader_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot1/Index");
}
public string LeaderConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["LeaderConfirm_Result"] = item["LeaderConfirm_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A12dot1/Index");
}
public static void PushWorkFlowRun(object wfe_id)
{
//等待sendtoDRBPMsystem函数返回
Thread.Sleep(2000);
int i_wfe_id = Convert.ToInt32(wfe_id);
CWFEngine.SubmitSignal(i_wfe_id, new Dictionary<string, string>());
}
// sendToDRBPMsystem
public string sendToDRBPMsystem(string param)
{
JObject item = (JObject)JsonConvert.DeserializeObject(param);
string wfe_id = item["wfe_id"].ToString();
string ser = CWFEngine.GetWorkFlowEntiy(Convert.ToInt32(wfe_id), false).serial;
//======================================2016.7.22=======================================
//DRBPM预防性计划 : writeDRBPM(string sbcode,string reason, bool isUrgent)
writeDRBPM(item["E_Code"].ToString(), "设备本体改造", false,ser); // write to drbpm
//======================================================================================
Thread th1 = new Thread(new ParameterizedThreadStart(PushWorkFlowRun));
th1.Start(wfe_id);
return "";
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
namespace WebApp.Controllers
{
public class A4dot3Controller : CommonController
{
// GET: /A4dot3/
public ActionResult Index()
{
return View(getIndexListRecords("A4dot3", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A4dot3/工程计划提报,确认工程管理单位、质量管理单位
public ActionResult PlanSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A4dot3/工程管理单位确认时间
public ActionResult CMConfirmSchedule(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot3/ 工程管理单位三查四定
public ActionResult CMZySCSD(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot3/相关单位确认三查四定
public ActionResult SCSDConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot3/工程管理单位组织中交
public ActionResult Zj(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot3/相关单位确认中交
public ActionResult ZjConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot3/确认是否合格
public ActionResult ZytdConfirmC(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot3/工程管理单位通知施工方整改
public ActionResult CMConfirmC(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot3/开箱验收,工程管理组织验收
public ActionResult YanShou(string wfe_id)
{
return View();
}
// GET: /A4dot3/随机专用工具及配件交车间保留、资料交技术档案室
public ActionResult CjJsQueRen(string wfe_id)
{
return View();
}
// GET: /A4dot3/物资处联系供应商补全
public ActionResult WuZiChu(string wfe_id)
{
return View();
}
// GET: /A4dot3/施工单位编制施工方案,工程管理单位确认
public ActionResult shigongPlan(string wfe_id)
{
return View();
}
// GET: /A4dot3/确认是否完工
public ActionResult IfSuccess(string wfe_id)
{
return View();
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string Plan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PlanSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Plan_Order"] = item["Plan_Order"].ToString();
signal["Plan_Name"] = item["Plan_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["CM_Department"] = item["CM_Department"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot3/Index");
}
public string ScheduleTimeSubmit(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ScheduleConfirm_Done"] = "true";
signal["ScheduleTime_Begin"] = item["ScheduleTime_Begin"].ToString();
signal["ScheduleTime_End"] = item["ScheduleTime_End"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot3/Index");
}
public string CMZySCSD_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["SCSD_Time"] = item["SCSD_Time"].ToString();
signal["CMZySCSD_Done"] = "true";
signal["SCSD_Place"] = item["SCSD_Place"].ToString();
signal["SCSD_Speci"] = item["SCSD_Speci"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot3/Index");
}
public string SCSDConfirm_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["SCSDConfirm_Done"] = item["SCSDConfirm_Done"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot3/Index");
}
public string ZJ_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["Zj_Done"] = "true";
signal["Zj_Time"] = item["ZJ_Time"].ToString();
signal["Zj_Place"] = item["ZJ_Place"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot3/Index");
}
public string ZjConfirm_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["ZjConfirm_Done"] = item["ZjConfirm_Done"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot3/Index");
}
public string ZytdConfirmC_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["ZytdConfirmC_Result"] = item["ZytdConfirmC_Result"].ToString();
signal["Equip_Type"] = "无";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot3/Index");
}
public string CMConfirmC_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["CMConfirmC_Done"] = item["CMConfirmC_Done"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot3/Index");
}
}
}<file_sep>using FlowDesigner.ConfigItems;
using System;
using System.Activities.Presentation.Converters;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.PropertyEditing;
using System.Collections.Generic;
using System.Drawing.Design;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Design;
using System.Windows.Markup;
namespace FlowDesigner.PropertyEditor
{
public class EventActionEditor : DialogPropertyValueEditor
{
public EventActionEditor()
{
string template = @"
<DataTemplate
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:pe='clr-namespace:System.Activities.Presentation.PropertyEditing;assembly=System.Activities.Presentation'>
<DockPanel LastChildFill='True'>
<pe:EditModeSwitchButton TargetEditMode='Dialog' Name='EditButton_Action'
DockPanel.Dock='Right'>...</pe:EditModeSwitchButton>
<TextBlock Text='设置' Margin='2,0,0,0' VerticalAlignment='Center'/>
</DockPanel>
</DataTemplate>";
using (var sr = new MemoryStream(Encoding.UTF8.GetBytes(template)))
{
this.InlineEditorTemplate = XamlReader.Load(sr) as DataTemplate;
}
}
public override void ShowDialog(PropertyValue propertyValue, System.Windows.IInputElement commandSource)
{
EventActionWin wn = new EventActionWin();
EventActionDefine action = propertyValue.Value as EventActionDefine;
wn.action_url = action.url;
wn.action_params = action.action_params;
wn.event_linkParams = action.event_params;
if (wn.ShowDialog().Equals(true))
{
var ownerActivityConverter = new ModelPropertyEntryToOwnerActivityConverter();
ModelItem activityItem = ownerActivityConverter.Convert(propertyValue.ParentProperty, typeof(ModelItem), false, null) as ModelItem;
using (ModelEditingScope editingScope = activityItem.BeginEdit())
{
EventActionDefine newValue = new EventActionDefine();
newValue.url = wn.action_url;
newValue.action_params = wn.action_params;
newValue.event_params = wn.event_linkParams;
propertyValue.Value = newValue;
editingScope.Complete();
var control = commandSource as Control;
var oldData = control.DataContext;
control.DataContext = null;
control.DataContext = oldData;
}
}
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using WebApp.Models;
using WebApp.Models.User;
namespace WebApp.Models
{
public class UserAccount : DropCreateDatabaseIfModelChanges<UserContext>
{
protected override void Seed(UserContext context)
{
var partments = new List<Depart>
{
new Depart {dep_name = "设计"}
};
partments.ForEach(s => context.department.Add(s));
var roles = new List<Role>
{
new Role {r_name = "职员"},
new Role {r_name = "经理"}
};
roles.ForEach(s => context.roles.Add(s));
context.SaveChanges();
var users = new List<UserInfo>
{
new UserInfo {name = "cb",
password="123",
my_depart = context.department.Where(s=>s.dep_name=="设计").First(),
my_role = context.roles.Where(s=>s.r_name=="职员").First()},
new UserInfo {name = "cb1",
password="123",
my_depart = context.department.Where(s=>s.dep_name=="设计").First(),
my_role = context.roles.Where(s=>s.r_name=="经理").First()}
};
users.ForEach(s => context.users.Add(s));
context.SaveChanges();
base.Seed(context);
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using WebApp.Models.DateTables;
using System.Collections.Specialized;
using EquipBLL.AdminManagment.MenuConfig;
using FlowEngine.DAL;
using FlowEngine.Modals;
using FlowEngine.TimerManage;
namespace WebApp.Controllers
{
public class CallBackController : Controller
{
//
// GET: /CallBack/
Jobs js = new Jobs();
DsWorkManagment dm = new DsWorkManagment();
public ActionResult Index()
{
return View();
}
public string GetDSRemind()
{
List<Timer_Jobs> Tjs = js.GetDSRemind();
List<string> Remind_list = new List<string>();
for (int i = 0; i < Tjs.Count;i++)
{
//TriggerTiming TT = new TriggerTiming();
//TT.FromString(Tjs[i].corn_express);
//TT.RefreshNextTiming(DateTime.Now);
//DateTime next_dt = TT.NextTiming.Value;
UI_MISSION u = CWFEngine.GetActiveMission<Person_Info>(Tjs[i].workflow_ID, null, false);
string work_name = u.WE_Name;
string event_desc = u.WE_Event_Desc;
string event_name = work_name + ":" + event_desc;
Remind_list.Add(event_name);
}
string Remind_Str = "定时任务提醒!!!请按时完成以下流程:";
for (int i = 0; i < Remind_list.Count; i++)
{
Remind_Str += Remind_list[i] + "、";
}
return Remind_Str;
}
public static int WeekOfMonth(DateTime day, int WeekStart)
{
//WeekStart
//1表示 周一至周日 为一周
//2表示 周日至周六 为一周
DateTime FirstofMonth;
FirstofMonth = Convert.ToDateTime(day.Date.Year + "-" + day.Date.Month + "-" + 1);
int i = (int)FirstofMonth.Date.DayOfWeek;
if (i == 0)
{
i = 7;
}
if (WeekStart == 1)
{
return (day.Date.Day + i - 2) / 7 + 1;
}
if (WeekStart == 2)
{
return (day.Date.Day + i - 1) / 7;
}
return 0;
//错误返回值0
}
public void testCallBack(int timer_id, string user_params)
{
JObject item = (JObject)JsonConvert.DeserializeObject(user_params);
int eneity_id = Convert.ToInt32(item["entity_id"]);
string event_name = item["event_name"].ToString();
DSEventDetail ds = new DSEventDetail();
DateTime now = DateTime.Now;
ds.year = now.Year;
ds.month = now.Month;
ds.day = now.Day;
ds.week = WeekOfMonth(now,1);
ds.state =0;
ds.entity_id = eneity_id;
//List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(eneity_id);
UI_MISSION u = CWFEngine.GetActiveMission<Person_Info>(eneity_id, null, false);
string work_name = u.WE_Name;
string event_desc = u.WE_Event_Desc;
ds.event_name = work_name + ":" + event_desc;
Timer_Jobs tj = js.GetTimerJob(timer_id);
ds.DSTime_Desc = tj.STR_RES_2;
//if (dm.getdetailbyE_id(eneity_id) == null)
dm.AddDsEvent(ds);
}
public void CSA11dot2ZzSubmit(string param)
{
JObject item = (JObject)JsonConvert.DeserializeObject(param);
int entity_id = Convert.ToInt32 (item["Entity_id"]);
UI_MISSION u = CWFEngine.GetActiveMission<Person_Info>(entity_id, null, false);
string work_name = u.WE_Name;
string event_desc = u.WE_Event_Desc;
string event_name = work_name + ":" + event_desc;
dm.modifystate(entity_id, event_name);
}
public void A5dot1ZzSubmit()
{
}
/// <summary>
/// 有以前的通过Excel表读取数据模式改为现在的直接读取ERP中数据,通过周期调用此函数,周期存库
/// </summary>
/// <param name="json1"></param>
/// <returns></returns>
public void ERPSubmit()
{
try
{
PersonManagment PM = new PersonManagment();
A6dot2Managment WM = new A6dot2Managment();
A6dot2Tab1 WDT_list = new A6dot2Tab1();
ERPInfoManagement erp = new ERPInfoManagement();
EquipManagment EM = new EquipManagment();
string EquipPhaseB;
WDT_list.uploadDesc = "";//字段保留,(以前用于上传五定表的描述)
WDT_list.uuploadFileName = "";//字段保留,(以前用于上传五定表的名字)
//string[] savedFileName = WDT_list.uuploadFileName.Split(new char[] { '$' });
//string wdt_filename = Path.Combine(Request.MapPath("~/Upload"), savedFileName[1]);//没有用到的变量
//WDT_list.userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
WDT_list.userName = "自动提取自ERP";
WDT_list.uploadtime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
//WDT_list.pqName = PM.Get_Person_Depart((Session["User"] as EquipModel.Entities.Person_Info).Person_Id).Depart_Name;
WDT_list.pqName = "待定";
int WDT_ID = WM.add_WDT_list(WDT_list);
List<OilInfo> OilInfo_Overdue = erp.getOilInfo_overdue();
List<A6dot2Tab2> wdt_list = new List<A6dot2Tab2>();
foreach (var i in OilInfo_Overdue)
{
A6dot2Tab2 tmp = new A6dot2Tab2();
tmp.isValid = 1;
tmp.equipCode = i.oil_EquipCode;
tmp.equipDesc = i.oil_EquipDesc;
tmp.funLoc = i.oil_Fun_Loc;
tmp.funLoc_desc = i.oil_Fun_LocDesc;
tmp.oilLoc = i.oil_Loc;
tmp.oilLoc_desc = i.oil_Loc;
tmp.oilInterval = Convert.ToInt32(i.oil_Interval);
tmp.unit = i.oil_Unit;
tmp.lastOilTime = i.oil_LastDate;
tmp.lastOilNumber = Convert.ToDouble(i.oil_LastNum);
tmp.lastOilUnit = i.oil_Unit;
tmp.NextOilTime = i.oil_NextDate.ToString();
tmp.NextOilNumber = Convert.ToDouble(i.oil_NextNum);
tmp.NextOilUnit = i.oil_Unit2;
tmp.oilCode = i.oil_Code;
tmp.oilCode_desc = i.oil_Desc;
tmp.substiOilCode = "";
tmp.substiOilCode_desc = "";
if (EM.getEquip_Info(tmp.equipCode) != null)
{
EquipPhaseB = EM.getEquip_Info(tmp.equipCode).Equip_PhaseB;
if (EquipPhaseB==null)
tmp.isOilType = 0;
else
{
if (EquipPhaseB.Equals("机泵") || EquipPhaseB.Equals("风机"))
tmp.isOilType = 1;
else
tmp.isOilType = 0;
}
List<Equip_Archi> ZzCj = EM.getEquip_ZzBelong(EM.getEquip_Info(tmp.equipCode).Equip_Id);
tmp.equip_ZzName = ZzCj.First().EA_Name;
tmp.equip_CjName = ZzCj.Last().EA_Name;
tmp.equip_PqName = EM.GetPqofZz(tmp.equip_ZzName).Pq_Name;
}
tmp.isExceed = 1;
tmp.Tab1_Id = WDT_ID;
wdt_list.Add(tmp);
}
WM.add_WDT_content(WDT_ID, wdt_list);
/* foreach(var i in wdt_content)
{
return i.equip_CjName;
}
* */
// return "/A6dot2/Index_Tj";
}
catch { }
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.Modals
{
/// <summary>
/// 任务类别
/// </summary>
public enum TIMER_JOB_TYPE { CREATE_WORKFLOW, CHANGE_STATUS, TIME_OUT, EMPTY, Normal };
/// <summary>
/// 任务状态
/// </summary>
public enum TM_STATUS { TM_STATUS_ACTIVE, TM_STATUS_STOP, TM_FINISH, TM_DELETE };
/// <summary>
/// 任务用途
/// </summary>
public enum TIMER_USING { FOR_SYSTEM, FOR_CUSTOM}
/// <summary>
/// 关于定时性工作的定义
/// </summary>
public class Timer_Jobs
{
/// <summary>
/// 工作任务ID, 主键
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int JOB_ID
{
get;
set;
}
/// <summary>
/// 任务名称
/// </summary>
public string job_name { get; set; }
/// <summary>
/// 任务类型
/// </summary>
public TIMER_JOB_TYPE Job_Type { get; set; }
/// <summary>
/// 上一次任务执行时间
/// </summary>
public DateTime? PreTime { get; set; }
/// <summary>
/// 任务状态
/// </summary>
public TM_STATUS status { get; set; }
/// <summary>
/// 任务用途
/// </summary>
public TIMER_USING t_using { get; set; }
/// <summary>
/// 该字段可能存储 工作流定义的ID或工作流实体的ID, 具体含义依据不同类型的任务而定
/// </summary>
public int workflow_ID { get; set; }
/// <summary>
/// 该字段存储任务运行参数
/// </summary>
public string run_params { get; set; }
/// <summary>
/// 运行结果
/// </summary>
public string run_result { get; set; }
/// <summary>
/// 表示执行时间的corn表达式
/// </summary>
public string corn_express { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime create_time { get; set; }
/// <summary>
/// 自定义事件
/// </summary>
public string custom_action { get; set; }
/// <summary>
/// 自定义标签
/// </summary>
public int custom_flag { get; set; }
#region 保留字段
/// <summary>
/// 整数型保留字段
/// </summary>
public int INT_RES_1 { get; set; }
public int INT_RES_2 { get; set; }
public int INT_RES_3 { get; set; }
/// <summary>
/// 字符串型保留字段
/// </summary>
public string STR_RES_1 { get; set; }
public string STR_RES_2 { get; set; }
public string STR_RES_3 { get; set; }
#endregion
public void copy(Timer_Jobs job)
{
JOB_ID = job.JOB_ID;
job_name = job.job_name;
Job_Type = job.Job_Type;
PreTime = job.PreTime;
status = job.status;
t_using = job.t_using;
workflow_ID = job.workflow_ID;
run_params = job.run_params;
run_result = job.run_result;
corn_express = job.corn_express;
INT_RES_1 = job.INT_RES_1;
INT_RES_2 = job.INT_RES_2;
INT_RES_3 = job.INT_RES_3;
STR_RES_1 = job.STR_RES_1;
STR_RES_2 = job.STR_RES_2;
STR_RES_3 = job.STR_RES_3;
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace WebApp.Controllers
{
public class MyDSWorksController : Controller
{
public class DSIndex_Model
{
public int Month_Num;
public List<string> title;
}
//
// GET: /MyDSWorks/
public ActionResult Index()
{
return View(getIndex());
}
public DSIndex_Model getIndex()
{
DSIndex_Model Ds = new DSIndex_Model();
int month_num = DateTime.Now.Month;
List<string> titlename = new List<string>();
Ds.Month_Num = month_num;
for (int i = 1; i < month_num + 1; i++)
{
titlename.Add(i.ToString() + "月完成情况");
}
Ds.title = titlename;
return Ds;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.UserInterface
{
public class UI_WF_Define
{
public int wf_id { get; set; }
public string wf_name { get; set; }
public string wf_description { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class dongmodel
{
public double? gzqdkf { get; set; }
public double? djzgzl { get; set; }
public double? gzwxl { get; set; }
public double? qtlxbmfxhl { get; set; }
public double? jjqxgsl { get; set; }
public double? gdpjwcsj { get; set; }
public double? jxmfpjsm { get; set; }
public double? zcpjsm { get; set; }
public double? sbwhl { get; set; }
public double? jxychgl { get; set; }
public double? zyjbpjxl { get; set; }
public double? jzpjxl { get; set; }
public double? wfjzgzl { get; set; }
public double? ndbtjbcfjxtc { get; set; }
public double? jbpjwgzjgsjMTBF { get; set; }
}
public class Dianmodel
{
//故障强度扣分
public double? gzqdkf { get; set; }
//电气误操作次数
public double? dqwczcs { get; set; }
//继电保护正确动作率
public double? jdbhzqdzl { get; set; }
//设备故障率
public double? sbgzl { get; set; }
// 电机MTBF
public double? djMTBF { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EquipBLL.AdminManagment.MenuConfig;
using EquipBLL.AdminManagment;
using EquipModel.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using FlowEngine;
using FlowEngine.UserInterface;
using EquipModel.Context;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using EquipBLL.AdminManagment.ZyConfig;
using System.Security.Cryptography;
using System.Text;
namespace WebApp.Controllers
{
public class UserManagerController : Controller
{
private SysMenuManagment menuconfig = new SysMenuManagment();
//
// GET: /UserManager/
public ActionResult Index()
{ PersonManagment PM=new PersonManagment();
List<Person_Info> r = PM.Get_All_basePersonInfo();
return View(r);
}
public ActionResult AddUser()
{
BaseDataManagment DM = new BaseDataManagment();
List<Role_Info> R_obj = DM.GetAllRoles();
return View(R_obj);
}
public ActionResult UpdateUser(int userId)
{
PersonManagment PM = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pm_info = PM.Get_PersonModal(userId);
return View(pm_info);
}
public JsonResult List_Roles(string Role_selected)
{
PersonManagment PM = new PersonManagment();
List<EquipBLL.AdminManagment.PersonManagment.Role_viewModal> role_obj = PM.Get_All_Roles(Role_selected);
return Json(role_obj.ToArray());
}
public JsonResult List_Depart()
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> Depart_obj = DM.BuildDepartList();
return Json(Depart_obj.ToArray());
}
public JsonResult List_EquipArchi()
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> EquipArchi_obj = DM.BuildEquipArchiList();
return Json(EquipArchi_obj.ToArray());
}
public JsonResult List_Speciaties()
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> Speciaty_obj = DM.BuildSpeciatyList();
return Json(Speciaty_obj.ToArray());
}
public JsonResult List_Menus(string Role_Ids)
{
BaseDataManagment DM = new BaseDataManagment();
List<Menu> Menu_obj = DM.GetRole_Menus(Role_Ids);
List<object> r = new List<object>();
foreach (Menu item in Menu_obj)
{
object o = new
{
Menu_Id = item.Menu_Id,
Menu_Name = item.Menu_Name,
};
r.Add(o);
}
return Json(r.ToArray());
}
public JsonResult List_MenuTree(string Role_Ids)
{
BaseDataManagment DM = new BaseDataManagment();
List<TreeListNode> Menu_obj = DM.BuildMenuList(Role_Ids);
return Json(Menu_obj.ToArray());
}
public bool submitDeleteUser(int userId)
{
try
{
PersonManagment PM = new PersonManagment();
PM.Delete_Person(userId);
return true;
}
catch
{ return false; }
}
public string submitUpdateUser(string json1)
{
try
{
SpeciatyManagment SM = new SpeciatyManagment();
PersonManagment PM=new PersonManagment();
Person_Info newP=new Person_Info();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
newP.Person_Id = Convert.ToInt32(item["UserId"].ToString());
newP.Person_Name= item["UserName"].ToString();
newP.Person_tel= item["UserTel"].ToString();
newP.Person_mail=item["UserMail"].ToString();
var roleStr = item["UserRole"].ToString();
var speciatyStr = item["UserSpeciatySel"].ToString();
var MenuStr = item["UserMenus"].ToString();
var equipArchiStr = item["UserEquipArchiSel"].ToString();
int Depart_id = Convert.ToInt32(item["UserDepartId"].ToString());
List<int> EquipArchiList = new List<int>();
if (equipArchiStr != "")
{
string[] s = equipArchiStr.Split(new char[] { ',' });
for (int i = 0; i < s.Length; i++)
{ EquipArchiList.Add(Convert.ToInt32(s[i])); }
}
/* List<int> SpeciatyList = new List<int>();
if (speciatyStr != "")
{
string[] s = speciatyStr.Split(new char[] { ',' });
for (int i = 0; i < s.Length; i++)
{ SpeciatyList.Add(Convert.ToInt32(s[i])); }
}*/
List<int> SpeciatyList = new List<int>();
if (speciatyStr != "")
{
string[] s = speciatyStr.Split(new char[] { ',' });
for (int i = 0; i < s.Length; i++)
{
int id = Convert.ToInt16(s[i]);
List<Speciaty_Info> r = SM.GetChildsspecialty(id);
if (r == null)
{ if (SpeciatyList.Where(x => x == id).Count() == 0) SpeciatyList.Add(Convert.ToInt32(s[i])); }
else
{
if (SpeciatyList.Where(x => x == id).Count() == 0) SpeciatyList.Add(Convert.ToInt32(s[i]));
foreach (var t in r)
{
if (SpeciatyList.Where(x => x == t.Specialty_Id).Count() == 0) SpeciatyList.Add(Convert.ToInt32(t.Specialty_Id));
}
}
}
}
List<int> MenuList = new List<int>();
if (MenuStr != "")
{
string[] s1 = MenuStr.Split(new char[] { ',' });
for (int i = 0; i < s1.Length; i++)
{ MenuList.Add(Convert.ToInt32(s1[i])); }
}
List<int> RoleList = new List<int>();
if (roleStr != "")
{
string[] s2 = roleStr.Split(new char[] { ',' });
for (int i = 0; i < s2.Length; i++)
{ RoleList.Add(Convert.ToInt32(s2[i])); }
}
PM.Update_Person(newP, Depart_id, RoleList, EquipArchiList,SpeciatyList, MenuList); //保存基础信息
return "用户信息修改成功!";
}
catch { return ""; };
}
public string submitNewUser(string json1)
{
try
{
SpeciatyManagment SM = new SpeciatyManagment();
PersonManagment PM=new PersonManagment();
Person_Info newP=new Person_Info();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
newP.Person_Name= item["UserName"].ToString();
/*0710添加*/
var pwd = item["UserPwd"].ToString();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(pwd.Trim()));
newP.Person_Pwd = result;
/*0710end*/
newP.Person_tel= item["UserTel"].ToString();
newP.Person_mail=item["UserMail"].ToString();
var equipArchiStr=item["UserEquipArchiSel"].ToString();
var roleStr = item["UserRole"].ToString();
var speciatyStr = item["UserSpeciatySel"].ToString();
var MenuStr = item["UserMenus"].ToString();
int Depart_id = Convert.ToInt32(item["UserDepartId"].ToString());
List<int> EquipArchiList = new List<int>();
if (equipArchiStr != "")
{
string[] s = equipArchiStr.Split(new char[] { ',' });
for (int i = 0; i < s.Length; i++)
{ EquipArchiList.Add(Convert.ToInt32(s[i])); }
}
/* List<int> SpeciatyList = new List<int>();
if (speciatyStr != "")
{
string[] s = speciatyStr.Split(new char[] { ',' });
for (int i = 0; i < s.Length; i++)
{ SpeciatyList.Add(Convert.ToInt32(s[i])); }
}*/
List<int> SpeciatyList = new List<int>();
if (speciatyStr != "")
{
string[] s = speciatyStr.Split(new char[] { ',' });
for (int i = 0; i < s.Length; i++)
{
int id = Convert.ToInt16(s[i]);
List<Speciaty_Info> r = SM.GetChildsspecialty(id);
if(r==null)
{ if (SpeciatyList.Where(x=>x==id).Count()==0) SpeciatyList.Add(Convert.ToInt32(s[i]));}
else
{
if (SpeciatyList.Where(x => x == id).Count() == 0) SpeciatyList.Add(Convert.ToInt32(s[i]));
foreach(var t in r)
{
if (SpeciatyList.Where(x =>x== t.Specialty_Id).Count() == 0) SpeciatyList.Add(Convert.ToInt32(t.Specialty_Id));
}
}
}
}
List<int> MenuList = new List<int>();
if (MenuStr != "")
{
string[] s1 = MenuStr.Split(new char[] { ',' });
for (int i = 0; i < s1.Length; i++)
{ MenuList.Add(Convert.ToInt32(s1[i])); }
}
List<int> RoleList = new List<int>();
if (roleStr != "")
{
string[] s2 = roleStr.Split(new char[] { ',' });
for (int i = 0; i < s2.Length; i++)
{ RoleList.Add(Convert.ToInt32(s2[i])); }
}
PM.Add_Person(newP, Depart_id, RoleList, EquipArchiList,SpeciatyList, MenuList); //保存基础信息
return "保存成功!";
}
catch { return ""; };
}
}
}<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class WorkSum : BaseDAO
{
public bool delete(int fId)
{
try
{
using (var db = base.NewDB())
{
db.WorkSumFiles.Remove(db.WorkSumFiles.Where(s => s.File_Id == fId).First());
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using iTextSharp.text.pdf;
using iTextSharp.text;
using EquipBLL.AdminManagment.MenuConfig;
namespace WebApp.Controllers
{
public class A15dot1DianController : CommonController
{
private KpiManagement Jx = new KpiManagement();
public class submitmodel
{
public string timesNonPlanStop;//非计划停工次数
public string scoreDeductFaultIntensity;//四类以上故障强度扣分
public string rateBigUnitFault;//大机组故障率K
public string rateFaultMaintenance;//故障维修率F
public string MTBF;//一般机泵设备平均无故障间隔期MTBF
public string rateEquipUse; // 设备投用率R
public string avgLifeSpanSeal;//密封平均寿命S
public string avgLifeSpanAxle;//轴承平均寿命B
public string percentEquipAvailability;//设备完好率W
public string percentPassOnetimeRepair;//检修一次合格率
public List<Equip_Archi> UserHasEquips;
public int kkxgcs;
public int jwxry;
}
public ActionResult Index()
{
return View();
}
public ActionResult Submit()
{
submitmodel sm = new submitmodel();
ViewBag.curtime = DateTime.Now;
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
sm.UserHasEquips = pm.Get_Person_Cj((Session["User"] as EquipModel.Entities.Person_Info).Person_Id);
return View(sm);
}
public bool Submit_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
A15dot1TabDian new_15dot1Dian = new A15dot1TabDian();
new_15dot1Dian.gzqdkf = Convert.ToInt32(item["gzqdkf"].ToString());
new_15dot1Dian.dqwczcs = Convert.ToInt32(item["dqwczcs"].ToString());
new_15dot1Dian.sbgzl = Convert.ToDouble(item["sbgzl"].ToString());
new_15dot1Dian.jdbhzqdzl = Convert.ToDouble(item["jdbhzqdzl"].ToString());
new_15dot1Dian.djMTBF = Convert.ToDouble(item["djMTBF"].ToString());
new_15dot1Dian.dzdlsbMTBF = Convert.ToDouble(item["dzdlsbMTBF"].ToString());
new_15dot1Dian.zbglys = Convert.ToDouble(item["zbglys"].ToString());
new_15dot1Dian.dnjlphl = Convert.ToDouble(item["dnjlphl"].ToString());
new_15dot1Dian.temp3 = item["cjname"].ToString();
new_15dot1Dian.submitDepartment = item["submitDepartment"].ToString();
new_15dot1Dian.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
new_15dot1Dian.submitTime = DateTime.Now;
new_15dot1Dian.state = 0;
//new_15dot1.state = Convert.ToInt32(item["state"].ToString());
new_15dot1Dian.reportType = item["reportType"].ToString();
new_15dot1Dian.temp2 = "电气专业";
bool res = Jx.AddDianItem(new_15dot1Dian);
return res;
}
public ActionResult KkxSubmit(string id)
{
return View(getRecord_detail(id));
}
public class Index_ModelforA15
{
public List<A15dot1TabDian> Am;
public List<A15dot1TabDian> Hm;
public int isSubmit;
public int kkxgcs;
public int am;
public int hm;
public List<Equip_Archi> UserHasEquips;
}
public Index_ModelforA15 getRecord_detail(string id)
{
Index_ModelforA15 RecordforA15 = new Index_ModelforA15();
RecordforA15.Am = new List<A15dot1TabDian>();
//RecordforA15.Hm = new List<A15dot1Tab>();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
int IntId = Convert.ToInt32(id);
KpiManagement Jx = new KpiManagement();
List<A15dot1TabDian> miss = Jx.GetJxItem_detailDian(IntId);
foreach (var item in miss)
{
A15dot1TabDian a = new A15dot1TabDian();
//a.timesNonPlanStop = item.timesNonPlanStop;
a.gzqdkf = item.gzqdkf;
a.dqwczcs = item.dqwczcs;
a.sbgzl = item.sbgzl;
a.jdbhzqdzl = item.jdbhzqdzl;
a.djMTBF = item.djMTBF;
a.dzdlsbMTBF = item.dzdlsbMTBF;
a.zbglys = item.zbglys;
a.reportType = item.reportType;
a.dnjlphl = item.dnjlphl;
a.submitDepartment = item.submitDepartment;
a.submitUser = item.submitUser;
a.temp2 = item.temp2;
a.temp3 = item.temp3;
a.Id = item.Id;
RecordforA15.Am.Add(a);
}
string name = RecordforA15.Am[0].submitUser;
PersonManagment pm = new PersonManagment();
int UserId = pm.Get_Person(name).Person_Id;
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
RecordforA15.am = 1;
else
RecordforA15.am = 0;
// List<A15dot1TabDian> His = Jx.GetHisJxItem_detail(IntId);
// foreach (var item in His)
// {
// A15dot1Tab a = new A15dot1Tab();
// a.timesNonPlanStop = item.timesNonPlanStop;
// a.scoreDeductFaultIntensity = item.scoreDeductFaultIntensity;
// a.rateBigUnitFault = item.rateBigUnitFault;
// a.rateFaultMaintenance = item.rateFaultMaintenance;
// a.MTBF = item.MTBF;
// a.rateEquipUse = item.rateEquipUse;
// a.rateUrgentRepairWorkHour = item.rateUrgentRepairWorkHour;
// a.hourWorkOrderFinish = item.hourWorkOrderFinish;
// a.avgLifeSpanSeal = item.avgLifeSpanSeal;
// a.avgLifeSpanAxle = item.avgLifeSpanAxle;
// a.percentEquipAvailability = item.percentEquipAvailability;
// a.percentPassOnetimeRepair = item.percentPassOnetimeRepair;
// a.avgEfficiencyPump = item.avgEfficiencyPump;
// a.avgEfficiencyUnit = item.avgEfficiencyUnit;
// a.hiddenDangerInvestigation = item.hiddenDangerInvestigation;
// a.rateLoad = item.rateLoad;
// a.gyChange = item.gyChange;
// a.equipChange = item.equipChange;
// a.otherDescription = item.otherDescription;
// a.evaluateEquipRunStaeDesc = item.evaluateEquipRunStaeDesc;
// a.evaluateEquipRunStaeImgPath = item.evaluateEquipRunStaeImgPath;
// a.reliabilityConclusion = item.reliabilityConclusion;
// a.jdcAdviseImproveMeasures = item.jdcAdviseImproveMeasures;
// a.submitDepartment = item.submitDepartment;
// a.submitUser = item.submitUser;
// a.submitTime = item.submitTime;
// a.jdcOperator = item.jdcOperator;
// a.jdcOperateTime = item.jdcOperateTime;
// a.reportType = item.reportType;
// a.temp1 = Convert.ToString(miss.IndexOf(item) + 1);
// a.submitUser = item.submitUser;
// a.submitTime = item.submitTime;
// a.state = item.state;
// a.Id = item.Id;
// //增加变量--参与统计台数
// a.Count_timesNonPlanStop = item.Count_timesNonPlanStop;
// a.Count_scoreDeductFaultIntensity = item.Count_scoreDeductFaultIntensity;
// a.Count_rateBigUnitFault = item.Count_rateBigUnitFault;
// a.Count_rateFaultMaintenance = item.Count_rateFaultMaintenance;
// a.Count_MTBF = item.Count_MTBF;
// a.Count_rateEquipUse = item.Count_rateEquipUse;
// a.Count_avgLifeSpanSeal = item.Count_avgLifeSpanSeal;
// a.Count_avgLifeSpanAxle = item.Count_avgLifeSpanAxle;
// a.Count_percentEquipAvailability = item.Count_percentEquipAvailability;
// a.Count_percentPassOnetimeRepair = item.Count_percentPassOnetimeRepair;
// RecordforA15.Hm.Add(a);
// }
// name = RecordforA15.Hm[0].submitUser;
// UserId = pm.Get_Person(name).Person_Id;
// pv = pm.Get_PersonModal(UserId);
// if (pv.Role_Names.Contains("可靠性工程师"))
// RecordforA15.hm = 1;
// else
// RecordforA15.hm = 0;
return RecordforA15;
}
//public JsonResult Modify_submitsignal(string json1)
//{
// JObject item = (JObject)JsonConvert.DeserializeObject(json1);
// A15dot1TabDian new_15dot1Dian = new A15dot1TabDian();
// new_15dot1Dian.Id = Convert.ToInt32(item["A15dot1Dian_id"].ToString());
// new_15dot1Dian.gzqdkf = Convert.ToInt32(item["gzqdkf"].ToString());
// new_15dot1Dian.dqwczcs = Convert.ToInt32(item["dqwczcs"].ToString());
// new_15dot1Dian.sbgzl = Convert.ToDouble(item["sbgzl"].ToString());
// new_15dot1Dian.jdbhzqdzl = Convert.ToDouble(item["jdbhzqdzl"].ToString());
// new_15dot1Dian.djMTBF = Convert.ToDouble(item["djMTBF"].ToString());
// new_15dot1Dian.dzdlsbMTBF = Convert.ToDouble(item["dzdlsbMTBF"].ToString());
// new_15dot1Dian.zbglys = Convert.ToDouble(item["zbglys"].ToString());
// new_15dot1Dian.dnjlphl = Convert.ToDouble(item["dnjlphl"].ToString());
// new_15dot1Dian.state = Convert.ToInt32(item["state"].ToString());
// new_15dot1Dian.reliabilityConclusion = item["reliabilityConclusion"].ToString();
// new_15dot1Dian.temp3 = item["cjname"].ToString();
// new_15dot1Dian.submitDepartment = item["submitDepartment"].ToString();
// new_15dot1Dian.submitUser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// new_15dot1Dian.submitTime = DateTime.Now;
// new_15dot1Dian.reportType = item["reportType"].ToString();
// bool res = Jx.ModifyJxItem(new_15dot1Dian);
// return Json(new { result = res });
//}
public string qst(string grahpic_name, string zzname)
{
List<object> res = Jx.qst(grahpic_name, zzname);
string str = JsonConvert.SerializeObject(res);
return (str);
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
namespace WebApp.Controllers
{
public class A4dot2Controller : CommonController
{
public ActionResult Index()
{
return View(getIndexListRecords("A4dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
public ActionResult CaiGouSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));//
}
public ActionResult WzcPriceBatch(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdConfirmEquip(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdTechSign(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult PqTechSign(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdAppoint(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UploadBidFile(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/确定中标单位
public ActionResult WzcConfirmSupplier(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/专业团队确定是否需要监造明细
public ActionResult ZytdConfirmJZ(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/上传监造反馈文件
public ActionResult JZEquipDetail(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/ 物资处通知验收
public ActionResult WzcNoticeCheck(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/专业团队指定验收人员
public ActionResult ZytdAppointCheck(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/验收人员确定已验收
public ActionResult CheckPersonConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/物资处发出到货通知
public ActionResult WzcNoticeArrived(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/工程管理开箱验收
public ActionResult CMWriConKXD(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot2/工程管理确认移交是否完成
public ActionResult CMConfirmHandover(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string CaiGouSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CaiGouSubmit_Done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = "";
signal["Plan_Order"] = item["Plan_Order"].ToString();
signal["Plan_Name"] = item["Plan_Name"].ToString();
signal["CM_Department"] = item["CM_Department"].ToString();
signal["Fittings_Name"] = item["Fittings_Name"].ToString();
signal["Fittings_Code"] = item["Fittings_Code"].ToString();
//EquipManagment em = new EquipManagment();
//Equip_Info eqinfo = em.getEquip_Info(item["Equip_Code"].ToString());
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
//由于DongZyConfirm_done 等变量未与该Event关联, 所以submitSignal不会将确认信息提交到工作流
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string WzcPriceBatch_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["Job_Order"] = item2["Plan_num"].ToString();
signal["Purchase_Batch"] = item["Purchase_Batch"].ToString();
signal["Budgeted_Price"] = item["Budgeted_Price"].ToString();
signal["IsMoreThanFifty_Result"] = item["IsMoreThanFifty_Result"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string ZytdConfirmEquip_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["Job_Order"] = item2["Plan_num"].ToString();
signal["TechSign_Person"] = item["TechSign_Person"].ToString();
signal["Supplier_List"] = item["Supplier_List"].ToString();
signal["IsVIPEquip_Result"] = item["IsVIPEquip_Result"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string ZytdTechSign_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["Job_Order"] = item2["Plan_num"].ToString();
signal["TechAgreement_File"] = item["TechAgreement_File"].ToString();
signal["ZytdTechSign_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string PqTechSign_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["Job_Order"] = item2["Plan_num"].ToString();
signal["TechAgreement_File"] = item["TechAgreement_File"].ToString();
signal["PqTechSign_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string ZytdAppoint_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["Job_Order"] = item2["Plan_num"].ToString();
signal["TechDemandMake_Header"] = item["TechDemandMake_Header"].ToString();
signal["TechDemandMake_Person"] = item["TechDemandMake_Person"].ToString();
signal["Supplier_List"] = item["Supplier_List"].ToString();
signal["ZytdAppoint_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string UploadBidFile_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["Job_Order"] = item2["Plan_num"].ToString();
signal["Bid_File"] = item["Bid_File"].ToString();
signal["UploadBidFile_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string BidSupplier_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["WzcConfirmSupplier_Done"] = "true";
signal["Bid_Supplier"] = item["Bid_Supplier"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot2/Index");
}
public string ZytdConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JZEquip_Detail"] = item["JZEquip_Detail"].ToString();
signal["ZytdConfirmJZ_Result"] = item["ZytdConfirmJZ_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot2/Index");
}
//上传明细文件JZEquipDetail_submitsignal
public string JZEquipDetail_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
//signal["JZEquip_Detail"] = item["JZEquip_Detail"].ToString();
signal["JZEquip_File"] = item["JZEquip_File"].ToString();
signal["JZEquipDetail_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot2/Index");
}
public string WZC_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
// signal["ZytdConfirm_Result"] = item["ZytdConfirm_Result"].ToString();
signal["WzcNoticeCheck_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot2/Index");
}
public string Check_Person_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["Check_Person"] = item["Check_Person"].ToString();
signal["Check_Header"] = item["Check_Header"].ToString();
signal["ZytdAppointCheck_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot2/Index");
}
public string CheckPersonConfirm_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["CheckPersonConfirm_Result"] = "是";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot2/Index");
}
public string WzcNoticeArrived_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["WzcNoticeArrived_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot2/Index");
}
public string CMWriConKXD_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["CMConfirmKXD_Result"] = item["CMConfirmKXD_Result"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot2/Index");
}
public string CMConfirmHandover_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//new input paras
signal["CMConfirmHandover_Done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot2/Index");
}
}
}<file_sep>using FlowEngine.Modals;
using FlowEngine.TimerManage;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.Event
{
class CWaitingEvent : CEvent
{
private struct WaitingTime{
public int Minute;
public int Hours;
public int Days;
public int Months;
public int Years;
}
#region 构造函数
public CWaitingEvent(CWorkFlow parent) : base(parent)
{
m_timer.AttachWFEntity(parent);
m_timer.for_using = TIMER_USING.FOR_SYSTEM;
m_timer.SetRunParam(WE_STATUS.ACTIVE);
}
~CWaitingEvent()
{
}
#endregion
#region 属性
/// <summary>
/// 与之关联的定时性任务
/// </summary>
public CTimerWFStatus m_timer = new CTimerWFStatus();
public int m_timerID = -1;
private WaitingTime m_waitingTime = new WaitingTime() { Minute = 0, Hours = 0, Days = 0, Months = 0, Years = 0};
#endregion
#region 公共接口
/// <summary>
/// 不能序列化为XML node
/// </summary>
/// <param name="xmlNode"></param>
public override void InstFromXmlNode(System.Xml.XmlNode xmlNode)
{
return;
}
public override System.Xml.XmlNode WriteToXmlNode()
{
return null;
}
/// <summary>
/// 进入该事件
/// </summary>
/// <param name="strjson"></param>
public override void EnterEvent(string strjson)
{
base.UpdateCurrentEvent();
Parent.UpdateEntity(WE_STATUS.SUSPEND);
DateTime dt = DateTime.Now;
dt = dt.AddYears(m_waitingTime.Years);
dt = dt.AddMonths(m_waitingTime.Months);
dt = dt.AddDays(m_waitingTime.Days);
dt = dt.AddHours(m_waitingTime.Hours);
dt = dt.AddMinutes(m_waitingTime.Minute);
string strCorn = string.Format("{0} {1} {2} {3} {4} {5} {6}",
0,
dt.Minute,
dt.Hour,
dt.Day,
dt.Month,
"?",
dt.Year);
m_timer.SetTriggerTiming(strCorn);
m_timer.CreateTime = DateTime.Now;
m_timer.AttachWFEntity(Parent);
m_timer.Save();
m_timerID = m_timer.ID;
CTimerManage.AppendMissionToActiveList(m_timer);
//m_timeout.RegTimeoutTimer(false);
}
/// <summary>
/// 离开该事件
/// </summary>
/// <param name="strjson"></param>
public override void LeaveEvent(string strjson)
{
//保存信息到数据库
//base.InsertMissionToDB();
//m_timeout.UnregTimeoutTimer();
var t = CTimerManage.LoadTimerMission(m_timerID);
if (t != null)
{
t.status = TM_STATUS.TM_FINISH;
t.Save();
CTimerManage.RemoveFromActiveList(t.ID);
}
}
/// <summary>
/// 设置等待时间间隔
/// </summary>
/// <param name="str_waiting">"H D M Y"</param>
/// <returns></returns>
public bool SetWaitingTime(string str_waiting)
{
var subs = str_waiting.Split(new char[] { ' ' });
if (subs.Length != 5)
return false;
try
{
m_waitingTime.Minute = Convert.ToInt32(subs[0]);
m_waitingTime.Hours = Convert.ToInt32(subs[1]);
m_waitingTime.Days = Convert.ToInt32(subs[2]);
m_waitingTime.Months = Convert.ToInt32(subs[3]);
m_waitingTime.Years = Convert.ToInt32(subs[4]);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 获得等待时间字符串表达格式
/// </summary>
/// <returns></returns>
public string GetWaitingTime()
{
return string.Format("{0} {1} {2} {3} {4}", m_waitingTime.Minute, m_waitingTime.Hours, m_waitingTime.Days, m_waitingTime.Months, m_waitingTime.Years);
}
#endregion
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using EquipModel.Entities;
using System;
namespace EquipDAL.Implement
{
public class A6dot2Tabs : BaseDAO
{
public class WDT_PqTj
{
public string pqName;
public int tjNum;
}
public class WDT_CjTj
{
public string pqName;
public string cjName;
public int tjNum;
}
public class WDT_ZzTj
{
public string pqName;
public string cjName;
public string zzName;
public int tjNum;
}
public A6dot2Tab1 get_WDTInfo(int Id)
{
using (var db = base.NewDB())
{
return db.A6dot2Tab1.Where(a => a.Id == Id).First();
}
}
public List<EquipModel.Entities.A6dot2Tab1> getWDTList(string startTime, string endTime)
{
using (var db = base.NewDB())
{
return db.A6dot2Tab1.Where(a => a.uploadtime.CompareTo(startTime) > 0 && a.uploadtime.CompareTo(endTime) < 0).ToList();
}
}
public List<EquipModel.Entities.A6dot2Tab2> getCQList(string pqName, string startTime, string endTime)
{
using (var db = base.NewDB())
{
return db.A6dot2Tab2.Where(x => x.equip_PqName == pqName && x.isValid == 1 && x.isOilType == 1 && x.isExceed == 1 && x.Tab1_Belong.uploadtime.CompareTo(startTime) >= 0 && x.Tab1_Belong.uploadtime.CompareTo(endTime) <= 0).ToList();
}
}
public List<EquipModel.Entities.A6dot2Tab2> getCQListId(int Id,string pqName )
{
using (var db = base.NewDB())
{
return db.A6dot2Tab2.Where(x => x.equip_PqName == pqName && x.Tab1_Id == Id && x.isValid == 1 && x.isOilType == 1 && x.isExceed == 1).ToList();
}
}
public List<EquipModel.Entities.A6dot2Tab1> getWDTList()
{
using (var db = base.NewDB())
{
return db.A6dot2Tab1.ToList();
}
}
public List<WDT_PqTj> PqGroup(string starttime, string endtime)
{
using (var db = base.NewDB())
{
var a = db.A6dot2Tab2.Where(x => x.isValid == 1 && x.isOilType == 1 && x.Tab1_Belong.uploadtime.CompareTo(starttime) >= 0 && x.Tab1_Belong.uploadtime.CompareTo(endtime) <= 0).GroupBy(x => new { x.equip_PqName }).Select(g => new { PqName = g.Key.equip_PqName, ExceedNum = g.Sum(x => x.isExceed) });
//var b = db.A6dot2Tab2.Where(x => x.isValid == 1 && x.isOilType == 1).First().Tab1_Belong.uploadtime;
List<WDT_PqTj> r = new List<WDT_PqTj>();
foreach (var item in a)
{
WDT_PqTj tmp = new WDT_PqTj();
tmp.pqName = item.PqName;
tmp.tjNum = item.ExceedNum;
r.Add(tmp);
}
return r;
}
}
public List<WDT_PqTj> PqGroup(int Id)
{
using (var db = base.NewDB())
{
var a = db.A6dot2Tab2.Where(x => x.isValid == 1 && x.isOilType == 1 && x.Tab1_Id == Id).GroupBy(x => new { x.equip_PqName }).Select(g => new { PqName = g.Key.equip_PqName, ExceedNum = g.Sum(x => x.isExceed) });
List<WDT_PqTj> r = new List<WDT_PqTj>();
foreach (var item in a)
{
WDT_PqTj tmp = new WDT_PqTj();
tmp.pqName = item.PqName;
tmp.tjNum = item.ExceedNum;
r.Add(tmp);
}
return r;
}
}
public List<WDT_CjTj> CjGroup(string starttime, string endtime)
{
using (var db = base.NewDB())
{
var a = db.A6dot2Tab2.Where(x => x.isValid == 1 && x.isOilType == 1 && x.Tab1_Belong.uploadtime.CompareTo(starttime) >= 0 && x.Tab1_Belong.uploadtime.CompareTo(endtime) <= 0).GroupBy(x => new { x.equip_PqName, x.equip_CjName }).Select(g => new { PqName = g.Key.equip_PqName, cjName = g.Key.equip_CjName, ExceedNum = g.Sum(x => x.isExceed) });
List<WDT_CjTj> r = new List<WDT_CjTj>();
foreach (var item in a)
{
WDT_CjTj tmp = new WDT_CjTj();
tmp.pqName = item.PqName;
tmp.cjName = item.cjName;
tmp.tjNum = item.ExceedNum;
r.Add(tmp);
}
return r;
}
}
public List<WDT_CjTj> CjGroup(int Id)
{
using (var db = base.NewDB())
{
var a = db.A6dot2Tab2.Where(x => x.isValid == 1 && x.isOilType == 1 && x.Tab1_Id == Id).GroupBy(x => new { x.equip_PqName, x.equip_CjName }).Select(g => new { PqName = g.Key.equip_PqName, cjName = g.Key.equip_CjName, ExceedNum = g.Sum(x => x.isExceed) });
List<WDT_CjTj> r = new List<WDT_CjTj>();
foreach (var item in a)
{
WDT_CjTj tmp = new WDT_CjTj();
tmp.pqName = item.PqName;
tmp.cjName = item.cjName;
tmp.tjNum = item.ExceedNum;
r.Add(tmp);
}
return r;
}
}
public List<WDT_ZzTj> ZzGroup(string starttime, string endtime)
{
using (var db = base.NewDB())
{
var a = db.A6dot2Tab2.Where(x => x.isValid == 1 && x.isOilType == 1 && x.Tab1_Belong.uploadtime.CompareTo(starttime) >= 0 && x.Tab1_Belong.uploadtime.CompareTo(endtime) <= 0).GroupBy(x => new { x.equip_PqName, x.equip_CjName, x.equip_ZzName }).Select(g => new { PqName = g.Key.equip_PqName, cjName = g.Key.equip_CjName, zzName = g.Key.equip_ZzName, ExceedNum = g.Sum(x => x.isExceed) });
List<WDT_ZzTj> r = new List<WDT_ZzTj>();
foreach (var item in a)
{
WDT_ZzTj tmp = new WDT_ZzTj();
tmp.pqName = item.PqName;
tmp.cjName = item.cjName;
tmp.zzName = item.zzName;
tmp.tjNum = item.ExceedNum;
r.Add(tmp);
}
return r;
}
}
public List<WDT_ZzTj> ZzGroup(int Id)
{
using (var db = base.NewDB())
{
var a = db.A6dot2Tab2.Where(x => x.isValid == 1 && x.isOilType == 1 && x.Tab1_Id == Id).GroupBy(x => new { x.equip_PqName, x.equip_CjName, x.equip_ZzName }).Select(g => new { PqName = g.Key.equip_PqName, cjName = g.Key.equip_CjName, zzName = g.Key.equip_ZzName, ExceedNum = g.Sum(x => x.isExceed) });
List<WDT_ZzTj> r = new List<WDT_ZzTj>();
foreach (var item in a)
{
WDT_ZzTj tmp = new WDT_ZzTj();
tmp.pqName = item.PqName;
tmp.cjName = item.cjName;
tmp.zzName = item.zzName;
tmp.tjNum = item.ExceedNum;
r.Add(tmp);
}
return r;
}
}
public A6dot2Tab1 Add_A6dot2Tab1(A6dot2Tab1 New_Tab1)
{
try
{
using (var db = base.NewDB())
{
A6dot2Tab1 newP = db.A6dot2Tab1.Add(New_Tab1);
db.SaveChanges();
return newP;
}
}
catch
{
return null;
}
}
public int Add_A6dot2Tab2(int id, List<A6dot2Tab2> New_Tab2s)
{
try
{
using (var db = base.NewDB())
{
var p = db.A6dot2Tab1.Where(a => a.Id == id).First();
foreach (var item in New_Tab2s)
{ p.WDTable_details.Add(item); }
db.SaveChanges();
return 1;
}
}
catch
{
return 0;
}
}
//向File_Info中写数据
public bool AddFiletoCatalog(int pID, File_Info nf)
{
try
{
using (var db = base.NewDB())
{
db.FCatalogs.Where(s => s.Catalog_Id == pID).First().Files_Included.Add(nf);
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
//通过上传时间找到File_Id(其实可以与AddFiletoCatalog合并,返回File_Id)
public int getfileid(DateTime time)
{
try
{
using (var db = base.NewDB())
{
var p = db.Files.Where(a => a.File_UploadTime == time).First().File_Id;
return p;
}
}
catch
{
return 0;
}
}
/// <summary>
/// 通过设备编号来获得Equip_Id
/// </summary>
/// <param name="sbcode"></param>
/// <returns></returns>
public int getequipid(string sbcode)
{
try
{
using (var db = base.NewDB())
{
var p = db.Equips.Where(a => a.Equip_Code == sbcode).First().Equip_Id;
return p;
}
}
catch
{
return 0;
}
}
public List<EQ> getguicheng()
{
List<EQ> c = new List<EQ>();
try
{
using (var db = base.NewDB())
{
List<File_Info> p = db.Files.Where(a => a.Self_Catalog.Catalog_Id == 28).ToList();//跨表查询Self_Catalog.Catalog_Id
for (int i = 0; i < p.Count; i++)
{
for (int k = 0; k < p[i].File_Equips.Count; k++)//存在文件对应的设备才进入,File_Equips.Count只可能等于一
{
Equip_Info[] zz = new Equip_Info[1];
p[i].File_Equips.CopyTo(zz, 0);
EQ temp = new EQ();
temp.sbGyCode = zz[0].Equip_GyCode;
temp.sbCode = zz[0].Equip_Code;
temp.sbType = zz[0].Equip_Type;
temp.GCnewname = p[i].File_NewName;
temp.GColdname = p[i].File_OldName;
c.Add(temp);
}
}
return c;
}
}
catch
{
return c;
}
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.Modals;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Xml;
using FlowEngine.Event;
using FlowEngine.DAL;
namespace WebApp.Controllers
{
public class A4dot4Controller : CommonController
{
//
// GET: /A4dot4/
public ActionResult Index()
{
return View(getIndexListRecords("A4dot4", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A4dot4/装置提报
public ActionResult SySubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}//车间现场工程师编写设备试运方案
public ActionResult WriteSyPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}//编写设备试运方案
public ActionResult ZytdConfirmPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}//专业团队组织审核方案
public ActionResult ZzSy(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}//现场工程师组织设备试运
public ActionResult SyReform(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}//设备试运整改确认
public ActionResult PqConfirmSy(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//可靠性工程师组织设备试运
public ActionResult CMUploadSy(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//工程管理单位上传试运记录
public ActionResult ZytdConfirmSyRecord(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}// 专业团队审核试运记录
public ActionResult CMUpload(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}//工程单位
public ActionResult JscConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}//技术处确认竣工资料
//erp进入
public ActionResult ERP(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult JumpToA3dot3(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A4dot4/跳转到其它模块--仅用于测试
/* public ActionResult JumpToAx(string wfe_id)
{
UI_MISSION miModel = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.MODULE_NAME = miModel.Miss_Params["temp_ModuleName"].ToString();//根据可靠性工程师分类结果,得到跳转的模块名,并传参数
return View(getWFDetail_Model(wfe_id));
}
*/
// 人工提报
public string SySubmit_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
// signal["submit_user"] = item["submit_user"].ToString();
signal["SySubmit_Done"] = "true";
signal["Plan_Name"] = item["Plan_Name"].ToString();
signal["Plan_Order"] = item["Plan_Order"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["CM_Department"] = item["CM_Department"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
// 设备试运方案
public string WriteSyPlan_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
// signal["submit_user"] = item["submit_user"].ToString();
signal["WriteSyPlan_Done"] = "true";
signal["SyPlan"] = item["SyPlan"].ToString();
signal["SyPlan_File"] = item["SyPlan_File"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
//试运方案
public string ZytdConfirmPlan_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirmPlan_Result"] = item["ZytdConfirmPlan_Result"].ToString();
//signal["SyfaConfirm_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
// 试运条件
public string ZzSy_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
// signal["Confirm_result"] = item["Confirm_result"].ToString();
// signal["ZzSy_Done"] = "true";
signal["ZzSy_Done"] = item["ZzSy_Done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
// 试运结果
public string PqConfirmSy_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirmSy_Result"] = item["PqConfirmSy_Result"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
// 设备试运整改
public string SyReform_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["SyReform_Done"] = item["SyReform_Done"].ToString();
// signal["SyReform_Done"] = "true";
////DangerType_isgreen:需要根据逻辑判断
//UI_MISSION miModel = CWFEngine.GetActiveMission<Person_Info>(int.Parse(flowname), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
//RiskMatrixElement rme = riskMatrixAnalysis(miModel.Miss_Params["Danger_Intensity"].ToString(), miModel.Miss_Params["Time_Level"].ToString());
//signal["DangerType_isgreen"] = rme.DangerType_isgreen;
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
// 上传试运记录
public string CMUploadSy_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
// signal["submit_user"] = item["submit_user"].ToString();
signal["UploadSy_Done"] = "true";
signal["SyRecord_File"] = item["SyRecord_File"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
// 专业团队审核试运记录
public string ZytdConfirmSyRecord_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirmSyRecord_Result"] = item["ZytdConfirmSyRecord_Result"].ToString();
// signal["ZytdConfirmSyRecord_Result"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
// 工程管理单位上传竣工资料
public string CMUpload_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
// signal["submit_user"] = item["submit_user"].ToString();
signal["CMUpload_Done"] = "true";
signal["Js_File"] = item["Js_File"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
//技术处确认存档
public string JscConfirm_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JscConfirm_Result"] = item["JscConfirm_Result"].ToString();
// signal["JscConfirm_done"] = "true";
////DangerType_isgreen:需要根据逻辑判断
//UI_MISSION miModel = CWFEngine.GetActiveMission<Person_Info>(int.Parse(flowname), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
//RiskMatrixElement rme = riskMatrixAnalysis(miModel.Miss_Params["Danger_Intensity"].ToString(), miModel.Miss_Params["Time_Level"].ToString());
//signal["DangerType_isgreen"] = rme.DangerType_isgreen;
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot4/Index");
}
public string JumpToA3dot3_submitsignal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
string mname = item["module_name"].ToString();
signal["JumpToA3dot3_Done"] = item["JumpToA3dot3_Done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A4dot4/Index");
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Collections;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A11dot2Controller : CommonController
{
EquipManagment Em = new EquipManagment();
//
// GET: /A11dot2/
public ActionResult Index()
{
return View(getIndexListRecords("A11dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A11dot2/装置提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A11dot2/可靠性工程师风险矩阵评估
public ActionResult PqAssess(string wfe_id)
{
//判断是否为专家团队不同意,需要重新评估的
int num_HistoryMissions = CWFEngine.GetHistoryMissions(int.Parse(wfe_id)).Count;
if(num_HistoryMissions>=4)
ViewBag.zjtdOpinion = 0;
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/专业团队审核
public ActionResult ZytdConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/车间确立应急预案
public ActionResult CjCreatePlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/车间组织和实施应急方案
public ActionResult CjImplementPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/可靠性工程师监督执行
public ActionResult PqSupervise(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/车间确立管控措施
public ActionResult CjMngCtlPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/可靠性工程师审核车间管控措施
public ActionResult PqConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/车间组织监督实施
public ActionResult CjSupervise(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/专业团队确立管控措施
public ActionResult PgxzMngCtlPlan(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/机动处组织监督实施
public ActionResult JdcSupervise(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/确认风险是否可控,并进行风险登记
public ActionResult RiskAcceptRecord(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/确认风险是否消除,并进行风险登记
public ActionResult RiskCleanRecord(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A11dot2/跳转到[A11.3]风险管控模块--仅用于测试
public ActionResult JumpToA11dot3(string wfe_id)
{
ViewBag.WF_NAME = wfe_id;
ViewBag.MODULE_NAME = "【A11.3】风险管控模块";
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//一级菜单
public ActionResult A11()
{
return View();
}
public ActionResult fengxiandengji()
{
return View();
}
public string submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
signal["Problem_Desc"] = item["Problem_Desc"].ToString();
signal["Problem_DescFilePath"] = item["Problem_DescFilePath"].ToString();
signal["Zy_Type"] = item["Zy_Type"].ToString();
signal["Zy_SubType"] = item["Zy_SubType"].ToString();
EquipManagment em = new EquipManagment();
signal["Equip_ABCMark"] = em.getEquip_Info(item["Equip_Code"].ToString()).Equip_ABCmark;
//signal["Equip_ABCMark"] = "A";//for test
signal["Data_Src"] = "人工提报"; //格式统一
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string submitAssess_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
string Danger_Intensity = item["Danger_Intensity"].ToString();
string Time_Level = item["Time_Level"].ToString();
signal["Danger_Intensity"] = Danger_Intensity;
signal["Time_Level"] = Time_Level;
//RiskMatrix_Color,DangerType_isgreen:根据逻辑判断
RiskMatrixElement rme = riskMatrixAnalysis(Danger_Intensity, Time_Level);
signal["RiskMatrix_Color"] = rme.color;
signal["DangerType_isgreen"] = rme.DangerType_isgreen;
signal["Assess_done"] = "true";
//record:
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string submitZytdConfirm_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdConfirm_Result"] = item["ZytdConfirm_Result"].ToString();
signal["ZytdConfirm_Reason"] = item["ZytdConfirm_Reason"].ToString();
////DangerType_isgreen:需要根据逻辑判断
//UI_MISSION miModel = CWFEngine.GetActiveMission<Person_Info>(int.Parse(flowname), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
//RiskMatrixElement rme = riskMatrixAnalysis(miModel.Miss_Params["Danger_Intensity"].ToString(), miModel.Miss_Params["Time_Level"].ToString());
//signal["DangerType_isgreen"] = rme.DangerType_isgreen;
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
//风险矩阵分析
public RiskMatrixElement riskMatrixAnalysis(string Danger_Intensity, string Time_Level)
{
string DangerType_isgreen = "";
string color = "";
int danger_intensity=int.Parse(Danger_Intensity.Substring(1,1));
int time_level=int.Parse(Time_Level.Substring(1,1));
if ((danger_intensity == 1 && time_level <= 3) || (danger_intensity == 2 && time_level <= 2))
{
color = "red";
DangerType_isgreen = "false";
}
else if (danger_intensity >= 5 || (danger_intensity == 4 && time_level >= 2) || (danger_intensity == 3 && time_level >= 3))
{
color = "green";
DangerType_isgreen = "true";
}
else
{
color = "yellow";
DangerType_isgreen = "false";
}
//
RiskMatrixElement rme = new RiskMatrixElement();
rme.danger_intensity = danger_intensity;
rme.time_level = time_level;
rme.color = color;
rme.DangerType_isgreen = DangerType_isgreen;
return rme;
}
public string submitCreatePlan_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//paras
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
signal["CreatePlan_done"] = "true";
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string submitImplementPlan_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//paras
signal["ImplementPlan_done"] = item["ImplementPlan_done"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string submitSupervise_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//paras
signal["Supervise_done"] = item["Supervise_done"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string CjMngCtlPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CreatePlan_done"] = item["CreatePlan_done"].ToString();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string PqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqConfirm_done"] = item["PqConfirm_done"].ToString();
signal["PqConfirm_Result"] = item["PqConfirm_Result"].ToString();
signal["PqConfirm_Reason"] = item["PqConfirm_Reason"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string CjSupervise_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ImplementPlan_done"] = item["ImplementPlan_done"].ToString();
signal["flag_NandD"] = "一般风险";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string PgxzMngCtlPlan_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["CreatePlan_done"] = item["CreatePlan_done"].ToString();
signal["Plan_Desc"] = item["Plan_Desc"].ToString();
signal["Plan_DescFilePath"] = item["Plan_DescFilePath"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string JdcSupervise_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ImplementPlan_done"] = item["ImplementPlan_done"].ToString();
signal["flag_NandD"] = "重大风险";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
public string RiskAcceptRecord_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["RiskAcceptRecord_done"] = item["RiskAcceptRecord_done"].ToString();
signal["RiskIsAcceptable"] = item["Risk_IsAcceptable"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A11dot2/Index");
}
//test
public string submitA11dot3_signal(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
Dictionary<string, string> signal = new Dictionary<string, string>();
//paras
signal["temp_A11dot3"] = item["temp_A11dot3"].ToString();
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
return ("/A11dot2/Index");
}
public ActionResult WorkFolw_DetailforA11(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public class Gxqmodel
{
public string WE_Ser;
public int WE_Id;
}
//=========================2016.8.7by XuS===========================================================
/// <summary>
/// 删除重复行,若查询条件有时间,则会将一个流水号的所有事件查询出来,下面两个函数可将流水号筛选一遍剔除重复
/// </summary>
/// <param name="indexList"></param>
/// <param name="index"></param>
/// <returns></returns>
public static bool IsContain(ArrayList indexList, int index)
{
for (int i = 0; i < indexList.Count; i++)
{
int tempIndex = Convert.ToInt32(indexList[i]);
if (tempIndex == index)
{
return true;
}
}
return false;
}
public static DataTable DeleteSameRow(DataTable dt, string Field)
{
ArrayList indexList = new ArrayList();
if (dt.Rows.Count > 1)
{
// 找出待删除的行索引
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
if (!IsContain(indexList, i))
{
for (int j = i + 1; j < dt.Rows.Count; j++)
{
if (dt.Rows[i][Field].ToString() == dt.Rows[j][Field].ToString())
{
indexList.Add(j);
}
}
}
}
// 根据待删除索引列表删除行
for (int i = indexList.Count - 1; i >= 0; i--)
{
int index = Convert.ToInt32(indexList[i]);
dt.Rows.RemoveAt(index);
}
}
return dt;
}
//========================================================================================================
public string A11MissList(string WorkFlow_Name)
{
string username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
DateTime nowtime = DateTime.Now;
string record_filter;
string WE_Status = "0";
string query_list = "distinct E.WE_Ser, E.WE_Id, R.username,R.time";
string query_condition = "E.W_Name='" + WorkFlow_Name + "' and R.username is not null";
record_filter = "time >= '" + nowtime.Year + "/" + nowtime.Month + "/" + "1" + " 00:00:00'" + "and time <= '" + nowtime.AddMonths(1).Year + "/" + nowtime.AddMonths(1).Month + "/" + "1" + " 00:00:00'";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
DataTable dt2= DeleteSameRow( dt,"WE_Ser");
//DataView dv = new DataView(dt); //虚拟视图吧,我这么认为
//DataTable dt2 = dv.ToTable(true, "WE_Ser","WE_Id");
List<Gxqmodel> Gmlist = new List<Gxqmodel>();
for (int i = 0; i < dt2.Rows.Count; i++)
{
Gxqmodel Gm = new Gxqmodel();
Gm.WE_Id = Convert.ToInt16(dt.Rows[i]["WE_Id"]);
Gm.WE_Ser = dt.Rows[i]["WE_Ser"].ToString();
Gmlist.Add(Gm);
}
List<HistroyModel> Hm = new List<HistroyModel>();
foreach (var item in Gmlist)
{
HistroyModel h = new HistroyModel();
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Equip_GyCode"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(item.WE_Id, paras);
List<UI_MISSION> AllHistoryMiss = CWFEngine.GetHistoryMissions(item.WE_Id);
int Miss_Id = AllHistoryMiss[0].Miss_Id;
h.miss_LastStatusdesc = AllHistoryMiss[AllHistoryMiss.Count - 1].WE_Event_Desc;
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(Miss_Id);
if (r.Count > 0)
{
h.missStartName = r["username"];
h.missStartTime = r["time"];
}
else
{
h.missStartName = "";
h.missStartTime = "";
}
h.wfe_serial = item.WE_Ser;
// h.miss_wfe_Id = wfei.EntityID;
h.miss_wfe_Id = item.WE_Id;
h.workFlowName = wfei.description;
h.sbGycode = paras["Equip_GyCode"].ToString();
Hm.Add(h);
}
List<object> or = new List<object>();
for (int i = 0; i < Hm.Count; i++)
{
object o = new
{
wfe_serial = Hm[i].wfe_serial,
equip_gycode = Hm[i].sbGycode,
workflow_name = Hm[i].workFlowName,
missStartName = Hm[i].missStartName,
missStartTime = Hm[i].missStartTime,
miss_LastStatusdesc = Hm[i].miss_LastStatusdesc,
miss_wfe_Id = Hm[i].miss_wfe_Id
};
or.Add(o);
}
string str = JsonConvert.SerializeObject(or);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class yimodel //仪
{
//故障强度扣分
public double ?gzqdkf { get; set; }
//联锁系统正确动作率
public double ?lsxtzqdzl { get; set; }
// 控制系统故障次数
public double ?kzxtgzcs { get; set; }
//仪表控制率
public double ?ybkzl { get; set; }
//仪表实际控制率
public double ?ybsjkzl { get; set; }
//联锁系统投用率
public double ?lsxttyl { get; set; }
//关键控制阀门故障次数
public double ?gjkzfmgzcs { get; set; }
//控制系统故障报警次数
public double ?kzxtgzbjcs { get; set; }
// 常规仪表故障率
public double ?cgybgzl { get; set; }
//调节阀门MTBF
public double ?tjfMDBF { get; set; }
}
}
<file_sep>using FlowEngine;
using FlowEngine.DAL;
using FlowEngine.Modals;
using FlowEngine.TimerManage;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using WebApp.Models.DateTables;
using EquipBLL.AdminManagment;
using EquipBLL.AdminManagment.MenuConfig;
namespace WebApp.Controllers
{
public class TempJobController : CommonController
{
WorkFlows wfs = new WorkFlows();
EquipArchiManagment Em = new EquipArchiManagment();
// GET: JobsManagement
public ActionResult Index()
{
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("专业团队") || pv.Role_Names.Contains("专家团队") || pv.Role_Names.Contains("专业团队负责人"))
ViewBag.zytd = 1;
else
ViewBag.zytd = 0;
return View();
}
public ActionResult A6dot2Mission(string wfe_id)
{
ViewBag.flows = CWFEngine.ListAllWFDefine();
return View();
}
public ActionResult createmission(string wfe_id)
{
ViewBag.flows = CWFEngine.ListAllWFDefine();
return View(getSubmitModel(wfe_id));
}
[HttpPost]
public JsonResult GetTimerJobs()
{
List<CTimerMission> miss = CTimerManage.GetTimerJobsForCustom();
List<object> res = new List<object>();
for (int i = 0; i < miss.Count; i++)
{
var m = miss[i];
CWorkFlow wf = m.GetAttachWorkFlow();
object o = new
{
ID = m.ID,
job_name = m.mission_name,
job_type = m.type,
order_item = i + 1,
workflow = wf == null ? null : "{ \"id\" : " + wf.DefineID + ", \"name\" : \"" + wf.name + "\", \"desc\" : \"" + wf.description + "\"}",
status = m.status,
pretime = m.PerTime.ToString(),
corn_express = m.GetTriggerTimmingString(),
create_time = m.CreateTime.ToString()
};
res.Add(o);
}
return Json(new { data = res.ToArray() });
}
/// <summary>
/// 解析datatables 请求的Form数据
/// </summary>
/// <param name="Form"></param>
/// <returns></returns>
private List<KeyValuePair<string, string>> ParsePostForm(NameValueCollection Form)
{
var list = new List<KeyValuePair<string, string>>();
if (Form != null)
{
foreach (var f in Form.AllKeys)
{
list.Add(new KeyValuePair<string, string>(f, Form[f]));
}
}
return list;
}
/// <summary>
/// 处理datatables请求
/// </summary>
/// <param name="data"></param>
private DtResponse ProcessRequest(List<KeyValuePair<string, string>> data)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
if (http.ContainsKey("action"))
{
string action = http["action"] as string;
if (action == "edit")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
List<string> pros = new List<string>();
List<object> vals = new List<object>();
Dictionary<string, object> m_kv = new Dictionary<string, object>();
foreach (var dd in d.Value as Dictionary<string, object>)
{
pros.Add(dd.Key);
if (dd.Key == "job_type")
{
switch (dd.Value as string)
{
case "CreateWorkFlow":
vals.Add(TIMER_JOB_TYPE.CREATE_WORKFLOW);
break;
default:
case "Empty":
vals.Add(TIMER_JOB_TYPE.EMPTY);
break;
}
}
else if (dd.Key == "workflow")
{
JObject obj = JObject.Parse((string)dd.Value);
vals.Add(Convert.ToInt32(obj["id"]));
}
else
vals.Add(dd.Value);
}
CTimerMission m = CTimerManage.UpdateTimerMission(id, pros, vals);
m_kv["ID"] = m.ID;
m_kv["job_name"] = m.mission_name;
m_kv["job_type"] = m.type;
CWorkFlow wf = m.GetAttachWorkFlow();
m_kv["workflow"] = wf == null ? null : "{ \"id\" : " + wf.DefineID + ", \"name\" : \"" + wf.name + "\", \"desc\" : \"" + wf.description + "\"}";
m_kv["status"] = m.status;
m_kv["pretime"] = m.PerTime.ToString();
m_kv["corn_express"] = m.GetTriggerTimmingString();
m_kv["create_time"] = m.CreateTime.ToString();
dt.data.Add(m_kv);
}
}
else if (action == "create") //新建工作流
{
CTimerMission m = CTimerManage.CreateAEmptyMission();
m.mission_name = "新建任务";
m.SetTriggerTiming("0 0 0 * * ?");
m.Save();
Dictionary<string, object> m_kv = new Dictionary<string, object>();
m_kv["ID"] = m.ID;
m_kv["order_item"] = 1;
m_kv["job_name"] = m.mission_name;
m_kv["job_type"] = m.type;
CWorkFlow wf = m.GetAttachWorkFlow();
m_kv["workflow"] = wf == null ? null : "{ \"id\" : " + wf.DefineID + ", \"name\" : \"" + wf.name + "\", \"desc\" : \"" + wf.description + "\"}";
m_kv["status"] = m.status;
m_kv["pretime"] = m.PerTime.ToString();
m_kv["corn_express"] = m.GetTriggerTimmingString();
m_kv["create_time"] = m.CreateTime.ToString();
dt.data.Add(m_kv);
}
else if (action == "remove")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
CTimerMission m = CTimerManage.DeleteTimerJob(id);
}
}
}
return dt;
}
//提交定时任务修改
[HttpPost]
public JsonResult PostChanges()
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = ProcessRequest(list);
return Json(dtRes);
}
//提交变量修改
//在这里仅做一个回应,不写到数据库
//待“确定”时整体提交
[HttpPost]
public JsonResult PostParChanges()
{
var request = System.Web.HttpContext.Current.Request;
DtResponse dt = new DtResponse();
var list = ParsePostForm(request.Form);
var http = DtRequest.HttpData(list);
if (http.ContainsKey("action"))
{
string action = http["action"] as string;
if (action == "edit")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
Dictionary<string, object> m_kv = new Dictionary<string, object>();
m_kv["par_name"] = d.Key;
foreach (var dd in d.Value as Dictionary<string, object>)
{
m_kv[dd.Key] = dd.Value;
}
dt.data.Add(m_kv);
}
}
}
return Json(dt);
}
[HttpPost]
public JsonResult ListKeyParams(int defId)
{
List<object> pars = new List<object>();
if (defId == -1)
{
return Json(new { data = pars.ToArray() });
}
CWorkFlow wf = new CWorkFlow();
WorkFlows wfs = new WorkFlows();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.Default.GetString(wfs.GetWorkFlowDefineByID(defId).W_Xml));
wf.InstFromXmlNode((XmlNode)doc.DocumentElement);
var ev = wf.events["Start"];
foreach (var k in ev.paramlist)
{
pars.Add(new
{
par_name = k.Value.name,
par_desc = k.Value.description,
par_value = ""
});
}
return Json(new { data = pars.ToArray() });
}
//设置临时任务
public string LSJob_Submit(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string WorkFlowName = item["Work_Name"].ToString();
// WorkFlows ws = new WorkFlows();
int workflow_id = wfs.GetWorkFlowDefine(WorkFlowName).W_ID;
string cj_ids = item["Cj_Name"].ToString();
string Zz_ids = item["Zz_Name"].ToString();
string[] cjids = cj_ids.Split(new char[] { ',' });
string[] zzids = Zz_ids.Split(new char[] { ',' });
string Depts = item["Dept"].ToString();
string qr_endtime = item["ZhengGaiTime"].ToString();
CTimerCreateWF m = new CTimerCreateWF();
//使用lambda表达式过滤掉空字符串
zzids = zzids.Where(t => !string.IsNullOrEmpty(t)).ToArray();
//这里需要创建一个回调函数
string TempJobName = item["Job_Name"].ToString();
string corn = "0 0 0 * * ?";
string ReservationTime = item["ReservationTime"].ToString();
m.Set_Res_Value("STR_RES_1", Depts);
string[] s = ReservationTime.Split(new char[] { '-' });
string[] ss = s[0].Split(new char[] { '/' });
string endtime = s[1].Replace(" ", "");
DateTime Endtime = DateTime.Parse(endtime);
m.Set_Res_Value("STR_RES_2", Endtime);
//11.12改
if (qr_endtime != "")
m.Set_Res_Value("STR_RES_3", DateTime.Parse(qr_endtime));
corn = "0 0 0 " + ss[2] + "" + ss[1] + " " + "? " + ss[0];
//未写
if (WorkFlowName == "A6dot2")
{
for (int i = 0; i < cjids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Cj_Name", Em.getEa_namebyId(Convert.ToInt16(cjids[i])));
record.Add("username", "system_temporary");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = Endtime.ToString();
time_set.Offset_time = "";
time_set.Action = "SUSPEND";
time_set.Call_back = "";
TCP.AppendTimer("Xc_Sample", time_set);
}
}
else if (WorkFlowName == "A5dot1")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_temporary");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = Endtime.ToString();
time_set.Offset_time = "";
time_set.Action = "SUSPEND";
time_set.Call_back = "";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A11dot2dot1")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_temporary");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = Endtime.ToString();
time_set.Offset_time = "";
time_set.Action = "SUSPEND";
time_set.Call_back = "";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A6dot2dot2")
{
for (int i = 0; i < cjids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Cj_Name", cjids[i]);
param.Add("Job_Name", TempJobName);
param.Add("Job_Ztdanwei", Depts);
record.Add("username", "system_temporary");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = Endtime.ToString();
time_set.Offset_time = "";
time_set.Action = "SUSPEND";
time_set.Call_back = "";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A5dot2dot1")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_temporary");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = Endtime.ToString();
time_set.Offset_time = "";
time_set.Action = "SUSPEND";
time_set.Call_back = "";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
m.for_using = TIMER_USING.FOR_CUSTOM;
m.CreateTime = DateTime.Now;
m.SetTriggerTiming(corn);
m.mission_name = item["Job_Name"].ToString();
m.status = TM_STATUS.TM_STATUS_ACTIVE;
//m.CreateCallback = "/zxhtest/QxFunction?depts="+Depts+"";//和权限有关的回调函数
m.CustomFlag = 1;
WorkFlow_Define wfd = wfs.GetWorkFlowDefineByID(workflow_id);
m.attachTarget(wfd);
m.GetAttachWorkFlow();//0910
m.Save();
CTimerManage.ActiveListActionForMission(m);
return "/TempJob/index";
}
//获取临时待处理任务
public string getJobList()
{
Jobs m = new Jobs();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
int zytd;
if (pv.Role_Names.Contains("专业团队") || pv.Role_Names.Contains("专家团队") || pv.Role_Names.Contains("专业团队负责人"))
zytd = 1;
else
zytd = 0;
List<Timer_Jobs> Joblist = m.GetAllTimerJob();
List<object> r = new List<object>();
for (int i = 0; i < Joblist.Count; i++)
{
if (Joblist[i].custom_flag == 1 && Joblist[i].Job_Type == TIMER_JOB_TYPE.CREATE_WORKFLOW)
{
List<string> cjnames = new List<string>();
string Cj_Names = "";
JArray jsonVal = JArray.Parse(Joblist[i].run_params) as JArray;
dynamic table2 = jsonVal;
foreach (dynamic T in table2)
{
WorkFlow_Define wfd = wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID);
if (wfd.W_Name == "A6dot2dot2")
{
// JObject item = (JObject)JsonConvert.DeserializeObject(T.PARAMS);
string cjid = T.PARAMS.Cj_Name.ToString();
string cj_name = Em.getEa_namebyId(Convert.ToInt16(cjid));
cjnames.Add(cj_name);
}
else
{
foreach (dynamic t in T.PARAMS)
{
string cjtemp = "";
cjtemp = t.Value;
cjnames.Add(cjtemp);
}
}
}
for (int k = 0; k < cjnames.Count; k++)
{
EquipArchiManagment em = new EquipArchiManagment();
// Cj_Names = Cj_Names + em.getEa_namebyId(Convert.ToInt16(cjnames[k])) + "、";
Cj_Names = Cj_Names + cjnames[k] + "、";
}
//string job_time = "";
//string[] job_timelist = Joblist[i].corn_express.Split(new char[] { ' ' });
//job_time = job_timelist[6] + "年" + job_timelist[4] + "月" + job_timelist[3] + "日";
string wf_name = wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID).W_Name + ":" + wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID).W_Attribution;
string job_desc = wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID).W_Name;
object o = new
{
job_id = Joblist[i].JOB_ID,
index = i + 1,
jobName = Joblist[i].job_name,
jobType = wf_name,
job_desc = job_desc,
jobTIme = Joblist[i].STR_RES_2,
jobRunPara = Cj_Names,
jobStatus = Joblist[i].status,
job_dep = Joblist[i].STR_RES_1,
job_result = Joblist[i].run_result,
iszytd=zytd
};
r.Add(o);
}
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
}
}<file_sep>using EquipBLL.AdminManagment;
using EquipBLL.AdminManagment.MenuConfig;
using EquipModel.Entities;
using FlowEngine.DAL;
using FlowEngine.Modals;
using FlowEngine.TimerManage;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp.Controllers
{
public class DingShiController : CommonController
{
//
// GET: /DingShi/
public ActionResult Index()
{
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("专业团队") || pv.Role_Names.Contains("专家团队") || pv.Role_Names.Contains("专业团队负责人"))
ViewBag.zytd = 1;
else
ViewBag.zytd = 0;
return View();
}
public ActionResult Submit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
WorkFlows wfs = new WorkFlows();
EquipArchiManagment Em = new EquipArchiManagment();
public string DSJob_Submit(string json1)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string WorkFlowName = item["Work_Name"].ToString();
// WorkFlows ws = new WorkFlows();
int workflow_id = wfs.GetWorkFlowDefine(WorkFlowName).W_ID;
Jobs job = new Jobs();
List<Timer_Jobs> job_list = job.GetDSbyWorkflow(workflow_id);
if (job_list.Count == 0)
{
string cj_ids = item["Cj_Name"].ToString();
string Zz_ids = item["Zz_Name"].ToString();
string[] cjids = cj_ids.Split(new char[] { ',' });
string[] zzids = Zz_ids.Split(new char[] { ',' });
CTimerCreateWF m = new CTimerCreateWF();
//这里需要创建一个回调函数
string DingShiJobName = item["Job_Name"].ToString();
//使用lambda表达式过滤掉空字符串
zzids = zzids.Where(s => !string.IsNullOrEmpty(s)).ToArray();
//未写
if (WorkFlowName == "A6dot2")
{
for (int i = 0; i < cjids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Cj_Name", Em.getEa_namebyId(Convert.ToInt16(cjids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
//time_set.Offset_time = (DateTime.Now.AddMinutes(3) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("Xc_Sample", time_set);
}
}
if (WorkFlowName == "A15dot1")
{
List<string> pq_list = new List<string>();
pq_list.Add("联合一片区");
pq_list.Add("联合二片区");
pq_list.Add("联合三片区");
pq_list.Add("联合四片区");
pq_list.Add("化工片区");
pq_list.Add("综合片区");
pq_list.Add("其他");
//pq_list.Add("检修单位");
for (int i = 0; i < pq_list.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Pqname", pq_list[i]);
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(1) - DateTime.Now).ToString();
//time_set.Offset_time = (DateTime.Now.AddMinutes(3) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A5dot1dot2")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
//time_set.Offset_time = (DateTime.Now.AddMinutes(3) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A5dot2dot2")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
//time_set.Offset_time = (DateTime.Now.AddMinutes(3) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A11dot2dot2")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
//time_set.Offset_time = (DateTime.Now.AddMinutes(3) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
if (WorkFlowName == "A12dot2dot1")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A6dot3")
{
for (int i = 0; i < cjids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(1) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("Ineligible_Submit", time_set);
}
}
else if (WorkFlowName == "A7dot1dot1")
{
List<Equip_Info> Th_sb = new List<Equip_Info>();
EquipManagment Epm = new EquipManagment();
Th_sb = Epm.getAllThEquips();
for (int i = 0; i < Th_sb.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Equip_GyCode", Th_sb[i].Equip_GyCode);
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(1) - DateTime.Now).ToString();
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
else if (WorkFlowName == "A14dot2")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Action = "INVILID";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
TCP.AppendTimer("JxdwSubmit", time_set);
//TCP.AppendTimer("ZzConfirm", time_set);
}
}
else if (WorkFlowName == "A14dot3dot2")
{
for (int i = 0; i < zzids.Count(); i++)
{
TimerCreateWFPa TCP = new TimerCreateWFPa();//
Dictionary<string, string> param = new Dictionary<string, string>();
Dictionary<string, string> record = new Dictionary<string, string>();
param.Add("Zz_Name", Em.getEa_namebyId(Convert.ToInt16(zzids[i])));
record.Add("username", "system_scheduled");
record.Add("time", DateTime.Now.ToString());
TCP.wf_params = param;
TCP.wf_record = record;
m.AppendCreateParam(TCP);
TimerCreateWFPa.TimerSetting time_set = new TimerCreateWFPa.TimerSetting();
time_set.Time_start = "wf_create";
time_set.Exact_time = "";
time_set.Offset_time = (DateTime.Now.AddDays(5) - DateTime.Now).ToString();
time_set.Action = "SUSPEND";
time_set.Call_back = "http://localhost/CallBack/testCallBack";
TCP.AppendTimer("ZzSubmit", time_set);
}
}
string corn = "0 0 0 * * ?";
string corn_express = item["corn_express"].ToString();
string ReservationTime = item["reservationtime"].ToString();
m.Set_Res_Value("STR_RES_2", ReservationTime);
corn = corn_express;
m.for_using = TIMER_USING.FOR_CUSTOM;
m.CreateTime = DateTime.Now;
m.SetTriggerTiming(corn);
m.mission_name = item["Job_Name"].ToString();
m.status = TM_STATUS.TM_STATUS_ACTIVE;
//m.CreateCallback = "/zxhtest/QxFunction?depts="+Depts+"";//和权限有关的回调函数
m.CustomFlag = 0;
WorkFlow_Define wfd = wfs.GetWorkFlowDefineByID(workflow_id);
m.attachTarget(wfd);
m.GetAttachWorkFlow();//0910
m.Save();
CTimerManage.ActiveListActionForMission(m);
return "成功发起定时任务";
}
else
{
return "该工作流已经提报过,请删除后再发起";
}
}
//获取定时待处理任务
public string getJobList()
{
Jobs m = new Jobs();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
int zytd;
if (pv.Role_Names.Contains("专业团队") || pv.Role_Names.Contains("专家团队") || pv.Role_Names.Contains("专业团队负责人"))
zytd = 1;
else
zytd = 0;
List<Timer_Jobs> Joblist = m.GetAllTimerJob();
List<object> r = new List<object>();
int w = 0;
for (int i = 0; i < Joblist.Count; i++)
{
if (Joblist[i].custom_flag == 0 && Joblist[i].Job_Type == 0 && Joblist[i].status==TM_STATUS.TM_STATUS_ACTIVE)
{
List<string> cjnames = new List<string>();
string Cj_Names = "";
JArray jsonVal = JArray.Parse(Joblist[i].run_params) as JArray;
dynamic table2 = jsonVal;
foreach (dynamic T in table2)
{
WorkFlow_Define wfd = wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID);
if (wfd.W_Name == "A6dot2dot2")
{
// JObject item = (JObject)JsonConvert.DeserializeObject(T.PARAMS);
string cjid = T.PARAMS.Cj_Name.ToString();
string cj_name = Em.getEa_namebyId(Convert.ToInt16(cjid));
cjnames.Add(cj_name);
}
else
{
foreach (dynamic t in T.PARAMS)
{
string cjtemp = "";
cjtemp = t.Value;
cjnames.Add(cjtemp);
}
}
}
for (int k = 0; k < cjnames.Count; k++)
{
EquipArchiManagment em = new EquipArchiManagment();
// Cj_Names = Cj_Names + em.getEa_namebyId(Convert.ToInt16(cjnames[k])) + "、";
Cj_Names = Cj_Names + cjnames[k] + "、";
}
string wf_name = wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID).W_Name + ":" + wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID).W_Attribution;
string job_desc = wfs.GetWorkFlowDefineByID(Joblist[i].workflow_ID).W_Name;
object o = new
{
job_id = Joblist[i].JOB_ID,
index = w + 1,
jobName = Joblist[i].job_name,
jobType = wf_name,
job_desc = job_desc,
jobTIme = Joblist[i].STR_RES_2,
jobRunPara = Cj_Names,
jobStatus = Joblist[i].status,
job_dep = Joblist[i].STR_RES_1,
job_result = Joblist[i].run_result,
iszytd=zytd
};
r.Add(o);
w++;
}
}
string str = JsonConvert.SerializeObject(r);
return ("{" + "\"data\": " + str + "}");
}
public string delete_job(string json)
{
JObject item = (JObject)JsonConvert.DeserializeObject(json);
int job_id = Convert.ToInt32(item["job_id"].ToString());
CTimerMission m = CTimerManage.RemoveFromActiveList(job_id);
List<string> property = new List<string>();
property.Add("status");
List<object> val = new List<object>();
val.Add(TM_STATUS.TM_DELETE);
CTimerManage.UpdateTimerMission(job_id, property, val);
return "删除成功";
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
namespace WebApp.Controllers
{
public class A6dot3Controller : CommonController
{
//
// GET: /A6dot3/
public ActionResult Index()
{
return View(getIndexListRecords("A6dot3", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A6dot3/不具备备用条件设备装置提报
public ActionResult Ineligible_Submit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
// GET: /A6dot3/现场工程师确认
public ActionResult Xcgcs_Confirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
// GET: /A6dot3/可靠性工程师确认
public ActionResult Kkxgcs_Confirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string Ineligible_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
// signal["Data_Src"] = "人工提报";
signal["Ineligible_Reason"] = item["Ineligible_Reason"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
//SubmitDSEventDetails("A6.3", "备用设备管理");
}
catch (Exception e)
{
return "";
}
return ("/A6dot3/Index");
}
public string XcgcsConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Xcgcs_Confirm"] = item["CMConfirmC_Done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot3/Index");
}
public string kkxgcsConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Kkxgcs_Confirm"] = item["KkxgcsConfirm"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot3/Index");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class DsTimeOfWork
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string work_name { get; set; }
public string event_name { get; set; }
public string time { get; set; }
public string time_describe { get; set; }
}
}
<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class KpiManagement
{
private Kpi db_Kpi = new Kpi();
public bool AddJxItem(A15dot1TabQiYe add)
{
return db_Kpi.AddJxRecord(add);
}
public bool AddDianItem(A15dot1TabDian add)
{
return db_Kpi.AddDianRecord(add);
}
public bool AddJingItem(A15dot1TabJing add)
{
return db_Kpi.AddJingRecord(add);
}
public bool AddYiItem(A15dot1TabYi add)
{
return db_Kpi.AddYiRecord(add);
}
public List<object> qst(string grahpic_name, string zz)
{
return db_Kpi.qstdata(grahpic_name, zz);
}
//public List<object> qstQiYe(string grahpic_name, string zzId,string zy)
//{
// return db_Kpi.qstdataQiYe(grahpic_name, zzId,zy);
//}
public List<object> qstqc(string grahpic_name, string graphic_zdm, string graphic_zy, string graphic_subdipartment)//全厂的趋势图
{
return db_Kpi.qstdataqc(grahpic_name, graphic_zdm, graphic_zy, graphic_subdipartment);
}
public bool ModifyQcQyJxItem(A15dot1TabQiYe add,DateTime stime,DateTime etime)
{
return db_Kpi.ModifyQcQyJxItem(add, stime, etime);
}
public bool ModifyJxItem(A15dot1TabQiYe add)
{
return db_Kpi.ModifyJxRecord(add);
}
public bool ModifyQcDongJxItem(A15dot1TabDong add, DateTime stime, DateTime etime)
{
return db_Kpi.ModifyQcDongJxItem(add, stime, etime);
}
public bool ModifyQcJingJxItem(A15dot1TabJing add, DateTime stime, DateTime etime)
{
return db_Kpi.ModifyQcJingJxItem(add, stime, etime);
}
public bool ModifyQcDianJxItem(A15dot1TabDian add, DateTime stime, DateTime etime)
{
return db_Kpi.ModifyQcDianJxItem(add, stime, etime);
}
public bool ModifyQcYiJxItem(A15dot1TabYi add, DateTime stime, DateTime etime)
{
return db_Kpi.ModifyQcYiJxItem(add, stime, etime);
}
public bool ModifyJxItemDong(A15dot1TabDong add)
{
return db_Kpi.ModifyJxRecordDong(add);
}
public bool ModifyJxItemDian(A15dot1TabDian add)
{
return db_Kpi.ModifyJxRecordDian(add);
}
public bool ModifyJxItemJing(A15dot1TabJing add)
{
return db_Kpi.ModifyJxRecordJing(add);
}
public bool ModifyJxItemYi(A15dot1TabYi add)
{
return db_Kpi.ModifyJxRecordYi(add);
}
public List<A15dot1TabQiYe> GetJxItem(string roles, string dep, string name,List<string > cjname)//cjname存于temp3,专业存于temp2
{
return db_Kpi.GetJxRecord(roles, dep, name, cjname);
}
public List<A15dot1TabQiYe> GetJxItem_detail(int id)
{
return db_Kpi.GetJxRecord_detail(id);
}
public List<A15dot1TabDian> GetJxItem_detailDian(int id)
{
return db_Kpi.GetJxRecord_detailDian(id);
}
public List<A15dot1TabQiYe> GetHisJxItem(string roles, string dep, string name)
{
return db_Kpi.GetHisJxRecord(roles, dep, name);
}
public List<A15dot1TabQiYe> GetHisJxItem_detail(int id)
{
return db_Kpi.GetHisJxRecord_detail(id);
}
//判断管理员是否已经保存了修改的数据
public bool GetifQiYeQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifQiYeQc(zy, stime, etime);
}
public bool GetifDongQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifDongQc(zy, stime, etime);
}
public bool GetifJingQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifJingQc(zy, stime, etime);
}
public bool GetifDianQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifDianQc(zy, stime, etime);
}
public bool GetifYiQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifYiQc(zy, stime, etime);
}
//按车间查询判断库里是否存在数据(即片区长是否提交保存数据)
public bool GetifQiYeCj(string cjname,string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifQiYeCj(cjname, zy, stime, etime);
}
public bool GetifDongCj(string cjname,string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifDongCj(cjname,zy, stime, etime);
}
public bool GetifJingCj(string cjname,string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifJingCj(cjname,zy, stime, etime);
}
public bool GetifDianCj(string cjname,string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifDianCj(cjname,zy, stime, etime);
}
public bool GetifYiCj(string cjname,string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetifYiCj(cjname,zy, stime, etime);
}
public List<A15dot1TabQiYe> GetQiYeJxByA2(DateTime astime,DateTime aetime, string zzname, string zy)
{
return db_Kpi.GetQiYeJxByA2(astime,aetime, zzname, zy);
}
public List<A15dot1TabDong> GetDongJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
return db_Kpi.GetDongJxByA2(astime, aetime, zzname, zy);
}
public List<A15dot1TabJing> GetJingJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
return db_Kpi.GetJingJxByA2(astime, aetime, zzname, zy);
}
public List<A15dot1TabDian> GetDianJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
return db_Kpi.GetDianJxByA2(astime, aetime, zzname, zy);
}
public List<A15dot1TabYi> GetYiJxByA2(DateTime astime, DateTime aetime, string zzname, string zy)
{
return db_Kpi.GetYiJxByA2(astime, aetime, zzname, zy);
}
//动的 全厂提取
public List<object> GetQiYeQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetQiYeQc(zy, stime, etime);
}
public List<object> GetDongQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetDongQc(zy, stime, etime);
}
public List<object> GetJingQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetJingQc(zy, stime, etime);
}
public List<object> GetDianQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetDianQc(zy, stime, etime);
}
public List<object> GetYiQc(string zy, DateTime stime, DateTime etime)
{
return db_Kpi.GetYiQc(zy, stime, etime);
}
public List<object> GetCjQiYe(string zy, string cjname, DateTime astime, DateTime aetime)
{
return db_Kpi.GetCjQiYe(zy, cjname, astime, aetime);
}
public List<object> GetCjDong(string zy, string cjname, DateTime astime, DateTime aetime)
{
return db_Kpi.GetCjDong(zy, cjname, astime, aetime);
}
public List<object> GetCjJing(string zy, string cjname, DateTime astime, DateTime aetime)
{
return db_Kpi.GetCjJing(zy, cjname, astime, aetime);
}
public List<object> GetCjDian(string zy, string cjname, DateTime astime, DateTime aetime)
{
return db_Kpi.GetCjDian(zy, cjname, astime, aetime);
}
public List<object> GetCjYi(string zy, string cjname, DateTime astime, DateTime aetime)
{
return db_Kpi.GetCjYi(zy, cjname, astime, aetime);
}
public bool AddDongJxItem(A15dot1TabDong add)
{
return db_Kpi.AddDongJxRecord(add);
}
//public List<object> Dongqst(string grahpic_name, string pianqu)
//{
// return db_Kpi.Dongqstdata(grahpic_name, pianqu);
//}
public List<object> qstQiYe(string grahpic_name, string zzname)
{
return db_Kpi.qstdataQiYe(grahpic_name, zzname);
}
public List<object> qstDong(string grahpic_name, string zzname)
{
return db_Kpi.qstdataDong(grahpic_name, zzname);
}
public List<object> qstJing(string grahpic_name, string zzname)
{
return db_Kpi.qstdataJing(grahpic_name, zzname);
}
public List<object> qstDian(string grahpic_name, string zzname)
{
return db_Kpi.qstdataDian(grahpic_name, zzname);
}
public List<object> qstYi(string grahpic_name, string zzname)
{
return db_Kpi.qstdataYi(grahpic_name, zzname);
}
public bool GetifzztibaoQiYe(DateTime stime, DateTime etime, string Zz_Name)
{
return db_Kpi.GetifzztibaoQiYe(stime, etime, Zz_Name);
}
public bool GetifzztibaoDong(DateTime stime, DateTime etime, string Zz_Name)
{
return db_Kpi.GetifzztibaoDong(stime, etime, Zz_Name);
}
public bool GetifzztibaoJing(DateTime stime, DateTime etime, string Zz_Name)
{
return db_Kpi.GetifzztibaoJing(stime, etime, Zz_Name);
}
public bool GetifzztibaoDian(DateTime stime, DateTime etime, string Zz_Name)
{
return db_Kpi.GetifzztibaoDian(stime, etime, Zz_Name);
}
public bool GetifzztibaoYi(DateTime stime, DateTime etime, string Zz_Name)
{
return db_Kpi.GetifzztibaoYi(stime, etime, Zz_Name);
}
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Files : BaseDAO
{
public bool delete(int fId)
{
try
{
using (var db = base.NewDB())
{
db.Files.Remove(db.Files.Where(s => s.File_Id == fId).First());
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public bool AttachtoEuip(int fId, int EuipID)
{
try
{
using (var db = base.NewDB())
{
File_Info file = db.Files.Where(s => s.File_Id == fId).First();
Equip_Info equip = db.Equips.Where(s => s.Equip_Id == EuipID).First();
file.File_Equips.Add(equip);
db.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
}
}
<file_sep>using EquipModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipDAL.Implement
{
public class Depart_Archis:BaseDAO
{
public Depart_Archi getDepart_info(int Depart_id)
{
using(var db=base.NewDB())
{
return db.Department.Where(a => a.Depart_Id == Depart_id).First();
}
}
public Depart_Archi getDepart_root(string Depart_name)
{
using (var db = base.NewDB())
{
return db.Department.Where(a => a.Depart_Name == Depart_name).First();
}
}
public string getDepart_Pq(string Depart_name)
{
using (var db = base.NewDB())
{
return db.Department.Where(a => a.Depart_Name == Depart_name).First().Depart_Parent.Depart_Name;
}
}
public int getDepart_Id(string Depart_name)
{
using (var db = base.NewDB())
{
return db.Department.Where(a => a.Depart_Name == Depart_name).First().Depart_Id;
}
}
public List<Depart_Archi> getDepart_Childs(int Depart_id)
{
using (var db = base.NewDB())
{
var DepartArchi = db.Department.Where(a => a.Depart_Id == Depart_id).First();
return DepartArchi.Depart_child.ToList();
}
}
public List<Depart_Archi> getDepart_Childs(string Depart_name)
{
using (var db = base.NewDB())
{
var DepartArchi = db.Department.Where(a => a.Depart_Name == Depart_name).First();
return DepartArchi.Depart_child.ToList();
}
}
public List<Person_Info> getPersons_Belong(int Depart_id)
{
using (var db = base.NewDB())
{
var DepartArchi = db.Department.Where(a => a.Depart_Id == Depart_id).First();
return DepartArchi.Depart_Persons.ToList();
}
}
public Depart_Archi getDepart_Parent(int Depart_id)
{
using (var db = base.NewDB())
{
var DepartArchi = db.Department.Where(a => a.Depart_Id == Depart_id).First();
return DepartArchi.Depart_Parent;
}
}
public bool AddDepart_Archi(int parentId,Depart_Archi New_Depart_info)
{
using (var db = base.NewDB())
{
try
{
Depart_Archi parent = db.Department.Where(a => a.Depart_Id == parentId).First();
if (parent == null)
return false;
parent.Depart_child.Add(New_Depart_info);
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
public bool DeleteDepart_Archi(int Depart_id)
{
using (var db = base.NewDB())
{
try
{
var P = db.Department.Where(a => a.Depart_Id==Depart_id).First();
if (P == null)
return false;
else
{
// foreach(var pc in P.Depart_child)
//{ DeleteDepart_Archi(pc.Depart_Id); }
P.Depart_Persons.Clear();
db.Department.Remove(P);
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
public bool ModifyDepart_Archi(int Depart_id,Depart_Archi New_Depart_info)
{
using (var db = base.NewDB())
{
try
{
var P = db.Department.Where(a => a.Depart_Id == Depart_id).First();
if (P == null)
return false;
else
{
P.Depart_Name = New_Depart_info.Depart_Name;
db.SaveChanges();
return true;
}
}
catch { return false; }
}
}
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
namespace WebApp.Controllers
{
public class A6dot2Controller : CommonController
{
A6dot2Managment WDTManagment = new A6dot2Managment();
public class WDT_detail_Role
{
public List<EquipBLL.AdminManagment.A6dot2Managment.WDTHistoy_ListModal> wdt_List = new List<EquipBLL.AdminManagment.A6dot2Managment.WDTHistoy_ListModal>();
public int isRole;
}
public ActionResult Index0()
{
return View();
}
public ActionResult WDT_TjQuery()
{
return View();
}
public ActionResult Index_Tj()
{
WDT_detail_Role r = new WDT_detail_Role();
PersonManagment PM = new PersonManagment();
if (PM.Get_Person_Roles((Session["User"] as EquipModel.Entities.Person_Info).Person_Id).Where(x => x.Role_Name == "现场工程师").Count() > 0)
r.isRole = 1;
else
r.isRole = 0;
r.wdt_List = WDTManagment.getHistoryList();
return View(r);
}
public ActionResult WDT_detail(int WDT_Id)
{
return View(WDTManagment.getWDT_detail(WDT_Id));
}
public ActionResult UploadWDT()
{
PersonManagment pm = new PersonManagment();
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
return View();
}
public JsonResult Tj_PrePrint(int Id)
{
A6dot2Managment WM = new A6dot2Managment();
List<EquipBLL.AdminManagment.A6dot2Managment.WDTTJ_RowModal> r = WM.WDTTJ(Id);
return Json(r.ToArray());
}
public JsonResult Tj_Search(string daterange)
{
string starttime, endtime;
if (!daterange.Equals(""))
{
string[] strtime = daterange.Split(new char[] { '-' });
starttime = strtime[0].Trim() + " 00:00:00";
endtime = strtime[1].Trim() + " 23:59:59";
}
else
{
starttime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
endtime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
}
A6dot2Managment WM = new A6dot2Managment();
List<EquipBLL.AdminManagment.A6dot2Managment.WDTTJ_RowModal> r = WM.WDTTJ(starttime, endtime);
return Json(r.ToArray());
}
public JsonResult Tj_PrePrintIndex(string starttime, string endtime)
{
A6dot2Managment WM = new A6dot2Managment();
List<EquipBLL.AdminManagment.A6dot2Managment.WDTTJ_RowModal> r = WM.WDTTJ(starttime, endtime);
return Json(r.ToArray());
}
public string WDTSubmit(string json1)
{
try
{
PersonManagment PM = new PersonManagment();
A6dot2Managment WM = new A6dot2Managment();
A6dot2Tab1 WDT_list = new A6dot2Tab1();
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
WDT_list.uploadDesc = item["WDT_Desc"].ToString();
WDT_list.uuploadFileName = item["WDT_filename"].ToString();
string[] savedFileName = WDT_list.uuploadFileName.Split(new char[] { '$' });
string wdt_filename = Path.Combine(Request.MapPath("~/Upload"), savedFileName[1]);
WDT_list.userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
WDT_list.uploadtime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
WDT_list.pqName = PM.Get_Person_Depart((Session["User"] as EquipModel.Entities.Person_Info).Person_Id).Depart_Name;
int WDT_ID = WM.add_WDT_list(WDT_list);
JArray wdt_content = (JArray)JsonConvert.DeserializeObject(item["WDT_content"].ToString());
List<A6dot2Tab2> wdt_list = new List<A6dot2Tab2>();
foreach (var i in wdt_content)
{
if (Convert.ToInt32(i["isValid"].ToString()) == 0) continue;
A6dot2Tab2 tmp = new A6dot2Tab2();
tmp.isValid = Convert.ToInt32(i["isValid"].ToString());
tmp.equipCode = i["equipCode"].ToString(); ;
tmp.equipDesc = i["equipDesc"].ToString();
tmp.funLoc = i["funLoc"].ToString();
tmp.funLoc_desc = i["funLoc_desc"].ToString();
tmp.oilLoc = i["oilLoc"].ToString();
tmp.oilLoc_desc = i["oilLoc_desc"].ToString();
tmp.oilInterval = Convert.ToInt32(i["oilInterval"].ToString());
tmp.unit = i["unit"].ToString();
tmp.lastOilTime = i["lastOilTime"].ToString();
tmp.lastOilNumber = Convert.ToDouble(i["lastOilNumber"].ToString());
tmp.lastOilUnit = i["lastOilUnit"].ToString();
tmp.NextOilTime = i["NextOilTime"].ToString();
tmp.NextOilNumber = Convert.ToDouble(i["NextOilNumber"].ToString());
tmp.NextOilUnit = i["NextOilUnit"].ToString();
tmp.oilCode = i["oilCode"].ToString();
tmp.oilCode_desc = i["oilCode_desc"].ToString();
tmp.substiOilCode = i["substiOilCode"].ToString();
tmp.substiOilCode_desc = i["substiOilCode_desc"].ToString();
tmp.equip_ZzName = i["equip_ZzName"].ToString();
tmp.equip_CjName = i["equip_CjName"].ToString();
tmp.equip_PqName = i["equip_PqName"].ToString();
tmp.isExceed = Convert.ToInt32(i["isExceed"].ToString());
tmp.isOilType = Convert.ToInt32(i["isOilType"].ToString());
tmp.Tab1_Id = WDT_ID;
wdt_list.Add(tmp);
}
WM.add_WDT_content(WDT_ID, wdt_list);
/* foreach(var i in wdt_content)
{
return i.equip_CjName;
}
* */
return "/A6dot2/Index_Tj";
}
catch { return ""; }
}
public string CQ_detail(string pqName, string starttime, string endtime)
{
starttime = starttime + " 00:00:00";
endtime = endtime + " 23:59:59";
A6dot2Managment WM = new A6dot2Managment();
string str = JsonConvert.SerializeObject(WM.getCQdetail(pqName, starttime, endtime));
return ("{" + "\"data\": " + str + "}");
}
public string CQ_detailId(int Id,string pqName)
{
A6dot2Managment WM = new A6dot2Managment();
string str = JsonConvert.SerializeObject(WM.getCQdetailId(Id,pqName));
return ("{" + "\"data\": " + str + "}");
}
public string Tj(string file)
{
List<A6dot2Tab2> tb_list = new List<A6dot2Tab2>();
if (file.Equals(""))
{
List<A6dot2Tab2> t = new List<A6dot2Tab2>();
string str = JsonConvert.SerializeObject(t);
return ("{" + "\"data\": " + str + "}");
}
EquipManagment EM = new EquipManagment();
string curdate = DateTime.Now.ToString("yyyy.MM.dd");
string EquipPhaseB;
DataSet ds = new DataSet();
string[] savedFileName = file.Split(new char[] { '$' });
string filePath = Path.Combine(Request.MapPath("~/Upload"), savedFileName[1]);
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;HDR=Yes;IMEX=1";
//strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filePath + ";" + "Extended Properties=Excel 12.0;HDR=Yes;IMEX=1";
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\equipweb\\1\\CODE\\WebApp\\WebApp\\Upload\\1.xls;Extended Properties=\"Excel 12.0 XML;HDR=YES;IMEX=1\"";
// string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
// + strFilepPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"";
// 参数HDR的值:
// HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
//IMEX 有三种模式:
//当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。
//当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。
//当 IMEX=2 时为“连結模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。
OleDbConnection conn = new OleDbConnection(strConn);
//SqlConnection conn = new SqlConnection(strConn);
try
{
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetNames.Rows[0][2] + "]", conn); //为Sheet命名后,顺序可以能编号,要注意
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
//
for (int i = 1; i < ds.Tables[0].Rows.Count - 1; i++) // HDR=Yes,故从i=2开始,而非i=3, xwm modify
{
string name = ds.Tables[0].Rows[i][0].ToString();
string standard_value = ds.Tables[0].Rows[i][1].ToString();
A6dot2Tab2 tmp = new A6dot2Tab2();
tmp.equipCode = ds.Tables[0].Rows[i][0].ToString(); ;
tmp.equipDesc = ds.Tables[0].Rows[i][1].ToString();
tmp.funLoc = ds.Tables[0].Rows[i][2].ToString();
tmp.funLoc_desc = ds.Tables[0].Rows[i][3].ToString();
tmp.oilLoc = ds.Tables[0].Rows[i][4].ToString();
tmp.oilLoc_desc = ds.Tables[0].Rows[i][5].ToString();
tmp.oilInterval = Convert.ToInt32(ds.Tables[0].Rows[i][6].ToString());
tmp.unit = ds.Tables[0].Rows[i][7].ToString();
tmp.lastOilTime = ds.Tables[0].Rows[i][8].ToString();
tmp.lastOilNumber = Convert.ToDouble(ds.Tables[0].Rows[i][9].ToString());
tmp.lastOilUnit = ds.Tables[0].Rows[i][10].ToString();
tmp.NextOilTime = ds.Tables[0].Rows[i][11].ToString();
tmp.NextOilNumber = Convert.ToDouble(ds.Tables[0].Rows[i][12].ToString());
tmp.NextOilUnit = ds.Tables[0].Rows[i][13].ToString();
tmp.oilCode = ds.Tables[0].Rows[i][14].ToString();
tmp.oilCode_desc = ds.Tables[0].Rows[i][15].ToString();
tmp.substiOilCode = ds.Tables[0].Rows[i][16].ToString();
tmp.substiOilCode_desc = ds.Tables[0].Rows[i][17].ToString();
if (EM.getEquip_Info(tmp.equipCode) != null)
{
EquipPhaseB = EM.getEquip_Info(tmp.equipCode).Equip_PhaseB;
if (EquipPhaseB.Equals("机泵") || EquipPhaseB.Equals("风机"))
tmp.isOilType = 1;
else
tmp.isOilType = 0;
List<Equip_Archi> ZzCj = EM.getEquip_ZzBelong(EM.getEquip_Info(tmp.equipCode).Equip_Id);
tmp.equip_ZzName = ZzCj.First().EA_Name;
tmp.equip_CjName = ZzCj.Last().EA_Name;
tmp.equip_PqName = EM.getPq(tmp.equip_CjName);
tmp.isValid = 1;
}
else
tmp.isValid = 0;
if (curdate.CompareTo(tmp.NextOilTime) > 0)
tmp.isExceed = 1;
else
tmp.isExceed = 0;
tb_list.Add(tmp);
}
conn.Close();
string str = JsonConvert.SerializeObject(tb_list);
return ("{" + "\"data\": " + str + "}");
}
catch (Exception e)
{
List<A6dot2Tab2> t = new List<A6dot2Tab2>();
string str = JsonConvert.SerializeObject(t);
return ("{" + "\"data\": " + str + "}");
}
}
public class Equipinfo
{
public string username;
public int userid;
public string belong_depart;
public List<Equip_Info> pp;
}
public class k_model
{
public List<UI_MISSION> ALLHistoryMiss;
public List<string> MissTime;
public List<string> MissUser;
public Dictionary<string, string> e_name;
//可靠性工程师上传整改方案
public List<Kk_change> Kk;
public List<Kk_change> Zj;
}
public class Kk_change
{
public string eq_name;
public string eq_code;
public string eq_check_result;
public string eq_check_reason;
public string eq_detail;
public string eq_file;
public string eq_file_0;
public string eq_file_1;
public string eq_zj_reason;
}
public ActionResult Index()
{
return View(getIndexListRecords("A6dot2", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A6dot2/不具备备用条件设备装置提报
public ActionResult Xc_Sample(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult Sj_Result(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult Kk_Confirm(string wfe_id)
{
return View(get_kmodel(wfe_id));
}
public k_model get_kmodel(string wfe_id)
{
k_model cm = new k_model();
ViewBag.WF_NAME = wfe_id;
cm.ALLHistoryMiss = CWFEngine.GetHistoryMissions(int.Parse(wfe_id));
ViewBag.WF_Ser = cm.ALLHistoryMiss[0].WE_Entity_Ser;
cm.MissTime = new List<string>();
cm.MissUser = new List<string>();
string t;
foreach (var item in cm.ALLHistoryMiss)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
t = r["username"];
cm.MissUser.Add(t);
t = r["time"];
cm.MissTime.Add(t);
}
else
{
cm.MissUser.Add("");
cm.MissTime.Add("");
}
}
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
string a = miss.Miss_Params["Equip_Info"].ToString();
string file = miss.Miss_Params["Assay_File"].ToString();
JArray jsonVal = JArray.Parse(a) as JArray;
dynamic table2 = jsonVal;
Dictionary<string, string> e_name = new Dictionary<string, string>();
List<string> e_code = new List<string>();
foreach (dynamic T in table2)
{
if (T.equip_check == "true")
{
string temp = T.equip_name;
string tcode = T.equip_code;
e_name.Add(temp,tcode);
}
}
ViewBag.file = file;
cm.e_name = e_name;
return cm;
}
public ActionResult Kk_Change_File(string wfe_id)
{
return View(get_Kk_Changemodel(wfe_id));
}
public k_model get_Kk_Changemodel(string wfe_id)
{
k_model cm = new k_model();
ViewBag.WF_NAME = wfe_id;
cm.ALLHistoryMiss = CWFEngine.GetHistoryMissions(int.Parse(wfe_id));
ViewBag.WF_Ser = cm.ALLHistoryMiss[0].WE_Entity_Ser;
cm.MissTime = new List<string>();
cm.MissUser = new List<string>();
string t;
foreach (var item in cm.ALLHistoryMiss)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
t = r["username"];
cm.MissUser.Add(t);
t = r["time"];
cm.MissTime.Add(t);
}
else
{
cm.MissUser.Add("");
cm.MissTime.Add("");
}
}
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
string a = miss.Miss_Params["Equip_Info"].ToString();
cm.Kk=new List<Kk_change>();
JArray jsonVal = JArray.Parse(a) as JArray;
dynamic table2 = jsonVal;
// k_model result = new k_model();
foreach (dynamic T in table2)
{
if (T.equip_check_result == "false" && T.equip_zj_result == "")
{
Kk_change aa = new Kk_change();
aa.eq_name = T.equip_name;
aa.eq_check_reason = T.equip_reason;
aa.eq_code = T.equip_code;
cm.Kk.Add(aa);
// result.Add();
}
else if (T.equip_zj_result == "false" && T.equip_check_result == "false")
{
Kk_change aa = new Kk_change();
aa.eq_name = T.equip_name;
aa.eq_check_reason = T.equip_reason;
aa.eq_code = T.equip_code;
aa.eq_zj_reason = T.equip_zj_reason;
aa.eq_file = T.equip_file;
if (aa.eq_file != "")
{
string[] ss = (aa.eq_file).Split(new char[] { '$' });
aa.eq_file_0 = ss[0];
aa.eq_file_1 = ss[1];
string ExistFilename = Path.Combine("/Upload", aa.eq_file_1);
aa.eq_file_1 = ExistFilename;
}
cm.Kk.Add(aa);
ViewBag.zj_1 = "否";
}
}
return cm;
}
public ActionResult Zytd_Confirm(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(get_Zj_confirm(wfe_id));
}
public k_model get_Zj_confirm(string wfe_id)
{
k_model cm = new k_model();
ViewBag.WF_NAME = wfe_id;
cm.ALLHistoryMiss = CWFEngine.GetHistoryMissions(int.Parse(wfe_id));
ViewBag.WF_Ser = cm.ALLHistoryMiss[0].WE_Entity_Ser;
cm.MissTime = new List<string>();
cm.MissUser = new List<string>();
string t;
foreach (var item in cm.ALLHistoryMiss)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
t = r["username"];
cm.MissUser.Add(t);
t = r["time"];
cm.MissTime.Add(t);
}
else
{
cm.MissUser.Add("");
cm.MissTime.Add("");
}
}
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
string a = miss.Miss_Params["Equip_Info"].ToString();
cm.Zj = new List<Kk_change>();
JArray jsonVal = JArray.Parse(a) as JArray;
dynamic table2 = jsonVal;
// k_model result = new k_model();
foreach (dynamic T in table2)
{
Kk_change aa = new Kk_change();
aa.eq_name = T.equip_name;
aa.eq_code = T.equip_code;
aa.eq_check_reason = T.equip_reason;
aa.eq_file = T.equip_file;
if (aa.eq_file != "") {
string[] ss = (aa.eq_file).Split(new char[] { '$' });
aa.eq_file_0 = ss[0];
aa.eq_file_1 = ss[1];
string ExistFilename = Path.Combine("/Upload", aa.eq_file_1);
aa.eq_file_1 = ExistFilename;
}
cm.Zj.Add(aa);
// result.Add();
}
return cm;
}
public ActionResult Xc_Confirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult Sj_Assay_File(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult Kk_Confirm_Again(string wfe_id)
{
return View(get_Kk_Again(wfe_id));
}
public k_model get_Kk_Again(string wfe_id)
{
k_model cm = new k_model();
ViewBag.WF_NAME = wfe_id;
cm.ALLHistoryMiss = CWFEngine.GetHistoryMissions(int.Parse(wfe_id));
ViewBag.WF_Ser = cm.ALLHistoryMiss[0].WE_Entity_Ser;
cm.MissTime = new List<string>();
cm.MissUser = new List<string>();
string t;
foreach (var item in cm.ALLHistoryMiss)
{
IDictionary<string, string> r = CWFEngine.GetMissionRecordInfo(item.Miss_Id);
if (r.Count > 0)
{
t = r["username"];
cm.MissUser.Add(t);
t = r["time"];
cm.MissTime.Add(t);
}
else
{
cm.MissUser.Add("");
cm.MissTime.Add("");
}
}
ViewBag.curtime = DateTime.Now.ToString();
ViewBag.curuser = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
string a = miss.Miss_Params["Equip_Info"].ToString();
string file = miss.Miss_Params["Sj_Assay_File"].ToString();
JArray jsonVal = JArray.Parse(a) as JArray;
dynamic table2 = jsonVal;
Dictionary<string, string> e_name = new Dictionary<string, string>();
List<string> e_code = new List<string>();
foreach (dynamic T in table2)
{
if (T.equip_zj_result == "true")
{
string temp = T.equip_name;
string tcode = T.equip_code;
e_name.Add(temp, tcode);
}
}
ViewBag.file = file;
cm.e_name = e_name;
return cm;
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
//public string submit(string name)
//{
// string s = name;
// string c = "";
// string[] namesubmit = s.Split(new char[] { ',' });
// int user_id = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
// PersonManagment PM = new PersonManagment();
// EquipBLL.AdminManagment.PersonManagment.P_viewModal user_part = PM.Get_PersonModal(user_id);
// for (int i = 0; i < namesubmit.Length; i++)
// {
// int submitid = (Session[namesubmit[i]] as EquipModel.Entities.Person_Info).Person_Id;
// PersonManagment Pp = new PersonManagment();
// EquipBLL.AdminManagment.PersonManagment.P_viewModal sub_part = Pp.Get_PersonModal(submitid);
// if (sub_part == user_part)
// {
// c = "false";
// }
// else
// {
// c = "true";
// };
// }
// if (c == "false")
// {
// return ("false");
// }
// else
// {
// return ("true");
// }
//}
public string get_equip_info()
{
Equipinfo info = new Equipinfo();
PersonManagment PM = new PersonManagment();
EquipManagment Em=new EquipManagment();
info.userid = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
info.pp = PM.Get_Person_Equips(info.userid);
List<Object> miss_obj = new List<object>();
foreach (var item in info.pp)
{
string ie = item.Equip_PhaseB;
if (ie.Contains("机组"))
{
object m = new
{
equip_id=item.Equip_Id,
equip_code=item.Equip_Code,
equip_name = item.Equip_GyCode,
equip_type = item.Equip_Type,
//equip_zzid=Em.getEA_id_byCode(item.Equip_Code),
equip_cjname = Em.getCjnamebyEa_id(Em.getEA_id_byCode(item.Equip_Code)),
equip_pqname=Em.getPq(Em.getCjnamebyEa_id(Em.getEA_id_byCode(item.Equip_Code))),
//equip_cjname=
equip_check="",
equip_reason="",
equip_file=""
};
miss_obj.Add(m);
}
}
string str = JsonConvert.SerializeObject(miss_obj);
return ("{" + "\"data\": " + str + "}");
}
//每月20号提醒现场工程师采样
public string submit_sample(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Equip_Info"] = item["sample"].ToString();
signal["Cj_Name"] = item["cjname"].ToString();
signal["Pq_Name"] = item["pqname"].ToString();
signal["Equip_GyCode"] = "";
signal["sample_done"] ="true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//每月30号提醒设监中心上传化验结果
//先判断用户是不是设监中心
public string Is_Sjzx() {
string userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name.ToString();
int userId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(userId);
if (pv.Department_Name.Contains("设监中心")) {
return "yes";
}else
return "no";
}
public string index_SjFile(string json1) {
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string wef_id_str = item["wef_id_str"].ToString();
string Sj_File = item["Sj_File"].ToString();
string[] wef_id = wef_id_str.Split(new char[] { ',' });
for (int i = 0; i < wef_id.Length - 1; i++) {
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Assay_File"] = Sj_File;
signal["Time_Assay"] = DateTime.Now.ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(wef_id[i]), signal, record);
}
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
public string SjFile_signal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Assay_File"] = item["Sj_File"].ToString();
signal["Time_Assay"] = DateTime.Now.ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//可靠性工程师判断化验结果
public string submit_KkConfirm(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Assay_Result"] = item["Assay_result"].ToString();
signal["Equip_Info"] = item["equip_info"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//可靠性工程师上传整改方案
public string Kkxgcs_Change_File(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Equip_Info"] = item["equip_info"].ToString();
signal["Zg_desc"] = item["Zg_detail"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//专业团队审核方案是否通过
public string ZjConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Zytd_Confirm"] = item["ZjConfirm_Done"].ToString();
signal["Equip_Info"] = item["equip_info"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//现场工程师实施确认
public string XcConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Xc_Confirm"] = item["XcConfirm_Done"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//设监中心再次上传结果
public string SjFile_signal_2(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Sj_Assay_File"] = item["Sj_File_2"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//可靠性工程师再次判断
public string submit_KkConfirm_Again(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Assay_Result_Again"] = item["Assay_result"].ToString();
signal["Equip_Info"] = item["equip_info"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A6dot2/Index");
}
//导出excel2016-7-18 zxh
public string out_excel(string json1)
{
//json1的值包括表格1,3,5列的值,包括表头(在下面取值到s11,s33,s55数组时已去掉表头),由于前台页面的表格存在合并单元格的情况,致使取到的表格的第一列,第三列,第五列的值并不是直观上的列值,故,若今后表格的格式发生了变化,此处的代码赋值处也需要相应的改变
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string cols_1 = item["cols1"].ToString();//第一列的值
string[] s11 = new string[22];//生成的表格中有22处属于第一列值(严格按照现有表格的总览设计的)
for (int i = 0; i < s11.Length; i++)//给数组赋值,全为空
{
s11[i] = "";
}
string[] s1 = cols_1.Split(new char[] { ',' });
for (int i = 1; i < s1.Length; i++)//将前台传来的第一列值放置在固定长度的数组中
{
s11[i - 1] = s1[i];
}
string cols_3 = item["cols3"].ToString();
string[] s33 = new string[15];
for (int i = 0; i < s33.Length; i++)
{
s33[i] = "";
}
string[] s3 = cols_3.Split(new char[] { ',' });
for (int i = 1; i < s3.Length; i++)
{
s33[i - 1] = s3[i];
}
string cols_5 = item["cols5"].ToString();
string[] s55 = new string[8];
for (int i = 0; i < s55.Length; i++)
{
s55[i] = "";
}
string[] s5 = cols_5.Split(new char[] { ',' });
for (int i = 1; i < s5.Length; i++)
{
s55[i - 1] = s5[i];
}
// 创建Excel 文档
HSSFWorkbook wk = new HSSFWorkbook();
ISheet tb = wk.CreateSheet("sheet1");
//设置单元的宽度
tb.SetColumnWidth(0, 25 * 256);
tb.SetColumnWidth(1, 20 * 256);
tb.SetColumnWidth(2, 20 * 256);
tb.SetColumnWidth(3, 20 * 256);
tb.SetColumnWidth(4, 20 * 256);
tb.SetColumnWidth(5, 20 * 256);
//合并标题头,该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 5));
IRow head = tb.CreateRow(0);
head.Height = 20 * 30;
ICell head_first_cell = head.CreateCell(0);
ICellStyle cellStyle_head = wk.CreateCellStyle();
//对齐
cellStyle_head.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
// 字体
IFont font = wk.CreateFont();
font.FontName = "微软雅黑";
font.Boldweight = 8;
font.FontHeightInPoints = 16;
cellStyle_head.SetFont(font);
head_first_cell.CellStyle = head.CreateCell(1).CellStyle
= head.CreateCell(2).CellStyle
= head.CreateCell(3).CellStyle
= cellStyle_head;
head_first_cell.SetCellValue("本周超期未换油统计结果");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 0, 5));
IRow row1 = tb.CreateRow(1);
row1.Height = 20 * 20;
IRow table_head = tb.CreateRow(2);
ICellStyle cellStyle_normal = wk.CreateCellStyle();//表格主体部分样式
//cellStyle_normal.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
//cellStyle_normal.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
//cellStyle_normal.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
//cellStyle_normal.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//水平居中
cellStyle_normal.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
//表头
ICell pq_name = table_head.CreateCell(0);
pq_name.CellStyle = cellStyle_normal;
pq_name.SetCellValue("片区名称");
ICell pq_count = table_head.CreateCell(1);
pq_count.CellStyle = cellStyle_normal;
pq_count.SetCellValue("片区超时未换油设备数");
ICell cj_name = table_head.CreateCell(2);
cj_name.CellStyle = cellStyle_normal;
cj_name.SetCellValue("车间名称");
ICell cj_count = table_head.CreateCell(3);
cj_count.CellStyle = cellStyle_normal;
cj_count.SetCellValue("车间超时未换油设备数");
ICell zz_name = table_head.CreateCell(4);
zz_name.CellStyle = cellStyle_normal;
zz_name.SetCellValue("装置名称");
ICell zz_count = table_head.CreateCell(5);
zz_count.CellStyle = cellStyle_normal;
zz_count.SetCellValue("装置超时未换油设备数");
//联合一片区
IRow tb3 = tb.CreateRow(3);//创建excel时,由于本次的表格样式固定,每行每列的位置固定,且存在合并单元格的情况,故此表格是一行一行的设计。在设计表格时,首先定义一行,即, IRow tb3 = tb.CreateRow(3);表示定义了excel的第三行,接下来的第三行设计将基于tb3
ICell pq_1 = tb3.CreateCell(0);//定义第三行的第0列
pq_1.SetCellValue("联合一片区");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, 5, 0, 0));//第三行第0列,存在合并单元格,3,5,0,0表示合并的起始行,终止行,起始列,终止列
pq_1.CellStyle = cellStyle_normal;//样式
ICell pq_1_count = tb3.CreateCell(1);
pq_1_count.CellStyle = cellStyle_normal;
pq_1_count.SetCellValue(s11[0]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, 5, 1, 1));
ICell cj_1 = tb3.CreateCell(2);
cj_1.CellStyle = cellStyle_normal;
cj_1.SetCellValue("联合一车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, 5, 2, 2));
ICell cj_1_count = tb3.CreateCell(3);
cj_1_count.CellStyle = cellStyle_normal;
cj_1_count.SetCellValue(s33[0]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, 5, 3, 3));
ICell lhy_cy = tb3.CreateCell(4);
lhy_cy.CellStyle = cellStyle_normal;
lhy_cy.SetCellValue("联合一常压");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, 3, 4, 4));
ICell lhy_cy_count = tb3.CreateCell(5);
lhy_cy_count.CellStyle = cellStyle_normal;
lhy_cy_count.SetCellValue(s55[0]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, 3, 5, 5));
IRow tb4 = tb.CreateRow(4);//注:由于tb3中存在合并单元格的情况,故tb4的设计是与合并单元格的平行设计
ICell lhy_cz = tb4.CreateCell(4);
lhy_cz.CellStyle = cellStyle_normal;
lhy_cz.SetCellValue("联合一重整");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(4, 4, 4, 4));
ICell lhy_cz_count = tb4.CreateCell(5);
lhy_cz_count.CellStyle = cellStyle_normal;
lhy_cz_count.SetCellValue(s11[1]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(4, 4, 5, 5));
IRow tb5 = tb.CreateRow(5);
ICell lhy_jq = tb5.CreateCell(4);
lhy_jq.CellStyle = cellStyle_normal;
lhy_jq.SetCellValue("联合一加氢");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(5, 5, 4, 4));
ICell lhy_jq_count = tb5.CreateCell(5);
lhy_jq_count.CellStyle = cellStyle_normal;
lhy_jq_count.SetCellValue(s11[2]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(5, 5, 5, 5));
//联合二片区
IRow tb6 = tb.CreateRow(6);
ICell pq_2 = tb6.CreateCell(0);
pq_2.CellStyle = cellStyle_normal;
pq_2.SetCellValue("联合二片区");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(6, 8, 0, 0));
ICell pq_2_count = tb6.CreateCell(1);
pq_2_count.CellStyle = cellStyle_normal;
pq_2_count.SetCellValue(s11[3]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(6, 8, 1, 1));
ICell cj_2 = tb6.CreateCell(2);
cj_2.CellStyle = cellStyle_normal;
cj_2.SetCellValue("联合二车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(6, 8, 2, 2));
ICell cj_2_count = tb6.CreateCell(3);
cj_2_count.CellStyle = cellStyle_normal;
cj_2_count.SetCellValue(s33[1]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(6, 8, 3, 3));
ICell lhe_ch_1 = tb6.CreateCell(4);
lhe_ch_1.CellStyle = cellStyle_normal;
lhe_ch_1.SetCellValue("联合二 1#催化");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(6, 6, 4, 4));
ICell lhe_ch_1_count = tb6.CreateCell(5);
lhe_ch_1_count.CellStyle = cellStyle_normal;
lhe_ch_1_count.SetCellValue(s55[1]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(6, 6, 5, 5));
IRow tb7 = tb.CreateRow(7);
ICell lhe_ch_2 = tb7.CreateCell(4);
lhe_ch_2.CellStyle = cellStyle_normal;
lhe_ch_2.SetCellValue("联合二 2#催化");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 7, 4, 4));
ICell lhe_ch_2_count = tb7.CreateCell(5);
lhe_ch_2_count.CellStyle = cellStyle_normal;
lhe_ch_2_count.SetCellValue(s11[4]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 7, 5, 5));
IRow tb8 = tb.CreateRow(8);
ICell lhe_jq = tb8.CreateCell(4);
lhe_jq.CellStyle = cellStyle_normal;
lhe_jq.SetCellValue("联合二加氢处理");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(8, 8, 4, 4));
ICell lhe_jq_count = tb8.CreateCell(5);
lhe_jq_count.CellStyle = cellStyle_normal;
lhe_jq_count.SetCellValue(s11[5]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(8, 8, 5, 5));
//联合三片区
IRow tb9 = tb.CreateRow(9);
ICell pq_3 = tb9.CreateCell(0);
pq_3.CellStyle = cellStyle_normal;
pq_3.SetCellValue("联合三片区");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(9, 11, 0, 0));
ICell pq_3_count = tb9.CreateCell(1);
pq_3_count.CellStyle = cellStyle_normal;
pq_3_count.SetCellValue(s11[6]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(9, 11, 1, 1));
ICell cj_3 = tb9.CreateCell(2);
cj_3.CellStyle = cellStyle_normal;
cj_3.SetCellValue("联合三车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(9, 11, 2, 2));
ICell cj_3_count = tb9.CreateCell(3);
cj_3_count.CellStyle = cellStyle_normal;
cj_3_count.SetCellValue(s33[2]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(9, 11, 3, 3));
ICell jq_lh = tb9.CreateCell(4);
jq_lh.CellStyle = cellStyle_normal;
jq_lh.SetCellValue("加氢裂化");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(9, 9, 4, 4));
ICell jq_lh_count = tb9.CreateCell(5);
jq_lh_count.CellStyle = cellStyle_normal;
jq_lh_count.SetCellValue(s55[2]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(9, 9, 5, 5));
IRow tb10 = tb.CreateRow(10);
ICell zq_tn = tb10.CreateCell(4);
zq_tn.CellStyle = cellStyle_normal;
zq_tn.SetCellValue("制氢及干气提浓");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(10, 10, 4, 4));
ICell zq_tn_count = tb10.CreateCell(5);
zq_tn_count.CellStyle = cellStyle_normal;
zq_tn_count.SetCellValue(s11[7]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(10, 10, 5, 5));
IRow tb11 = tb.CreateRow(11);
ICell lhs_gq = tb11.CreateCell(4);
lhs_gq.CellStyle = cellStyle_normal;
lhs_gq.SetCellValue("联合三罐区");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(11, 11, 4, 4));
ICell lhs_gq_count = tb11.CreateCell(5);
lhs_gq_count.CellStyle = cellStyle_normal;
lhs_gq_count.SetCellValue(s11[8]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(11, 11, 5, 5));
//焦化片区
IRow tb12 = tb.CreateRow(12);
ICell jh_pq = tb12.CreateCell(0);
jh_pq.CellStyle = cellStyle_normal;
jh_pq.SetCellValue("焦化片区");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(12, 13, 0, 0));
ICell jh_pq_count = tb12.CreateCell(1);
jh_pq_count.CellStyle = cellStyle_normal;
jh_pq_count.SetCellValue(s11[9]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(12, 13, 1, 1));
ICell jh_cj = tb12.CreateCell(2);
jh_cj.CellStyle = cellStyle_normal;
jh_cj.SetCellValue("焦化车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(12, 12, 2, 2));
ICell jh_cj_count = tb12.CreateCell(3);
jh_cj_count.CellStyle = cellStyle_normal;
jh_cj_count.SetCellValue(s33[3]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(12, 12, 3, 3));
ICell jh = tb12.CreateCell(4);
jh.CellStyle = cellStyle_normal;
jh.SetCellValue("焦化");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(12, 12, 4, 4));
ICell jh_count = tb12.CreateCell(5);
jh_count.CellStyle = cellStyle_normal;
jh_count.SetCellValue(s55[3]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(12, 12, 5, 5));
IRow tb13 = tb.CreateRow(13);
ICell tl_cj = tb13.CreateCell(2);
tl_cj.CellStyle = cellStyle_normal;
tl_cj.SetCellValue("铁路车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(13, 13, 2, 2));
ICell tl_cj_count = tb13.CreateCell(3);
tl_cj_count.CellStyle = cellStyle_normal;
tl_cj_count.SetCellValue(s11[10]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(13, 13, 3, 3));
ICell tl = tb13.CreateCell(4);
tl.CellStyle = cellStyle_normal;
tl.SetCellValue("铁路(资产)");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(13, 13, 4, 4));
ICell tl_count = tb13.CreateCell(5);
tl_count.CellStyle = cellStyle_normal;
tl_count.SetCellValue(s33[4]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(13, 13, 5, 5));
//化工片区
IRow tb14 = tb.CreateRow(14);
ICell hg_pq = tb14.CreateCell(0);
hg_pq.CellStyle = cellStyle_normal;
hg_pq.SetCellValue("化工片区");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(14, 16, 0, 0));
ICell hg_pq_count = tb14.CreateCell(1);
hg_pq_count.CellStyle = cellStyle_normal;
hg_pq_count.SetCellValue(s11[11]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(14, 16, 1, 1));
ICell qj_cj = tb14.CreateCell(2);
qj_cj.CellStyle = cellStyle_normal;
qj_cj.SetCellValue("气加车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(14, 14, 2, 2));
ICell qj_cj_count = tb14.CreateCell(3);
qj_cj_count.CellStyle = cellStyle_normal;
qj_cj_count.SetCellValue(s33[5]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(14, 14, 3, 3));
ICell qi_jg = tb14.CreateCell(4);
qi_jg.CellStyle = cellStyle_normal;
qi_jg.SetCellValue("气加加工");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(14, 14, 4, 4));
ICell qi_jg_count = tb14.CreateCell(5);
qi_jg_count.CellStyle = cellStyle_normal;
qi_jg_count.SetCellValue(s55[4]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(14, 14, 5, 5));
IRow tb15 = tb.CreateRow(15);
ICell jbx_cj = tb15.CreateCell(2);
jbx_cj.CellStyle = cellStyle_normal;
jbx_cj.SetCellValue("聚丙烯车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(15, 16, 2, 2));
ICell jbx_cj_count = tb15.CreateCell(3);
jbx_cj_count.CellStyle = cellStyle_normal;
jbx_cj_count.SetCellValue(s11[12]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(15, 16, 3, 3));
ICell jbx_1 = tb15.CreateCell(4);
jbx_1.CellStyle = cellStyle_normal;
jbx_1.SetCellValue("聚丙烯一");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(15, 15, 4, 4));
ICell jbx_1_count = tb15.CreateCell(5);
jbx_1_count.CellStyle = cellStyle_normal;
jbx_1_count.SetCellValue(s33[6]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(15, 15, 5, 5));
IRow tb16 = tb.CreateRow(16);
ICell jbx_2 = tb16.CreateCell(4);
jbx_2.CellStyle = cellStyle_normal;
jbx_2.SetCellValue("聚丙烯二");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(16, 16, 4, 4));
ICell jbx_2_count = tb16.CreateCell(5);
jbx_2_count.CellStyle = cellStyle_normal;
jbx_2_count.SetCellValue(s11[13]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(16, 16, 5, 5));
//综合片区
IRow tb17 = tb.CreateRow(17);
ICell zh_pq = tb17.CreateCell(0);
zh_pq.CellStyle = cellStyle_normal;
zh_pq.SetCellValue("综合片区");
ICell zh_pq_count = tb17.CreateCell(1);
zh_pq_count.CellStyle = cellStyle_normal;
zh_pq_count.SetCellValue(s11[14]);
ICell zh_cj = tb17.CreateCell(2);
zh_cj.CellStyle = cellStyle_normal;
zh_cj.SetCellValue("综合车间");
ICell zh_cj_count = tb17.CreateCell(3);
zh_cj_count.CellStyle = cellStyle_normal;
zh_cj_count.SetCellValue(s33[7]);
ICell zh = tb17.CreateCell(4);
zh.CellStyle = cellStyle_normal;
zh.SetCellValue("综合");
ICell zh_count = tb17.CreateCell(5);
zh_count.CellStyle = cellStyle_normal;
zh_count.SetCellValue(s55[5]);
//系统片区
IRow tb18 = tb.CreateRow(18);
ICell xt_pq = tb18.CreateCell(0);
xt_pq.CellStyle = cellStyle_normal;
xt_pq.SetCellValue("系统片区");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(18, 22, 0, 0));
ICell xt_pq_count = tb18.CreateCell(1);
xt_pq_count.CellStyle = cellStyle_normal;
xt_pq_count.SetCellValue(s11[15]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(18, 22, 1, 1));
ICell yp_cj = tb18.CreateCell(2);
yp_cj.CellStyle = cellStyle_normal;
yp_cj.SetCellValue("油品车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(18, 18, 2, 2));
ICell yp_cj_count = tb18.CreateCell(3);
yp_cj_count.CellStyle = cellStyle_normal;
yp_cj_count.SetCellValue(s33[8]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(18, 18, 3, 3));
ICell yp = tb18.CreateCell(4);
yp.CellStyle = cellStyle_normal;
yp.SetCellValue("油品");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(18, 18, 4, 4));
ICell yp_count = tb18.CreateCell(5);
yp_count.CellStyle = cellStyle_normal;
yp_count.SetCellValue(s55[6]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(18, 18, 5, 5));
IRow tb19 = tb.CreateRow(19);
ICell ps_cj = tb19.CreateCell(2);
ps_cj.CellStyle = cellStyle_normal;
ps_cj.SetCellValue("排水车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(19, 19, 2, 2));
ICell ps_cj_count = tb19.CreateCell(3);
ps_cj_count.CellStyle = cellStyle_normal;
ps_cj_count.SetCellValue(s11[16]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(19, 19, 3, 3));
ICell ps = tb19.CreateCell(4);
ps.CellStyle = cellStyle_normal;
ps.SetCellValue("排水");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(19, 19, 4, 4));
ICell ps_count = tb19.CreateCell(5);
ps_count.CellStyle = cellStyle_normal;
ps_count.SetCellValue(s33[9]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(19, 19, 5, 5));
IRow tb20 = tb.CreateRow(20);
ICell gs_cj = tb20.CreateCell(2);
gs_cj.CellStyle = cellStyle_normal;
gs_cj.SetCellValue("供水车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(20, 20, 2, 2));
ICell gs_cj_count = tb20.CreateCell(3);
gs_cj_count.CellStyle = cellStyle_normal;
gs_cj_count.SetCellValue(s11[17]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(20, 20, 3, 3));
ICell gs_zc = tb20.CreateCell(4);
gs_zc.CellStyle = cellStyle_normal;
gs_zc.SetCellValue("供水(资产)");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(20, 20, 4, 4));
ICell gs_zc_count = tb20.CreateCell(5);
gs_zc_count.CellStyle = cellStyle_normal;
gs_zc_count.SetCellValue(s33[10]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(20, 20, 5, 5));
IRow tb21 = tb.CreateRow(21);
ICell rd_cj = tb21.CreateCell(2);
rd_cj.CellStyle = cellStyle_normal;
rd_cj.SetCellValue("热电车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(21, 21, 2, 2));
ICell rd_cj_count = tb21.CreateCell(3);
rd_cj_count.CellStyle = cellStyle_normal;
rd_cj_count.SetCellValue(s11[18]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(21, 21, 3, 3));
ICell rd_zc = tb21.CreateCell(4);
rd_zc.CellStyle = cellStyle_normal;
rd_zc.SetCellValue("热电(资产)");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(21, 21, 4, 4));
ICell rd_zc_count = tb21.CreateCell(5);
rd_zc_count.CellStyle = cellStyle_normal;
rd_zc_count.SetCellValue(s33[11]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(21, 21, 5, 5));
IRow tb22 = tb.CreateRow(22);
ICell mt_cj = tb22.CreateCell(2);
mt_cj.CellStyle = cellStyle_normal;
mt_cj.SetCellValue("码头车间");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(22, 22, 2, 2));
ICell mt_cj_count = tb22.CreateCell(3);
mt_cj_count.CellStyle = cellStyle_normal;
mt_cj_count.SetCellValue(s11[19]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(22, 22, 3, 3));
ICell mt_zc = tb22.CreateCell(4);
mt_zc.CellStyle = cellStyle_normal;
mt_zc.SetCellValue("码头(资产)");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(22, 22, 4, 4));
ICell mt_zc_count = tb22.CreateCell(5);
mt_zc_count.CellStyle = cellStyle_normal;
mt_zc_count.SetCellValue(s33[12]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(22, 22, 5, 5));
//其他
IRow tb23 = tb.CreateRow(23);
ICell qt = tb23.CreateCell(0);
qt.CellStyle = cellStyle_normal;
qt.SetCellValue("其他");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(23, 24, 0, 0));
ICell qt_count = tb23.CreateCell(1);
qt_count.CellStyle = cellStyle_normal;
qt_count.SetCellValue(s11[20]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(23, 24, 1, 1));
ICell xfd_cj = tb23.CreateCell(2);
xfd_cj.CellStyle = cellStyle_normal;
xfd_cj.SetCellValue("消防队");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(23, 23, 2, 2));
ICell xfd_cj_count = tb23.CreateCell(3);
xfd_cj_count.CellStyle = cellStyle_normal;
xfd_cj_count.SetCellValue(s33[13]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(23, 23, 3, 3));
ICell xfd_zz = tb23.CreateCell(4);
xfd_zz.CellStyle = cellStyle_normal;
xfd_zz.SetCellValue("消防队");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(23, 23, 4, 4));
ICell xfd_zz_count = tb23.CreateCell(5);
xfd_zz_count.CellStyle = cellStyle_normal;
xfd_zz_count.SetCellValue(s55[7]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(23, 23, 5, 5));
IRow tb24 = tb.CreateRow(24);
ICell jlz_cj = tb24.CreateCell(2);
jlz_cj.CellStyle = cellStyle_normal;
jlz_cj.SetCellValue("计量站");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(24, 24, 2, 2));
ICell jlz_cj_count = tb24.CreateCell(3);
jlz_cj_count.CellStyle = cellStyle_normal;
jlz_cj_count.SetCellValue(s11[21]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(24, 24, 3, 3));
ICell jlz_zz = tb24.CreateCell(4);
jlz_zz.CellStyle = cellStyle_normal;
jlz_zz.SetCellValue("计量站");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(24, 24, 4, 4));
ICell jlz_zz_count = tb24.CreateCell(5);
jlz_zz_count.CellStyle = cellStyle_normal;
jlz_zz_count.SetCellValue(s33[14]);
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(24, 24, 5, 5));
string path = Server.MapPath("~/Upload//本周超期未换油统计结果.xls");
using (FileStream fs = System.IO.File.OpenWrite(path)) //打开一个xls文件,如果没有则自行创建,如果存在myxls.xls文件则在创建是不要打开该文件!
{
wk.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。
Console.WriteLine("提示:创建成功!");
}
return Path.Combine("/Upload", "本周超期未换油统计结果.xls");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return "";
}
}
}
}<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment.ZyConfig
{
public class SpeciatyManagment
{
private ISpecialty db_specialty = new Zy();
//添加一个菜单
//parentID == -1 ,添加到根节点
public bool AddSpecialtyItem(int parentID, Speciaty_Info add)
{
if (parentID == -1)
{
Speciaty_Info root = GetRootItem();
return db_specialty.AddSpecialty(root.Specialty_Id, add);
}
else
return db_specialty.AddSpecialty(parentID, add);
}
//修改一个菜单
public bool ModifySpecialtyItem(Speciaty_Info modify)
{
return db_specialty.ModifySpecialty(modify.Specialty_Id, modify);
}
//删除一个菜单
public bool DeleteSpecialtyItem(int del)
{
return db_specialty.DeleteSpecialty(del);
}
//获得菜单的根节点
public Speciaty_Info GetRootItem()
{
try
{
List<Speciaty_Info> res = db_specialty.GetSpecialty("root");
if (res.Count > 1)
throw new Exception("DB has not only one root item");
return res[0];
}
catch (Exception e)
{
return null;
}
}
public Speciaty_Info GetItemById(int id)
{
return db_specialty.GetSpecialty(id);
}
//获得某一个菜单项的子节点
public List<Speciaty_Info> GetChildsspecialty(int specialtyID)
{
List<Speciaty_Info> childs = new List<Speciaty_Info>();
childs = db_specialty.GetChildSpecialty(specialtyID);
return childs;
}
private SpecialtyTree BuildChildTree(int parentId)
{
SpecialtyTree cRoot = new SpecialtyTree();
Speciaty_Info cRootM = GetItemById(parentId);
cRoot.Specialty_Id = cRootM.Specialty_Id;
cRoot.Specialty_Name = cRootM.Specialty_Name;
List<Speciaty_Info> childs = GetChildsspecialty(parentId);
foreach (Speciaty_Info m in childs)
{
SpecialtyTree mt = BuildChildTree(m.Specialty_Id);
cRoot.childs.Add(mt);
}
return cRoot;
}
public SpecialtyTree BuildSpecialtyTree()
{
Speciaty_Info root = GetRootItem();
return BuildChildTree(root.Specialty_Id);
}
private void BuildSpeciatyList_inter(SpecialtyListNode parent, List<SpecialtyListNode> list)
{
List<Speciaty_Info> childs = GetChildsspecialty(parent.Specialty_Id);
foreach (Speciaty_Info m in childs)
{
SpecialtyListNode mn = new SpecialtyListNode();
mn.Specialty_Id = m.Specialty_Id;
mn.Specialty_Name = m.Specialty_Name;
mn.Parent_id = parent.Specialty_Id;
mn.level = parent.level + 1;
parent.Childs.Add(mn.Specialty_Id);
list.Add(mn);
BuildSpeciatyList_inter(mn, list);
mn.Childs.ForEach(i => parent.Childs.Add(i));
}
}
public List<SpecialtyListNode> BuildSpeciatyList()
{
Speciaty_Info root = GetRootItem();
SpecialtyListNode rmn = new SpecialtyListNode();
rmn.Specialty_Id = root.Specialty_Id;
rmn.Specialty_Name = root.Specialty_Name;
rmn.level = -1;
List<SpecialtyListNode> list = new List<SpecialtyListNode>();
BuildSpeciatyList_inter(rmn, list);
foreach (SpecialtyListNode mn in list)
{
if (mn.Parent_id == root.Specialty_Id)
mn.Parent_id = 0;
}
return list;
}
private Speciaties sps = new Speciaties();
public List<Speciaty_Info> getsps()
{
List<Speciaty_Info> r = sps.getSepciaty_Parent();
return r;
}
public List<Speciaty_Info> getsps_child(int sp_id)
{
List<Speciaty_Info> r = sps.getSepciaty_Childs(sp_id);
return r;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EquipBLL.AdminManagment.MenuConfig;
using EquipBLL.AdminManagment;
using EquipModel.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using FlowEngine;
using FlowEngine.UserInterface;
using EquipModel.Context;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data;
using FlowEngine.Modals;
using FlowEngine.DAL;
using FlowEngine.TimerManage;
using System.Xml;
namespace WebApp.Controllers
{
public class MainController :CommonController
{
// GET: Main
private SysMenuManagment menuconfig = new SysMenuManagment();
private PersonManagment PM = new PersonManagment();
public class getIndexmodel
{
public List<MenuListNode> mt;
public int isManager;
public string username;
public int userid;
public string belong_depart;
}
public ActionResult Index1()
{
MenuTree mtree = menuconfig.BuildMenuTree();
return View(mtree);
}
public ActionResult Index()
{
//CWFEngine.CreateAWFEntityByName("");
List<MenuListNode> mt = menuconfig.BuildMenuList();
int a = mt.Count();
return View(mt);
}
public ActionResult Index0()
{
if(Session["User"]==null)
{
Response.Redirect("/Login/chaoshi");
return View();
}
else
{
getIndexmodel model = new getIndexmodel();
model.mt = menuconfig.BuildMenuList();
model.username = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
model.userid = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment PM = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pm_info = PM.Get_PersonModal(model.userid);
model.belong_depart = pm_info.Department_Name;
model.isManager = PM.is_Role_admin(model.username);
//int a = mt.Count();
return View(model);
}
}
// Get: Home
public class homemodel
{
public int[] q_cunzai;
public string userName;
public int userId;
public string A7dot1Isdone;
public string A6dot2Isdone;
public string A6dot2SjFile;
}
public ActionResult Home()
{
homemodel hm = new homemodel();
hm.userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name.ToString();
hm.userId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
//string cj = pm.Get_Person_Cj(hm.userId).First().EA_Name;
string cj = "联合一车间";
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(hm.userId);
QEntranceManagment qem = new QEntranceManagment();
List<Quick_Entrance> qe = qem.GetQ_EbyP_Id(hm.userId);
hm.q_cunzai = new int[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
if (qe != null)
{
foreach (var q in qe)
{
hm.q_cunzai[q.xuhao - 1] = 1;
}
}
//if (pv.Role_Names == "现场工程师")
if (pv.Role_Names.Contains("现场工程师"))
{
DateTime now = DateTime.Now;
DateTime LastThursday = now;
DateTime Day20 = now;
string a = now.DayOfWeek.ToString("d");
if (a == "1")
{
LastThursday = now.AddDays(-4).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
}
if (a == "2")
{
LastThursday = now.AddDays(-5).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
}
if (a == "3")
{
LastThursday = now.AddDays(-6).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
}
if (a == "4")
{
LastThursday = now.AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
}
if (a == "5")
{
LastThursday = now.AddDays(-1).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
}
if (a == "6")
{
LastThursday = now.AddDays(-2).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
}
if (a == "0")
{
LastThursday = now.AddDays(-3).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
}
if (now.Day >= 20)
{
Day20 = now.AddDays(20 - now.Day).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
string query_list1 = "E.WE_Ser,R.time";
string query_condition1 = " P.Cj_Name ='" + cj + "' and E.W_Name='A6dot2' and M.Miss_Name ='Xc_Sample' ";
string record_filter1 = "Convert(datetime,time)>'" + Day20.ToString() + "' and Convert(datetime,time)<'" + now.ToString() + "'";
DataTable dt1 = CWFEngine.QueryAllInformation(query_list1, query_condition1, record_filter1);
if (dt1.Rows.Count != 0)
hm.A6dot2Isdone = "false";
else
hm.A6dot2Isdone = "true";
}
else
{
hm.A6dot2Isdone = "false";
}
string query_list = "E.WE_Ser,R.time";
string query_condition = " P.Cj_Name ='" + cj + "' and E.W_Name='A7dot1dot1'";
string record_filter = "Convert(datetime,time)>'" + LastThursday.ToString() + "' and Convert(datetime,time)<'" + now.ToString() + "'";
DataTable dt = CWFEngine.QueryAllInformation(query_list, query_condition, record_filter);
if(dt!=null)
{
if (dt.Rows.Count != 0)
hm.A7dot1Isdone = "true";
else
hm.A7dot1Isdone = "false";
}
}
else
{
hm.A7dot1Isdone = "true";
}
//注:这里判断的是部门为设监中心的
if (pv.Department_Name.Contains("设监中心"))
{
DateTime now = DateTime.Now;
DateTime Day27 = now;
if (now.Day >= 27)
{
Day27 = now.AddDays(27 - now.Day).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second);
string query_list1 = "E.WE_Ser,R.time";
string query_condition1 = "E.W_Name='A6dot2' and M.Miss_Name ='Sj_Result' ";
string record_filter1 = "Convert(datetime,time)>'" + Day27.ToString() + "' and Convert(datetime,time)<'" + now.ToString() + "'";
DataTable dt1 = CWFEngine.QueryAllInformation(query_list1, query_condition1, record_filter1);
if (dt1.Rows.Count != 0)
hm.A6dot2SjFile = "false";
else
hm.A6dot2SjFile = "true";
}
else
{
hm.A6dot2SjFile = "false";
}
}
else
{
hm.A6dot2SjFile = "false";
}
return View(hm);
}
//public string CreateFlow(string flowname)
//{
// UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
// if (wfe != null)
// {
// Dictionary<string, string> record = wfe.GetRecordItems();
// record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// record["time"] = DateTime.Now.ToString();
// return wfe.Start(record);
// //Json(new { url = wfe.Start(record), wfe_id = wfe.EntityID });
// //"{url:'" + wfe.Start(record) + "', wfe_id:'" + wfe.EntityID + "'}";
// }
// else
// return null;
//}
public string CreateFlow(string flowname)
{
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName(flowname);
if (wfe != null)
{
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["currentuser"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
signal["start_done"] = "true";
//submit
CWFEngine.SubmitSignal(wfe.EntityID, signal, record);
CWorkFlow wf = new CWorkFlow();
XmlDocument doc = new XmlDocument();
doc.LoadXml(CWFEngine.GetWorkFlowEntiy(wfe.EntityID, true).Binary);
wf.InstFromXmlNode(doc.DocumentElement);
string returl = "";
if (wf.GetCurrentEvent().CheckAuthority<Person_Info>((Dictionary<string, object>)Session[CWFEngine.authority_params], ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext))
{
returl = wf.GetCurrentEvent().currentaction + "?wfe_id=" + wfe.EntityID.ToString();
//如果权限认证通过则返回正确的页面URL
return returl;
//return returl;
}
else
{
//如果权限认证不通过, 则删除刚创建的工作流实体, 并返回 -1
CWFEngine.RemoveWFEntity(wfe.EntityID);
return "-1";
}
//Json(new { url = wfe.Start(record), wfe_id = wfe.EntityID });
//"{url:'" + wfe.Start(record) + "', wfe_id:'" + wfe.EntityID + "'}";
}
else
return null;
}
/// <summary>
/// 获得当前的任务列表
/// </summary>
/// <returns>前台JS解析的任务JSon数据</returns>
[HttpPost]
public JsonResult ListMission()
{
IObjectContextAdapter IOca = new EquipWebContext();
List<UI_MISSION> miss = CWFEngine.GetActiveMissions<Person_Info>(IOca.ObjectContext);
List<Object> miss_obj = new List<object>();
foreach(UI_MISSION item in miss)
{
UI_MISSION mi = CWFEngine.GetHistoryMissions(item.WE_Entity_Id).Last();
IDictionary<string, string> record = CWFEngine.GetMissionRecordInfo(mi.Miss_Id);
DateTime dt = DateTime.Parse(!record.ContainsKey("time") ? DateTime.Now.ToString() : record["time"]);
TimeSpan ts = DateTime.Now - dt;
string time_last = "";
if (ts.TotalDays > 1)
time_last += (((int)ts.TotalDays).ToString() + "天之前");
else if (ts.TotalHours > 1)
time_last += (((int)ts.TotalHours).ToString() + "小时之前");
else
time_last += (((int)ts.TotalMinutes).ToString() + "分钟之前");
object o = new {
WF_ICON = "fa fa-flash text-text-aqua",
MISS_Url = item.Mission_Url,
WF_Name = CWFEngine.GetWorkFlowEntiy(item.WE_Entity_Id, true).description,
MISS_Name = item.WE_Event_Desc,
TIME_Last = time_last};
miss_obj.Add(o);
}
return Json(miss_obj.ToArray());
}
public bool checktimeout()
{
bool result = false;
if (Session["User"] != null)
result = true;
return result;
}
//菜单栏的提示任务个数
public JsonResult task_mission()
{
IObjectContextAdapter IOca = new EquipWebContext();
List<UI_MISSION> miss = CWFEngine.GetActiveMissions<Person_Info>(IOca.ObjectContext);
List<Object> Url_List = new List<object>();
List<Object> urlobj = new List<object>();
foreach (UI_MISSION item in miss)//本模块的作用是:将MISS_Url中截取前面的字段;例如“/A4dot4/Zzsubmit?wef=123”截取“A4dot4”,并存入数组str。注:这些MISS_Url就是待处理任务的跳转路径,故与本模块待处理任务个数提示可以关联
{
UI_MISSION mi = CWFEngine.GetHistoryMissions(item.WE_Entity_Id).Last();
string MISS_Url = item.Mission_Url;
string[] s = MISS_Url.Split(new char[] { '/' });
string str = s[1];
Url_List.Add(str);
}
//判断数组str中的相同元素的个数,并将结果转为json格式,返回前台
var vs = from string p in Url_List group p by p into g select new { g, num = g.Count() };
foreach (var v in vs)
{
object m = new
{
url_name = v.g.Key,
url_count = v.num
};
urlobj.Add(m);
}
return Json(urlobj.ToArray());
}
//zxh
public string ListMission_zxh()
{
try
{
IObjectContextAdapter IOca = new EquipWebContext();
List<UI_MISSION> miss = CWFEngine.GetActiveMissions<Person_Info>(IOca.ObjectContext);
List<Object> miss_obj = new List<object>();
string userName = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name.ToString();
foreach (UI_MISSION item in miss)
{
MainMissionsModel mm = GetMainMissionsInfo(item.WE_Entity_Id);
Jobs js = new Jobs();
string endtime = "";
string lsh_xy = "1";
if (js.GetDSnexttime(mm.jobname, item.WE_Entity_Id) != null)
{
if (js.GetDSnexttime(mm.jobname, item.WE_Entity_Id).PreTime == null)
{
string end_corn = js.GetDSnexttime(mm.jobname, item.WE_Entity_Id).corn_express;
TriggerTiming TT = new TriggerTiming();
TT.FromString(end_corn);
TT.RefreshNextTiming(DateTime.Now);
endtime = TT.NextTiming.ToString();
}
else
{
endtime = js.GetDSnexttime(mm.jobname, item.WE_Entity_Id).PreTime.ToString();
}
}
if (mm.Equip_GyCode == null || mm.Equip_GyCode == "")
lsh_xy = "0";
object o = new
{
WF_ICON = "fa fa-flash text-text-aqua",
MISS_Url = item.Mission_Url,
WF_Name = mm.WF_Name,
MISS_Name = item.WE_Event_Desc,
wfe_serial = mm.wfe_serial,
sbCode = mm.Equip_GyCode,
time = mm.time,
endtime = endtime,
lsh_xy = lsh_xy
};
EquipManagment em=new EquipManagment ();
if (mm.WF_Name.Contains("定时KPI月报"))
{
if (userName == "龚海桥" && mm.WF_Name.Contains("联合一片区"))
miss_obj.Add(o);
else if (userName == "丁一刚" && mm.WF_Name.Contains("联合二片区"))
miss_obj.Add(o);
else if (userName == "邓杰" && (mm.WF_Name.Contains("联合三片区") || mm.WF_Name.Contains("化工片区")))
miss_obj.Add(o);
else if (userName == "杨书毅" && mm.WF_Name.Contains("联合四片区"))
miss_obj.Add(o);
else if (userName == "武文斌" && (mm.WF_Name.Contains("综合片区") || mm.WF_Name.Contains("系统片区")))
miss_obj.Add(o);
}
else
{
if (userName == "sa" || userName == "程聂")
miss_obj.Add(o);
else
{
if(lsh_xy=="1")
{
if(em.getEquip_ByGyCode(mm.Equip_GyCode).Equip_Specialty=="动")
miss_obj.Add(o);
}
else
miss_obj.Add(o);
}
}
}
TablesManagment tm = new TablesManagment();
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
if (pv.Role_Names.Contains("可靠性工程师"))
{
string wfe_ser = "";
List<string> cjname = new List<string>();
List<Equip_Archi> EA = pm.Get_Person_Cj(UserId);
foreach (var ea in EA)
{
cjname.Add(ea.EA_Name);
}
List<A5dot1Tab1> E = tm.Getdcl_listbyisZG(0, cjname);
for (int i = 0; i < E.Count; i++)
{
if (E[i].dataSource != null)
wfe_ser = E[i].dataSource;
object o = new
{
WF_ICON = "fa fa-flash text-text-aqua",
MISS_Url = "/A5dot1/Index",
WF_Name = "设备完好",
MISS_Name = "可靠性工程师确认整改",
wfe_serial = wfe_ser,
sbCode = E[i].sbGyCode.ToString(),
time = E[i].zzSubmitTime.ToString(),
endtime = "",
lsh_xy = 1
};
miss_obj.Add(o);
}
SxglManagment Sx = new SxglManagment();
List<A5dot2Tab1> EE = Sx.GetSxItem(cjname);
foreach (var item in EE)
{
if (item.temp2 != null)
wfe_ser = item.temp2;
object o = new
{
WF_ICON = "fa fa-flash text-text-aqua",
MISS_Url = "/A5dot2/Index",
WF_Name = "竖向问题",
MISS_Name = "可靠性工程师确认整改",
wfe_serial = wfe_ser,
sbCode = item.sbGyCode.ToString(),
time = item.jxSubmitTime.ToString(),
endtime = "",
lsh_xy = 1
};
miss_obj.Add(o);
}
}
string str = JsonConvert.SerializeObject(miss_obj);
return ("{" + "\"data\": " + str + "}");
}
catch (Exception e)
{
return null;
}
}
//zxh
//退出登录
public string login_out()
{
Session.RemoveAll();
Session.Clear();
return("/Login/Index");
}
/// <summary>
/// 获得工作流进度信息
/// </summary>
/// <returns>前台JS解析的JSon数据</returns>
[HttpPost]
public JsonResult ListProcess()
{
List<UI_WFEntity_Info> start_entities = CWFEngine.GetWFEntityByHistoryStatus(t => t.Record_Info.Count(q => q.Re_Name=="username" && q.Re_Value=="cb") > 0);
List<object> proc_list = new List<object>();
IObjectContextAdapter IOca = new EquipWebContext();
foreach (var en in start_entities)
{
string startUser = CWFEngine.GetMissionRecordInfo(CWFEngine.GetHistoryMissions(en.EntityID).First().Miss_Id)["username"];
if (startUser != (Session["User"] as Person_Info).Person_Name)
continue;
int total = CWFEngine.GetWorkFlowAvgSteps(en.name);
int curr = CWFEngine.GetWFEntityFinishSteps(en.EntityID);
if (total == 0)
total = 5;
if (curr == 0)
curr = 1;
object o = new
{
WF_Name = en.description,
MISS_Name = CWFEngine.GetActiveMission<Person_Info>(en.EntityID, IOca.ObjectContext).WE_Event_Desc,
MISS_Present = (double)curr/(double)total * 100
};
proc_list.Add(o);
}
return Json(proc_list.ToArray());
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
namespace WebApp.Controllers
{
public class A4dot1Controller : CommonController
{
public ActionResult Index()
{
return View(getIndexListRecords("A4dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult Design(string wfe_id)
{
//find cj zz namme
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
//miss.Miss_Params
ViewBag.flag = 0;
if (miss.Miss_Params["Cj_Name"].ToString() != "")
{
ViewBag.CjName = miss.Miss_Params["Cj_Name"].ToString();
ViewBag.ZzName = miss.Miss_Params["Zz_Name"].ToString();
ViewBag.flag = 1;
}
// ViewBag.CjName = "CCCJJJ";
// ViewBag.ZzName = "ZZZZZZ";
return View(getSubmitModel(wfe_id));//
}
public ActionResult PqConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult UploadBlueprint(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdConfirm2(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult OrderForm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult ZytdConfirm3(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult JscSave(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public ActionResult WzcConfirm(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string Design_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Design_Done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Client"] = item["Client"].ToString();
signal["Design_Description"] = item["Design_Description"].ToString();
signal["Plan_Order"] = item["Plan_Order"].ToString();
signal["Plan_Name"] = item["Plan_Name"].ToString();
signal["CM_Department"] = item["CM_Department"].ToString();
signal["Equip_GyCode"] = "";//业务流水号需要正常工作必须有这一字段?
signal["start_done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot1/Index");
}
public string PqConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["PqSuggestion"] = item["Pqsuggestion"].ToString();
signal["PqConfirm_Result"] = item["PqConfirm_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot1/Index");
}
public string ZytdConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdSuggestion"] = item["Zytdsuggestion"].ToString();
signal["ZytdConfirm_Result"] = item["ZytdConfirm_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot1/Index");
}
public string UploadBlueprint_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Blueprint"] = item["Blueprint"].ToString();
signal["UploadBlueprint_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot1/Index");
}
public string ZytdConfirm2_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdReason"] = item["ZytdReason"].ToString();
signal["ZytdConfirm2_Result"] = item["ZytdConfirm2_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot1/Index");
}
public string OrderForm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["Order_Form"] = item["Order_Form"].ToString();
signal["Fittings_Name"] = item["Fittings_Name"].ToString();
signal["Fittings_Code"] = item["Fittings_Code"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = "";
signal["OrderForm_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A4dot1/Index");
}
public string ZytdConfirm3_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZytdReason2"] = item["ZytdReason2"].ToString();
signal["ZytdConfirm3_Result"] = item["ZytdConfirm3_Result"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot1/Index");
}
public string JscSave_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JscSave_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot1/Index");
}
public string WzcConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["WzcConfirm_Done"] = "true";
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{ return ""; }
return ("/A4dot1/Index");
}
}
}<file_sep>using EquipDAL.Implement;
using EquipDAL.Interface;
using EquipModel.Context;
using EquipModel.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipBLL.AdminManagment
{
public class PersonManagment
{
public class P_viewModal
{
public int Person_Id;
public string Person_Name;
public string Person_mail;
public string Person_tel;
public int Department_Id;
public string Department_Name;
public string EquipArchi_Ids;
public string EquipArchi_Names;
public string Speciaty_Ids;
public string Speciaty_Names;
public string Role_Ids;
public string Role_Names;
public string Menu_Ids;
public List<Menu> Menus;
}
public class Role_viewModal
{
public int Role_Id;
public string Role_Name;
public bool Role_selected;
}
private Person_Infos Persons= new Person_Infos();
//功能:已知用户名称,查询用户对应信息
//参数:userName 用户姓名
//返回值:Person_Info
public Person_Info Get_Person(string userName)
{
var P = Persons.GetPerson_info(userName);
return P;
}
//20161212月添加的方法,获取用户管理的某指定车间的装置
public List<Equip_Archi> Get_Person_Zz_ofCj(int id, int cj_id)
{
List<Equip_Archi> r = Persons.getZz_of_Person(id, cj_id);
return r;
}
/// <summary>
/// 获取用户管辖的装置
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public List<Equip_Archi> Get_Person_Zz(int id)
{
List<Equip_Archi> r = Persons.getZzByPerson(id);
return r;
}
//功能:获取所有角色的List集合,并且用户已分配的角色默认为选中状态
//参数:PersonRoles,用户已分配角色Id串,若干角色Id之间以","分隔,Example:"1,4,17",该参数默认为"",若只是显示所有角色集合,则取默认值
//返回值:List<Role_viewModal>,前台程序可以在这个的基础上将角色信息显示在Select下拉框中
/* Role_viewModal的定义如下:
public class Role_viewModal
{
public int Role_Id;
public string Role_Name;
public bool Role_selected;
}
*/
public List<Role_viewModal> Get_All_Roles( string PersonRoles = "")
{
RoleManagment RM = new RoleManagment();
var P = RM.get_ALl_Roles();
List<int> RoleList = new List<int>();
string[] s1 = PersonRoles.Split(new char[] { ',' });
if (PersonRoles != "")
{
for (int i = 0; i < s1.Length; i++)
{ RoleList.Add(Convert.ToInt32(s1[i])); }
}
List<Role_viewModal> pr = new List<Role_viewModal>();
Role_viewModal ii ;
foreach(var item in P)
{
ii = new Role_viewModal();
ii.Role_Id = item.Role_Id;
ii.Role_Name = item.Role_Name;
if (RoleList.Contains(item.Role_Id))
ii.Role_selected = true;
else
ii.Role_selected = false;
pr.Add(ii);
}
return pr;
}
//功能:获取某用户的详细信息,为用户管理模块做数据准备
//参数:userId 用户Id
//返回值:P_viewModal
/* P_viewModal的定义如下:
public class P_viewModal
{
public int Person_Id;
public string Person_Name;
public string Person_mail;
public string Person_tel;
public int Department_Id;
public string Department_Name;
public string Speciaty_Ids; //若用户有多个专业,各专业Id之间用","隔开
public string Speciaty_Names;//若用户有多个专业,各专业名称之间用","隔开
public string Role_Ids; //若用户有多个角色
public string Role_Names;
public string Menu_Ids;
public List<Menu> Menus;
}
*/
public P_viewModal Get_PersonModal(int userId)
{ int i;
var P = Persons.Get_PersonModal(userId);
P_viewModal p_item=new P_viewModal();
p_item.Person_Id=P.P_Info.Person_Id;
p_item.Person_Name=P.P_Info.Person_Name;
p_item.Person_mail=P.P_Info.Person_mail;
p_item.Person_tel=P.P_Info.Person_tel;
p_item.Department_Id=P.D_Info.Depart_Id;
p_item.Department_Name=P.D_Info.Depart_Name;
//管理区域
p_item.EquipArchi_Ids = "";
if(P.EA_Info.Count>0)
{
for (i = 0; i < P.EA_Info.Count - 1; i++)
{
p_item.EquipArchi_Ids = p_item.EquipArchi_Ids + (P.EA_Info[i]).EA_Id + ",";
}
p_item.EquipArchi_Ids = p_item.EquipArchi_Ids + (P.EA_Info[i]).EA_Id;
}
p_item.EquipArchi_Names = "";
if (P.EA_Info.Count > 0)
{
for (i = 0; i < P.EA_Info.Count - 1; i++)
{
p_item.EquipArchi_Names = p_item.EquipArchi_Names + (P.EA_Info[i]).EA_Name + ",";
}
p_item.EquipArchi_Names = p_item.EquipArchi_Names + (P.EA_Info[i]).EA_Name;
}
//专业信息
p_item.Speciaty_Ids="";
if (P.S_Info.Count > 0)
{
for (i = 0; i < P.S_Info.Count - 1; i++)
{
p_item.Speciaty_Ids = p_item.Speciaty_Ids + (P.S_Info[i]).Specialty_Id + ",";
}
p_item.Speciaty_Ids = p_item.Speciaty_Ids + (P.S_Info[i]).Specialty_Id;
}
p_item.Speciaty_Names="";
if (P.S_Info.Count > 0)
{
for (i = 0; i < P.S_Info.Count - 1; i++)
{
p_item.Speciaty_Names = p_item.Speciaty_Names + (P.S_Info[i]).Specialty_Name + ",";
}
p_item.Speciaty_Names = p_item.Speciaty_Names + (P.S_Info[i]).Specialty_Name;
}
//角色信息
p_item.Role_Ids="";
if (P.R_Info.Count > 0)
{ for( i=0;i<P.R_Info.Count-1;i++)
{ p_item.Role_Ids= p_item.Role_Ids + (P.R_Info[i]).Role_Id +",";
}
p_item.Role_Ids=p_item.Role_Ids +(P.R_Info[i]).Role_Id ;
}
p_item.Role_Names="";
if(P.R_Info.Count>0)
{
for( i=0;i<P.R_Info.Count-1;i++)
{ p_item.Role_Names= p_item.Role_Names + (P.R_Info[i]).Role_Name +",";
}
p_item.Role_Names=p_item.Role_Names +(P.R_Info[i]).Role_Name ;
}
//系统权限
p_item.Menu_Ids = "";
if (P.M_Info.Count > 0)
{
for (i = 0; i < P.M_Info.Count - 1; i++)
{
p_item.Menu_Ids = p_item.Menu_Ids + (P.M_Info[i]).Menu_Id + ",";
}
p_item.Menu_Ids = p_item.Menu_Ids + (P.M_Info[i]).Menu_Id;
}
p_item.Menus = P.M_Info;
return p_item ;
}
/*
* 功能:获取某用户所有信息
* 参数:Id 用户Id
* 返回值:PersonModal 其具体定义见Person_Info.cs文件
* public class PersonModal
{
public Person_Info P_Info;//用户基本信息
public Depart_Archi D_Info;//部门信息
public List<Speciaty_Info> S_Info;//专业信息
public List<Role_Info> R_Info;//角色信息
public List<Menu> M_Info;//系统菜单信息
}
* */
public Person_Infos.PersonModal get_PersonInfo(int userId)
{
try
{
var P = Persons.Get_PersonModal(userId);
return P;
}
catch { return null; }
}
//功能:获取所有用户的基本信息
//参数:空
//返回值:List<Person_Info>
public List<Person_Info> Get_All_basePersonInfo()
{
var p = Persons.GetAllPerson_info();
return p;
}
private List<int> Get_EquipArchi_Allleafs(List<int> EquipArchi_IDs)
{
Equip_Archis EA = new Equip_Archis();
List<int> leafEA_IDs = new List<int>();
foreach (int Id in EquipArchi_IDs)
{
if (EA.getEA_Childs(Id).Count == 0) leafEA_IDs.Add(Id);
else
SearchLeafEA(Id, leafEA_IDs);
}
return leafEA_IDs;
}
private void SearchLeafEA(int Id, List<int> leafEA_IDs)
{
Equip_Archis EA = new Equip_Archis();
List<Equip_Archi> Childs = EA.getEA_Childs(Id);
foreach (Equip_Archi item in Childs)
{
if (EA.getEA_Childs(item.EA_Id).Count == 0) leafEA_IDs.Add(item.EA_Id);
else SearchLeafEA(item.EA_Id, leafEA_IDs);
}
}
/*功能:往数据库添加用户基本信息,并设置用户部门、角色、专业和系统菜单信息
参数: p 新用户Person_Info对象
Depart_id 所属部门Id
* Role_IDs 分配的所有角色Id集合
* Speciaty_IDs 所属专业Id集合
* Menu_IDs 分配系统菜单Id集合
*返回值:bool
* */
public bool Add_Person(Person_Info p,int Depart_id,List<int> Role_IDs,List<int> EquipArchi_IDs,List<int> Speciaty_IDs,List<int> Menu_IDs)
{
try
{
int NewpP_id=Persons.AddPerson_info(p);
Persons.Person_LinkDepart(NewpP_id, Depart_id);
Persons.Person_LinkSpeciaties(NewpP_id, Speciaty_IDs);
Persons.Person_LinkEAs(NewpP_id, EquipArchi_IDs);
List<int> Zz_IDs = Get_EquipArchi_Allleafs(EquipArchi_IDs);
Persons.Person_LinkEquip(NewpP_id, Zz_IDs, Speciaty_IDs);
Persons.Person_LinkRole(NewpP_id, Role_IDs);
Persons.Person_LinkMenus(NewpP_id, Menu_IDs);
return true;
}
catch { return false; }
}
/*功能:修改用户的基本信息,并设置用户新的部门、角色、专业和系统菜单信息
参数: p 提交的用户基本新信息Person_Info对象
Depart_id 新的所属部门Id
* Role_IDs 新分配的所有角色Id集合
* Speciaty_IDs 新的所属专业Id集合
* Menu_IDs 新分配的系统菜单Id集合
*返回值:bool
* */
public bool Update_Person(Person_Info p,int Depart_id,List<int> Role_IDs,List<int> EquipArchi_IDs,List<int> Speciaty_IDs,List<int> Menu_IDs)
{
try
{
Persons.ModifyPerson_info(p);
Persons.Person_LinkDepart(p.Person_Id, Depart_id);
Persons.Person_LinkSpeciaties(p.Person_Id, Speciaty_IDs);
Persons.Person_LinkEAs(p.Person_Id, EquipArchi_IDs);
List<int> Zz_IDs = Get_EquipArchi_Allleafs(EquipArchi_IDs);
Persons.Person_LinkEquip(p.Person_Id, Zz_IDs, Speciaty_IDs);
Persons.Person_LinkRole(p.Person_Id, Role_IDs);
Persons.Person_LinkMenus(p.Person_Id, Menu_IDs);
return true;
}
catch { return false; }
}
/*功能:删除用户,并自动删除用户的部门、角色、专业和系统菜单等相关链接信息
参数: id 用户Id
*返回值:bool
* */
public bool Delete_Person(int id)
{
return Persons.DeletePerson_info(id);
}
/*功能:获取某用户已分配的所有角色信息集合
*参数:id 用户Id
*返回值:List<Role_Info>
*/
public List<Role_Info> Get_Person_Roles(int id)
{
List<Role_Info> r = new List<Role_Info>();
r=Persons.GetPerson_Roles(id);
return r;
}
/*
* 功能:获取某用户管理的所有设备对应的车间信息列表
* 参数:id 用户Id
* 返回值:List<Equip_Archi>
*/
public List<Equip_Archi> Get_Person_Cj(int id)
{
List<Equip_Archi> r = Persons.getEA_of_Person(id);
return r;
}
/// <summary>
///16/9/8新增,获取润滑油间列表
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public List<Runhua_Info> Get_Runhua_Cj()
{
List<Runhua_Info> r = Persons.getRunhuaCj();
return r;
}
/*
* 功能:获取某用户管理的所有设备信息列表
* 参数:id 用户Id
* 返回值:List<Equip_Info>
*/
public List<Equip_Info> Get_Person_Equips(int id)
{
List<Equip_Info> r = new List<Equip_Info>();
r = Persons.GetPerson_Equips(id);
return r;
}
/*
* 功能:获取某用户所属部门信息
* 参数:id 用户Id
* 返回值:Depart_Archi
*/
public Depart_Archi Get_Person_Depart(int id)
{
Depart_Archi r = new Depart_Archi();
r = Persons.GetPerson_Depart(id);
return r;
}
/*
* 功能:获取某装置管理员所属的车间
* 参数:id 用户Id
* 返回值:Depart_Archi
*/
public Depart_Archi Get_Person_DepartOfParent(int id)
{
Depart_Archi r = new Depart_Archi();
r = Persons.GetPerson_Depart(id);
Depart_Archis DA = new Depart_Archis();
r = DA.getDepart_Parent(r.Depart_Id);
return r;
}
/*
* 功能:获取某用户所分配的所有系统菜单
* 参数:id 用户Id
* 返回值:List<Menu>
*/
public List<Menu> Get_Person_Menus(int id)
{
try {
List<Menu> lm = Persons.GetPerson_Menus(id);
return lm;
}
catch { return null; }
}
//给用户添加一组角色
public bool Add_Equips(int Person_Id,List<int> EquipIdSet)
{
try {
foreach(var i in EquipIdSet)
{
Persons.AddEquip(Person_Id, i);
}
return true;
}
catch { return false; }
}
public int is_Role_admin(string username)
{
int r = Persons.isAdmin(username);
return r;
}
public bool ModifyPerson_Pwd(string userName, byte[] userPwd)
{
return Persons.ModifyPerson_Pwd(userName, userPwd);
}
public Person_Info Get_Person(string userName, byte[] userPwd)
{
var P = Persons.GetPerson_info(userName, userPwd);
return P;
}
public string Get_PqnamebyCjname(string CjName)
{
var P = Persons.Get_PqnamebyCjname(CjName);
return P;
}
//2016.10.8
public bool AddPW(int personid, int menuid)
{
PersonAndWorkflow PW = new PersonAndWorkflow();
bool res = PW.AttachtoMenu(personid, menuid);
return res;
}
public int GetPersonId(string Person_Name)
{
PersonAndWorkflow PW = new PersonAndWorkflow();
int PersonId = PW.GetPersonIdByName(Person_Name);
return PersonId;
}
public int GetMenuId(string Menu_Name)
{
PersonAndWorkflow PW = new PersonAndWorkflow();
int MenuId = PW.GetMenuIdByName(Menu_Name);
return MenuId;
}
}
}
<file_sep>using FlowEngine.Event;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.UserInterface
{
public interface UI_WorkFlow_Entity
{
string name { get; }
int EntityID { get; }
string description { get; }
string EntitySerial { get; }
bool CreateEntity(string wf_name, string Ser_Num = null/*2016/2/12--保证子工作流串号与父工作流相同*/);
//工作流引擎开始工作,并返回需要跳转的页面
string Start(IDictionary<string, string> record);
IDictionary<string, IEvent> events{get;}
Dictionary<string, string> GetRecordItems();
IEvent GetCurrentEvent();
}
}
<file_sep>///////////////////////////////////////////////////////////
// Mission.cs
// Implementation of the Class Mission
// Generated by Enterprise Architect
// Created on: 13-11月-2015 20:40:36
// Original author: Chenbin
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FlowEngine.Modals {
/// <summary>
/// 任务表,记录了已处理的工作
/// </summary>
public class Mission {
public Mission(){
}
~Mission(){
}
/// <summary>
/// 主键
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Miss_Id{
get;
set;
}
/// <summary>
/// 创建任务任务的事件名称
/// </summary>
public string Event_Name{
get;
set;
}
/// <summary>
/// 任务的名称
/// </summary>
public string Miss_Name { get; set; }
/// <summary>
/// 任务的描述
/// </summary>
public string Miss_Desc { get; set; }
/// <summary>
/// 任务所属工作流实体
/// </summary>
public virtual WorkFlow_Entity Miss_WFentity{
get;
set;
}
/// <summary>
/// 该任务的前一任务
/// </summary>
public virtual Mission pre_Mission
{
get;
set;
}
/// <summary>
/// 该任务的后一任务
/// </summary>
public virtual ICollection<Mission> next_Mission
{
get;
set;
}
/// <summary>
/// 任务包含的Record数据
/// </summary>
public virtual ICollection<Process_Record> Record_Info
{
get;
set;
}
/// <summary>
/// 任务包含的参数值
/// </summary>
public virtual ICollection<Mission_Param> Params_Info
{
get;
set;
}
}//end Mission
}//end namespace FlowEngine.Modals<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquipModel.Entities
{
public class EQ
{
public string sbGyCode;
public string sbCode;
public string sbType;
public string GCnewname;
public string GColdname;
}
}
<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using WebApp.Models.DateTables;
using System.Collections.Specialized;
using System.Data;
namespace WebApp.Controllers
{
public class LSA6dot2Controller : CommonController
{
EquipManagment Em = new EquipManagment();
// GET: /LSA6dot2/
public ActionResult Index( )
{
return View( );
}
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));
}
public ActionResult LSA6dot2(string run_result ,string job_title)
{
string s = run_result;
// ViewBag.flows = CWFEngine.ListAllWFDefine();
ViewBag.run_result = run_result;
ViewBag.jobtitle = job_title;
return View();
}
public JsonResult A6dot2GetTimerJobs(string run_result)
{
string run_results= run_result.TrimStart('[').TrimEnd(']');
List<string> run_enity_id=new List<string>();
List<object> res = new List<object>();
if (run_results.Contains(','))
{
run_enity_id = run_results.Split(new char[] { ',' }).ToList();
}else
{
run_enity_id.Add(run_results);
}
for (int i = 0; i < run_enity_id.Count; i++)
{
List<string> Zz_list = new List<string>();//整改方案
List<string> equip_list = new List<string>();//设备name
List<string> equip_code_list = new List<string>();//设备code
List<string> equip_file_list = new List<string>();//整改方案
List<string> equip_check_result_list = new List<string>();//化验结果
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Cj_Name"] = null;
paras["Equip_Info"] = null;
paras["Assay_Result"] = null;
paras["Time_Assay"]=null;
paras["Assay_File"] = null;
paras["Xc_Confirm"] = null;
paras["Assay_Result_Again"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(Convert.ToInt16(run_enity_id[i]), paras);
if (paras["Equip_Info"].ToString() != "")
{
JArray jsonVal = JArray.Parse(paras["Equip_Info"].ToString());
dynamic table = jsonVal;
foreach (dynamic T in table)
{
string eq_name = T.equip_name;
equip_list.Add(eq_name);
string eq_code = T.equip_code;
equip_code_list.Add(eq_code);
string equip_file = T.equip_file;
equip_file_list.Add(equip_file);
string equip_check_result=T.equip_check_result;
equip_check_result_list.Add(equip_check_result);
}
for (int k = 0; k < equip_list.Count; k++)
{
object o = new
{
ID = k + 1,
zz_name = Em.getZzName(Convert.ToInt16(Em.getEA_id_byCode(equip_code_list[k]))),
jz_name = equip_list[k],
sb_code = equip_code_list[k],
last_check_month = paras["Time_Assay"].ToString(),
check_result = equip_check_result_list[k],
zz_file = equip_file_list[k],
zz_done = paras["Xc_Confirm"].ToString(),
second_check_result = paras["Assay_Result_Again"].ToString()
};
res.Add(o);
}
}
}
return Json(new { data = res.ToArray() });
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A7dot1dot1Controller : CommonController
{
//
public class TableModel
{
public string name;
public string standard_value;
public string exact_value;
}
// GET: /A7dot1/
public ActionResult Index()
{
return View(getIndexListRecords("A7dot1dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
// GET: /A7dot1dot1/装置提报
public ActionResult ZzSubmit(string wfe_id)
{
return View(getSubmitModel(wfe_id));//
}
// GET: /A7dot1dot1/检修单位确认
public ActionResult JxdwConfirm(string wfe_id)
{
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_specis = pv.Speciaty_Names;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
//由于DongZyConfirm_done 等变量未与该Event关联,所以无法获取, 故而我在下面模拟了这几个变量
//同样的问题也会出现在JxdwConfirm_submitsignal函数中
//WFDetail_Model dfm = getWFDetail_Model(wfe_id);
//dfm.ALLHistoryMiss.Last().Miss_Params["DongZyConfirm_done"] = true.ToString();
//dfm.ALLHistoryMiss.Last().Miss_Params["DongZyMan"] = "fhp";
//dfm.ALLHistoryMiss.Last().Miss_Params["DianZyConfirm_done"] = false.ToString();
//dfm.ALLHistoryMiss.Last().Miss_Params["DianZyMan"] = "";
//dfm.ALLHistoryMiss.Last().Miss_Params["YiZyConfirm_done"] = false.ToString();
//dfm.ALLHistoryMiss.Last().Miss_Params["YiZyMan"] = "";
return View(getWFDetail_Model(wfe_id));
//return View(dfm);
}
// GET: /A7dot1dot1/机动处确认
public ActionResult JdcConfirm(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
public ActionResult GraphicData(string wfe_id)
{
int cur_PersionID = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(cur_PersionID);
ViewBag.user_specis = pv.Speciaty_Names;
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext,false);
ViewBag.currentMiss = miss;
return View(getWFDetail_Model(wfe_id));
}
// GET: /A7dot1dot1/机动处确认
public void createA13dot1(string from_wfe_id)
{
//create new flow A13.1
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(Convert.ToInt32(from_wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
string th_problem = Convert.ToString(miss.Miss_Params["Th_ProblemRecords"]);
JArray j_Problem_data = JArray.Parse(th_problem);
for (int i = 0; i < j_Problem_data.Count; i++)
{
JObject j_obj = JObject.Parse(j_Problem_data[i].ToString());
string problem_catalogy = j_obj["problem_catalogy"].ToString();
string problem_detail = j_obj["problem_detail"].ToString();
//将7.1.1的串号赋给新产生的13.1的工作流
WorkFlows wfsd = new WorkFlows();
WorkFlow_Entity wfecurrent = wfsd.GetWorkFlowEntity(Convert.ToInt32(from_wfe_id));
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName("A13dot1", wfecurrent.WE_Ser);
if (wfe != null)
{
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
wfe.Start(record);
int flow_id = wfe.EntityID;
Dictionary<string, string> signal1 = new Dictionary<string, string>();
signal1["start_done"] = "true";
CWFEngine.SubmitSignal(flow_id, signal1, record);
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = miss.Miss_Params["Cj_Name"].ToString();
signal["Zz_Name"] = miss.Miss_Params["Zz_Name"].ToString();
signal["Equip_GyCode"] = miss.Miss_Params["Equip_GyCode"].ToString();
signal["Equip_Code"] = miss.Miss_Params["Equip_Code"].ToString();
signal["Equip_Type"] = miss.Miss_Params["Equip_Type"].ToString();
signal["Problem_Desc"] = problem_detail;
signal["Problem_DescFilePath"] = "";
signal["Zy_Type"] = problem_catalogy;
signal["Zy_SubType"] = miss.Miss_Params["Zy_SubType"].ToString();
signal["Equip_ABCMark"] = miss.Miss_Params["Equip_ABCMark"].ToString();
signal["Data_Src"] = "特护记录";
//submit
//record
//record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(flow_id, signal, record);
}
}
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
ViewBag.wfe_id = wfe_id;
return View(getWFDetail_Model(wfe_id));
}
public string ZzSubmit_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["ZzSubmit_done"] = "true";
signal["Cj_Name"] = item["Cj_Name"].ToString();
signal["Zz_Name"] = item["Zz_Name"].ToString();
signal["Equip_GyCode"] = item["Equip_GyCode"].ToString();
signal["Equip_Code"] = item["Equip_Code"].ToString();
signal["Equip_Type"] = item["Equip_Type"].ToString();
EquipManagment em = new EquipManagment();
Equip_Info eqinfo=em.getEquip_Info(item["Equip_Code"].ToString());
signal["Equip_ABCMark"] = eqinfo.Equip_ABCmark;
signal["Zy_Type"] = eqinfo.Equip_Type;
signal["Zy_SubType"] = eqinfo.Equip_PhaseB;
signal["Data_Src"] = "特护记录";
signal["Th_CheckTime"] = DateTime.Now.ToString();
signal["Th_CheckMen"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
signal["Group_State"] = item["Group_State"].ToString();
//string Thjl_data = item["Thjl_data"].ToString();
//string Problem_data = item["Problem_data"].ToString();
//string workdetail = item["workdetail"].ToString();
signal["Th_ItemRecord"] = item["Thjl_data"].ToString();
signal["Th_WorkDetail"] = item["workdetail"].ToString();
signal["Th_ProblemRecords"] = item["Problem_data"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString("yyyyMMddhhmmss");
//submit
//由于DongZyConfirm_done 等变量未与该Event关联, 所以submitSignal不会将确认信息提交到工作流
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal,record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot1dot1/Index");
}
public string JxdwConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["DongZyConfirm_done"] = item["DongZyConfirm_done"].ToString();
signal["DianZyConfirm_done"] = item["DianZyConfirm_done"].ToString();
signal["YiZyConfirm_done"] = item["YiZyConfirm_done"].ToString();
signal["DongZyMan"] = item["DongZyMan"].ToString();
signal["DianZyMan"] = item["DianZyMan"].ToString();
signal["YiZyMan"] = item["YiZyMan"].ToString();
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot1dot1/Index");
}
public string JdcConfirm_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
string flowname = item["Flow_Name"].ToString();
//create new flow A13.1
createA13dot1(flowname);
//paras
Dictionary<string, string> signal = new Dictionary<string, string>();
signal["JdcConfirm_done"] = item["JdcConfirm_done"].ToString();
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(flowname), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
signal["Th_CheckMen"] = miss.Miss_Params["Th_CheckMen"].ToString() + "," + miss.Miss_Params["DongZyMan"].ToString() + "," + miss.Miss_Params["DianZyMan"].ToString() + "," + miss.Miss_Params["YiZyMan"].ToString() + "," + (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
//record
Dictionary<string, string> record = new Dictionary<string, string>();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(flowname), signal, record);
}
catch (Exception e)
{
return "";
}
return ("/A7dot1dot1/Index");
}
public JsonResult Read_THRecord(int WFE_ID)
{
List<TableModel> tb_list = new List<TableModel>();
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(WFE_ID, ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
//由于Th_ItemRecord等变量未于当前event关联, 导致我无法从当前任务中读取这些变量
//所以我读取了上一条历史Mission, 这种方法效率较低, 应该将这些变量与之关联,并使用上面被注释的语句,更为妥当
//UI_MISSION miss = CWFEngine.GetHistoryMissions(WFE_ID).Last();
string th_record = Convert.ToString(miss.Miss_Params["Th_ItemRecord"]);
string th_problem = Convert.ToString(miss.Miss_Params["Th_ProblemRecords"]);
string th_detail = Convert.ToString(miss.Miss_Params["Th_WorkDetail"]);
return Json(new { th_record = th_record, th_problem = th_problem, th_detail = th_detail });
}
public String judge(int thjl_id)//判断upload下面有没有对应的excel表格,连接成功返回true,失败返回false
{
int Thji_Code = thjl_id;
List<TableModel> tb_list = new List<TableModel>();
DataSet ds = new DataSet();
string DirectoryPath = Server.MapPath("~/Upload/特护记录表//");
String strFilepPath = DirectoryPath + "" + Thji_Code + "特护记录表.xls";
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strFilepPath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
//SqlConnection conn = new SqlConnection(strConn);
try
{
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetNames.Rows[0][2] + "]", conn); //为Sheet命名后,顺序可以能编号,要注意
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
conn.Close();
return ("true");
}
catch (Exception e)
{
return ("false");
}
}
public JsonResult Thjl_excel(int thjl_id)
{
int Thji_Code = thjl_id;
List<TableModel> tb_list = new List<TableModel>();
DataSet ds = new DataSet();
string DirectoryPath = Server.MapPath("~/Upload/特护记录表//");
String strFilepPath = DirectoryPath + "" + Thji_Code + "特护记录表.xls";
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strFilepPath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\equipweb\\1\\CODE\\WebApp\\WebApp\\Upload\\1.xls;Extended Properties=\"Excel 12.0 XML;HDR=YES;IMEX=1\"";
// string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
// + strFilepPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"";
// 参数HDR的值:
// HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
//IMEX 有三种模式:
//当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。
//当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。
//当 IMEX=2 时为“连結模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。
OleDbConnection conn = new OleDbConnection(strConn);
//SqlConnection conn = new SqlConnection(strConn);
try
{
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetNames.Rows[0][2] + "]", conn); //为Sheet命名后,顺序可以能编号,要注意
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
for (int i = 2; i < ds.Tables[0].Rows.Count - 1; i++) // HDR=Yes,故从i=2开始,而非i=3, xwm modify
{
string name = ds.Tables[0].Rows[i][0].ToString();
string standard_value = ds.Tables[0].Rows[i][1].ToString();
TableModel tmp = new TableModel();
tmp.name = name;
tmp.standard_value = standard_value;
tb_list.Add(tmp);
}
conn.Close();
return Json(tb_list.ToArray(), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
// List<Object> urlobj = new List<object>();
// object tmp = new
// {
// name = "0",
// standard_value = "0"
// };
// urlobj.Add(tmp);
//return Json(urlobj.ToArray());
return Json("");
// Console.WriteLine(e.Message);
}
}
public string OutputExcel(string wfe_id)
{
UI_MISSION miss = CWFEngine.GetActiveMission<Person_Info>(int.Parse(wfe_id), ((IObjectContextAdapter)(new EquipWebContext())).ObjectContext);
try
{
string th_record = Convert.ToString(miss.Miss_Params["Th_ItemRecord"]);
string th_problem = Convert.ToString(miss.Miss_Params["Th_ProblemRecords"]);
string th_detail = Convert.ToString(miss.Miss_Params["Th_WorkDetail"]);
string work_detail = th_detail;
JArray j_Problem_data = JArray.Parse(th_problem);
JArray j_Thjl_data = JArray.Parse(th_record);
// Console.WriteLine(work_detail);
// 创建Excel 文档
HSSFWorkbook wk = new HSSFWorkbook();
ISheet tb = wk.CreateSheet("sheet1");
//设置单元的宽度
tb.SetColumnWidth(0, 25 * 256);
tb.SetColumnWidth(1, 20 * 256);
tb.SetColumnWidth(2, 20 * 256);
tb.SetColumnWidth(3, 45 * 256);
//合并标题头,该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 3));
IRow head = tb.CreateRow(0);
head.Height = 20 * 30;
ICell head_first_cell = head.CreateCell(0);
ICellStyle cellStyle_head = wk.CreateCellStyle();
//对齐
cellStyle_head.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
// 边框
/*
cellStyle_head.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_head.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
* */
// 字体
IFont font = wk.CreateFont();
font.FontName = "微软雅黑";
font.Boldweight = 8;
font.FontHeightInPoints = 16;
cellStyle_head.SetFont(font);
head_first_cell.CellStyle = head.CreateCell(1).CellStyle
= head.CreateCell(2).CellStyle
= head.CreateCell(3).CellStyle
= cellStyle_head;
head_first_cell.SetCellValue("Ⅰ催化气压机特护记录");
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 0, 3));
IRow row1 = tb.CreateRow(1);
row1.Height = 20 * 20;
ICell row1_last = row1.CreateCell(0);
ICellStyle cellStyle_row1 = wk.CreateCellStyle();
cellStyle_row1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Right;
/*
cellStyle_row1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_row1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_row1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_row1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
* */
row1_last.CellStyle = row1.CreateCell(1).CellStyle = row1.CreateCell(2).CellStyle = row1.CreateCell(3).CellStyle = cellStyle_row1;
row1_last.SetCellValue("JD04-JD01"); ;
IRow table_head = tb.CreateRow(2);
ICellStyle cellStyle_normal = wk.CreateCellStyle();
cellStyle_normal.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle_normal.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
ICell table_head_name = table_head.CreateCell(0);
table_head_name.CellStyle = cellStyle_normal;
table_head_name.SetCellValue("项目");
ICell table_head_standrad = table_head.CreateCell(1);
table_head_standrad.CellStyle = cellStyle_normal;
table_head_standrad.SetCellValue("设计值");
ICell table_head_exact = table_head.CreateCell(2);
table_head_exact.CellStyle = cellStyle_normal;
table_head_exact.SetCellValue("实测值");
ICell table_head_thjl = table_head.CreateCell(3);
table_head_thjl.CellStyle = cellStyle_normal;
table_head_thjl.SetCellValue("特护记录");
ICellStyle thjl_record_cellStyle = wk.CreateCellStyle();
thjl_record_cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
thjl_record_cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
//水平对齐
thjl_record_cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
//垂直对齐
thjl_record_cellStyle.VerticalAlignment = VerticalAlignment.Top;
//自动换行
thjl_record_cellStyle.WrapText = true;
int row_index = 3;
for (int i = 0; i < j_Thjl_data.Count; i++)
{
JObject j_obj = JObject.Parse(j_Thjl_data[i].ToString());
IRow thjl_row = tb.CreateRow(row_index);
ICell thjl_name = thjl_row.CreateCell(0);
thjl_name.CellStyle = cellStyle_normal;
thjl_name.SetCellValue(j_obj["name"].ToString());
ICell thjl_standard_value = thjl_row.CreateCell(1);
thjl_standard_value.CellStyle = cellStyle_normal;
thjl_standard_value.SetCellValue(j_obj["standard_value"].ToString());
ICell thjl_exact_value = thjl_row.CreateCell(2);
thjl_exact_value.CellStyle = cellStyle_normal;
thjl_exact_value.SetCellValue(j_obj["exact_value"].ToString());
thjl_row.CreateCell(3).CellStyle = thjl_record_cellStyle;
row_index++;
}
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, row_index - 1, 3, 3));
ICell thjl_record = tb.GetRow(3).CreateCell(3);
thjl_record.CellStyle = thjl_record_cellStyle;
String thjl_detail = "工作要点: " + "\r\n" + work_detail + "\r\n" + "\r\n" + "\r\n";
thjl_detail = thjl_detail + "设备问题: " + "\r\n";
for (int i = 0; i < j_Problem_data.Count; i++)
{
JObject j_obj = JObject.Parse(j_Problem_data[i].ToString());
Console.WriteLine(j_obj["problem_catalogy"].ToString());
Console.WriteLine(j_obj["problem_detail"].ToString());
thjl_detail = thjl_detail + (i + 1) + ". " + "问题分类: " +
j_obj["problem_catalogy"].ToString() + " ; 问题描述: " + j_obj["problem_detail"].ToString() + "\r\n";
}
thjl_record.SetCellValue(thjl_detail);
IRow last_row = tb.CreateRow(row_index);
last_row.CreateCell(0).SetCellValue("检查时间:");
last_row.CreateCell(1).SetCellValue(miss.Miss_Params["Th_CheckTime"].ToString());
last_row.CreateCell(2).SetCellValue("检查人:");
last_row.CreateCell(3).SetCellValue(miss.Miss_Params["Th_CheckMen"].ToString());
string path = Server.MapPath("~/Upload//特护记录表.xls");
using (FileStream fs = System.IO.File.OpenWrite(path)) //打开一个xls文件,如果没有则自行创建,如果存在myxls.xls文件则在创建是不要打开该文件!
{
wk.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。
Console.WriteLine("提示:创建成功!");
}
return Path.Combine("/Upload", "特护记录表.xls");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return "";
}
}
[HttpPost]
public JsonResult GetGraphicData(string graphicName,string ser)
{
List<double> result = new List<double>();
List<string> r_time = new List<string>();
DateTime time_now = DateTime.Now.AddYears(-1);
DataTable dt = CWFEngine.QueryAllInformation("E.WE_Ser, E.W_Name, M.Event_Name, R.time, P.Th_ItemRecord",
"E.W_Name = 'A7dot1dot1' and M.Event_Name = 'ZzSubmit'", "time >= '" + time_now.ToString() + "'");
DataRow[] NNullRows = dt.Select("Th_ItemRecord is not Null");
foreach (DataRow r in NNullRows)
{
if (r["WE_Ser"].ToString() == ser)
{
string val = r["Th_ItemRecord"].ToString();
JArray item = (JArray)JsonConvert.DeserializeObject(val);
if (item != null)
{
foreach (var i in item)
{
if (i["name"].ToString() == graphicName)
{
string val1 = i["exact_value"].ToString();
r_time.Add(r["time"].ToString());
try
{
double e_val = Convert.ToDouble(val1);
result.Add(e_val);
}
catch
{
result.Add(0.0);
}
break;
}
}
}
}
}
return Json(new { val = result.ToArray(), valtime = r_time.ToArray() });
}
public JsonResult A7Zz_Equips(int Zz_id)
{
EquipManagment pm = new EquipManagment();
List<Equip_Info> Equips_of_Zz = pm.getThEquips_OfZz(Zz_id);
List<object> Equip_obj = new List<object>();
foreach (var item in Equips_of_Zz)
{
object o = new
{
Equip_Id = item.Equip_Id,
Equip_GyCode = item.Equip_GyCode,
// Equip_Code=item.Equip_Code,
// Equip_Type=item.Equip_Type,
// Equip_Specialty=item.Equip_Specialty
};
Equip_obj.Add(o);
}
return Json(Equip_obj.ToArray());
}
}
}<file_sep>using EquipModel.Entities;
using FlowEngine;
using FlowEngine.UserInterface;
using WebApp.Models;
using WebApp.Models.User;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using EquipModel.Context;
using System.Text;
using EquipBLL.AdminManagment;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System.Collections.Specialized;
using WebApp.Models.DateTables;
using FlowEngine.DAL;
using FlowEngine.Modals;
namespace WebApp.Controllers
{
public class A14dot3Controller : CommonController
{
public ActionResult Index()
{
return View(getIndexListRecords("A14dot3dot1", (Session["User"] as EquipModel.Entities.Person_Info).Person_Name));
}
public ActionResult WorkFolw_Detail(string wfe_id)
{
return View(getWFDetail_Model(wfe_id));
}
public string CreateA14dot3s_submitsignal(string json1)
{
try
{
JObject item = (JObject)JsonConvert.DeserializeObject(json1);
EquipManagment tm = new EquipManagment();
string temp = item["sample"].ToString();
JArray jsonVal = JArray.Parse(temp) as JArray;
dynamic table2 = jsonVal;
foreach (dynamic T in table2)
{
UI_WorkFlow_Entity wfe = CWFEngine.CreateAWFEntityByName("A14dot3");
Dictionary<string, string> record = wfe.GetRecordItems();
record["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record["time"] = DateTime.Now.ToString();
string returl = wfe.Start(record);
Dictionary<string, string> signal = new Dictionary<string, string>();
string Equip_Code = T.Equip_Code;
int Equip_location_EA_Id = tm.getEA_id_byCode(Equip_Code);
signal["Zz_Name"] = tm.getZzName(Equip_location_EA_Id);
signal["Equip_GyCode"] = T.Equip_GyCode;
signal["Equip_Code"] = T.Equip_Code;
signal["Equip_ABCMark"] = T.Equip_ABCMark;
signal["SubmitJxPlan_Done"] = "true";
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(wfe.EntityID), signal, record1);
}
}
catch (Exception e)
{
return "";
}
return ("/A14dot3/Index");
}
private List<KeyValuePair<string, string>> ParsePostForm(NameValueCollection Form)
{
var list = new List<KeyValuePair<string, string>>();
if (Form != null)
{
foreach (var f in Form.AllKeys)
{
list.Add(new KeyValuePair<string, string>(f, Form[f]));
}
}
return list;
}
private DtResponse ProcessRequest(List<KeyValuePair<string, string>> data)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
var Data = http["data"] as Dictionary<string, object>;
int wfe_id = -1;
foreach (var d in Data)
{
wfe_id = Convert.ToInt32(d.Key);
}
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
foreach (var dd in d.Value as Dictionary<string, object>)
{
ERPInfoManagement erp = new ERPInfoManagement();
Dictionary<string, string> signal = new Dictionary<string, string>();
if (dd.Key == "plan_name")
{
signal["Plan_Name"] = dd.Value.ToString();
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "jxreason")
{
signal["JxCauseDesc"] = dd.Value.ToString();
signal["CompleteNameReason_Done"] = "true";
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "xcconfirm")
{
string[] result = dd.Value.ToString().Split(new char[] { '$' });
signal["XcConfirm_Result"] = result[0];
if (result.Length > 1)
signal["XcConfirm_Reason"] = result[1];
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "kkconfirm")
{
if (dd.Value.ToString() == "")
continue;
string[] result = dd.Value.ToString().Split(new char[] { '$' });
signal["KkConfirm_Result"] = result[0];
if (result.Length > 1)
signal["KkConfirm_Reason"] = result[1];
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "zytdconfirm")
{
if (dd.Value.ToString() == "")
continue;
string[] result = dd.Value.ToString().Split(new char[] { '$' });
signal["ZytdConfirm_Result"] = result[0];
if (result.Length > 1)
signal["ZytdConfirm_Reason"] = result[1];
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "notice_order")
{
if (dd.Value.ToString() == "")
continue;
signal["NoticeOrder"] = "00" + dd.Value.ToString();
GD_InfoModal res = erp.getGD_Modal_Notice("00" + dd.Value.ToString());
if (res != null)
signal["JobOrder"] = res.GD_Id;
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
if (dd.Key == "job_order")
{
if (dd.Value.ToString() == "")
continue;
signal["JobOrder"] = "00" + dd.Value.ToString();
GD_InfoModal res = erp.getGD_Modal_GDId("00" + dd.Value.ToString());
if (res != null)
signal["NoticeOrder"] = res.GD_Notice_Id;
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
}
//if (dd.Key == "JumpA8dot2T")
//{
// //补充跳转A8dot2的变量,Cj_Name,Zy_Type,Zy_SubType
// Dictionary<string, object> paras1 = new Dictionary<string, object>();
// paras1["Zz_Name"] = null;
// paras1["Equip_GyCode"] = null;
// paras1["Equip_Code"] = null;
// paras1["Plan_Name"] = null;
// UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(id, paras1);
// //获取设备专业类别和子类别及设备所属车间
// EquipManagment tm = new EquipManagment();
// Equip_Info getZy = tm.getEquip_ByGyCode(paras1["Equip_GyCode"].ToString());
// signal["Zy_Type"] = getZy.Equip_Specialty;
// signal["Zy_SubType"] = getZy.Equip_PhaseB;
// signal["Equip_Type"] = getZy.Equip_Type;
// //EA_Name_EA_Id= tm.getEquip(paras1["Zz_Name"].ToString()).EA_Parent.EA_Id;
// signal["Cj_Name"] = tm.getEquip(paras1["Zz_Name"].ToString());
// signal["Plan_Name"] = paras1["Plan_Name"].ToString();
// signal["JxdwAttachPlanOrder_Done"] = dd.Value.ToString();
// //record
// Dictionary<string, string> record1 = new Dictionary<string, string>();
// record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
// record1["time"] = DateTime.Now.ToString();
// //submit
// CWFEngine.SubmitSignal(Convert.ToInt32(id), signal, record1);
//}
}
}
Dictionary<string, object> paras = new Dictionary<string, object>();
paras["Zz_Name"] = null;
paras["Equip_GyCode"] = null;
paras["Equip_Code"] = null;
paras["Equip_Type"] = null;
paras["Equip_ABCMark"] = null;
paras["Plan_Name"] = null;
paras["JxCauseDesc"] = null;
paras["XcConfirm_Result"] = null;
paras["KkConfirm_Result"] = null;
paras["ZytdConfirm_Result"] = null;
paras["JobOrder"] = null;
paras["NoticeOrder"] = null;
if (wfe_id != -1)
{
WorkFlows wfsd = new WorkFlows();
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(wfe_id, paras);
Dictionary<string, object> m_kv = new Dictionary<string, object>();
Mission db_miss = wfsd.GetWFEntityMissions(wfe_id).Last();//获取该实体最后一个任务
int UserId = (Session["User"] as EquipModel.Entities.Person_Info).Person_Id;
PersonManagment pm = new PersonManagment();
EquipBLL.AdminManagment.PersonManagment.P_viewModal pv = pm.Get_PersonModal(UserId);
m_kv["index_Id"] = wfe_id;
m_kv["zz_name"] = paras["Zz_Name"].ToString();
m_kv["sb_gycode"] = paras["Equip_GyCode"].ToString();
m_kv["sb_code"] = paras["Equip_Code"].ToString();
m_kv["sb_type"] = paras["Equip_Type"].ToString();
m_kv["sb_ABCMark"] = paras["Equip_ABCMark"].ToString();
m_kv["plan_name"] = paras["Plan_Name"].ToString();
m_kv["jxreason"] = paras["JxCauseDesc"].ToString();
m_kv["xcconfirm"] = paras["XcConfirm_Result"].ToString();
m_kv["kkconfirm"] = paras["KkConfirm_Result"].ToString();
m_kv["zytdconfirm"] = paras["ZytdConfirm_Result"].ToString();
m_kv["job_order"] = paras["JobOrder"].ToString();
m_kv["notice_order"] = paras["NoticeOrder"].ToString();
m_kv["missionname"] = db_miss.Miss_Desc;
m_kv["role"] = pv.Role_Names;
dt.data.Add(m_kv);
}
return dt;
}
public string click_submitsignal(string wfe_id)
{
try
{
Dictionary<string, string> signal = new Dictionary<string, string>();
//补充跳转A8dot2的变量,Cj_Name,Zy_Type,Zy_SubType
Dictionary<string, object> paras1 = new Dictionary<string, object>();
paras1["Zz_Name"] = null;
paras1["Equip_GyCode"] = null;
paras1["Equip_Code"] = null;
paras1["Plan_Name"] = null;
paras1["JobOrder"] = null;
UI_WFEntity_Info wfei = CWFEngine.GetWorkFlowEntityWithParams(Convert.ToInt32(wfe_id), paras1);
//获取设备专业类别和子类别及设备所属车间
EquipManagment tm = new EquipManagment();
ERPInfoManagement erp = new ERPInfoManagement();
GD_InfoModal res = erp.getGD_Modal_GDId(paras1["JobOrder"].ToString());
if (res != null)
{
//if (String.Compare(res.GD_EquipCode.Trim(), paras1["Equip_Code"].ToString().Trim()) != 0)
if (!res.GD_EquipCode.Contains(paras1["Equip_Code"].ToString()))
{
return "工单号与设备不匹配";
}
}
else
{
return "系统中无此工单";
}
Equip_Info getZy = tm.getEquip_ByGyCode(paras1["Equip_GyCode"].ToString());
signal["Zy_Type"] = getZy.Equip_Specialty;
signal["Zy_SubType"] = getZy.Equip_PhaseB;
signal["Equip_Type"] = getZy.Equip_Type;
//EA_Name_EA_Id= tm.getEquip(paras1["Zz_Name"].ToString()).EA_Parent.EA_Id;
signal["Cj_Name"] = tm.getEquip(paras1["Zz_Name"].ToString());
signal["Plan_Name"] = paras1["Plan_Name"].ToString();
signal["JxdwAttachPlanOrder_Done"] = "true";
signal["Data_Src"] = "计划管理";
//record
Dictionary<string, string> record1 = new Dictionary<string, string>();
record1["username"] = (Session["User"] as EquipModel.Entities.Person_Info).Person_Name;
record1["time"] = DateTime.Now.ToString();
//submit
CWFEngine.SubmitSignal(Convert.ToInt32(wfe_id), signal, record1);
return "/A14dot3/Index";
}
catch (Exception e)
{
return "";
}
//return ("/A13dot2/Index");
}
public JsonResult PostChanges()
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = ProcessRequest(list);
return Json(dtRes);
}
}
}<file_sep>using FlowEngine.DAL;
using FlowEngine.Modals;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowEngine.TimerManage
{
/// <summary>
/// 改变工作流状态
/// </summary>
public class CTimerWFStatus : CTimerMission
{
#region 构造函数
public CTimerWFStatus()
{
//默认情况下是置工作流为激活状态
m_run_params = WE_STATUS.ACTIVE;
type = "ChangeStatus";
}
#endregion
#region 属性
/// <summary>
/// 任务执行对象
/// </summary>
private int m_wfentityID = -1;
#endregion
#region 公共方法
/// <summary>
/// 绑定处理对象
/// </summary>
/// <param name="wf">工作流实体</param>
/// <returns></returns>
public bool AttachWFEntity(CWorkFlow wf)
{
if (wf == null)
return false;
m_wfentityID = wf.EntityID;
return true;
}
/// <summary>
/// 设置该任务的参数
/// </summary>
/// <param name="status">设置的工作流实体状态</param>
public void SetRunParam(WE_STATUS status)
{
m_run_params = status;
}
/// <summary>
/// 从数据库记录加载类对象
/// </summary>
/// <param name="job">数据库记录</param>
public override void Load(Timer_Jobs job)
{
m_wfentityID = job.workflow_ID;
base.Load(job);
}
/// <summary>
/// 保存定时性任务到数据库
/// </summary>
/// <param name="job"></param>
public override void Save(Timer_Jobs job = null)
{
Timer_Jobs self = new Timer_Jobs();
self.workflow_ID = m_wfentityID;
self.Job_Type = TIMER_JOB_TYPE.CHANGE_STATUS;
base.Save(self);
}
public int GetAttachWFEntityID()
{
return m_wfentityID;
}
#endregion
#region 私有方法
/// <summary>
/// 执行设置工作流实体状态的工作
/// </summary>
protected override void __processing()
{
try
{
//更新工作流实体的状态
WorkFlows wfs = new WorkFlows();
wfs.UpdateWorkFlowEntity(m_wfentityID, "WE_Status", m_run_params);
//如果要改变的状态为ACTIVE, 则发送一个空消息,推动工作流运转
if (((WE_STATUS)m_run_params) == WE_STATUS.ACTIVE)
CWFEngine.SubmitSignal(m_wfentityID, new Dictionary<string, string>(), null);
}
catch
{
string error = string.Format("Set workflow entity {0} error!", m_wfentityID);
Trace.WriteLine(error);
}
}
/// <summary>
/// 解析参数
/// </summary>
/// <param name="strPars"></param>
public override void ParseRunParam(string strPars)
{
switch(strPars)
{
case "ACTIVE":
m_run_params = WE_STATUS.ACTIVE;
break;
case "SUSPEND":
m_run_params = WE_STATUS.SUSPEND;
break;
case "CREATED":
m_run_params = WE_STATUS.CREATED;
break;
case "DONE":
m_run_params = WE_STATUS.DONE;
break;
case "DELETED":
m_run_params = WE_STATUS.DELETED;
break;
default:
m_run_params = WE_STATUS.ACTIVE;
break;
}
}
/// <summary>
/// 解析运行结果
/// </summary>
/// <param name="strResult"></param>
public override void ParseRunResult(string strResult)
{
throw new NotImplementedException();
}
/// <summary>
/// 解析运行参数到数据库
/// </summary>
/// <returns></returns>
public override object ParseRunParamsToJObject()
{
string str_val = "";
switch ((WE_STATUS)m_run_params)
{
case WE_STATUS.ACTIVE:
str_val = "ACTIVE";
break;
case WE_STATUS.SUSPEND:
str_val = "SUSPEND";
break;
case WE_STATUS.CREATED:
str_val = "CREATED";
break;
case WE_STATUS.DONE:
str_val = "DONE";
break;
case WE_STATUS.DELETED:
str_val = "DELETED";
break;
}
return str_val;
}
/// <summary>
/// 解析运行结果
/// </summary>
/// <returns></returns>
public override object ParseRunResultToJobject()
{
throw new NotImplementedException();
}
#endregion
}
}
<file_sep>using FlowEngine;
using FlowEngine.DAL;
using FlowEngine.Modals;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using WebApp.Models.DateTables;
namespace WebApp.Controllers
{
public class A5TimeJobController : Controller
{
//
// GET: /A5TimeJob/
public ActionResult Index()
{
// ViewBag.flows = CWFEngine.ListAllWFDefine();
return View();
}
public ActionResult A6dot2TimerJobs()
{
ViewBag.flows = CWFEngine.ListAllWFDefine();
return View();
}
public JsonResult A5dot1GetTimerJobs()
{
List<object> res = new List<object>();
for (int i = 0; i < 2; i++)
{
object o = new
{
ID = i + 1,
zz_name = "1#常压装置",
jz_name = "1#常压常顶空冷风机机B",
sb_code = "210000001",
last_check_month = "12",
check_result = "",
zz_file = "",
};
res.Add(o);
}
return Json(new { data = res.ToArray() });
}
public JsonResult A6dot2GetTimerJobs()
{
List<object> res = new List<object>();
for (int i = 0; i < 2; i++)
{
object o = new
{
ID = i + 1,
zz_name = "1#常压装置",
jz_name = "1#常压常顶空冷风机机B",
sb_code = "210000001",
last_check_month = "12",
check_result = "",
zz_file = "",
zz_done = "",
second_check_result = ""
};
res.Add(o);
}
return Json(new { data = res.ToArray() });
}
private DtResponse A5ProcessRequest(List<KeyValuePair<string, string>> data)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
if (http.ContainsKey("action"))
{
string action = http["action"] as string;
if (action == "edit")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
List<string> pros = new List<string>();
List<object> vals = new List<object>();
Dictionary<string, object> m_kv = new Dictionary<string, object>();
foreach (var dd in d.Value as Dictionary<string, object>)
{
pros.Add(dd.Key);
vals.Add(dd.Value);
}
// CTimerMission m = CTimerManage.UpdateTimerMission(id, pros, vals);
m_kv["ID"] = "12345";
m_kv["zz_name"] = "2#催化装置";
m_kv["jz_name"] = "2#催化主风机K101";
m_kv["sb_code"] = "210023808";
m_kv["last_check_month"] = "4";
m_kv["check_result"] = "5";
m_kv["zz_file"] = "";
dt.data.Add(m_kv);
}
}
else if (action == "create") //新建工作流
{
//CTimerMission m = CTimerManage.CreateAEmptyMission();
Dictionary<string, object> m_kv = new Dictionary<string, object>();
m_kv["ID"] = "123";
m_kv["zz_name"] = "选择装置";
m_kv["jz_name"] = "选择机组";
m_kv["sb_code"] = " ";
m_kv["last_check_month"] = " ";
m_kv["check_result"] = "";
m_kv["zz_file"] = "";
dt.data.Add(m_kv);
}
else if (action == "remove")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
//CTimerMission m = CTimerManage.DeleteTimerJob(id);
}
}
}
return dt;
}
private DtResponse ProcessRequest1(List<KeyValuePair<string, string>> data)
{
DtResponse dt = new DtResponse();
var http = DtRequest.HttpData(data);
if (http.ContainsKey("action"))
{
string action = http["action"] as string;
if (action == "edit")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
List<string> pros = new List<string>();
List<object> vals = new List<object>();
Dictionary<string, object> m_kv = new Dictionary<string, object>();
foreach (var dd in d.Value as Dictionary<string, object>)
{
pros.Add(dd.Key);
vals.Add(dd.Value);
}
// CTimerMission m = CTimerManage.UpdateTimerMission(id, pros, vals);
m_kv["ID"] = "12345";
m_kv["zz_name"] = "1";
m_kv["jz_name"] = "22";
m_kv["sb_code"] = "3";
m_kv["last_check_month"] = "4";
m_kv["check_result"] = "5";
m_kv["zz_file"] = "";
m_kv["zz_done"] = "";
m_kv["second_check_result"] = "";
dt.data.Add(m_kv);
}
}
else if (action == "create") //新建工作流
{
// CTimerMission m = CTimerManage.CreateAEmptyMission();
Dictionary<string, object> m_kv = new Dictionary<string, object>();
m_kv["ID"] = "12";
m_kv["zz_name"] = "选择装置";
m_kv["jz_name"] = "选择机组";
m_kv["sb_code"] = " ";
m_kv["last_check_month"] = " ";
m_kv["check_result"] = "";
m_kv["zz_file"] = "";
m_kv["zz_done"] = "";
m_kv["second_check_result"] = "";
dt.data.Add(m_kv);
}
else if (action == "remove")
{
var Data = http["data"] as Dictionary<string, object>;
foreach (var d in Data)
{
int id = Convert.ToInt32(d.Key);
// CTimerMission m = CTimerManage.DeleteTimerJob(id);
}
}
}
return dt;
}
private List<KeyValuePair<string, string>> ParsePostForm(NameValueCollection Form)
{
var list = new List<KeyValuePair<string, string>>();
if (Form != null)
{
foreach (var f in Form.AllKeys)
{
list.Add(new KeyValuePair<string, string>(f, Form[f]));
}
}
return list;
}
public JsonResult A5PostChanges()
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = A5ProcessRequest(list);
return Json(dtRes);
}
public JsonResult PostChanges1()
{
var request = System.Web.HttpContext.Current.Request;
var list = ParsePostForm(request.Form);
var dtRes = ProcessRequest1(list);
return Json(dtRes);
}
}
} | 228090e0202c880601de748a7590dcfd6b1e7f45 | [
"JavaScript",
"C#",
"Markdown"
] | 211 | C# | xeonye/equip-web | f3e965265bb23784866e85f5ca81688302b2e240 | db1c9e9670ff06cce5cb10075e51c7132042df97 |
refs/heads/master | <repo_name>kathleen-carroll/super_duper_sports_games<file_sep>/lib/standard_deviation.rb
ages = [24, 30, 18, 20, 41]
# Your code here for calculating the standard deviation
mean = ages.sum/ages.length.to_f
mean_diff = ages.map do |age|
change = age -= mean.to_f
change.round(2)
end
squares = mean_diff.map { |mean| (mean ** 2).round(2)}
square_root = ((squares.sum / ages.length) ** (0.5)).round(2)
# When you find the standard deviation, print it out
p square_root
<file_sep>/README.md
# Super Duper Sports Games (A revisit)

Imagine a world-wide competition where countries send athletes to compete in different events. Those athletes are awarded medallions based on the place they finish in the events, and countries compete against each other to see who can win the most medallions. These are the Super Sports Games!
## Standard Deviation
In this project, we are going to need to find the standard deviation of an array of numbers. Assume we have an array of numbers `[24, 30, 18, 20, 41]`. The steps for finding the standard deviation are:
Step | Description | Operation | Result
--- | --- | ---- | ---
0 | input | | [24, 30, 18, 20, 41]
1 | sum all the integers | 24 + 30 + 18 + 20 + 41 | 133
2 | find the number of integers in the input array | | 5 |
3 | divide the sum of the integers (step 1) by the number of integers (step 2). This is the average (also known as the mean). | 133 / 5 | 26.6
4 | subtract each integer by the average found in step 3 | [24 - 26.6, 30 - 26.6, 18 - 26.6, 20 - 26.6, 41 - 26.6] | [-2.6, 3.4, -8.6, -6.6, 14.4]
5 | Take the result from step 4 and square each number | [-2.6 ^ 2, 3.4 ^ 2, -8.6 ^ 2, -6.6 ^ 2, 14.4 ^ 2] | [6.76, 11.56, 73.96, 43.56, 207.36]
6 | sum all the numbers from step 5 | 6.76 + 11.56 + 73.96 + 43.56 + 207.36 | 343.2
7 | divide the result from step 6 by the number of integers (step 2) | 343.2 / 5 | 68.64
8 | take the square root of the result from step 7 | sqrt(68.64) | 8.28
# Assignment
## Setup
1. Fork [this Repository](https://github.com/turingschool-examples/super_sports_games)
1. Clone your forked repo to your machine with git clone <ssh key for your repo>
1. Make sure you clone it to a location that makes sense, for example `/Users/your_user_name/turing/1module/projects`.
## Submission
When you are ready to turn in the project, submit a pull request from your forked repository to the turingschool-examples repository.
**Make sure to put your name in your PR!**
## Iteration 1 - Standard Deviation
Open up the `standard_deviation.rb` file in the `lib` directory. You should see this template:
```ruby
ages = [24, 30, 18, 20, 41]
# Your code here for calculating the standard deviation
# When you find the standard deviation, print it out
```
Write code to find the standard deviation and print it to the screen. (You should not use any built-in code or gems for finding the standard deviation or average)
## Iteration 2 - Event Class
Create an `Event` class given the following criteria:
* An `Event` is initialized with two arguments
* The first is a string representing the name of the event
* The second is an Array of integers representing the ages of participants in the event.
* An `Event` has getter methods called `name` and `ages` for reading the name and ages of the event.
* An `Event` has a method called `max_age` that returns the largest age as an integer
* An `Event` has a method called `min_age` that returns the smallest age as an integer
* An `Event` has a method called `average_age` that returns the average age as a float rounded to 2 decimal places
* An `Event` has a method called `standard_deviation_age` that returns the standard deviation of the ages as a float rounded to 2 decimal places.
If your `Event` class follows all of the criteria, you should be able to run the `games_test.rb` test and see all of the tests pass.
Also, if the previous criteria are met, you should be able to interact with the `Event` class from a Pry session like so:
```ruby
pry(main)> require './lib/event'
#=> true
pry(main)> event = Event.new("Curling", [24, 30, 18, 20, 41])
#=> #<Event:0x00007fba3fc42ab0 @ages=[24, 30, 18, 20, 41], @name="Curling">
pry(main)> event.name
#=> "Curling"
pry(main)> event.ages
#=> [24, 30, 18, 20, 41]
pry(main)> event.max_age
#=> 41
pry(main)> event.min_age
#=> 18
pry(main)> event.average_age
#=> 26.6
pry(main)> event.standard_deviation_age
#=> 8.28
```
## Iteration 3 - Testing
Write tests for your `Event` class that cover that expected behavior described in the previous iteration.
## Iteration 4 - Extensions
* Create a program that allows a User to interact with the Games through the command line
* Upon starting the program, the User should enter the year for the games
* The User can then create new Events and get a Summary of the Events
<file_sep>/test/games_test.rb
require 'minitest/autorun'
require 'minitest/pride'
require './lib/games'
require './lib/event'
class GamesTest < Minitest::Test
def test_it_exists
games = Games.new(2017)
assert_instance_of Games, games
end
def test_it_has_a_year
games = Games.new(2017)
assert_equal 2017, games.year
end
def test_events_starts_empty
games = Games.new(2017)
assert_equal [], games.events
end
def test_it_can_add_events
curling = Event.new("Curling", [24, 30, 18, 20, 41])
ring_toss = Event.new("Ring Toss", [23, 22, 29, 18, 30])
games = Games.new(2017)
games.add_event(curling)
games.add_event(ring_toss)
assert_equal [curling, ring_toss], games.events
end
def test_it_can_create_headers
games = Games.new(2017)
expected = "Event Max Age Min Age Average Age StdDev Age"
assert_equal expected, games.headers
end
def test_it_can_create_a_single_event_summary
curling = Event.new("Curling", [24, 30, 18, 20, 41])
games = Games.new(2017)
expected = "Curling 41 18 26.6 8.28"
assert_equal expected, games.event_summary(curling)
end
def test_it_can_create_a_summary_for_all_events
curling = Event.new("Curling", [24, 30, 18, 20, 41])
ring_toss = Event.new("Ring Toss", [23, 22, 29, 18, 30])
games = Games.new(2017)
games.add_event(curling)
games.add_event(ring_toss)
expected = "Curling 41 18 26.6 8.28\n" +
"Ring Toss 30 18 24.4 4.5"
assert_equal expected, games.all_events_summary
end
def test_it_can_create_a_summary_for_the_games
curling = Event.new("Curling", [24, 30, 18, 20, 41])
ring_toss = Event.new("Ring Toss", [23, 22, 29, 18, 30])
games = Games.new(2017)
games.add_event(curling)
games.add_event(ring_toss)
expected = "Event Max Age Min Age Average Age StdDev Age\n" +
"Curling 41 18 26.6 8.28\n" +
"Ring Toss 30 18 24.4 4.5"
assert_equal expected, games.summary
end
end
<file_sep>/lib/event.rb
class Event
attr_reader :name, :ages
def initialize(name, participants_ages)
@name = name
@ages = participants_ages
end
def max_age
ages.max_by {|age| age}
end
def min_age
ages.min_by {|age| age}
end
def average_age
(ages.sum/ages.length.to_f).round(2)
end
def standard_deviation_age
mean_diff = ages.map do |age|
change = age -= average_age.to_f
change.round(2)
end
squares = mean_diff.map { |mean| (mean ** 2).round(2)}
((squares.sum/ages.length.to_f) ** (0.5)).round(2)
end
end
<file_sep>/lib/games.rb
class Games
attr_reader :events,
:year
def initialize(year)
@year = year
@events = []
end
def add_event(event)
@events << event
end
def summary
headers + "\n" + all_events_summary
end
def headers
"Event".ljust(15) +
"Max Age".ljust(20) +
"Min Age".ljust(20) +
"Average Age".ljust(20) +
"StdDev Age"
end
def event_summary(event)
event.name.ljust(15) +
event.max_age.to_s.ljust(20) +
event.min_age.to_s.ljust(20) +
event.average_age.to_s.ljust(20) +
event.standard_deviation_age.to_s
end
def all_events_summary
@events.map do |event|
event_summary(event)
end.join("\n")
end
end
<file_sep>/runner.rb
require './lib/games'
require './lib/event'
puts "Welcome! Please enter a year of an Olympic games"
year = gets.chomp
until year.length == 4
puts "That's not a valid year. Please enter a 4 digit year:"
year = gets.chomp
end
games = Games.new(year)
puts "Olympic games #{games.year}!!! Please create events. How many events would you like to create?"
event_count = gets.chomp
until event_count.to_i > 0
puts "That's not a valid number. Please enter a number:"
event_count = gets.chomp
end
puts "You want to create #{event_count} events. You will need to enter the name of the event and the ages of all participants"
event_count.to_i.times do
puts "Name of event:"
event_name = gets.chomp
puts "Age of participants, please seperate with a comma"
ages = gets.chomp
if ages.include?(",") == true
ages = ages.gsub(/ /, "").split(",")
else ages = ages.split
end
ages = ages.map {|age| age.to_i}
event = Event.new(event_name, ages)
games.add_event(event)
end
puts "Here's the stats for the #{games.year} Olympics:"
puts games.summary
<file_sep>/test/event_test.rb
require 'minitest/autorun'
require 'minitest/pride'
require './lib/event'
class EventTest < Minitest::Test
def setup
@event = Event.new("Curling", [24, 30, 18, 20, 41])
end
def test_it_exists
assert_instance_of Event, @event
end
def test_it_has_attributes
assert_equal "Curling", @event.name
assert_equal [24, 30, 18, 20, 41], @event.ages
end
def test_it_can_calculate_age_stats_properly
assert_equal 41, @event.max_age
assert_equal 18, @event.min_age
assert_equal 26.6, @event.average_age
assert_equal 8.28, @event.standard_deviation_age
end
end
| 3302c9ea2fc7d27fd6b1edb99aeadcbf38cf0551 | [
"Markdown",
"Ruby"
] | 7 | Ruby | kathleen-carroll/super_duper_sports_games | b470e6fa8cdbd988aa161ce2e0d30f2b4aff92cb | a6d97ad67791bb3b3a1ad35f7a141ededb3913af |
refs/heads/master | <repo_name>Fantastic-Dave/DRP-Core<file_sep>/externalsql/server.lua
local authToken = nil
-- Generate Token On Start
AddEventHandler("onResourceStart", function(resource)
if resource == GetCurrentResourceName() then
if SQLConfig.CreateTokenOnStart then
Wait(1000)
DBCreateToken(function()
print("^1[DRP] Database: ^4Resource Start Token Generated")
print("^1[DRP] Database: ^4Database Started Successfully")
TriggerEvent("ExternalSQL:ExternalSqlReady")
end)
end
end
end)
function AsyncQueryCallback(queryData, callback)
Citizen.CreateThread(function()
if authToken ~= nil then
queryData.data = queryData.data or {}
PerformHttpRequest("http://" .. SQLConfig.host .. ":" .. SQLConfig.port .. SQLConfig.apipath .. "/execute", function(code, text, headers)
local decode = json.decode(text)
if decode.status ~= false then
callback({status = true, data = decode.results})
else
callback({status = false, data = {}})
end
end, "POST", json.encode({
query = queryData.query,
data = queryData.data,
secret = SQLConfig.secret
}), {
["Content-Type"] = "application/json",
["Authentication"] = tostring("Bearer " .. authToken)
})
end
end)
end
exports("AsyncQueryCallback", AsyncQueryCallback)
function AsyncQuery(queryData)
local p = promise.new()
if authToken ~= nil then
PerformHttpRequest("http://" .. SQLConfig.host .. ":" .. SQLConfig.port .. SQLConfig.apipath .. "/execute", function(code, text, headers)
local decode = json.decode(text)
if decode.status ~= false then
p:resolve({status = true, data = decode.results})
else
p:resolve({status = false, data = {}})
end
end, "POST", json.encode({
query = queryData.query,
data = queryData.data,
secret = SQLConfig.secret
}), {
["Content-Type"] = "application/json",
["Authentication"] = tostring("Bearer " .. authToken)
})
else
p:reject("[ExternalSQL]: Invalid Authentication Token!")
end
return Citizen.Await(p)
end
exports("AsyncQuery", AsyncQuery)
function DBCreateToken(callback)
authToken = nil
PerformHttpRequest("http://" .. SQLConfig.host .. ":" .. SQLConfig.port .. SQLConfig.apipath .. "/authentication", function(code, text, headers)
local decode = json.decode(text)
if decode.status ~= false then
authToken = decode.authToken
else
print(decode.message)
end
callback()
end, "POST", json.encode({
community = SQLConfig.community,
secret = SQLConfig.secret
}), {
["Content-Type"] = "application/json"
})
end<file_sep>/DatabaseAPI/database.js
const mysql = require("mysql");
const config = require("./config").database;
const devmode = require("./config").dev;
// Connection Pool
var pool = mysql.createPool(config);
function SendQuery(query, data) {
return new Promise((resolve) => {
pool.getConnection((error, connection) => {
if (error) {
resolve([false, error, "[]"]);
} else {
connection.query(query, data, (error, results, fields) => {
if (error) {
resolve([false, error, "[]"]);
}
else {
resolve([true, "Query Success", results]);
}
});
}
connection.release();
});
});
}
pool.on("connection", (connection) => {
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
});
pool.on("acquire", (connection) => {
if (devmode){ DisplayConnections() }
});
pool.on("enqueue", () => {
console.log("Waiting for available connection slot");
})
pool.on("release", (connection) => {
if (devmode){ DisplayConnections() }
})
function DisplayConnections() {
console.log(`Acquiring Connections: ${pool._acquiringConnections.length}`);
console.log("------------------------------------------------")
console.log(`All Connections: ${pool._allConnections.length}`);
console.log("------------------------------------------------")
console.log(`Free Connections: ${pool._freeConnections.length}`);
console.log("------------------------------------------------")
console.log(`Connections Queued: ${pool._connectionQueue.length}`);
console.log("------------------------------------------------")
}
module.exports = SendQuery;
console.log("^1[DatabaseAPI Message] : ^4Loaded 'database.js'"); | 2470d474594b5e7b7edf8bfae1384b78ae3ca8c1 | [
"JavaScript",
"Lua"
] | 2 | Lua | Fantastic-Dave/DRP-Core | 7a80f4bf32c90ff8045422d94cd1134f560623fb | 5fbe1a3f8d4f24b999018a2cd4be01a735152d90 |
refs/heads/master | <file_sep>// <SnippetAddUsings>
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Transforms;
// </SnippetAddUsings>
namespace TextClassificationTF
{
class Program
{
// <SnippetDeclareGlobalVariables>
public const int FeatureLength = 600;
static readonly string _modelPath = Path.Combine(Environment.CurrentDirectory, "sentiment_model");
// </SnippetDeclareGlobalVariables>
static void Main(string[] args)
{
// Create MLContext to be shared across the model creation workflow objects
// <SnippetCreateMLContext>
MLContext mlContext = new MLContext();
// </SnippetCreateMLContext>
// Dictionary to encode words as integers.
// <SnippetCreateLookupMap>
var lookupMap = mlContext.Data.LoadFromTextFile(Path.Combine(_modelPath, "imdb_word_index.csv"),
columns: new[]
{
new TextLoader.Column("Words", DataKind.String, 0),
new TextLoader.Column("Ids", DataKind.Int32, 1),
},
separatorChar: ','
);
// </SnippetCreateLookupMap>
// The model expects the input feature vector to be a fixed length vector.
// This action resizes the integer vector to a fixed length vector. If there
// are less than 600 words in the sentence, the remaining indices will be filled
// with zeros. If there are more than 600 words in the sentence, then the
// array is truncated at 600.
// <SnippetResizeFeatures>
Action<IMDBSentiment, IntermediateFeatures> ResizeFeaturesAction = (s, f) =>
{
f.Sentiment_Text = s.SentimentText;
var features = s.VariableLengthFeatures;
Array.Resize(ref features, FeatureLength);
f.Features = features;
};
// </SnippetResizeFeatures>
// Load the TensorFlow model.
// <SnippetLoadTensorFlowModel>
TensorFlowModel tensorFlowModel = mlContext.Model.LoadTensorFlowModel(_modelPath);
// </SnippetLoadTensorFlowModel>
// <SnippetGetModelSchema>
DataViewSchema schema = tensorFlowModel.GetModelSchema();
Console.WriteLine(" =============== TensorFlow Model Schema =============== ");
var featuresType = (VectorDataViewType)schema["Features"].Type;
Console.WriteLine($"Name: Features, Type: {featuresType.ItemType.RawType}, Size: ({featuresType.Dimensions[0]})");
var predictionType = (VectorDataViewType)schema["Prediction/Softmax"].Type;
Console.WriteLine($"Name: Prediction/Softmax, Type: {predictionType.ItemType.RawType}, Size: ({predictionType.Dimensions[0]})");
// </SnippetGetModelSchema>
// <SnippetTokenizeIntoWords>
IEstimator<ITransformer> pipeline =
// Split the text into individual words
mlContext.Transforms.Text.TokenizeIntoWords("TokenizedWords", "SentimentText")
// </SnippetTokenizeIntoWords>
// <SnippetMapValue>
// Map each word to an integer value. The array of integer makes up the input features.
.Append(mlContext.Transforms.Conversion.MapValue("VariableLengthFeatures", lookupMap,
lookupMap.Schema["Words"], lookupMap.Schema["Ids"], "TokenizedWords"))
// </SnippetMapValue>
// <SnippetCustomMapping>
// Resize variable length vector to fixed length vector.
.Append(mlContext.Transforms.CustomMapping(ResizeFeaturesAction, "Resize"))
// </SnippetCustomMapping>
// <SnippetScoreTensorFlowModel>
// Passes the data to TensorFlow for scoring
.Append(tensorFlowModel.ScoreTensorFlowModel("Prediction/Softmax", "Features"))
// </SnippetScoreTensorFlowModel>
// <SnippetCopyColumns>
// Retrieves the 'Prediction' from TensorFlow and and copies to a column
.Append(mlContext.Transforms.CopyColumns("Prediction", "Prediction/Softmax"));
// </SnippetCopyColumns>
// <SnippetCreateModel>
// Create an executable model from the estimator pipeline
IDataView dataView = mlContext.Data.LoadFromEnumerable(new List<IMDBSentiment>());
ITransformer model = pipeline.Fit(dataView);
// </SnippetCreateModel>
// <SnippetCallPredictSentiment>
PredictSentiment(mlContext, model);
// </SnippetCallPredictSentiment>
}
public static void PredictSentiment(MLContext mlContext, ITransformer model)
{
// <SnippetCreatePredictionEngine>
var engine = mlContext.Model.CreatePredictionEngine<IMDBSentiment, IMDBSentimentPrediction>(model);
// </SnippetCreatePredictionEngine>
// <SnippetCreateTestData>
var data = new[] { new IMDBSentiment() {
SentimentText = "this film is really good"
}};
// </SnippetCreateTestData>
// Predict with TensorFlow pipeline.
// <SnippetPredict>
var prediction = engine.Predict(data[0]);
// </SnippetPredict>
// <SnippetDisplayPredictions>
Console.WriteLine("Number of classes: {0}", prediction.Prediction.Length);
Console.WriteLine("Is sentiment/review positive? {0}", prediction.Prediction[1] > 0.5 ? "Yes." : "No.");
Console.WriteLine("Prediction[0]: {0}", prediction.Prediction[0]);
Console.WriteLine("Prediction[1]: {0}", prediction.Prediction[1]);
Console.WriteLine("Sum: {0}", prediction.Prediction[0] + prediction.Prediction[1]);
// </SnippetDisplayPredictions>
/////////////////////////////////// Expected output ///////////////////////////////////
//
// Name: Features, Type: System.Int32, Size: 600
// Name: Prediction/Softmax, Type: System.Single, Size: 2
//
// Number of classes: 2
// Is sentiment/review positive ? Yes
// Prediction Confidence: 0.65
}
// <SnippetDeclareIntermediateFeatures>
/// <summary>
/// Class to hold intermediate data. Mostly used by CustomMapping Estimator
/// </summary>
public class IntermediateFeatures
{
public string Sentiment_Text { get; set; }
[VectorType(FeatureLength)]
public int[] Features { get; set; }
}
// </SnippetDeclareIntermediateFeatures>
}
}
| 0f144d48c7832e9e7c2403a458d998377de0f8ac | [
"C#"
] | 1 | C# | tonidy/samples | 6db1cfbf82f6bcf917f988efd448f6614ae5a681 | 0955d816b233c20c2f86afcd727d33763d679841 |
refs/heads/master | <file_sep>STools
======
An useful extension of Visual Studio.<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace S2.STools.Commands
{
class NamingRuleChecker : ICommand
{
public bool IsEnable(EnvDTE.DTE dte)
{
return true;
}
public void Execute(EnvDTE.DTE dte)
{
throw new NotImplementedException();
}
public bool IsYourId(uint commandId)
{
return commandId == PkgCmdIDList.CommandIdDocumentThisChild;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Text.Editor;
using EnvDTE;
using System.Windows.Forms;
using System.Globalization;
namespace S2.STools.Commands
{
class DocumentThis : ICommand
{
public bool IsYourId(uint commandId)
{
return commandId == PkgCmdIDList.CommandIdDocumentThis;
}
public bool IsEnable(DTE dte)
{
FileCodeModel cm = dte.ActiveDocument.ProjectItem.FileCodeModel;
return cm.Language == CodeModelLanguageConstants.vsCMLanguageVC;
}
public void Execute(DTE dte)
{
CodeFunction func = GetSelectedFunction(dte);
if (func == null)
{
MessageBox.Show(Resources.FunctionNotSelected);
return;
}
func.StartPoint.CreateEditPoint().Insert(GetFuncComment(func));
}
private static CodeFunction GetSelectedFunction(DTE dte)
{
foreach (CodeFunction func in SearchFunctions(dte))
{
if (IsFuncSelected(dte, func)) return func;
}
return null;
}
private static IEnumerable<CodeFunction> SearchFunctions(DTE dte)
{
CodeModel cm = dte.ActiveDocument.ProjectItem.ContainingProject.CodeModel;
return SearchFunctionsCore(cm.CodeElements);
}
private static IEnumerable<CodeFunction> SearchFunctionsCore(CodeElements codeElements)
{
foreach (CodeElement e in codeElements)
{
if (e.Kind == vsCMElement.vsCMElementClass)
{
CodeClass c = (CodeClass)e;
foreach (CodeFunction f in SearchFunctionsCore(c.Children))
{
yield return f;
}
}
if (e.Kind != vsCMElement.vsCMElementFunction) continue;
yield return (CodeFunction)e;
}
yield break;
}
private static bool IsFuncSelected(DTE dte, CodeFunction func)
{
int selLine = ((TextSelection)dte.ActiveDocument.Selection).AnchorPoint.Line;
return func.StartPoint.Line <= selLine
&& selLine <= func.EndPoint.Line;
}
private string GetFuncComment(CodeFunction func)
{
StringBuilder str = new StringBuilder();
str.Append(@"///<summary>" + GetDescriptionFromCamelcase(func.Name) + @"</summary>" + Environment.NewLine);
foreach (string param in GetParamNames(func))
{
str.Append(@"///<param name='" + param + "'>" + GetDescriptionFromCamelcase(param) + @"</param>" + Environment.NewLine);
}
return str.ToString();
}
private static string GetDescriptionFromCamelcase(string funcName)
{
StringBuilder buff = new StringBuilder();
bool isFirst = true;
foreach (char c in funcName.ToCharArray())
{
if (isFirst)
{
isFirst = false;
buff.Append(Char.ToUpper(c, CultureInfo.CurrentCulture));
}
else
{
if (Char.IsUpper(c))
{
buff.Append(" ");
buff.Append(Char.ToLower(c, CultureInfo.CurrentCulture));
}
else
{
buff.Append(c);
}
}
}
return buff.ToString();
}
private IEnumerable<string> GetParamNames(CodeFunction func)
{
foreach (CodeParameter param in func.Parameters)
{
yield return param.FullName;
}
}
}
}
| 5130aad424c39c5a41d0695f179208e6f60f4c61 | [
"Markdown",
"C#"
] | 3 | Markdown | sonesuke/STools | 31c9cc676d99cdad92fd9b4f04ab592f466fad2f | 88dc53495921a1e7f1d00a9420fbb3afba075191 |
refs/heads/master | <file_sep>#ifndef _EXCEPTION_H_
#define _EXCEPTION_H_
#include <string>
#include <exception>
class Exception : public std::exception
{
public:
Exception(std::string error) : err(error) {}
const char* what() const throw() { return err.c_str(); }
private:
std::string err;
};
#endif~ <file_sep>#ifndef _SAFEARRAY_H_
#define _SAFEARRAY_H_
template<class T>
class SafeArray
{
public:
SafeArray(unsigned int size);
~SafeArray(void);
T* getArray()const;
T& operator[](const unsigned int index);
T operator++();
T operator--();
void SafeArray<T>::print()const;
private:
unsigned int m_size;
T* m_array;
unsigned int m_index;
};
// c'tor & d'tor
template<class T>
SafeArray<T>::SafeArray(unsigned int size) : m_size(size), m_index(0)
{
if (size <1)
throw Exception("ERROR: Array size must positive!");
m_array = new T[m_size];
//Initialized the array from 0 to 4.
for (unsigned int i = 0; i < m_size; i++)
m_array[i] = i;
}
template<class T>
SafeArray<T>::~SafeArray(void)
{
delete[] m_array;
}
// operator [] overload
template<class T>
T& SafeArray<T>::operator[](const unsigned int index)
{
if (index > (m_size - 1))
throw Exception("ERROR: array index out of range.");
return m_array[index];
}
// operator ++ overload
template<class T>
T SafeArray<T>::operator++()
{
if (m_index >= (m_size - 1))
throw Exception("ERROR: array index out of range.");
return m_array[++m_index];
}
// operator -- overload
template<class T>
T SafeArray<T>::operator--()
{
if (m_index == 0)
throw Exception("ERROR: array index out of range.");
return m_array[--m_index];
}
//return the array.
template<class T>
T* SafeArray<T>::getArray()const { return m_array; }
//create output stream for the array.
template<class T>
std::ostream& operator<<(std::ostream &os, const SafeArray<T>& sArray) { return os << *(sArray.getArray()); }
//Print the array.
template<class T>
void SafeArray<T>::print()const
{
for (int i = 0; i < m_size; i++)
cout << m_array[i] << " ";
cout << endl;
}
#endif | 254cf29d0dba1210bfdb575f94d30885650ccb78 | [
"C++"
] | 2 | C++ | GabrielLurie/safeArrayCPP | 9e9f5abeddfa28abdfacc8907eb5443030cbfcd1 | b8034f08d7b3b1a81d3a97ae47585ceb3a7cb3a6 |
refs/heads/master | <file_sep><div class="row featurette" id="registrationform">
<div class="col-md-1"></div>
<div class="col-md-10" id="registrationbox">
<img src="<?php echo $this->base; ?>/img/pin.png" class="pull-right" />
<h2>Registration</h2>
<?php echo $this->Form->create('Company'); ?>
<table class="table table-hovered">
<tr>
<td>Pelayanan yang diinginkan</td>
<td>:</td>
<td>
<div class="control-group">
<div class="controls">
<?php foreach($services as $key=>$item) : ?>
<?php if ($item['Service']['parent_id'] == NULL) {?>
<?php echo $this->Form->checkbox('CompanyService.'.$key.'.service_id',array('value'=>$item['Service']['id']));?>
<?php echo $this->Form->label($item['Service']['nama_layanan']) ?>
<?php } ?>
<?php endforeach; ?>
</div>
</div>
</td>
</tr>
<tr>
<td colspan="3"><h3 class="judul_tabel">Data Perusahaan</h3></td>
</tr>
<tr>
<td>Nama Perusahaan</td>
<td>:</td>
<td><?php echo $this->Form->input('nama_perusahaan',array('label'=>false,'style'=>'width:100%','placeholder'=>'Nama Perusahaan'));?></td>
</tr>
<tr>
<td>NPWP</td>
<td>:</td>
<td><?php echo $this->Form->input('npwp',array('label'=>false,'style'=>'width:100%','placeholder'=>'NPWP'));?></td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td><?php echo $this->Form->textarea('alamat',array('label'=>false,'style'=>'width:100%','placeholder'=>'Alamat'));?></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><?php echo $this->Form->input('email',array('label'=>false,'style'=>'width:100%','placeholder'=>'Email'));?></td>
</tr>
<tr>
<td>Tingkat Organisasi</td>
<td>:</td>
<td><?php echo $this->Form->input('tingkat_organisasi',array('label'=>false,'style'=>'width:100%','placeholder'=>'Pusat / Cabang'));?></input></td>
</tr>
<tr>
<td>Alamat Penagihan</td>
<td>:</td>
<td><?php echo $this->Form->textarea('alamat_penagihan',array('label'=>false,'style'=>'width:100%','placeholder'=>'Alamat Penagihan'));?></td>
</tr>
<tr>
<td>Masa Berlaku</td>
<td>:</td>
<td><?php echo $this->Form->date('masa_berlaku',array('label'=>false,'placeholder'=>'Masa Berlaku','class'=>'dp4'));?></td>
</tr>
<tr>
<td>No Telepon</td>
<td>:</td>
<td><?php echo $this->Form->input('no_telepon',array('label'=>false,'style'=>'width:100%','placeholder'=>'Nomor Telepon'));?></td>
</tr>
<tr>
<td>Group Usaha</td>
<td>:</td>
<td><?php echo $this->Form->input('group_usaha',array('label'=>false,'style'=>'width:100%','placeholder'=>'Group Usaha'));?></td>
</tr>
<tr>
<td>Bidang Usaha</td>
<td>:</td>
<td>
<div class="control-group">
<div class="controls">
<?php foreach($areas as $key=>$item) : ?>
<?php echo $this->Form->checkbox('CompanyArea.'.$key.'.area_id',array('value'=>$item['Area']['id']));?>
<?php echo $this->Form->label($item['Area']['nama']) ?>
<?php endforeach; ?>
</div>
</div>
</td>
</tr>
<tr>
<td colspan="3" ><h3 class="judul_tabel">Data Penanggung Jawab</h3></td>
</tr>
<tr>
<td>Nama Pimpinan Perusahaan</td>
<td>:</td>
<td><?php echo $this->Form->input('CompanyResponsible.0.nama_pimpinan',array('label'=>false,'style'=>'width:100%','placeholder'=>'Nama Penanggung Jawab'));?></td>
</tr>
<tr>
<td>Jabatan</td>
<td>:</td>
<td><?php echo $this->Form->input('CompanyResponsible.0.jabatan',array('label'=>false,'style'=>'width:100%','placeholder'=>'Jabatan'));?></td>
</tr>
<tr>
<td>Tempat Lahir</td>
<td>:</td>
<td>
<?php echo $this->Form->input('CompanyResponsible.0.tempat_lahir',array('label'=>false,'style'=>'width:100%','placeholder'=>'Tempat Lahir'));?>
</td>
</tr>
<tr>
<td>Tanggal Lahir</td>
<td>:</td>
<td>
<?php echo $this->Form->date('CompanyResponsible.0.tanggal_lahir',array('label'=>false));?>
</td>
</tr>
<tr>
<td><span class="fg-green">Alamat Rumah</span> <br /><span style="font-size: 12px;">(sesuai tanda pengenal)</span></td>
<td>:</td>
<td><?php echo $this->Form->textarea('CompanyResponsible.0.alamat',array('label'=>false,'style'=>'width:100%','placeholder'=>'Alamat'));?></td>
</tr>
<tr>
<td><span class="fg-green">No Telepon</span></td>
<td>:</td>
<td><?php echo $this->Form->input('CompanyResponsible.0.no_telepon',array('label'=>false,'style'=>'width:100%','placeholder'=>'No Telepon'));?></td>
</tr>
<tr>
<td><span class="fg-green">Email</span></td>
<td>:</td>
<td><?php echo $this->Form->input('CompanyResponsible.0.email',array('label'=>false,'style'=>'width:100%','placeholder'=>'Email'));?></td>
</tr>
<!--<tr>
<td><span class="fg-green">Telepon Rumah</span></td>
<td>:</td>
<td><?php //echo $this->Form->input('CompanyResponsible.0.nama_pimpinan',array('label'=>false,'style'=>'width:100%','placeholder'=>'Telepon'));?></input></td>
</tr>
<tr>
<td><span class="fg-cyan">Alamat Kantor</span></td>
<td>:</td>
<td><textarea rows="3" style="width:100%;"></textarea></td>
</tr>
<tr>
<td><span class="fg-cyan">Kota</span></td>
<td>:</td>
<td><input type="text" placeholder="City" style="width:100%;"></input></td>
</tr>
<tr>
<td><span class="fg-cyan">Kode Pos</span></td>
<td>:</td>
<td><input type="text" placeholder="Postal Code" style="width:100%;"></input></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input type="email" placeholder="Email" style="width:100%;"></input></td>
</tr>-->
<tr>
<td><strong>Tanda Pengenal</strong></td>
<td>:</td>
<td>
<div class="control-group">
<div class="controls">
<!--<label class="radio-inline">
<input type="radio" name="" id="ktpcheck" value="">
KTP
</label>
<label class="radio-inline">
<input type="radio" name="" id="simcheck" value="">
SIM
</label>
<label class="radio-inline">
<input type="radio" name="" id="passportcheck" value="">
Passport
</label>
<label class="radio-inline">
<input type="radio" name="" id="lainnyacheck" value="">
Lainnya
</label>-->
<input type="hidden" name="data[CompanyResponsible][0][tanda_pengenal]" id="CompanyResponsible0TandaPengenal_" value />
<input type="checkbox" name="data[CompanyResponsible][0][tanda_pengenal]" id="ktpcheck" value="KTP" required="false" />
<label for="ktpcheck" >KTP</label>
<input type="checkbox" name="data[CompanyResponsible][0][tanda_pengenal]" id="simcheck" value="SIM" required="false" />
<label for="simcheck" >SIM</label>
<input type="checkbox" name="data[CompanyResponsible][0][tanda_pengenal]" id="passportcheck" value="Passport" required="false" />
<label for="passportcheck" >Passport</label>
<input type="checkbox" name="data[CompanyResponsible][0][tanda_pengenal]" id="lainnyacheck" value="Lainnya" required="false" />
<label for="lainnyacheck" >Lainnya</label>
<?php //echo $this->Form->input('CompanyResponsible.0.tanda_pengenal',array('label'=>false,'options'=>array(0=>'Please select','KTP'=>'KTP','SIM'=>'SIM','PASSPORT'=>'PASSPORT')));?>
</div>
</div>
</td>
</tr>
<tr id="ktp" style="display:none">
<td><span style="margin-left: 40px;">No. KTP</span></td>
<td>:</td>
<td><input name="data[CompanyResponsible][0][nomor_tanda_pengenal]" style="width:100%" type="text" id="CompanyResponsible0NomorTandaPengenal" required="required" placeholder="KTP Number" /></td>
</tr>
<tr id="sim" style="display:none">
<td><span style="margin-left: 40px;">No. SIM</span></td>
<td>:</td>
<td><input name="data[CompanyResponsible][0][nomor_tanda_pengenal]" style="width:100%" type="text" id="CompanyResponsible0NomorTandaPengenal" required="required" placeholder="Driver Number" /></td>
</tr>
<tr id="passport" style="display:none">
<td><span style="margin-left: 40px;">No. Passport</span></td>
<td>:</td>
<td><input name="data[CompanyResponsible][0][nomor_tanda_pengenal]" style="width:100%" type="text" id="CompanyResponsible0NomorTandaPengenal" required="required" placeholder="Passport Number" /></td>
</tr>
<tr id="lainnya" style="display:none">
<td><span style="margin-left: 40px;">Lainnya</span></td>
<td>:</td>
<td><input name="data[CompanyResponsible][0][nomor_tanda_pengenal]" style="width:100%" type="text" id="CompanyResponsible0NomorTandaPengenal" required="required" placeholder="Lainnya Number" /></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<td>:</td>
<td>
<div class="control-group">
<div class="controls">
<?php echo $this->Form->radio('CompanyResponsible.0.jenis_kelamin',array('M' => 'Laki - Laki', 'F' => 'Perempuan'),array('legend'=>false)); ?>
</div>
</div>
</td>
</tr>
<tr>
<td>Agama</td>
<td>:</td>
<td>
<div class="control-group">
<div class="controls">
<?php echo $this->Form->radio('CompanyResponsible.0.agama',array('Islam'=>'Islam','Kristen'=>'Kristen','Katolik'=>'Katolik','Buddha'=>'Buddha','Hindu'=>'Hindu'),array('legend'=>false)); ?>
</div>
</div>
</td>
</tr>
</table>
<h3 class="judul_tabel">Pengurus Perusahaan</h3>
<table class="table table-striped" id="pengurus">
<thead>
<tr class="bg-olive fg-white">
<th>No</th>
<th>Nama</th>
<th>Jabatan</th>
<th>Alamat</th>
<th>Alamat Perusahaan</th>
</tr>
</thead>
<tbody>
<?php for($x = 0 ; $x<4 ;$x++) { ?>
<tr>
<td><?php echo $x+1 ?></td>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.nama',array('label'=>false, 'required'=>false)); ?></td>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.jabatan',array('label'=>false, 'required'=>false)); ?></td>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.alamat',array('label'=>false, 'required'=>false)); ?></td>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.alamat_perusahaan',array('label'=>false, 'required'=>false)); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<!--
<h3 class="judul_tabel" style="margin-top:80px;">Kontrak</h3>
<table class="table table-hovered">
<tr>
<td>Alamat Penagihan</td>
<td>:</td>
<td><textarea rows="3" style="width:100%;"></textarea></td>
</tr>
<tr>
<td>Masa Berlaku Kontrak</td>
<td>:</td>
<td><input class="span2" size="16" type="text" value="" id="dp4"> </td>
</tr>
</table>
<div class="control-group" style="margin-top:30px; padding-bottom:20px;">
<div class="controls pull-right">
<button type="submit" class="btn bg-cyan">Submit</button>
</div>
</div>
</form>-->
<?php echo $this->Form->end(__('Submit')); ?>
</div>
</div>
<script>
$('#dp3').datepicker({
viewMode: 'years',
format:'dd-mm-yyyy'});
$('#dp4').datepicker({
viewMode: 'years',
format:'dd-mm-yyyy'});
</script>
<script>
var now = 3;
var nextrow = 4;
function addRow(){
$("#pengurus > tbody:last").append('<tr>'+
'<td>'+ nextrow +'</td>'+
'<td><input type="text" placeholder="Nama"></td>'+
'<td><input type="text" placeholder="Jabatan"></td>'+
'<td><textarea rows="2"></textarea></td>'+
'<td><textarea rows="2"></textarea></td>'+
'</tr>');
nextrow = nextrow + 1;
}
function deleteRow(){
$("#pengurus > tbody > tr:last").remove();
nextrow = nextrow - 1;
if(nextrow <= 0){
nextrow = 1;
}
}
</script>
<script>
$("#ktpcheck").change(function() {
if(this.checked) {
$("#ktp").show();
}
else{
$("#ktp").hide();
}
});
$("#simcheck").change(function() {
if(this.checked) {
$("#sim").show();
}
else{
$("#sim").hide();
}
});
$("#passportcheck").change(function() {
if(this.checked) {
$("#passport").show();
}
else{
$("#passport").hide();
}
});
$("#lainnyacheck").change(function() {
if(this.checked) {
$("#lainnya").show();
}
else{
$("#lainnya").hide();
}
});
</script><file_sep><?php echo $this->Form->create('User',array('id'=>'validate')); ?>
<!-- START THE FEATURETTES -->
<div class="row featurette" style="margin-top:30px; margin-bottom:30px;">
<div class="col-md-5">
<?php echo $this->Html->image('logopelindo.jpg', array('alt' => 'logo', 'class'=>'featurette-image')); ?>
</div>
<div class="col-md-7 ">
<h2 class="featurette-heading" style="font-size: 40px;">Welcome to IPC Customer Services</h2>
<?php echo $this->Form->input('username',array('class'=>'validate[required]','placeholder'=>'Username','label'=>false,'div'=>false)); ?>
<br />
<?php echo $this->Form->input('password',array('class'=>'validate[required]','placeholder'=>'<PASSWORD>','label'=>false,'div'=>false));?>
<div class="control-group" style="margin-top:10px;">
<div class="controls">
<input type="submit" class="btn bg-cyan" value="login" />
</div>
</div>
</div>
</div><file_sep><div class="submissions form">
<?php echo $this->Form->create('Submission'); ?>
<fieldset>
<legend><?php echo __('Add Submission'); ?></legend>
<?php
echo $this->Form->input('company_id',array('empty'=>'Choose One'));
echo $this->Form->hidden('agen_id',array('value'=>$this->Session->read('Auth.User.agen_id')));
echo $this->Form->input('reporter_id',array('empty'=>'Choose One'));
echo $this->Form->input('service_id',array('empty'=>'Choose One'));
// echo $this->Form->input('tanggal');
echo $this->Form->input('note');
echo $this->Form->input('status', array('options' => array('open'=>'Open', 'closed'=>'Close')));
// echo $this->Form->input('flag');
?>
</fieldset>
<fieldset>
<legend><?php echo __('Masukan Berkas (Jika Ada)'); ?></legend>
<?php
echo $this->Form->file('Dokumen.0.link_gambar',array('required'=>FALSE));
echo $this->Form->input('Dokumen.0.deskrpisi',array('required'=>FALSE));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Home'), array('controller'=>'users','action' => 'index')); ?></li>
</ul>
</div>
<file_sep><?php
App::uses('AppController', 'Controller');
/**
* Companies Controller
*
* @property Company $Company
* @property PaginatorComponent $Paginator
*/
class CompaniesController extends AppController {
/**
* Components
*
* @var array
*/
public $components = array('Paginator');
/**
* index method
*
* @return void
*/
public function index() {
$this->Company->recursive = 0;
$this->set('companies', $this->Paginator->paginate());
}
public function generatePassword() {
$length = 8;
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$count = mb_strlen($chars);
for ($i = 0, $result = ''; $i < $length; $i++) {
$index = rand(0, $count - 1);
$result .= mb_substr($chars, $index, 1);
}
return $result;
}
public function add_customer(){
if($this->request->is('post')){
$this->loadModel('User');
$this->User->create();
$this->request->data['User']['password'] = $<PASSWORD>();
// echo "<pre>";
// var_dump($this->request->data);
// exit;
// echo "</pre>";
// exit;
if ($this->User->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The Customer has been saved.'));
return $this->redirect(array('controller'=>'users','action' => 'index_backroom'));
} else {
$this->Session->setFlash(__('The company could not be saved. Please, try again.'));
}
}else{
$this->Company->recursive = 0;
$this->set('companies', $this->Paginator->paginate());
}
}
public function save_customer($id = null){
if($this->request->is('post')){
$this->User->create();
echo "<pre>";
var_dump($this->request->data);
exit;
echo "</pre>";
exit;
if ($this->Company->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The company has been saved.'));
return $this->redirect(array('controller'=>'users','action' => 'index'));
} else {
$this->Session->setFlash(__('The company could not be saved. Please, try again.'));
}
}
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->Company->exists($id)) {
throw new NotFoundException(__('Invalid company'));
}
$options = array('conditions' => array('Company.' . $this->Company->primaryKey => $id));
$this->set('company', $this->Company->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Company->create();
foreach ($this->request->data['CompanyService'] as $key=>$value) {
if($value['service_id'] == 0){
unset($this->request->data['CompanyService'][$key]);
}
}
foreach ($this->request->data['CompanyArea'] as $key=>$value) {
if($value['area_id'] == 0){
unset($this->request->data['CompanyArea'][$key]);
}
}
// echo "<pre>";
// var_dump($this->request->data);
// exit;
// echo "</pre>";
// exit;
if ($this->Company->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The company has been saved.'));
return $this->redirect(array('controller'=>'users','action' => 'index'));
} else {
$this->Session->setFlash(__('The company could not be saved. Please, try again.'));
}
}
$services = $this->Company->CompanyService->Service->find('all');
$this->set(compact('services'));
$areas = $this->Company->CompanyArea->Area->find('all');
$this->set(compact('areas'));
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->Company->exists($id)) {
throw new NotFoundException(__('Invalid company'));
}
if ($this->request->is(array('post', 'put'))) {
echo "<pre>";
var_dump($this->request->data);
echo "</pre>";
exit;
if ($this->Company->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The company has been saved.'));
return $this->redirect(array('controller'=>'users','action' => 'index'));
} else {
$this->Session->setFlash(__('The company could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Company.' . $this->Company->primaryKey => $id));
$this->request->data = $this->Company->find('first', $options);
}
//get all areas
$services = $this->Company->CompanyService->Service->find('list',array('fields'=>array('id','nama_layanan')));
//get all services
$areas = $this->Company->CompanyArea->Area->find('list',array('fields'=>array('id','nama')));
//selected area
$selectedArea = $this->getSelected($this->request->data['CompanyArea'] , 'area_id');
//get seleceted services
$selectedService = $this->getSelected($this->request->data['CompanyService'] , 'service_id');
$this->set(compact('areas','services','selectedArea','selectedService'));
}
function getSelected($data,$idKey){
foreach ($data as $key => $value) {
$selectedArea[] = $value[$idKey];
}
return (!empty($selectedArea)) ? $selectedArea : array();
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->Company->id = $id;
if (!$this->Company->exists()) {
throw new NotFoundException(__('Invalid company'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Company->delete()) {
$this->Session->setFlash(__('The company has been deleted.'));
} else {
$this->Session->setFlash(__('The company could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
}
<file_sep><div class="companyStaffs view">
<h2><?php echo __('Company Staff'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($companyStaff['CompanyStaff']['id']); ?>
</dd>
<dt><?php echo __('Company'); ?></dt>
<dd>
<?php echo $this->Html->link($companyStaff['Company']['id'], array('controller' => 'companies', 'action' => 'view', $companyStaff['Company']['id'])); ?>
</dd>
<dt><?php echo __('Nama'); ?></dt>
<dd>
<?php echo h($companyStaff['CompanyStaff']['nama']); ?>
</dd>
<dt><?php echo __('Jabatan'); ?></dt>
<dd>
<?php echo h($companyStaff['CompanyStaff']['jabatan']); ?>
</dd>
<dt><?php echo __('Alamat'); ?></dt>
<dd>
<?php echo h($companyStaff['CompanyStaff']['alamat']); ?>
</dd>
<dt><?php echo __('Alamat Perusahaan'); ?></dt>
<dd>
<?php echo h($companyStaff['CompanyStaff']['alamat_perusahaan']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Company Staff'), array('action' => 'edit', $companyStaff['CompanyStaff']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Company Staff'), array('action' => 'delete', $companyStaff['CompanyStaff']['id']), null, __('Are you sure you want to delete # %s?', $companyStaff['CompanyStaff']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Company Staffs'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Staff'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Companies'), array('controller' => 'companies', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company'), array('controller' => 'companies', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="companyServices view">
<h2><?php echo __('Company Service'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($companyService['CompanyService']['id']); ?>
</dd>
<dt><?php echo __('Service'); ?></dt>
<dd>
<?php echo $this->Html->link($companyService['Service']['id'], array('controller' => 'services', 'action' => 'view', $companyService['Service']['id'])); ?>
</dd>
<dt><?php echo __('Company'); ?></dt>
<dd>
<?php echo $this->Html->link($companyService['Company']['id'], array('controller' => 'companies', 'action' => 'view', $companyService['Company']['id'])); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Company Service'), array('action' => 'edit', $companyService['CompanyService']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Company Service'), array('action' => 'delete', $companyService['CompanyService']['id']), null, __('Are you sure you want to delete # %s?', $companyService['CompanyService']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Company Services'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Service'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Services'), array('controller' => 'services', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Service'), array('controller' => 'services', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Companies'), array('controller' => 'companies', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company'), array('controller' => 'companies', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="reporters view">
<h2><?php echo __('Reporter'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($reporter['Reporter']['id']); ?>
</dd>
<dt><?php echo __('Nama'); ?></dt>
<dd>
<?php echo h($reporter['Reporter']['nama']); ?>
</dd>
<dt><?php echo __('Email'); ?></dt>
<dd>
<?php echo h($reporter['Reporter']['email']); ?>
</dd>
<dt><?php echo __('No Telpon'); ?></dt>
<dd>
<?php echo h($reporter['Reporter']['no_telpon']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Reporter'), array('action' => 'edit', $reporter['Reporter']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Reporter'), array('action' => 'delete', $reporter['Reporter']['id']), null, __('Are you sure you want to delete # %s?', $reporter['Reporter']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Reporters'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Reporter'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Issues'), array('controller' => 'issues', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Submissions'), array('controller' => 'submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
<div class="related">
<h3><?php echo __('Related Issues'); ?></h3>
<?php if (!empty($reporter['Issue'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Reporter Id'); ?></th>
<th><?php echo __('Category Id'); ?></th>
<th><?php echo __('No Resi'); ?></th>
<th><?php echo __('Note'); ?></th>
<th><?php echo __('Link Gambar'); ?></th>
<th><?php echo __('Tanggal'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($reporter['Issue'] as $issue): ?>
<tr>
<td><?php echo $issue['id']; ?></td>
<td><?php echo $issue['company_id']; ?></td>
<td><?php echo $issue['agen_id']; ?></td>
<td><?php echo $issue['reporter_id']; ?></td>
<td><?php echo $issue['category_id']; ?></td>
<td><?php echo $issue['no_resi']; ?></td>
<td><?php echo $issue['note']; ?></td>
<td><?php echo $issue['link_gambar']; ?></td>
<td><?php echo $issue['tanggal']; ?></td>
<td><?php echo $issue['status']; ?></td>
<td><?php echo $issue['flag']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'issues', 'action' => 'view', $issue['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'issues', 'action' => 'edit', $issue['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'issues', 'action' => 'delete', $issue['id']), null, __('Are you sure you want to delete # %s?', $issue['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Submissions'); ?></h3>
<?php if (!empty($reporter['Submission'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Reporter Id'); ?></th>
<th><?php echo __('Service Id'); ?></th>
<th><?php echo __('Note'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($reporter['Submission'] as $submission): ?>
<tr>
<td><?php echo $submission['id']; ?></td>
<td><?php echo $submission['company_id']; ?></td>
<td><?php echo $submission['agen_id']; ?></td>
<td><?php echo $submission['reporter_id']; ?></td>
<td><?php echo $submission['service_id']; ?></td>
<td><?php echo $submission['note']; ?></td>
<td><?php echo $submission['status']; ?></td>
<td><?php echo $submission['flag']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'submissions', 'action' => 'view', $submission['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'submissions', 'action' => 'edit', $submission['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'submissions', 'action' => 'delete', $submission['id']), null, __('Are you sure you want to delete # %s?', $submission['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<file_sep><?php
/**
*
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Layouts
* @since CakePHP(tm) v 0.10.0.1076
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
$cakeDescription = __d('cake_dev', 'CakePHP: the rapid development php framework');
?>
<!DOCTYPE html>
<html>
<head>
<?php $this->Html->css("bootstrap", null, array("inline"=>false)); ?>
<?php $this->Html->css("color", null, array("inline"=>false)); ?>
<?php $this->Html->css("site", null, array("inline"=>false)); ?>
<?php $this->Html->css("carousel", null, array("inline"=>false)); ?>
<?php $this->Html->css("jquery.jqplot.min", null, array("inline"=>false)); ?>
<?php $this->Html->css("datepicker", null, array("inline"=>false)); ?>
<?php $this->Html->script("bootstrap.min", array("inline"=>false)); ?>
<?php $this->Html->script("bootstrap-datepicker", array("inline"=>false)); ?>
<?php $this->Html->script("holder", array("inline"=>false)); ?>
<?php $this->Html->script("jquery-1.10.2.min", array("inline"=>false)); ?>
<?php $this->Html->script("jqplot.barRenderer.min", array("inline"=>false)); ?>
<?php $this->Html->script("jqplot.categoryAxisRenderer.min", array("inline"=>false)); ?>
<?php $this->Html->script("jqplot.pieRenderer.min", array("inline"=>false)); ?>
<?php $this->Html->script("jqplot.pointLabels.min", array("inline"=>false)); ?>
<?php $this->Html->script("jquery.jqplot", array("inline"=>false)); ?>
<?php $this->Html->script("jquery.mousewheel", array("inline"=>false)); ?>
<?php echo $this->Html->charset(); ?>
<title>
<?php echo $cakeDescription ?>:
<?php echo $title_for_layout; ?>
</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script>
var base = "<?php echo $this->base; ?>";
</script>
<?php
echo $this->Html->meta('icon');
echo $this->Html->css('cake.generic');
echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');
?>
</head>
<body>
<?php if($this->Session->read('Auth.User.id') == 0) { ?>
<div id="header">
<h1><?php //echo $this->Html->link($cakeDescription, 'http://cakephp.org'); ?></h1>
</div>
<div id="content" class="container marketing bg-transparent">
<?php echo $this->Session->flash(); ?>
<?php echo $this->fetch('content'); ?>
</div>
<?php } else { ?>
<div id="header">
<h1><?php //echo $this->Html->link($cakeDescription, 'http://cakephp.org'); ?></h1>
</div>
<div class="navbar-wrapper">
<div class="container">
<div class="navbar navbar-inverse navbar-fixed-top bg-orange" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<?php if($this->Session->read('Auth.User.agen_level') == 1) { ?>
<?php echo $this->Html->link(__('CS-IPC'), array('controller'=>'users','action' => 'index'),array('class'=>"navbar-brand")); ?>
<?php } else if($this->Session->read('Auth.User.agen_level') == 2) { ?>
<?php echo $this->Html->link(__('CS-IPC'), array('controller'=>'users','action' => 'index_backroom'),array('class'=>"navbar-brand")); ?>
<?php } else if($this->Session->read('Auth.User.agen_level') == 3) { ?>
<?php echo $this->Html->link(__('CS-IPC'), array('controller'=>'users','action' => 'index_admin'),array('class'=>"navbar-brand")); ?>
<?php } ?>
</div>
<div class="navbar-collapse collapse">
<?php if($this->Session->read('Auth.User.agen_level') != 3) { ?>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Complain Handling<b class="caret"></b></a>
<ul class="dropdown-menu">
<?php if($this->Session->read('Auth.User.agen_level') == 1) { ?>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues','action' => 'add')); ?></li>
<?php } ?>
<li><?php echo $this->Html->link(__('Issue Tracking'), array('controller' => 'issues','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('My Issue'), array('controller' => 'issues','action' => 'index')); ?></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Filling Service<b class="caret"></b></a>
<ul class="dropdown-menu">
<?php if($this->Session->read('Auth.User.agen_level') == 1) { ?>
<li><?php echo $this->Html->link(__('New Filling'), array('controller' => 'submissions','action' => 'add')); ?></li>
<?php } ?>
<li><?php echo $this->Html->link(__('Filling Tracking'), array('controller' => 'submissions','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('My Filling'), array('controller' => 'submissions','action' => 'index')); ?></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
<?php if($this->Session->read('Auth.User.agen_level') == 1) { ?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Registration<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link(__('New Registration'), array('controller' => 'companies','action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('Re-Registration'), array('controller' => 'companies','action' => 'index')); ?></li>
</ul>
</li>
<?php } else if($this->Session->read('Auth.User.agen_level') == 2) { ?>
<li><?php echo $this->Html->link(__('New Customer'), array('controller' => 'companies','action' => 'add_customer')); ?></li>
<?php } ?>
</ul>
<?php } else { ?>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Agen<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link(__('New Agen'), array('controller' => 'users','action' => 'add_agen')); ?></li>
<li><?php echo $this->Html->link(__('List Agen'), array('controller' => 'users','action' => 'list_user')); ?></li>
</ul>
</li>
</ul>
<?php } ?>
<?php if($this->Session->read('Auth.User.agen_level') == 1) { ?>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Information<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Link</a></li>
<li><a href="#">FAQ</a></li>
<li><a href="#">Business Process</a></li>
</ul>
</li>
</ul>
<?php } else { ?>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Category<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link(__('New Category'), array('controller' => 'categories','action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('List Category'), array('controller' => 'categories','action' => 'index')); ?></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Service<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link(__('New Service'), array('controller' => 'services','action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('List Service'), array('controller' => 'services','action' => 'index')); ?></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Areas<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link(__('New Areas'), array('controller' => 'areas','action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('List Areas'), array('controller' => 'areas','action' => 'index')); ?></li>
</ul>
</li>
</ul>
<?php } ?>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">CS Profile<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><?php echo $this->Html->link(__('Logout'), array('controller'=>'users','action' => 'logout')); ?></li>
<li><a href="#">Change Password</a></li>
<li><a href="#">Setting Profile</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div id="content" class="container marketing bg-transparent">
<?php echo $this->Session->flash(); ?>
<?php echo $this->fetch('content'); ?>
</div>
<?php } ?>
<div id="footer">
<?php //echo $this->Html->link(
// $this->Html->image('cake.power.gif', array('alt' => $cakeDescription, 'border' => '0')),
// 'http://www.cakephp.org/',
// array('target' => '_blank', 'escape' => false)
//);
?>
</div>
<?php //echo $this->element('sql_dump'); ?>
</body>
<script>
$(document).ready(function(){
var s1 = [8, 9, 6, 4, 3];
var s2 = [7, 5, 3, 2, 1];
var ticks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
plot2 = $.jqplot('chart2', [s1, s2], {
seriesColors:['#fa6800', '#a20025'],
seriesDefaults: {
renderer:$.jqplot.BarRenderer,
pointLabels: { show: true }
},
legend: {
show:true,
labels:['Complaints', 'Solved'],
show: true,
location: 'e',
placement: 'inside'
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
}
});
$('#chart2').bind('jqplotDataHighlight',
function (ev, seriesIndex, pointIndex, data) {
$('#info2').html('series: '+seriesIndex+', point: '+pointIndex+', data: '+data);
}
);
$('#chart2').bind('jqplotDataUnhighlight',
function (ev) {
$('#info2').html('Nothing');
}
);
});
</script>
</html>
<file_sep><div class="issues index">
<h2><?php echo __('Issues'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('company_id'); ?></th>
<th><?php echo $this->Paginator->sort('agen_id'); ?></th>
<th><?php echo $this->Paginator->sort('reporter_id'); ?></th>
<th><?php echo $this->Paginator->sort('category_id'); ?></th>
<th><?php echo $this->Paginator->sort('no_resi'); ?></th>
<th><?php echo $this->Paginator->sort('note'); ?></th>
<th><?php echo $this->Paginator->sort('link_gambar'); ?></th>
<th><?php echo $this->Paginator->sort('tanggal'); ?></th>
<th><?php echo $this->Paginator->sort('status'); ?></th>
<th><?php echo $this->Paginator->sort('flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($issues as $issue): ?>
<tr>
<td><?php echo h($issue['Issue']['id']); ?> </td>
<td>
<?php echo $this->Html->link($issue['Company']['id'], array('controller' => 'companies', 'action' => 'view', $issue['Company']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($issue['Agen']['id'], array('controller' => 'agens', 'action' => 'view', $issue['Agen']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($issue['Reporter']['id'], array('controller' => 'reporters', 'action' => 'view', $issue['Reporter']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($issue['Category']['id'], array('controller' => 'categories', 'action' => 'view', $issue['Category']['id'])); ?>
</td>
<td><?php echo h($issue['Issue']['no_resi']); ?> </td>
<td><?php echo h($issue['Issue']['note']); ?> </td>
<td><?php echo h($issue['Issue']['link_gambar']); ?> </td>
<td><?php echo h($issue['Issue']['tanggal']); ?> </td>
<td><?php echo h($issue['Issue']['status']); ?> </td>
<td><?php echo h($issue['Issue']['flag']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $issue['Issue']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $issue['Issue']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $issue['Issue']['id']), null, __('Are you sure you want to delete # %s?', $issue['Issue']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<?php if($this->Session->read('Auth.User.agen_level') == 1) { ?>
<li><?php echo $this->Html->link(__('Home'), array('controller'=>'users','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('New Issue'), array('action' => 'add')); ?></li>
<?php } else if($this->Session->read('Auth.User.agen_level') == 2) { ?>
<li><?php echo $this->Html->link(__('Home'), array('controller'=>'users','action' => 'index_backroom')); ?></li>
<?php } ?>
</ul>
</div>
<file_sep><div class="historySubmissions view">
<h2><?php echo __('History Submission'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($historySubmission['HistorySubmission']['id']); ?>
</dd>
<dt><?php echo __('Submission'); ?></dt>
<dd>
<?php echo $this->Html->link($historySubmission['Submission']['id'], array('controller' => 'submissions', 'action' => 'view', $historySubmission['Submission']['id'])); ?>
</dd>
<dt><?php echo __('Agen'); ?></dt>
<dd>
<?php echo $this->Html->link($historySubmission['Agen']['id'], array('controller' => 'agens', 'action' => 'view', $historySubmission['Agen']['id'])); ?>
</dd>
<dt><?php echo __('Tanggal'); ?></dt>
<dd>
<?php echo h($historySubmission['HistorySubmission']['tanggal']); ?>
</dd>
<dt><?php echo __('Status'); ?></dt>
<dd>
<?php echo h($historySubmission['HistorySubmission']['status']); ?>
</dd>
<dt><?php echo __('Comment'); ?></dt>
<dd>
<?php echo h($historySubmission['HistorySubmission']['comment']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit History Submission'), array('action' => 'edit', $historySubmission['HistorySubmission']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete History Submission'), array('action' => 'delete', $historySubmission['HistorySubmission']['id']), null, __('Are you sure you want to delete # %s?', $historySubmission['HistorySubmission']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List History Submissions'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New History Submission'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Submissions'), array('controller' => 'submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Agens'), array('controller' => 'agens', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Agen'), array('controller' => 'agens', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><?php
App::uses('AppController', 'Controller');
App::import('Controller', 'LogUsers');
/**
* Users Controller
*
* @property User $User
* @property PaginatorComponent $Paginator
*/
class UsersController extends AppController {
/**
* Components
*
* @var array
*/
public $components = array('Paginator');
public function beforeFilter() {
parent::beforeFilter();
// Allow users to register and logout.
$this -> Auth -> allow( 'logout','add','edit');
}
/**
* index method
*
* @return void
*/
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->Paginator->paginate());
}
public function index_backroom() {
$this->User->recursive = 0;
$this->set('users', $this->Paginator->paginate());
}
public function index_admin() {
$this->User->recursive = 0;
$this->set('users', $this->Paginator->paginate());
}
public function list_user(){
$this->User->recursive = 0;
$this->set('users', $this->Paginator->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function add_agen(){
if ($this->request->is('post')) {
$this->User->create();
// var_dump($this->request->data);
// exit;
if ($this->User->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index_admin'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function add_customer(){
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
$this->User->recursive = 0;
//$companies = $this->User->Company->find('all',array('conditions'=>array('user_id is NULL')));
$this->set('companies');
// ambil data dari company..
// cek dari company tersebut, ada ga yang user_id nya NULL dan jadikan sebagai list dari calon user dari customer
// lempar variable nya view nya.
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
echo "<pre>";
var_dump($this->request->data);
echo "</pre>";
exit;
if ($this->User->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index_admin'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->User->delete()) {
$this->Session->setFlash(__('The user has been deleted.'));
} else {
$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
public function login() {
$this->set('jsIncludes', $this->js);
if ($this -> request -> is('post')) {
if ($this -> Auth -> login()) {
// cek dulu dia ada di agen atau di costumer dengan id nya
$agens = $this->User->Agen->findByUserId($this->Session->read('Auth.User.id'));
$costumers = $this->User->Company->findByUserId($this->Session->read('Auth.User.id'));
$log = new LogUsersController();
$data = array(
'LogUser' => array(
'tanggal_log' => date('Y-m-d H:i:s'),
'user_id' => $this->Session->read('Auth.User.id'),
'action' => "Login"
)
);
//var_dump($data);
$log->createNew($data);
// jika dia agen berarti set logagen dan redirect nya ke halaman agen
if($agens){
$this->Session->write('Auth.User.agen_id', $agens['Agen']['id']);
$this->Session->write('Auth.User.agen_level', $agens['Agen']['level']);
// jika agen CSR
if($agens['Agen']['level'] == '1'){
return $this->redirect(array("controller"=>"users", "action"=>"index"));
}
// jika agen backroom
else if($agens['Agen']['level'] == '2'){
return $this->redirect(array("controller"=>"users", "action"=>"index_backroom"));
}
// jika agen manage user
else if($agens['Agen']['level'] == '3'){
return $this->redirect(array("controller"=>"users", "action"=>"index_admin"));
}
}else if($costumers){
return $this -> redirect(array("controller"=>"customers", "action"=>"index"));
}
}else{
$this -> Session -> setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
// set dulu log Agen nya
$log = new LogUsersController();
$data = array(
'LogUser' => array(
'tanggal_log' => date('Y-m-d H:i:s'),
'user_id' => $this->Session->read('Auth.User.id'),
'action' => "Logout"
)
);
var_dump($data);
$log->createNew($data);
return $this -> redirect($this -> Auth -> logout());
}
}
<file_sep><div class="companyAreas view">
<h2><?php echo __('Company Area'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($companyArea['CompanyArea']['id']); ?>
</dd>
<dt><?php echo __('Company'); ?></dt>
<dd>
<?php echo $this->Html->link($companyArea['Company']['id'], array('controller' => 'companies', 'action' => 'view', $companyArea['Company']['id'])); ?>
</dd>
<dt><?php echo __('Area'); ?></dt>
<dd>
<?php echo $this->Html->link($companyArea['Area']['id'], array('controller' => 'areas', 'action' => 'view', $companyArea['Area']['id'])); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Company Area'), array('action' => 'edit', $companyArea['CompanyArea']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Company Area'), array('action' => 'delete', $companyArea['CompanyArea']['id']), null, __('Are you sure you want to delete # %s?', $companyArea['CompanyArea']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Company Areas'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Area'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Companies'), array('controller' => 'companies', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company'), array('controller' => 'companies', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Areas'), array('controller' => 'areas', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Area'), array('controller' => 'areas', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep> <div class="issues form">
<?php echo $this->Form->create('Issue'); ?>
<fieldset>
<legend><?php echo __('Complain Handling'); ?></legend>
<?php
echo $this->Form->input('company_id', array('empty' => 'Pilih Perusahaan'));
echo $this->Form->hidden('agen_id',array('value'=>$this->Session->read('Auth.User.agen_id')));
echo $this->Form->input('reporter_id', array('empty' => 'Pilih Pelapor'));
echo $this->Form->input('category_id', array('empty' => 'Pilih Category'));
echo $this->Form->input('no_resi');
echo $this->Form->input('note');
echo $this->Form->file('link_gambar', array('required'=>FALSE));
//echo $this->Form->hidden('tanggal',array('value'=>date("Y-m-d H:i:s")));
echo $this->Form->input('status', array('options' => array('open'=>'Open', 'closed'=>'Close')));
//echo $this->Form->input('flag');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Home'), array('controller'=>'users','action' => 'index')); ?></li>
</ul>
</div>
<file_sep><div class="submissions view">
<h2><?php echo __('Submission'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($submission['Submission']['id']); ?>
</dd>
<dt><?php echo __('Company Id'); ?></dt>
<dd>
<?php echo h($submission['Submission']['company_id']); ?>
</dd>
<dt><?php echo __('Agen Id'); ?></dt>
<dd>
<?php echo h($submission['Submission']['agen_id']); ?>
</dd>
<dt><?php echo __('Reporter Id'); ?></dt>
<dd>
<?php echo h($submission['Submission']['reporter_id']); ?>
</dd>
<dt><?php echo __('Service Id'); ?></dt>
<dd>
<?php echo h($submission['Submission']['service_id']); ?>
</dd>
<dt><?php echo __('Tanggal'); ?></dt>
<dd>
<?php echo h($submission['Submission']['tanggal']); ?>
</dd>
<dt><?php echo __('Note'); ?></dt>
<dd>
<?php echo h($submission['Submission']['note']); ?>
</dd>
<dt><?php echo __('Status'); ?></dt>
<dd>
<?php echo h($submission['Submission']['status']); ?>
</dd>
<dt><?php echo __('Flag'); ?></dt>
<dd>
<?php echo h($submission['Submission']['flag']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Submission'), array('action' => 'edit', $submission['Submission']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Submission'), array('action' => 'delete', $submission['Submission']['id']), null, __('Are you sure you want to delete # %s?', $submission['Submission']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Submissions'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Submission'), array('action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="services view">
<h2><?php echo __('Service'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($service['Service']['id']); ?>
</dd>
<dt><?php echo __('Nama Layanan'); ?></dt>
<dd>
<?php echo h($service['Service']['nama_layanan']); ?>
</dd>
<dt><?php echo __('Deskripsi Layanan'); ?></dt>
<dd>
<?php echo h($service['Service']['deskripsi_layanan']); ?>
</dd>
<dt><?php echo __('Parent Service'); ?></dt>
<dd>
<?php echo $this->Html->link($service['ParentService']['id'], array('controller' => 'services', 'action' => 'view', $service['ParentService']['id'])); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Service'), array('action' => 'edit', $service['Service']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Service'), array('action' => 'delete', $service['Service']['id']), null, __('Are you sure you want to delete # %s?', $service['Service']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Services'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Service'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Services'), array('controller' => 'services', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Parent Service'), array('controller' => 'services', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Submissions'), array('controller' => 'submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
<div class="related">
<h3><?php echo __('Related Services'); ?></h3>
<?php if (!empty($service['ChildService'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Nama Layanan'); ?></th>
<th><?php echo __('Deskripsi Layanan'); ?></th>
<th><?php echo __('Parent Id'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($service['ChildService'] as $childService): ?>
<tr>
<td><?php echo $childService['id']; ?></td>
<td><?php echo $childService['nama_layanan']; ?></td>
<td><?php echo $childService['deskripsi_layanan']; ?></td>
<td><?php echo $childService['parent_id']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'services', 'action' => 'view', $childService['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'services', 'action' => 'edit', $childService['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'services', 'action' => 'delete', $childService['id']), null, __('Are you sure you want to delete # %s?', $childService['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Child Service'), array('controller' => 'services', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Submissions'); ?></h3>
<?php if (!empty($service['Submission'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Reporter Id'); ?></th>
<th><?php echo __('Service Id'); ?></th>
<th><?php echo __('Note'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($service['Submission'] as $submission): ?>
<tr>
<td><?php echo $submission['id']; ?></td>
<td><?php echo $submission['company_id']; ?></td>
<td><?php echo $submission['agen_id']; ?></td>
<td><?php echo $submission['reporter_id']; ?></td>
<td><?php echo $submission['service_id']; ?></td>
<td><?php echo $submission['note']; ?></td>
<td><?php echo $submission['status']; ?></td>
<td><?php echo $submission['flag']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'submissions', 'action' => 'view', $submission['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'submissions', 'action' => 'edit', $submission['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'submissions', 'action' => 'delete', $submission['id']), null, __('Are you sure you want to delete # %s?', $submission['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<file_sep><div class="agens index">
<h2><?php echo __('Agens'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('user_id'); ?></th>
<th><?php echo $this->Paginator->sort('nama'); ?></th>
<th><?php echo $this->Paginator->sort('alamat'); ?></th>
<th><?php echo $this->Paginator->sort('tempat_lahir'); ?></th>
<th><?php echo $this->Paginator->sort('tanggal_lahir'); ?></th>
<th><?php echo $this->Paginator->sort('no_telepon'); ?></th>
<th><?php echo $this->Paginator->sort('email'); ?></th>
<th><?php echo $this->Paginator->sort('level'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($agens as $agen): ?>
<tr>
<td><?php echo h($agen['Agen']['id']); ?> </td>
<td>
<?php echo $this->Html->link($agen['User']['username'], array('controller' => 'users', 'action' => 'view', $agen['User']['id'])); ?>
</td>
<td><?php echo h($agen['Agen']['nama']); ?> </td>
<td><?php echo h($agen['Agen']['alamat']); ?> </td>
<td><?php echo h($agen['Agen']['tempat_lahir']); ?> </td>
<td><?php echo h($agen['Agen']['tanggal_lahir']); ?> </td>
<td><?php echo h($agen['Agen']['no_telepon']); ?> </td>
<td><?php echo h($agen['Agen']['email']); ?> </td>
<td><?php echo h($agen['Agen']['level']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $agen['Agen']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $agen['Agen']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $agen['Agen']['id']), null, __('Are you sure you want to delete # %s?', $agen['Agen']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('New Agen'), array('action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('List Users'), array('controller' => 'users', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New User'), array('controller' => 'users', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Employees'), array('controller' => 'employees', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Employee'), array('controller' => 'employees', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List History Issues'), array('controller' => 'history_issues', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New History Issue'), array('controller' => 'history_issues', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List History Submissions'), array('controller' => 'history_submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New History Submission'), array('controller' => 'history_submissions', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Issues'), array('controller' => 'issues', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Submissions'), array('controller' => 'submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="agens view">
<h2><?php echo __('Agen'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($agen['Agen']['id']); ?>
</dd>
<dt><?php echo __('User'); ?></dt>
<dd>
<?php echo $this->Html->link($agen['User']['username'], array('controller' => 'users', 'action' => 'view', $agen['User']['id'])); ?>
</dd>
<dt><?php echo __('Nama'); ?></dt>
<dd>
<?php echo h($agen['Agen']['nama']); ?>
</dd>
<dt><?php echo __('Alamat'); ?></dt>
<dd>
<?php echo h($agen['Agen']['alamat']); ?>
</dd>
<dt><?php echo __('Tempat Lahir'); ?></dt>
<dd>
<?php echo h($agen['Agen']['tempat_lahir']); ?>
</dd>
<dt><?php echo __('Tanggal Lahir'); ?></dt>
<dd>
<?php echo h($agen['Agen']['tanggal_lahir']); ?>
</dd>
<dt><?php echo __('No Telepon'); ?></dt>
<dd>
<?php echo h($agen['Agen']['no_telepon']); ?>
</dd>
<dt><?php echo __('Email'); ?></dt>
<dd>
<?php echo h($agen['Agen']['email']); ?>
</dd>
<dt><?php echo __('Level'); ?></dt>
<dd>
<?php echo h($agen['Agen']['level']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Agen'), array('action' => 'edit', $agen['Agen']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Agen'), array('action' => 'delete', $agen['Agen']['id']), null, __('Are you sure you want to delete # %s?', $agen['Agen']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Agens'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Agen'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Users'), array('controller' => 'users', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New User'), array('controller' => 'users', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Employees'), array('controller' => 'employees', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Employee'), array('controller' => 'employees', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List History Issues'), array('controller' => 'history_issues', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New History Issue'), array('controller' => 'history_issues', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List History Submissions'), array('controller' => 'history_submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New History Submission'), array('controller' => 'history_submissions', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Issues'), array('controller' => 'issues', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Submissions'), array('controller' => 'submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
<div class="related">
<h3><?php echo __('Related History Issues'); ?></h3>
<?php if (!empty($agen['HistoryIssue'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Issue Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Tanggal'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Comment'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($agen['HistoryIssue'] as $historyIssue): ?>
<tr>
<td><?php echo $historyIssue['id']; ?></td>
<td><?php echo $historyIssue['issue_id']; ?></td>
<td><?php echo $historyIssue['agen_id']; ?></td>
<td><?php echo $historyIssue['tanggal']; ?></td>
<td><?php echo $historyIssue['status']; ?></td>
<td><?php echo $historyIssue['comment']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'history_issues', 'action' => 'view', $historyIssue['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'history_issues', 'action' => 'edit', $historyIssue['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'history_issues', 'action' => 'delete', $historyIssue['id']), null, __('Are you sure you want to delete # %s?', $historyIssue['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New History Issue'), array('controller' => 'history_issues', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related History Submissions'); ?></h3>
<?php if (!empty($agen['HistorySubmission'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Submission Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Tanggal'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Comment'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($agen['HistorySubmission'] as $historySubmission): ?>
<tr>
<td><?php echo $historySubmission['id']; ?></td>
<td><?php echo $historySubmission['submission_id']; ?></td>
<td><?php echo $historySubmission['agen_id']; ?></td>
<td><?php echo $historySubmission['tanggal']; ?></td>
<td><?php echo $historySubmission['status']; ?></td>
<td><?php echo $historySubmission['comment']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'history_submissions', 'action' => 'view', $historySubmission['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'history_submissions', 'action' => 'edit', $historySubmission['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'history_submissions', 'action' => 'delete', $historySubmission['id']), null, __('Are you sure you want to delete # %s?', $historySubmission['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New History Submission'), array('controller' => 'history_submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Issues'); ?></h3>
<?php if (!empty($agen['Issue'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Reporter Id'); ?></th>
<th><?php echo __('Category Id'); ?></th>
<th><?php echo __('No Resi'); ?></th>
<th><?php echo __('Note'); ?></th>
<th><?php echo __('Link Gambar'); ?></th>
<th><?php echo __('Tanggal'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($agen['Issue'] as $issue): ?>
<tr>
<td><?php echo $issue['id']; ?></td>
<td><?php echo $issue['company_id']; ?></td>
<td><?php echo $issue['agen_id']; ?></td>
<td><?php echo $issue['reporter_id']; ?></td>
<td><?php echo $issue['category_id']; ?></td>
<td><?php echo $issue['no_resi']; ?></td>
<td><?php echo $issue['note']; ?></td>
<td><?php echo $issue['link_gambar']; ?></td>
<td><?php echo $issue['tanggal']; ?></td>
<td><?php echo $issue['status']; ?></td>
<td><?php echo $issue['flag']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'issues', 'action' => 'view', $issue['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'issues', 'action' => 'edit', $issue['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'issues', 'action' => 'delete', $issue['id']), null, __('Are you sure you want to delete # %s?', $issue['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Submissions'); ?></h3>
<?php if (!empty($agen['Submission'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Reporter Id'); ?></th>
<th><?php echo __('Service Id'); ?></th>
<th><?php echo __('Tanggal'); ?></th>
<th><?php echo __('Note'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($agen['Submission'] as $submission): ?>
<tr>
<td><?php echo $submission['id']; ?></td>
<td><?php echo $submission['company_id']; ?></td>
<td><?php echo $submission['agen_id']; ?></td>
<td><?php echo $submission['reporter_id']; ?></td>
<td><?php echo $submission['service_id']; ?></td>
<td><?php echo $submission['tanggal']; ?></td>
<td><?php echo $submission['note']; ?></td>
<td><?php echo $submission['status']; ?></td>
<td><?php echo $submission['flag']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'submissions', 'action' => 'view', $submission['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'submissions', 'action' => 'edit', $submission['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'submissions', 'action' => 'delete', $submission['id']), null, __('Are you sure you want to delete # %s?', $submission['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<file_sep><div class="companies form">
<?php echo $this->Form->create('Company'); ?>
<fieldset>
<legend>Pelayanan Yang diinginkan</legend>
<?php
echo $this->form->input('CompanyService.nama_layanan', array('multiple' => 'checkbox', 'options' => $services, 'selected' => $selectedService));
?>
</fieldset>
<fieldset>
<legend><?php echo __('Kelengkapan Data Perusahaan'); ?></legend>
<?php
echo $this->Form->input('nama_perusahaan');
echo $this->Form->input('npwp');
echo $this->Form->input('alamat');
echo $this->Form->input('email');
echo $this->Form->input('tingkat_organisasi');
echo $this->Form->input('alamat_penagihan');
echo $this->Form->input('masa_berlaku');
echo $this->Form->input('no_telepon');
echo $this->Form->input('group_usaha');
?>
</fieldset>
<fieldset>
<legend>Bidang Usaha</legend>
<?php
echo $this->form->input('CompanyArea.name', array('multiple' => 'checkbox', 'options' => $areas, 'selected' => $selectedArea));
?>
</fieldset>
<fieldset>
<legend><?php echo __('Penanggung Jawab Perusahaan') ?></legend>
<?php
echo $this->Form->input('CompanyResponsible.0.nama_pimpinan');
echo $this->Form->input('CompanyResponsible.0.jabatan');
echo $this->Form->input('CompanyResponsible.0.tempat_lahir');
echo $this->Form->input('CompanyResponsible.0.tanggal_lahir');
echo $this->Form->input('CompanyResponsible.0.alamat');
echo $this->Form->input('CompanyResponsible.0.no_telepon');
echo $this->Form->input('CompanyResponsible.0.email');
echo $this->Form->input('CompanyResponsible.0.tanda_pengenal',array('options'=>array(0=>'Please select','KTP'=>'KTP','SIM'=>'SIM','PASSPORT'=>'PASSPORT')));
echo $this->Form->input('CompanyResponsible.0.nomor_tanda_pengenal');
echo $this->Form->radio('CompanyResponsible.0.jenis_kelamin',array('M' => 'Male', 'F' => 'Female'),array('legend' => 'Jenis Kelamin'));
echo $this->Form->radio('CompanyResponsible.0.agama',array('Islam'=>'Islam','Kristen'=>'Kristen','Katolik'=>'Katolik','Buddha'=>'Buddha','Hindu'=>'Hindu'));
?>
</fieldset>
<fieldset>
<legend><?php echo __('Pengurus Perusahaan') ?></legend>
<table>
<thead>
<th>Nama</th>
<th>Jabatan</th>
<th>Alamat</th>
<th>Alamat Perusahaan</th>
</thead>
<?php
for($x = 0 ; $x<4 ;$x++) {
?>
<tr>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.nama',array('label'=>false)); ?></td>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.jabatan',array('label'=>false)); ?></td>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.alamat',array('label'=>false)); ?></td>
<td><?php echo $this->Form->input('CompanyStaff.'.$x.'.alamat_perusahaan',array('label'=>false)); ?></td>
</tr>
<?php } ?>
</table>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Home'), array('controller'=>'users','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Companies'), array('action' => 'index')); ?></li>
</ul>
</div>
<file_sep>/**
* @author user
*/
$(document).ready(function(){
});
function autoComplete(key){
$.get(base+'/reporters/reporterLookUp/'+key+'.json',function(data){
$( "#reporter" ).autocomplete({
source: data
});
});
}
<file_sep><?php
App::uses('AppController', 'Controller');
/**
* CompanyStaffs Controller
*
* @property CompanyStaff $CompanyStaff
* @property PaginatorComponent $Paginator
*/
class CompanyStaffsController extends AppController {
/**
* Components
*
* @var array
*/
public $components = array('Paginator');
/**
* index method
*
* @return void
*/
public function index() {
$this->CompanyStaff->recursive = 0;
$this->set('companyStaffs', $this->Paginator->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->CompanyStaff->exists($id)) {
throw new NotFoundException(__('Invalid company staff'));
}
$options = array('conditions' => array('CompanyStaff.' . $this->CompanyStaff->primaryKey => $id));
$this->set('companyStaff', $this->CompanyStaff->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->CompanyStaff->create();
if ($this->CompanyStaff->save($this->request->data)) {
$this->Session->setFlash(__('The company staff has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The company staff could not be saved. Please, try again.'));
}
}
$companies = $this->CompanyStaff->Company->find('list');
$this->set(compact('companies'));
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->CompanyStaff->exists($id)) {
throw new NotFoundException(__('Invalid company staff'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->CompanyStaff->save($this->request->data)) {
$this->Session->setFlash(__('The company staff has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The company staff could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('CompanyStaff.' . $this->CompanyStaff->primaryKey => $id));
$this->request->data = $this->CompanyStaff->find('first', $options);
}
$companies = $this->CompanyStaff->Company->find('list');
$this->set(compact('companies'));
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->CompanyStaff->id = $id;
if (!$this->CompanyStaff->exists()) {
throw new NotFoundException(__('Invalid company staff'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->CompanyStaff->delete()) {
$this->Session->setFlash(__('The company staff has been deleted.'));
} else {
$this->Session->setFlash(__('The company staff could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
<file_sep><div class="issues form">
<?php echo $this->Form->create('Issue'); ?>
<fieldset>
<legend><?php echo __('Edit Issue'); ?></legend>
<?php
echo 'Nama Perusahan : '.$this->request->data['Company']['nama_perusahaan']."<br />";
echo 'CSR : '.$this->request->data['Agen']['nama']."<br />";
echo 'Pelapor : '.$this->request->data['Reporter']['nama']."<br />";
echo 'Kategori : '.$this->request->data['Category']['nama']."<br />";
echo 'Nomor Resi : '.$this->request->data['Issue']['no_resi']."<br />";
echo 'Catatan : '.$this->request->data['Issue']['note']."<br />";
echo 'Dokumen : '.$this->request->data['Issue']['link_gambar']."<br />";
echo 'Status : '.$this->request->data['Issue']['status']."<br />";
echo 'Tanggal Open : '.$this->request->data['Issue']['tanggal']."<br /><br />";
echo $this->Form->input('id');
// echo $this->Form->input('company_id');
// echo $this->Form->input('agen_id');
// echo $this->Form->input('reporter_id');
// echo $this->Form->input('category_id');
// echo $this->Form->input('no_resi');
// echo $this->Form->input('note');
// echo $this->Form->input('link_gambar');
// echo $this->Form->input('tanggal');
$i = 0;
foreach($this->request->data['HistoryIssue'] as $hist_issue){
if($i >= 0){
echo "Agen yang bertanggung jawab : ". $hist_issue['Agen']['nama']."<br />";
echo "Tanggal : ". $hist_issue['tanggal']."<br />";
echo "status : ". $hist_issue['status']."<br />";
echo "Catatan : ". $hist_issue['comment']."<br /><br />";
}
$i++;
}
if($this->Session->read('Auth.User.agen_level') == 1){
echo $this->Form->input('status',array('options' => array('closed'=>'Close', 'customer_pending'=>'Customer Pending','open'=>'Open Again')));
}else if($this->Session->read('Auth.User.agen_level') == 2){
echo $this->Form->input('status',array('options' => array('process'=>'Process', 'pending'=>'Pending' , 'done'=>'Done', 'ilcs_pending'=>'Ekskalasi ILCS')));
}
echo $this->Form->input('HistoryIssue.0.comment');
// echo $this->Form->input('flag');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Back'), array('action' => 'index')); ?></li>
</ul>
</div>
<file_sep><?php
/**
* SubmissionFixture
*
*/
class SubmissionFixture extends CakeTestFixture {
/**
* Fields
*
* @var array
*/
public $fields = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
'company_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'index'),
'agen_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'index'),
'reporter_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'index'),
'service_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'index'),
'tanggal' => array('type' => 'datetime', 'null' => false, 'default' => null),
'note' => array('type' => 'string', 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
'flag' => array('type' => 'boolean', 'null' => false, 'default' => null),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'fk_company_id' => array('column' => 'company_id', 'unique' => 0),
'fk_agen_id' => array('column' => 'agen_id', 'unique' => 0),
'fk_reporter_id' => array('column' => 'reporter_id', 'unique' => 0),
'fk_service_id' => array('column' => 'service_id', 'unique' => 0)
),
'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'InnoDB')
);
/**
* Records
*
* @var array
*/
public $records = array(
array(
'id' => 1,
'company_id' => 1,
'agen_id' => 1,
'reporter_id' => 1,
'service_id' => 1,
'tanggal' => '2014-01-27 14:04:32',
'note' => 'Lorem ipsum dolor sit amet',
'flag' => 1
),
);
}
<file_sep><div class="submissions form">
<?php echo $this->Form->create('Submission'); ?>
<fieldset>
<legend><?php echo __('Edit Submission'); ?></legend>
<?php
echo 'Nama Perusahan : '.$this->request->data['Company']['nama_perusahaan']."<br />";
echo 'CSR : '.$this->request->data['Agen']['nama']."<br />";
echo 'Pelapor : '.$this->request->data['Reporter']['nama']."<br />";
echo 'Service : '.$this->request->data['Service']['nama_layanan']."<br />";
echo 'Catatan : '.$this->request->data['Submission']['note']."<br />";
foreach($this->request->data['Dokumen'] as $dok){
echo "Dokumen : ".$dok['link_gambar']."<br />";
echo "Dokumen : ".$dok['deskrpisi']."<br />";
}
echo 'Status : '.$this->request->data['Submission']['status']."<br />";
echo 'Tanggal Open : '.$this->request->data['Submission']['tanggal']."<br /><br />";
echo $this->Form->input('id');
// echo $this->Form->input('company_id');
// echo $this->Form->input('agen_id');
// echo $this->Form->input('reporter_id');
// echo $this->Form->input('service_id');
// echo $this->Form->input('tanggal');
// echo $this->Form->input('note');
// echo $this->Form->input('status');
// echo $this->Form->input('flag');
$i = 0;
foreach($this->request->data['HistorySubmission'] as $his_sub){
if($i >= 0){
echo "Agen yang bertanggung jawab : ". $his_sub['Agen']['nama']."<br />";
echo "Tanggal : ". $his_sub['tanggal']."<br />";
echo "status : ". $his_sub['status']."<br />";
echo "Catatan : ". $his_sub['comment']."<br /><br />";
}
$i++;
}
if($this->Session->read('Auth.User.agen_level') == 1){
echo $this->Form->input('status',array('options' => array('closed'=>'Close', 'customer_pending'=>'Customer Pending','open'=>'Open Again')));
}else if($this->Session->read('Auth.User.agen_level') == 2){
echo $this->Form->input('status',array('options' => array('process'=>'Process', 'pending'=>'Pending' , 'done'=>'Done', 'ilcs_pending'=>'Ekskalasi ILCS')));
}
echo $this->Form->input('HistorySubmission.0.comment');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Back'), array('action' => 'index')); ?></li>
</ul>
</div>
<file_sep><div class="historyIssues view">
<h2><?php echo __('History Issue'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($historyIssue['HistoryIssue']['id']); ?>
</dd>
<dt><?php echo __('Issue'); ?></dt>
<dd>
<?php echo $this->Html->link($historyIssue['Issue']['id'], array('controller' => 'issues', 'action' => 'view', $historyIssue['Issue']['id'])); ?>
</dd>
<dt><?php echo __('Agen'); ?></dt>
<dd>
<?php echo $this->Html->link($historyIssue['Agen']['id'], array('controller' => 'agens', 'action' => 'view', $historyIssue['Agen']['id'])); ?>
</dd>
<dt><?php echo __('Tanggal'); ?></dt>
<dd>
<?php echo h($historyIssue['HistoryIssue']['tanggal']); ?>
</dd>
<dt><?php echo __('Status'); ?></dt>
<dd>
<?php echo h($historyIssue['HistoryIssue']['status']); ?>
</dd>
<dt><?php echo __('Comment'); ?></dt>
<dd>
<?php echo h($historyIssue['HistoryIssue']['comment']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit History Issue'), array('action' => 'edit', $historyIssue['HistoryIssue']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete History Issue'), array('action' => 'delete', $historyIssue['HistoryIssue']['id']), null, __('Are you sure you want to delete # %s?', $historyIssue['HistoryIssue']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List History Issues'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New History Issue'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Issues'), array('controller' => 'issues', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Agens'), array('controller' => 'agens', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Agen'), array('controller' => 'agens', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><?php
App::uses('AppController', 'Controller');
/**
* HistorySubmissions Controller
*
* @property HistorySubmission $HistorySubmission
* @property PaginatorComponent $Paginator
*/
class HistorySubmissionsController extends AppController {
/**
* Components
*
* @var array
*/
public $components = array('Paginator');
/**
* index method
*
* @return void
*/
public function index() {
$this->HistorySubmission->recursive = 0;
$this->set('historySubmissions', $this->Paginator->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->HistorySubmission->exists($id)) {
throw new NotFoundException(__('Invalid history submission'));
}
$options = array('conditions' => array('HistorySubmission.' . $this->HistorySubmission->primaryKey => $id));
$this->set('historySubmission', $this->HistorySubmission->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->HistorySubmission->create();
if ($this->HistorySubmission->save($this->request->data)) {
$this->Session->setFlash(__('The history submission has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The history submission could not be saved. Please, try again.'));
}
}
$submissions = $this->HistorySubmission->Submission->find('list');
$agens = $this->HistorySubmission->Agen->find('list');
$this->set(compact('submissions', 'agens'));
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->HistorySubmission->exists($id)) {
throw new NotFoundException(__('Invalid history submission'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->HistorySubmission->save($this->request->data)) {
$this->Session->setFlash(__('The history submission has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The history submission could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('HistorySubmission.' . $this->HistorySubmission->primaryKey => $id));
$this->request->data = $this->HistorySubmission->find('first', $options);
}
$submissions = $this->HistorySubmission->Submission->find('list');
$agens = $this->HistorySubmission->Agen->find('list');
$this->set(compact('submissions', 'agens'));
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->HistorySubmission->id = $id;
if (!$this->HistorySubmission->exists()) {
throw new NotFoundException(__('Invalid history submission'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->HistorySubmission->delete()) {
$this->Session->setFlash(__('The history submission has been deleted.'));
} else {
$this->Session->setFlash(__('The history submission could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
<file_sep><?php
/**
* Common web hooks for CakePHP app deployments.
*/
class HooksController extends AppController {
var $uses = array();
/**
* Action to call when a deployment is completed.
*
* Provided key is checked using HooksController::__check_key
*/
function completed_deployment($key = NULL) {
$this->__check_key($key);
// ceeram's ClearCache plugin is available here:
// https://github.com/ceeram/clear_cache
App::import('Libs', 'ClearCache.ClearCache');
$ClearCache = new ClearCache();
// Remove the models and persistent caches, to prevent DB changes
// from causing any trouble.
$ClearCache->files('models', 'persistent');
exit;
}
/**
* Check the provided key against the hookKey set in /app/config/config.php.
*/
function __check_key($key) {
// Compare the provided key against a value stored in your app's
// configuration.
if ($key != Configure::read('Misc.hookKey')) {
exit;
}
}
}<file_sep><div class="logCustomers view">
<h2><?php echo __('Log Customer'); ?></h2>
<dl>
<dt><?php echo __('Customer'); ?></dt>
<dd>
<?php echo $this->Html->link($logCustomer['Customer']['id'], array('controller' => 'customers', 'action' => 'view', $logCustomer['Customer']['id'])); ?>
</dd>
<dt><?php echo __('Tanggal Log'); ?></dt>
<dd>
<?php echo h($logCustomer['LogCustomer']['tanggal_log']); ?>
</dd>
<dt><?php echo __('Jam Log'); ?></dt>
<dd>
<?php echo h($logCustomer['LogCustomer']['jam_log']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Log Customer'), array('action' => 'edit', $logCustomer['LogCustomer']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Log Customer'), array('action' => 'delete', $logCustomer['LogCustomer']['id']), null, __('Are you sure you want to delete # %s?', $logCustomer['LogCustomer']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Log Customers'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Log Customer'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Customers'), array('controller' => 'customers', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Customer'), array('controller' => 'customers', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="users index">
<h2><?php echo __('Backroom Service page'); ?></h2>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('New Customer'), array('controller'=>'companies','action' => 'add_customer')); ?></li>
<li><?php echo $this->Html->link(__('Complain Tracking'), array('controller' => 'issues','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('Filling Tracking'), array('controller' => 'submissions','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('Category'), array('controller' => 'categories','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('Service'), array('controller' => 'services','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('Areas'), array('controller' => 'areas','action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('Logout'), array('controller'=>'users','action' => 'logout')); ?></li>
</ul>
</div>
<file_sep><div class="issues view">
<h2><?php echo __('Issue'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($issue['Issue']['id']); ?>
</dd>
<dt><?php echo __('Company'); ?></dt>
<dd>
<?php echo $this->Html->link($issue['Company']['id'], array('controller' => 'companies', 'action' => 'view', $issue['Company']['id'])); ?>
</dd>
<dt><?php echo __('Agen'); ?></dt>
<dd>
<?php echo $this->Html->link($issue['Agen']['id'], array('controller' => 'agens', 'action' => 'view', $issue['Agen']['id'])); ?>
</dd>
<dt><?php echo __('Reporter'); ?></dt>
<dd>
<?php echo $this->Html->link($issue['Reporter']['id'], array('controller' => 'reporters', 'action' => 'view', $issue['Reporter']['id'])); ?>
</dd>
<dt><?php echo __('Category'); ?></dt>
<dd>
<?php echo $this->Html->link($issue['Category']['id'], array('controller' => 'categories', 'action' => 'view', $issue['Category']['id'])); ?>
</dd>
<dt><?php echo __('No Resi'); ?></dt>
<dd>
<?php echo h($issue['Issue']['no_resi']); ?>
</dd>
<dt><?php echo __('Note'); ?></dt>
<dd>
<?php echo h($issue['Issue']['note']); ?>
</dd>
<dt><?php echo __('Link Gambar'); ?></dt>
<dd>
<?php echo h($issue['Issue']['link_gambar']); ?>
</dd>
<dt><?php echo __('Tanggal'); ?></dt>
<dd>
<?php echo h($issue['Issue']['tanggal']); ?>
</dd>
<dt><?php echo __('Status'); ?></dt>
<dd>
<?php echo h($issue['Issue']['status']); ?>
</dd>
<dt><?php echo __('Flag'); ?></dt>
<dd>
<?php echo h($issue['Issue']['flag']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Issue'), array('action' => 'edit', $issue['Issue']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Issue'), array('action' => 'delete', $issue['Issue']['id']), null, __('Are you sure you want to delete # %s?', $issue['Issue']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Issues'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Issue'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Companies'), array('controller' => 'companies', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company'), array('controller' => 'companies', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Agens'), array('controller' => 'agens', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Agen'), array('controller' => 'agens', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Reporters'), array('controller' => 'reporters', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Reporter'), array('controller' => 'reporters', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Categories'), array('controller' => 'categories', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Category'), array('controller' => 'categories', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="companyResponsibles index">
<h2><?php echo __('Company Responsibles'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('company_id'); ?></th>
<th><?php echo $this->Paginator->sort('nama_pimpinan'); ?></th>
<th><?php echo $this->Paginator->sort('jabatan'); ?></th>
<th><?php echo $this->Paginator->sort('tempat_lahir'); ?></th>
<th><?php echo $this->Paginator->sort('tanggal_lahir'); ?></th>
<th><?php echo $this->Paginator->sort('alamat'); ?></th>
<th><?php echo $this->Paginator->sort('no_telepon'); ?></th>
<th><?php echo $this->Paginator->sort('email'); ?></th>
<th><?php echo $this->Paginator->sort('tanda_pengenal'); ?></th>
<th><?php echo $this->Paginator->sort('nomor_tanda_pengenal'); ?></th>
<th><?php echo $this->Paginator->sort('jenis_kelamin'); ?></th>
<th><?php echo $this->Paginator->sort('agama'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($companyResponsibles as $companyResponsible): ?>
<tr>
<td><?php echo h($companyResponsible['CompanyResponsible']['id']); ?> </td>
<td>
<?php echo $this->Html->link($companyResponsible['Company']['id'], array('controller' => 'companies', 'action' => 'view', $companyResponsible['Company']['id'])); ?>
</td>
<td><?php echo h($companyResponsible['CompanyResponsible']['nama_pimpinan']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['jabatan']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['tempat_lahir']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['tanggal_lahir']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['alamat']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['no_telepon']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['email']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['tanda_pengenal']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['nomor_tanda_pengenal']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['jenis_kelamin']); ?> </td>
<td><?php echo h($companyResponsible['CompanyResponsible']['agama']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $companyResponsible['CompanyResponsible']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $companyResponsible['CompanyResponsible']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $companyResponsible['CompanyResponsible']['id']), null, __('Are you sure you want to delete # %s?', $companyResponsible['CompanyResponsible']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('New Company Responsible'), array('action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('List Companies'), array('controller' => 'companies', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company'), array('controller' => 'companies', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="companies view">
<h2><?php echo __('Company'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($company['Company']['id']); ?>
</dd>
<dt><?php echo __('Nama Perusahaan'); ?></dt>
<dd>
<?php echo h($company['Company']['nama_perusahaan']); ?>
</dd>
<dt><?php echo __('Npwp'); ?></dt>
<dd>
<?php echo h($company['Company']['npwp']); ?>
</dd>
<dt><?php echo __('Alamat'); ?></dt>
<dd>
<?php echo h($company['Company']['alamat']); ?>
</dd>
<dt><?php echo __('Email'); ?></dt>
<dd>
<?php echo h($company['Company']['email']); ?>
</dd>
<dt><?php echo __('Tingkat Organisasi'); ?></dt>
<dd>
<?php echo h($company['Company']['tingkat_organisasi']); ?>
</dd>
<dt><?php echo __('Alamat Penagihan'); ?></dt>
<dd>
<?php echo h($company['Company']['alamat_penagihan']); ?>
</dd>
<dt><?php echo __('Masa Berlaku'); ?></dt>
<dd>
<?php echo h($company['Company']['masa_berlaku']); ?>
</dd>
<dt><?php echo __('No Telepon'); ?></dt>
<dd>
<?php echo h($company['Company']['no_telepon']); ?>
</dd>
<dt><?php echo __('Group Usaha'); ?></dt>
<dd>
<?php echo h($company['Company']['group_usaha']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Company'), array('action' => 'edit', $company['Company']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Company'), array('action' => 'delete', $company['Company']['id']), null, __('Are you sure you want to delete # %s?', $company['Company']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Companies'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Company Areas'), array('controller' => 'company_areas', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Area'), array('controller' => 'company_areas', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Company Responsibles'), array('controller' => 'company_responsibles', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Responsible'), array('controller' => 'company_responsibles', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Company Services'), array('controller' => 'company_services', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Service'), array('controller' => 'company_services', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Company Staffs'), array('controller' => 'company_staffs', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Staff'), array('controller' => 'company_staffs', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Customers'), array('controller' => 'customers', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Customer'), array('controller' => 'customers', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Issues'), array('controller' => 'issues', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Submissions'), array('controller' => 'submissions', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
<div class="related">
<h3><?php echo __('Related Company Areas'); ?></h3>
<?php if (!empty($company['CompanyArea'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Area Id'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($company['CompanyArea'] as $companyArea): ?>
<tr>
<td><?php echo $companyArea['id']; ?></td>
<td><?php echo $companyArea['company_id']; ?></td>
<td><?php echo $companyArea['area_id']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'company_areas', 'action' => 'view', $companyArea['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'company_areas', 'action' => 'edit', $companyArea['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'company_areas', 'action' => 'delete', $companyArea['id']), null, __('Are you sure you want to delete # %s?', $companyArea['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Company Area'), array('controller' => 'company_areas', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Company Responsibles'); ?></h3>
<?php if (!empty($company['CompanyResponsible'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Nama Pimpinan'); ?></th>
<th><?php echo __('Jabatan'); ?></th>
<th><?php echo __('Tempat Lahir'); ?></th>
<th><?php echo __('Tanggal Lahir'); ?></th>
<th><?php echo __('Alamat'); ?></th>
<th><?php echo __('No Telepon'); ?></th>
<th><?php echo __('Email'); ?></th>
<th><?php echo __('Tanda Pengenal'); ?></th>
<th><?php echo __('Nomor Tanda Pengenal'); ?></th>
<th><?php echo __('Jenis Kelamin'); ?></th>
<th><?php echo __('Agama'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($company['CompanyResponsible'] as $companyResponsible): ?>
<tr>
<td><?php echo $companyResponsible['id']; ?></td>
<td><?php echo $companyResponsible['company_id']; ?></td>
<td><?php echo $companyResponsible['nama_pimpinan']; ?></td>
<td><?php echo $companyResponsible['jabatan']; ?></td>
<td><?php echo $companyResponsible['tempat_lahir']; ?></td>
<td><?php echo $companyResponsible['tanggal_lahir']; ?></td>
<td><?php echo $companyResponsible['alamat']; ?></td>
<td><?php echo $companyResponsible['no_telepon']; ?></td>
<td><?php echo $companyResponsible['email']; ?></td>
<td><?php echo $companyResponsible['tanda_pengenal']; ?></td>
<td><?php echo $companyResponsible['nomor_tanda_pengenal']; ?></td>
<td><?php echo $companyResponsible['jenis_kelamin']; ?></td>
<td><?php echo $companyResponsible['agama']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'company_responsibles', 'action' => 'view', $companyResponsible['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'company_responsibles', 'action' => 'edit', $companyResponsible['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'company_responsibles', 'action' => 'delete', $companyResponsible['id']), null, __('Are you sure you want to delete # %s?', $companyResponsible['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Company Responsible'), array('controller' => 'company_responsibles', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Company Services'); ?></h3>
<?php if (!empty($company['CompanyService'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Service Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($company['CompanyService'] as $companyService): ?>
<tr>
<td><?php echo $companyService['id']; ?></td>
<td><?php echo $companyService['service_id']; ?></td>
<td><?php echo $companyService['company_id']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'company_services', 'action' => 'view', $companyService['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'company_services', 'action' => 'edit', $companyService['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'company_services', 'action' => 'delete', $companyService['id']), null, __('Are you sure you want to delete # %s?', $companyService['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Company Service'), array('controller' => 'company_services', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Company Staffs'); ?></h3>
<?php if (!empty($company['CompanyStaff'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Nama'); ?></th>
<th><?php echo __('Jabatan'); ?></th>
<th><?php echo __('Alamat'); ?></th>
<th><?php echo __('Alamat Perusahaan'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($company['CompanyStaff'] as $companyStaff): ?>
<tr>
<td><?php echo $companyStaff['id']; ?></td>
<td><?php echo $companyStaff['company_id']; ?></td>
<td><?php echo $companyStaff['nama']; ?></td>
<td><?php echo $companyStaff['jabatan']; ?></td>
<td><?php echo $companyStaff['alamat']; ?></td>
<td><?php echo $companyStaff['alamat_perusahaan']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'company_staffs', 'action' => 'view', $companyStaff['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'company_staffs', 'action' => 'edit', $companyStaff['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'company_staffs', 'action' => 'delete', $companyStaff['id']), null, __('Are you sure you want to delete # %s?', $companyStaff['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Company Staff'), array('controller' => 'company_staffs', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Customers'); ?></h3>
<?php if (!empty($company['Customer'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('User Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($company['Customer'] as $customer): ?>
<tr>
<td><?php echo $customer['id']; ?></td>
<td><?php echo $customer['user_id']; ?></td>
<td><?php echo $customer['company_id']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'customers', 'action' => 'view', $customer['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'customers', 'action' => 'edit', $customer['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'customers', 'action' => 'delete', $customer['id']), null, __('Are you sure you want to delete # %s?', $customer['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Customer'), array('controller' => 'customers', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Issues'); ?></h3>
<?php if (!empty($company['Issue'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Reporter Id'); ?></th>
<th><?php echo __('Category Id'); ?></th>
<th><?php echo __('No Resi'); ?></th>
<th><?php echo __('Note'); ?></th>
<th><?php echo __('Link Gambar'); ?></th>
<th><?php echo __('Tanggal'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($company['Issue'] as $issue): ?>
<tr>
<td><?php echo $issue['id']; ?></td>
<td><?php echo $issue['company_id']; ?></td>
<td><?php echo $issue['agen_id']; ?></td>
<td><?php echo $issue['reporter_id']; ?></td>
<td><?php echo $issue['category_id']; ?></td>
<td><?php echo $issue['no_resi']; ?></td>
<td><?php echo $issue['note']; ?></td>
<td><?php echo $issue['link_gambar']; ?></td>
<td><?php echo $issue['tanggal']; ?></td>
<td><?php echo $issue['status']; ?></td>
<td><?php echo $issue['flag']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'issues', 'action' => 'view', $issue['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'issues', 'action' => 'edit', $issue['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'issues', 'action' => 'delete', $issue['id']), null, __('Are you sure you want to delete # %s?', $issue['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Issue'), array('controller' => 'issues', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<div class="related">
<h3><?php echo __('Related Submissions'); ?></h3>
<?php if (!empty($company['Submission'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('Company Id'); ?></th>
<th><?php echo __('Agen Id'); ?></th>
<th><?php echo __('Reporter Id'); ?></th>
<th><?php echo __('Service Id'); ?></th>
<th><?php echo __('Note'); ?></th>
<th><?php echo __('Status'); ?></th>
<th><?php echo __('Flag'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($company['Submission'] as $submission): ?>
<tr>
<td><?php echo $submission['id']; ?></td>
<td><?php echo $submission['company_id']; ?></td>
<td><?php echo $submission['agen_id']; ?></td>
<td><?php echo $submission['reporter_id']; ?></td>
<td><?php echo $submission['service_id']; ?></td>
<td><?php echo $submission['note']; ?></td>
<td><?php echo $submission['status']; ?></td>
<td><?php echo $submission['flag']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'submissions', 'action' => 'view', $submission['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'submissions', 'action' => 'edit', $submission['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'submissions', 'action' => 'delete', $submission['id']), null, __('Are you sure you want to delete # %s?', $submission['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Submission'), array('controller' => 'submissions', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<file_sep><?php
App::uses('AppController', 'Controller');
/**
* Issues Controller
*
* @property Issue $Issue
* @property PaginatorComponent $Paginator
*/
class IssuesController extends AppController {
/**
* Components
*
* @var array
*/
public $components = array('Paginator');
/**
* index method
*
* @return void
*/
public function index() {
$this->Issue->recursive = 0;
$this->set('issues', $this->Paginator->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->Issue->exists($id)) {
throw new NotFoundException(__('Invalid issue'));
}
$options = array('conditions' => array('Issue.' . $this->Issue->primaryKey => $id));
$this->set('issue', $this->Issue->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Issue->create();
$this->request->data['Issue']['tanggal'] = date('Y-m-d H:i:s');
$this->request->data['HistoryIssue'][0]['tanggal'] = date('Y-m-d H:i:s');
$this->request->data['HistoryIssue'][0]['agen_id'] = $this->request->data['Issue']['agen_id'];
$this->request->data['HistoryIssue'][0]['status'] = $this->request->data['Issue']['status'];
$this->request->data['HistoryIssue'][0]['comment'] = $this->request->data['Issue']['note'];
// echo "<pre>";
// var_dump($this->request->data);
// echo "</pre>";
// exit;
if ($this->Issue->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The issue has been saved.'));
return $this->redirect(array('controller'=>'users','action' => 'index'));
} else {
$this->Session->setFlash(__('The issue could not be saved. Please, try again.'));
}
}
$companies_all = $this->Issue->Company->find('all');
foreach ($companies_all as $key => $value) {
$companies[$value['Company']['id']] = $value['Company']['nama_perusahaan'];
}
$agens = $this->Issue->Agen->find('list');
$reporters_all = $this->Issue->Reporter->find('all');
foreach ($reporters_all as $key => $value) {
$reporters[$value['Reporter']['id']] = $value['Reporter']['nama'];
}
$categories_all = $this->Issue->Category->find('all');
foreach ($categories_all as $key => $value) {
$categories[$value['Category']['id']] = $value['Category']['nama'];
}
$this->set(compact('companies', 'agens','reporters','categories'));
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
$this->Issue->recursive = 2;
if (!$this->Issue->exists($id)) {
throw new NotFoundException(__('Invalid issue'));
}
if ($this->request->is(array('post', 'put'))) {
$this->request->data['HistoryIssue'][0]['tanggal'] = date('Y-m-d H:i:s');
$this->request->data['HistoryIssue'][0]['agen_id'] = $this->Session->read('Auth.User.agen_id');
$this->request->data['HistoryIssue'][0]['status'] = $this->request->data['Issue']['status'];
$this->request->data['Issue']['tanggal'] = date('Y-m-d H:i:s');
// echo "<pre>";
// var_dump($this->request->data);
// echo "</pre>";
// exit;
if ($this->Issue->saveAssociated($this->request->data,array('deep'=>TRUE))) {
$this->Session->setFlash(__('The History Issue has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The issue could not be saved. Please, try again.'));
}
}
$options = array('conditions' => array('Issue.' . $this->Issue->primaryKey => $id));
$this->request->data = $this->Issue->find('first', $options);
$companies = $this->Issue->Company->find('list',array('fields'=>'id,nama_perusahaan'));
$agens = $this->Issue->Agen->find('list',array('fields'=>'id,nama'));
$reporters = $this->Issue->Reporter->find('list',array('fields'=>'id,nama'));
$categories = $this->Issue->Category->find('list',array('fields'=>'id,nama'));
$this->set(compact('companies', 'agens', 'reporters', 'categories'));
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->Issue->id = $id;
if (!$this->Issue->exists()) {
throw new NotFoundException(__('Invalid issue'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Issue->delete()) {
$this->Session->setFlash(__('The issue has been deleted.'));
} else {
$this->Session->setFlash(__('The issue could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
<file_sep><div class="companyResponsibles view">
<h2><?php echo __('Company Responsible'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['id']); ?>
</dd>
<dt><?php echo __('Company'); ?></dt>
<dd>
<?php echo $this->Html->link($companyResponsible['Company']['id'], array('controller' => 'companies', 'action' => 'view', $companyResponsible['Company']['id'])); ?>
</dd>
<dt><?php echo __('Nama Pimpinan'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['nama_pimpinan']); ?>
</dd>
<dt><?php echo __('Jabatan'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['jabatan']); ?>
</dd>
<dt><?php echo __('Tempat Lahir'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['tempat_lahir']); ?>
</dd>
<dt><?php echo __('Tanggal Lahir'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['tanggal_lahir']); ?>
</dd>
<dt><?php echo __('Alamat'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['alamat']); ?>
</dd>
<dt><?php echo __('No Telepon'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['no_telepon']); ?>
</dd>
<dt><?php echo __('Email'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['email']); ?>
</dd>
<dt><?php echo __('Tanda Pengenal'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['tanda_pengenal']); ?>
</dd>
<dt><?php echo __('Nomor Tanda Pengenal'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['nomor_tanda_pengenal']); ?>
</dd>
<dt><?php echo __('Jenis Kelamin'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['jenis_kelamin']); ?>
</dd>
<dt><?php echo __('Agama'); ?></dt>
<dd>
<?php echo h($companyResponsible['CompanyResponsible']['agama']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Company Responsible'), array('action' => 'edit', $companyResponsible['CompanyResponsible']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Company Responsible'), array('action' => 'delete', $companyResponsible['CompanyResponsible']['id']), null, __('Are you sure you want to delete # %s?', $companyResponsible['CompanyResponsible']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Company Responsibles'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company Responsible'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Companies'), array('controller' => 'companies', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Company'), array('controller' => 'companies', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><div class="employees view">
<h2><?php echo __('Employee'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($employee['Employee']['id']); ?>
</dd>
<dt><?php echo __('Nama'); ?></dt>
<dd>
<?php echo h($employee['Employee']['nama']); ?>
</dd>
<dt><?php echo __('Alamat'); ?></dt>
<dd>
<?php echo h($employee['Employee']['alamat']); ?>
</dd>
<dt><?php echo __('Tempat Lahir'); ?></dt>
<dd>
<?php echo h($employee['Employee']['tempat_lahir']); ?>
</dd>
<dt><?php echo __('Tanggal Lahir'); ?></dt>
<dd>
<?php echo h($employee['Employee']['tanggal_lahir']); ?>
</dd>
<dt><?php echo __('No Telepon'); ?></dt>
<dd>
<?php echo h($employee['Employee']['no_telepon']); ?>
</dd>
<dt><?php echo __('Email'); ?></dt>
<dd>
<?php echo h($employee['Employee']['email']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Employee'), array('action' => 'edit', $employee['Employee']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Employee'), array('action' => 'delete', $employee['Employee']['id']), null, __('Are you sure you want to delete # %s?', $employee['Employee']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Employees'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Employee'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Agens'), array('controller' => 'agens', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Agen'), array('controller' => 'agens', 'action' => 'add')); ?> </li>
</ul>
</div>
<div class="related">
<h3><?php echo __('Related Agens'); ?></h3>
<?php if (!empty($employee['Agen'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php echo __('Id'); ?></th>
<th><?php echo __('User Id'); ?></th>
<th><?php echo __('Employee Id'); ?></th>
<th><?php echo __('Level'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php foreach ($employee['Agen'] as $agen): ?>
<tr>
<td><?php echo $agen['id']; ?></td>
<td><?php echo $agen['user_id']; ?></td>
<td><?php echo $agen['employee_id']; ?></td>
<td><?php echo $agen['level']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'agens', 'action' => 'view', $agen['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'agens', 'action' => 'edit', $agen['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'agens', 'action' => 'delete', $agen['id']), null, __('Are you sure you want to delete # %s?', $agen['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Agen'), array('controller' => 'agens', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
<file_sep><div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Edit User'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('status');
?>
</fieldset>
<fieldset>
<legend><?php echo __('Add Agen'); ?></legend>
<?php
echo $this->Form->hidden('Agen.0.id');
echo $this->Form->input('Agen.0.nama');
echo $this->Form->input('Agen.0.alamat');
echo $this->Form->input('Agen.0.tempat_lahir');
echo $this->Form->date('Agen.0.tanggal_lahir');
echo $this->Form->input('Agen.0.no_telepon');
echo $this->Form->input('Agen.0.email');
echo $this->Form->input('Agen.0.level', array('options' => array('empty'=>'Choose One','1'=>'CSR', '2'=>'Back Room', '3'=>'Admin','4'=>'indexer')));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Home'), array('action' => 'index_admin')); ?></li>
<li><?php echo $this->Html->link(__('List Agen'), array('action' => 'list_user')); ?></li>
</ul>
</div>
| 11aaf8ff6de2533746e281c75590dd7831275302 | [
"JavaScript",
"PHP"
] | 35 | PHP | nicobaruna/physical_outlet | 57a7ad6533c1e225515903e961893ccbaa14099f | 31dc0cfd10df2eb1578c2a338bad70496219de94 |
refs/heads/master | <file_sep># Qui suis-je ?
Je suis un futur développeur et suis actuellement en formation développeur Web et Web mobile à l'AFPA.
## Liste des compétences et langages acquis au cours de cette formation:
### Versioning, testing et gestion de projet
* HTML
* CSS
* JavaScript
* PHP
* SQL
### Liste des outils:
* GIT / GitHub
* REACT
* Node.js
* Symfony
* MySQL
* WordPress
J'ai également ajouté une *"github-page"* à ce repository [ici](https://thomaspanier.github.io/welcome/).
Cette page a pour but de lister les compétences acquises sur mon temps libre en dehors de la formation à l'AFPA.
<file_sep>//déclarer images
const images = [
"img/attestation_suivi_securite.png",
"img/certificat_comprendre_le_web.png",
"img/certificat_wordpress.png",
"img/certificat_html5_css3.png",
"img/Certificat_LeFonctionnementDesAlgorithmes.png",
"img/Certificat_ProgrammerAvecJavaScript.png"
];
//déclarer descriptions
const descriptions = [
"Attestation de suivi MOOC sur la sécurité informatique",
"Certificat de réussite: Comprendre le Web",
"Certificat de réussite: WordPress 5",
"Certificat de réussite: Créer votre site web avec HTML5 et CSS3",
"Certificat de réussite: Découvrez le fonctionnement des algorithmes",
"Certificat de réussite: Apprenez à programmer avec JavaScript"
];
var maxIndex = images.length - 1;
//récupérer image et description du document html
var imageContainer = document.getElementById("images");
var description = document.getElementById("descriptions");
//faire correspondre image et description dans l'index
function setCurrentContent() {
imageContainer.src = images[currentIndex];
description.innerHTML = descriptions[currentIndex];
}
function setIndex() {
currentIndex < maxIndex ? currentIndex +=1 : currentIndex = 0;
setCurrentContent();
}
//selectionner la première image et description, selectionner l'intervalle de temps(4s)
var currentIndex = 0;
setCurrentContent();
var sliderTurn = setInterval(setIndex, 4000);
//fonction du boutton gauche et droit
function action(click = false) {
clearInterval(sliderTurn);
click === true ? (currentIndex < maxIndex ? currentIndex ++ : currentIndex = 0) : (currentIndex > 0 ? currentIndex -- : currentIndex = maxIndex);
setCurrentContent();
sliderTurn = setInterval(setIndex, 4000);
} | f3d7b5deec90aee786f085c2e30c51740eef59a0 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ThomasPANIER/welcome | ec9a13a42c541b7c1c12243877642150764a8dbf | 29e9be0d977c956c8af44a689f0232157a2602cb |
refs/heads/master | <file_sep>Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
if (Meteor.isClient) {
Router.map(function() {
this.route('login', {
path: '/'
})
this.route('listLectures', {
path: '/courses',
data: function(){
templateData = {
lectures: Lectures.find(),
previousPage: '/'
};
return templateData;
}
});
this.route('adminTemplate', {
path: '/:index/admin',
action: function() {
var currentLectureId = parseInt(this.params.index);
var currentLecture = Lectures.findOne({index: currentLectureId});
if (Meteor.userId() == null || Meteor.userId() != currentLecture.admin) {
this.redirect('/');
}
else {
this.render();
}
},
waitOn: function() {
var currentLectureId = parseInt(this.params.index);
return Meteor.subscribe('messages', currentLectureId);
},
data: function(){
var currentLectureId = parseInt(this.params.index);
Session.set('currentLectureId', currentLectureId);
templateData = {
previousPage: "{{ pathFor listLectures }}",
lecture: Lectures.findOne({index: currentLectureId}),
messages: Messages.find({lecture: currentLectureId}, {sort: { timestamp: -1 }}),
tooFast: Messages.find({lecture: currentLectureId, presetType: "tooFast"}),
tooSlow: Messages.find({lecture: currentLectureId, presetType: "tooSlow"}),
goBack: Messages.find({lecture: currentLectureId, presetType: "backSlide"}),
dontUnderstand: Messages.find({lecture: currentLectureId, presetType: "dontUnderstand"}),
tooFastCount: Meteor.call('countMessagesByPresetType', currentLectureId, "tooFast"),
tooSlowCount: Meteor.call('countMessagesByPresetType', currentLectureId, "tooSlow"),
goBackCount: Meteor.call('countMessagesByPresetType', currentLectureId, "backSlide"),
dontUnderstandCount: Meteor.call('countMessagesByPresetType', currentLectureId, "dontUnderstand")
};
return templateData;
}
});
this.route('studentPresetTemplate', {
path: '/:index',
action: function() {
var currentLectureId = parseInt(this.params.index);
var currentLecture = Lectures.findOne({index: currentLectureId});
if (!currentLecture) {
this.redirect('/');
}
else {
this.render();
}
},
waitOn: function() {
var currentLectureId = parseInt(this.params.index);
return Meteor.subscribe('messages', currentLectureId);
},
data: function(){
var currentLectureId = parseInt(this.params.index);
Session.set('currentLectureId', currentLectureId);
templateData = {
previousPage: "{{ pathFor listLectures }}",
lectures: Lectures.find(),
lecture: Lectures.findOne({index: currentLectureId}),
messages: Messages.find({lecture: currentLectureId}, { sort: { timestamp: -1 }})
};
return templateData;
}
});
this.route('studentAskTemplate', {
path: '/:index/ask',
action: function() {
var currentLectureId = parseInt(this.params.index);
var currentLecture = Lectures.findOne({index: currentLectureId});
if (Meteor.Device.isPhone() == false) {
Router.go('/'+currentLectureId);
}
else if (!currentLecture) {
this.redirect('/');
}
else {
this.render();
}
},
waitOn: function() {
var currentLectureId = parseInt(this.params.index);
return Meteor.subscribe('messages', currentLectureId);
},
data: function(){
var currentLectureId = parseInt(this.params.index);
var currentLecture = Lectures.findOne({index: currentLectureId});
Session.set('currentLectureId', currentLectureId);
templateData = {
previousPage: "{{ pathFor studentPresetTemplate currentLecture}}",
lectures: Lectures.find(),
lecture: Lectures.findOne({index: currentLectureId}),
messages: Messages.find({lecture: currentLectureId}, {sort: { timestamp: -1 }})
};
return templateData;
}
});
this.route('notFound', {
path: '*'
});
});
}<file_sep>if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
Meteor.publish('lectures', function() {
return Lectures.find();
});
Meteor.publish('lecture', function(index) {
return Lectures.find({index: index});
});
Meteor.publish('messages', function(currentLectureId) {
return Messages.find({lecture: currentLectureId});
});
Meteor.publish('allUsers', function() {
return Meteor.users.find({}, {
fields: {
'profile.email': 1,
'profile.name': 1,
'profile.createdAt': 1,
'profile.adminFor': 1
}
});
});
if (Lectures.find().count() === 0) {
var firstUser = Accounts.createUser({
email: "<EMAIL>",
password: "<PASSWORD>",
});
var secondUser = Accounts.createUser({
email: "<EMAIL>",
password: "<PASSWORD>",
});
var thirdUser = Accounts.createUser({
email: "<EMAIL>",
password: "<PASSWORD>",
});
Lectures.insert({
name: "EECS 111",
index: CurrentIndex++,
admin: firstUser
});
Lectures.insert({
name: "EECS 211",
index: CurrentIndex++,
admin: secondUser
});
Lectures.insert({
name: "EECS 212",
index: CurrentIndex++,
admin: thirdUser
});
};
});
Meteor.methods({
createMessage: function(content, lectureId, presetType) {
if (content != '') {
Messages.insert({content: content,
lecture: lectureId,
presetType: presetType,
timestamp: Date.now()});
}
},
createMessageByButton: function(buttonId, lectureId) {
if (buttonId == "lectureTooFast") {
Messages.insert({ content: "You're going too fast",
lecture: lectureId,
presetType: "tooFast",
timestamp: Date.now() });
}
else if (buttonId == "lectureTooSlow") {
Messages.insert({ content: "You're going too slow",
lecture: lectureId,
presetType: "tooSlow",
timestamp: Date.now() });
}
else if (buttonId == "goBackSlide") {
Messages.insert({ content: "Can you go back a slide?",
lecture: lectureId,
presetType: "backSlide",
timestamp: Date.now() });
}
else if (buttonId == "dontUnderstand") {
Messages.insert({ content: "I don't understand",
lecture: lectureId,
presetType: "dontUnderstand",
timestamp: Date.now() });
}
else {
console.log("something");
}
},
countMessagesByPresetType: function(lectureId, presetType) {
Messages.find({lecture: lectureId, presetType: presetType}).count();
},
clearAll: function(lectureId) {
Messages.remove({lecture: lectureId});
}
});
}<file_sep>Lectures = new Meteor.Collection('lectures');
Messages = new Meteor.Collection('messages');
CurrentIndex = 0;
buttonsClicked = [];
if (Meteor.isClient) {
Meteor.subscribe('lectures');
Meteor.subscribe('allUsers');
Template.studentDesktop.events({
'click #hubdesktopsend': function() {
var content = document.getElementById("hubdesktopfield").value;
var currentLectureId = Session.get('currentLectureId');
Meteor.call('createMessage', content, currentLectureId, false);
document.getElementById("hubdesktopfield").value = '';
},
});
Template.studentMobileAsk.events({
'click #asksend': function() {
var content = document.getElementById("askfield").value;
var currentLectureId = Session.get('currentLectureId');
Meteor.call('createMessage', content, currentLectureId, false);
document.getElementById("askfield").value = '';
}
});
Template.studentMobilePresets.events({
'click #lectureTooFast': function() {
var currentLectureId = Session.get('currentLectureId');
Meteor.call('createMessage', "You're going too fast", currentLectureId, "tooFast");
},
'click #lectureTooSlow': function() {
var currentLectureId = Session.get('currentLectureId');
Meteor.call('createMessage', "You're going too slow", currentLectureId, "tooSlow");
},
'click #goBackSlide': function() {
var currentLectureId = Session.get('currentLectureId');
Meteor.call('createMessage', "Can you go back a slide?", currentLectureId, "backSlide");
},
'click #dontUnderstand': function() {
var currentLectureId = Session.get('currentLectureId');
Meteor.call('createMessage', "I don't understand", currentLectureId, "dontUnderstand");
}
});
Template.adminTemplate.events({
'click #adminremoveall': function() {
var currentLectureId = Session.get('currentLectureId');
Meteor.call('clearAll', currentLectureId);
}
});
Template.updateTooFast.rendered = function() {
$('#tooFastCount').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
Template.updateTooSlow.rendered = function() {
$('#tooSlowCount').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
Template.updateGoBack.rendered = function() {
$('#goBackCount').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
Template.updateDontUnderstand.rendered = function() {
$('#dontUnderstandCount').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
/* Button functionality */
Template.studentDesktop.rendered = function() {
$('#hubdesktop-wrapper #hubdesktoppresets input').click(function() {
var clickedButton = this;
var clickedButtonId = this.id;
var currentLectureId = Session.get('currentLectureId');
if(buttonsClicked.indexOf(clickedButtonId) < 0) {
buttonsClicked.push(clickedButtonId);
Meteor.call('createMessageByButton', clickedButtonId, currentLectureId);
$(this).css('background-color', '#3E606F');
var buttonTimer = setInterval(function() {
$(clickedButton).css('background-color', '#91AA9D');
var index = buttonsClicked.indexOf(clickedButtonId);
buttonsClicked.splice(index, 1);
window.clearInterval(buttonTimer)
}, 3000);
}
});
}
}
if (Meteor.isServer) {
Lectures.allow({ //can't do anything to lectures
insert: function(userId, doc) {
return false;
},
update: function(userId, doc, fieldNames, modifier) {
return false;
},
remove: function(userId, doc) {
return false;
}
});
Messages.allow({
insert: function(userId, doc) {
return true;
},
update: function() {
return false;
},
remove: function(userId, doc) {
return (userId && userId == doc.admin);
}
});
}
| fcac8d0543b635b10c994de7b998733f2d269eff | [
"JavaScript"
] | 3 | JavaScript | jonrovira/hackathon2014 | 8875c3507fb6f480b58d2cd92a85e934e7c3189c | bc4d510753a5c868624aa80bf2d9a35ea4aed013 |
refs/heads/main | <repo_name>sufyanAshraf/mscs20072_Project_DLSpring2021<file_sep>/test.py
import cv2
from tensorflow.keras.models import model_from_json
import numpy as np
json_file = open('out/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
new_model = model_from_json(loaded_model_json)
# load weights into new model
new_model.load_weights('out/weights_model_1.h5')
a = ["other",'lahore fort', 'minar-e-pakistan', 'badshahi mosque', "Diwan-i-Am", "guest house", "<NAME>","<NAME>","tomb of Iqbal" ]
for j in range(11,12):
img = cv2.imread('t2/'+str(j)+'.jpg')
img = cv2.resize(img, dsize=(224, 224))
img = np.array(img).reshape(-1, 224, 224, 3)
img = img/255.0
# new_model.summary()
output = new_model.predict(img)
# print(output)
temp = -255
c = 0
target =0
for i in output[0]:
if i > temp:
temp = i
target =c
c+=1
print(a[target])
<file_sep>/data_augmentation.py
"""
Created on Fri Jan 24 22:59:54 2020
@author: sufyan
"""
import matplotlib.pyplot as plt
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
import cv2
from skimage import io
def generate_data(end, folderName,no =20):
image_count = 1
fn = 'z/'+str(folderName)+'/'
saveFolder = 'gen/'+str(folderName)+'/'
no_gen = no
for j in range (1,end):
image_path = fn+str(j)+'.jpg'
image = np.expand_dims(io.imread(image_path),0)
aug_iter = gen.flow(image)
aug_images = [next(aug_iter)[0].astype(np.uint8) for i in range(no_gen)]
for i in range(no_gen):
cv2.imwrite(saveFolder+"a%d.jpg" % image_count, cv2.cvtColor(aug_images[i], cv2.COLOR_RGB2BGR))
image_count+=1
print(image_count-1)
gen = ImageDataGenerator(rotation_range=10, height_shift_range=0.1,
width_shift_range=0.1, zoom_range=0.2, shear_range=0.15,
channel_shift_range=20., horizontal_flip=True)
generate_data(49,8)
| 31df709422b2dd94f5a866f301b3f616b62f49d2 | [
"Python"
] | 2 | Python | sufyanAshraf/mscs20072_Project_DLSpring2021 | cc5141dfb18ddeb95918bbed9a86dd90c0d668c1 | 2f7933833e566daaea56966109e5cfc9bab3e38d |
refs/heads/main | <repo_name>kalaniocean/Project_Local_Library_1<file_sep>/public/src/home.js
// Note: Please do not change the name of the functions. The tests use those names to validate your code.
function getTotalBooksCount(books) {
return books.length
}
function getTotalAccountsCount(accounts) {
return accounts.length
}
function getBooksBorrowedCount(books) {
const bookie =
books.map(book => book.borrows.some(borrow =>
!borrow.returned) ? 1 : null).filter(book => !!book)
return bookie.length
}
function getMostCommonGenres(books) {
function groupByKey(array, key) {
return array
.reduce((hash, obj) => {
if(obj[key] === undefined) return hash;
return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
}, {});
}
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
const genres = groupByKey(books, 'genre');
let results = [];
for (const key in genres) {
results.push({
name: key,
count: Object.size(genres[key]),
})
}
const sortie = results.sort((sortA, sortB) => sortA.count < sortB.count ? 1 : -1).slice(0, 5)
return sortie
}
function getMostPopularBooks(books) {
const getTitle = books.map(book => book.title);
const getNum = books.map(book => book.borrows.map(borrows =>
borrows).length);
const objNum = getNum.map(el => ({count: el})).map(el2 => el2);
const objTit = getTitle.map(el => ({name: el})).map(el2 => el2);
let result = objTit.map((item, i) => Object.assign({}, item, objNum[i]));
const sortie = result.sort((sortA, sortB) => sortA.count < sortB.count ? 1 : -1).slice(0, 5)
return sortie
}
function getMostPopularAuthors(books, authors) {
//Give matching books to author
const authId = authors.map(author => author.id)
const authBooks = books.filter((book) => authId.includes(book.authorId))
//give match author to book list
const bookId = authBooks.map(book => book.authorId)
const matchAuth = authors.filter(authMat => bookId.includes(authMat.id))
//combines first, last of auth
let fullAuthorNames = matchAuth.map(authors =>
(`${authors.name.first} ${authors.name.last}`));
// gets count of borrows of matching book
const getNum = authBooks.map
(book => book.borrows.map(borrows =>
borrows).length);
//creates count of borrows
const objNum = getNum.map(el => ({count: el})).map(el2 => el2);
const objTit = fullAuthorNames.map(el => ({name: el})).map(el2 => el2);
let result = objTit.map((item, i) => Object.assign({}, item, objNum[i]));
// sort from msot to least and reduce to top 5
const sortie = result.sort((sortA, sortB) => sortA.count < sortB.count ? 1 : -1).slice(0, 5)
return sortie
}
module.exports = {
getTotalBooksCount,
getTotalAccountsCount,
getBooksBorrowedCount,
getMostCommonGenres,
getMostPopularBooks,
getMostPopularAuthors,
};
<file_sep>/public/src/books.js
// Note: Please do not change the name of the functions. The tests use those names to validate your code.
function findAuthorById(authors, id) {
return authors.find(auth => auth.id === id)
}
function findBookById(books, id) {
return books.find( boo => boo.id === id)
}
function partitionBooksByBorrowedStatus(books) {
const getfilt =
[
books.map(book => book.borrows.some(borrow =>
!borrow.returned) ? book : null).filter(book => !!book),
books.map(book => book.borrows.every(borrow =>
borrow.returned) ? book : null).filter(book =>
!!book),
];
return getfilt
// get prettier
}
function getBorrowersForBook(book, accounts) {
const userIdMap = accounts.map(account =>
({[account.id]:account})).reduce((a, b) => ({...a, ...b}))
return book.borrows.map(book => ({...userIdMap[book.id],...book})).slice(0, 10)
}
module.exports = {
findAuthorById,
findBookById,
partitionBooksByBorrowedStatus,
getBorrowersForBook,
};
| 24fc054b08a56b944ffdb4a6155b4034436ec815 | [
"JavaScript"
] | 2 | JavaScript | kalaniocean/Project_Local_Library_1 | 5a43ad9c36fe4daaf973d10ed183226975ff08dd | 5f24f2c847b8a63611d210e08e4844b81d5aea18 |
refs/heads/main | <repo_name>einsteinzweisteine/NEAPrototype-RAIL<file_sep>/NEAPrototype-Transport/Passenger.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NEAPrototype_Transport
{
/// <summary>
/// Passenger class represents passengers - physical entities that are:
/// <list type="number">
/// <item>Spawned at a Station</item>
/// <item>Assigned a target Station</item>
/// <item>Assigned a Train</item>
/// <item>Picked up by said Train</item>
/// <item>Deposited at the target Station before being disposed</item>
/// </list>
/// </summary>
public class Passenger:SimObject
{
public enum State
{
Travelling,
Waiting,
Idle
}
public State state;
private static int globalPassId = 0;
private readonly int passId = 0;
Station currentStation;
Station targetStation;
Train trainAssigned;
private bool onTrain;
public Passenger(Station currentStation, Station targetStation)
{
this.currentStation = currentStation;
this.targetStation = targetStation;
state = State.Idle;
onTrain = false;
passId = globalPassId;
globalPassId++;
new PssgrCreateEvent(currentStation, targetStation);
}
private void GetOn()
{
if (1==1)
{
}
}
private void GetOff()
{
if (onTrain && trainAssigned.speed == 0 && trainAssigned.dist == 0 && trainAssigned.currentPlace == targetStation)
{
trainAssigned.GetOff(this);
targetStation = null;
trainAssigned = null;
state = State.Idle;
}
}
protected override void Process(List<Event> events)
{
foreach (Event e in events)
{
if (e.GetType().Name == "PssgrAssignEvent")
{
trainAssigned = (Train)e.Data[0];
}
}
}
}
}
<file_sep>/NEAPrototype-Transport/Place.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NEAPrototype_Transport
{
/// <summary>
/// Class represents the physical location of places (tracks, stations, etc.)
/// </summary>
public abstract class Place:SimObject
{
//id is used to uniquely identify each Place object
private static int idGlobal = 0;
private readonly int id;
private List<Place> connPlace;
protected int Id
{
get
{
return id;
}
}
public Place()
{
id = idGlobal;
idGlobal++;
connPlace = new List<Place> { };
}
/// <summary>
/// Adds another connection the list of connections. In this prototype, there will only be one connecting place as we are dealing with a circle
/// </summary>
/// <param name="place">The Place object that should be connected to this Place</param>
public void addConn(Place place)
{
connPlace.Add(place);
}
}
/// <summary>
/// Station inherits from Place; it represents locations where passengers are created, picked up and then dropped off by Trains
/// </summary>
public class Station:Place
{
//statId is used to uniquely identify each Station object
private static int statIdGlobal = 0;
private readonly int statId;
public const int trsmRange = 500;
private static List<Station> statList = new List<Station> { };
//dist is the distance (in metres) from this station to the next station
private int dist;
//nickname of the station
private string name;
private List<Track> trackConn;
public string Name
{
get
{
return name;
}
}
public Station(int dist, List<Track> trackConn = null, string name = null)
{
statId = statIdGlobal;
statIdGlobal++;
statList.Add(this);
this.name = name;
this.dist = dist;
this.trackConn = trackConn;
}
/// <summary>
/// Station transmits its presence to all Train objects nearby
/// </summary>
/// <param name="events"></param>
protected override void Process(List<Event> events)
{
foreach (Train tr in Train.TrList)
{
if (tr.isCloseToStation(this))
{
new NetworkEvent(this, tr, NtwMsg.PRS, new object[] { this });
}
}
}
}
/// <summary>
/// Track objects represent stretches that Trains can travel down.
/// </summary>
public class Track:Place
{
private static int trckIdGlobal = 0;
private readonly int trckId;
private static List<Track> trckList = new List<Track> { };
// private Place lwrConn;
// For the prototype, we will only allow tracks to connect to exclusively two other Station objects
private Place uppConn;
public Track ()
{
trckId = trckIdGlobal;
trckIdGlobal++;
trckList.Add(this);
}
public void AdduppConn(Place uppConn)
{
this.uppConn = uppConn;
}
protected override void Process(List<Event> events)
{
//No process required (we can treat this object as a constant)
}
}
}
<file_sep>/NEAPrototype-Transport/SimObject.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NEAPrototype_Transport
{
/// <summary>
/// Class represents all of the simulator objects. It handles the pseudo-networking and the stepping of the simulation (as well as events).
/// </summary>
public abstract class SimObject:Object
{
//Global List will hold all objects and their corresponding events
private static Dictionary<SimObject,List<Event>> simObjects = new Dictionary<SimObject,List<Event>> { };
private const int timeStep = 1; //In milliseconds
protected static readonly Server ServerMain = new Server();
public SimObject()
{
simObjects.Add(this, new List<Event> { });
}
/// <summary>
/// Method handles the operation of a SimObject for each simulation step
/// </summary>
/// <param name="events">Contains all of the events concerning the object</param>
protected abstract void Process(List<Event> events);
#region Events
public class Event
{
protected object[] data;
public object[] Data
{
get { return data; }
}
protected void Attach(SimObject target)
{
simObjects[target].Add(this);
}
}
/// <summary>
/// NetworkEvent facilitates communication between trains, stations, and the server.
/// </summary>
public class NetworkEvent : Event
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="trsm">Object transmitting the data</param>
/// <param name="recv">Object receiving the data</param>
/// <param name="msg">NtwMsg representing the message type</param>
/// <param name="payload">Data transmitted</param>
public NetworkEvent(Object trsm, Object recv, NtwMsg msg, object[] payload = null)
{
data = new object[4] { trsm, recv, msg, payload };
}
}
/// <summary>
/// Enum covers all acronyms that will be used in network communications. Look at README.md for details
/// </summary>
public enum NtwMsg
{
STS,
STD,
STC,
NPR,
PDT,
CLK,
NPA,
NPD,
PSR,
PRS
}
public class PssgrCreateEvent:Event
{
public PssgrCreateEvent(Station currentStation, Station targetStation)
{
data = new object[1] { new Passenger(currentStation,targetStation) };
Attach(ServerMain);
}
}
public class PssgrDeleteEvent : Event
{
public PssgrDeleteEvent(Passenger pssgr)
{
simObjects.Remove(pssgr);
}
}
public class PssgrRemoveEvent : Event
{
public PssgrRemoveEvent(Passenger pssgr, Train train)
{
data = new object[2] { pssgr, train };
Attach(train);
}
}
public class PssgrAssignEvent : Event
{
public PssgrAssignEvent(Passenger pssgr, Train tr)
{
data = new object[] { tr };
Attach(pssgr);
}
}
#endregion
}
}
<file_sep>/README.md
# NEAPrototype-RAIL
Prototyping an autonomous rail network for my NEA. AKA my mini project
# Description
The aim of this project is to prototype my NEA - simulating an autonomous rail network.
# Requirements/Simulation Details
* Trains will move in one direction around a circular track
* This track will have stations on it
* There is one central server
* Tracks will:
* Be connected to exclusively two stations
* Will be a strictly straight line
* Stations will:
* Be connected by exclusively two tracks
* Will have a transmitter broadcasting their station name, and this transmitter will have a range
* Passengers will be instantiated at a station, then be given a target station and a specific train
* A central server will register a request from the passenger to go to a target station
* The server will then assign the passenger to a specific train and vice versa
* The server will give the passenger a minimum time of arrival, and an ETA
* Trains will:
* Communicate with each other to prevent them from crashing
* They will need a custom communications protocol with different signals corresponding to different scenarios
* Transmitters will have a range of 100m
* Need to be able to accelerate and decelerate
* Accelerate from a station
* Decelerate if needing to stop at a station to
* Pick up somebody
* Drop someone off
* Decelerate to stop hitting a train in front
* Train (when in a certain range to another train) will attempt to meet the same speed as the train in front
* Communicate with the central server
* All wireless communication will be instantaneous
* (Add in error-detection and contingency)
## Train-Train protocol signals
* STS - at station, stopped (global)
* Station
* STD - approaching station, decelerating (global)
* Station
* STC - approaching station, continuing (global)
* Station
## Server-Train protocol signals
* NPR - new passenger request
* Target train
* PDT - passenger data transfer
* Target train
* Passenger ID
## Train-Server protocol signals
* CLK - regular clock signal, updates the server on the position of the train
* Self
* Position
* NPA - new passenger accept
* Passenger
* PSR - passenger removal; occurs when a passenger leaves the train
* Passenger
## Station protocol signals
* PRS - station presence signal
* Self<file_sep>/NEAPrototype-Transport/Train.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NEAPrototype_Transport
{
public class Train : SimObject
{
private static int idGlobal = 0;
private readonly int id;
private static List<Train> trList = new List<Train> { };
private const int capacity = 6;
private List<Passenger> passengersCurrent;
private List<Passenger> passengersTarget;
public Place currentPlace;
public int dist;
public int speed;
public static List<Train> TrList
{
get
{
return trList;
}
}
public Train(Place currentPlace)
{
id = idGlobal;
idGlobal++;
this.currentPlace = currentPlace;
trList.Add(this);
}
public void GetOff(Passenger passenger)
{
passengersCurrent.Remove(passenger);
passengersTarget.Remove(passenger);
}
public void GetOn(Passenger passenger)
{
passengersCurrent.Add(passenger);
}
public bool isCloseToStation(Station stat)
{
if ((currentPlace.GetType().Name == "Station")&&(currentPlace == stat))
{
return true;
}
else if ((currentPlace.GetType().Name == "Station")&&(this.dist <= Station.trsmRange))
{
return true;
}
return false;
}
protected override void Process(List<Event> events)
{
foreach (Event e in events)
{
switch (e.GetType().Name)
{
case "NetworkEvent":
switch (e.Data[2])
{
case NtwMsg.NPR:
NtwMsg msg;
if (passengersTarget.Count < capacity)
{
msg = NtwMsg.NPA;
}
else
{
msg = NtwMsg.NPD;
}
NetworkEvent ntwEvnt = new NetworkEvent(this, SimObject.ServerMain,msg,new object[] { });
break;
case NtwMsg.PRS:
break;
}
break;
case "PssgrRemoveEvent":
passengersCurrent.Remove((Passenger)e.Data[0]);
passengersTarget.Remove((Passenger)e.Data[0]);
break;
}
}
}
}
}
<file_sep>/NEAPrototype-Transport/Server.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NEAPrototype_Transport
{
/// <summary>
/// Server class handles pseudo-networking between Trains, Passengers and itself - it is responsible for assigning Passengers to Trains
/// </summary>
public class Server:SimObject
{
protected override void Process(List<Event> eventss)
{
throw new NotImplementedException();
}
}
}
| 5ff4cb5510aff4d1a6400d645efc9201340b6832 | [
"Markdown",
"C#"
] | 6 | C# | einsteinzweisteine/NEAPrototype-RAIL | ee4f04fb1ab9fa99a5e3b722296083c23a73d1d5 | c61c615547ad62a8b0e6949bb35dbcaeecd97c60 |
refs/heads/master | <file_sep>// Hacker Rank (www.hackerrank.com)
// Counting_Sort_3
// author: <NAME>
t= input()
list_ = []
for i in range(t):
num, str1 = raw_input().split()
list_.append(int(num))
for j in range(100):
count = 0
for k in range(t):
if j>=list_[k]:
count+=1
print count,<file_sep># Hacker Rank (www.hackerrank.com)
# Triangle Numbers
# author: <NAME>
t =int(raw_input())
for i in xrange(t):
n = int(raw_input())
if(n<3):
print -1
elif(n%2 == 1):
print 2
elif(n%4 == 0):
print 3
else:
print 4
<file_sep>// Hacker Rank (www.hackerrank.com)
// Extra Long Factorials
// author: <NAME>
num = int(raw_input())
fact = 1
for i in range(1,num+1):
fact*=i
print fact<file_sep># Hacker Rank (www.hackerrank.com)
# Minimum Draws
# author: <NAME>
t = int(raw_input())
for i in xrange(t):
sox_pair = int(raw_input())
print sox_pair+1<file_sep>// Hacker Rank (www.hackerrank.com)
// Delete duplicate-value nodes from a sorted linked list
// author: <NAME>
Node RemoveDuplicates(Node head) {
// This is a "method-only" submission.
// You only need to complete this method.
Node temp = head;
while(head.next != null) {
if(head.data == head.next.data) {
head.next = head.next.next;
}
else {
head = head.next;
}
}
return temp;
}
<file_sep># Hacker Rank (www.hackerrank.com)
# Angry Children
# author: <NAME>
n = input()
k = input()
candies = [input() for _ in range(0,n)]
candies.sort()
best = candies[-1]
for i in range(n-k+1):
if(candies[i+k-1]-candies[i] < best):
best = candies[i+k-1]-candies[i]
print best<file_sep>// Hacker Rank (www.hackerrank.com)
// Time_Conversion
// author: <NAME>
# Version 1.0
old = list(raw_input())
if old[8] == 'A':
if(''.join(old[:2]))=='12':
old[0] = old[1] = '0'
new = old[:8]
new = ''.join(new)
else:
if(''.join(old[:2]))=='12':
new = list('12')+old[2:8]
else:
add = old[:2]
add = int(''.join(add))
new = 12+add
new = list(str(new))+old[2:8]
new = ''.join(new)
print new
# Version 2.0
t=raw_input()
a=map(int,t[:-2].split(':'))
t=t[-2:]
if t=='PM' and 1<=a[0]<=11 :
a[0]+=12
if t=='AM' and a[0]==12 :
a[0]-=12
a=map(str,a)
for i in range(3) :
if len(a[i])==1 :
a[i]='0'+a[i]
print ':'.join(a)
<file_sep># Hacker Rank (www.hackerrank.com)
# Pangrams
# author: <NAME>
# Version 1.0
from collections import Counter
from collections import OrderedDict
alphabet = 'abcdefghijklmnopqrstuvwxyz'
sentence = raw_input()
sentence = ''.join(e for e in sentence if e.isalnum()) ##join all alphanumeric into one string
a = Counter(sentence) ##convert string into dict
my_list = list(a.keys()) ##take the keys of a dict as a list
my_list = map(lambda x: x.lower(),my_list) ##apply lower() to all items in a list
my_list = ''.join(OrderedDict.fromkeys(sorted(my_list))) ##join into ordered string the items(letters) in an array
if alphabet == my_list:
print "pangram"
else:
print "not pangram"
# Version 2.0 (more efficient)
# Create a full set with list (string) of all chars
alphabet = set('abcdefghijklmnopqrstuvwxyz')
sentence = raw_input()
if not alphabet - set(sentence.lower()):
print "pangram"
else:
print "not pangram"
<file_sep># Hacker Rank (www.hackerrank.com)
# Running Time of Algorithms
# author: <NAME>
N = int(raw_input())
list_ = [int(i) for i in raw_input().split()]
count = 0
for j in range(N-1):
for k in range(1,N,1):
if (list_[k-1]>list_[k]):
value = list_[k]
list_[k] = list_[k-1]
list_[k-1] = value
count = count+1
print count<file_sep># Hacker Rank (www.hackerrank.com)
# Cavity Map
# author: <NAME>
import sys
n = int(sys.stdin.readline())
a = [list(map(int,sys.stdin.readline().strip())) for _ in range(n)]
for i in range(n):
for j in range(n):
if i==0 or j == n-1 or j ==0 or i == n-1:
print(a[i][j], end = '')
elif (a[i][j]>a[i-1][j] and a[i][j]>a[i][j-1] and a[i][j]>a[i][j+1] and a[i][j]>a[i+1][j]):
print('X',end= '')
else:
print(a[i][j],end = '')
print()<file_sep>// Hacker Rank (www.hackerrank.com)
// Counting_Sort_1
// author: <NAME>
t = input()
ar = [int(i) for i in raw_input().split()]
for i in range(100):
print ar.count(i),<file_sep>// Hacker Rank (www.hackerrank.com)
// Counting_Sort_2
// author: <NAME>
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = input()
ar = [int(i) for i in raw_input().split()]
for i in sorted(ar):
print i,<file_sep>// Hacker Rank (www.hackerrank.com)
// Delete a Node
// author: <NAME>
Node Delete(Node head, int position) {
Node temp = head;
if (position == 0) {
head = head.next;
}
else if (position == 1) {
head.next = head.next.next;
}
else {
for (int i = 1; i<position; i++) {
temp = temp.next;
}
temp.next = temp.next.next;
}
return head;
}
<file_sep># Hacker Rank (www.hackerrank.com)
# Insertion Sort - Part 1
# author: <NAME>
size = int(raw_input())
list1 = [int(i) for i in raw_input().split()]
for j in range(size-1,0,-1):
if(list1[j]<=list1[j-1]):
temp = list1[j]
list1[j] = list1[j-1]
print ' '.join(map(str,list1))
list1[j-1] = temp
else:
break
print ' '.join(map(str,list1))
<file_sep># Hacker Rank (www.hackerrank.com)
# Funny String
# author: <NAME>
t = int(raw_input())
for i in xrange(t):
word = raw_input()
reverse = word[::-1]
funny = 0
for j in xrange(1,len(word)):
if abs(ord(word[j])-ord(word[j-1])) == abs(ord(reverse[j])-ord(reverse[j-1])):
funny = 1
else:
funny = 0
break
if(funny ==1):
print "Funny"
else:
print "Not Funny"
<file_sep># Hacker Rank (www.hackerrank.com)
# Handshake
# author: <NAME>
t = int(raw_input())
for i in xrange(t):
n = int(raw_input())
res = 1
for j in xrange(n,n-2,-1):
res = res*j
print res/2<file_sep>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int numLines = scan.nextInt();
for(int i = 0; i<numLines;i++) {
int counter = 0;
char[] chars = scan.next().toCharArray();
int len = chars.length;
int half = len/2;
for (int j=0; j<half;j++) {
if(chars[j]!=chars[len-j-1]) {
System.out.println(chars[j]-chars[len-j-1]);
counter+=Math.abs(chars[j]-chars[len-j-1]);
}
}
System.out.println(counter);
}
}
}<file_sep>// Hacker Rank (www.hackerrank.com)
// Caesar Cipher
// author: <NAME>
N = int(raw_input())
str1 = raw_input()
str2 = ""
K = int(raw_input())%26
for i in str1:
if (ord(i)>=ord('A') and ord(i)<=ord('Z')):
if(ord(i)+K > ord('Z')):
str2+=chr(ord(i)+K-26)
else:
str2+=chr(ord(i)+K)
elif(ord(i)>=ord('a') and ord(i)<=ord('z')):
if(ord(i)+K > ord('z')):
str2+=chr(ord(i)+K-26)
else:
str2+=chr(ord(i)+K)
else:
str2+=i
print str2
<file_sep># Hacker Rank (www.hackerrank.com)
# Restaurant
# author: <NAME>
t = int(raw_input())
for j in xrange(t):
max_size = 0
l,b = [int(i) for i in raw_input().split()]
if(l<b):
smaller = l
else:
smaller = b
for k in xrange(1, smaller+1,1):
if(l%k == 0 and b%k == 0):
max_size = ((l*b)/(k*k))
print max_size
<file_sep># Hacker Rank (www.hackerrank.com)
# Song of Pi
# author: <NAME>
import string
T = int(raw_input())
pi = "31415926535897932384626433833"
for i in xrange(T):
my_str = raw_input().split()
current = 0
check = 0
list = []
for j in my_str:
list.append(str(len(j)))
check = ''.join(list)
if(check==pi[:len(list)]):
print "It's a pi song."
else:
print "It's not a pi song."<file_sep># Hacker Rank (www.hackerrank.com)
# Mutations
# author: <NAME>
string1 = raw_input()
index,char = raw_input().split()
index = int(index)
string1 = list(string1)
string1[index] = char
string1 = ''.join(string1)
print string1<file_sep># Hacker Rank (www.hackerrank.com)
# Manasa and Stones
# author: <NAME>
t = int(raw_input())
for i in range(t):
list_ = []
n = int(raw_input())
a = int(raw_input())
b = int(raw_input())
res = a*(n-1)
list_.append(res)
for j in range(n-1):
res = res + abs(b-a)
list_.append(res)
print ' '.join(map(str,list_))<file_sep># Hacker Rank (www.hackerrank.com)
# Sherlock and Array
# author: <NAME>
t = int(raw_input())
for i in xrange(t):
n = int(raw_input())
list_ = list(map(int,raw_input().split()))
if(n==1):
print "YES"
elif(n==2):
print "NO"
else:
left, right = 0, sum(list_[1:])
for j in xrange(1,n-1):
left,right = left+list_[j-1],right-list_[j]
if(left == right):
print "YES"
break
else:
print "NO"<file_sep># Hacker Rank (www.hackerrank.com)
# Ice Cream Parlor
# author: <NAME>
# Version 1.0
t = int(raw_input())
first, second = 0,0
for i in xrange(t):
money = int(raw_input())
num_ind = int(raw_input())
temp_list = raw_input().split()
for j in xrange(len(temp_list)-1):
for k in xrange(j+1, len(temp_list),1):
if (int(temp_list[j])+int(temp_list[k])) == money:
first, second = j+1, k+1
break
print first, second
# Version 2.0 (more efficient)
import sys
t = int(sys.stdin.readline())
for i in range(t):
money = int(sys.stdin.readline())
N = int(sys.stdin.readline())
C = list(map(int, sys.stdin.readline().split()))
for j, c in enumerate(C[:-1]):
for k in range(j + 1, len(C)):
if C[k] == money - c:
print j + 1, k + 1
break<file_sep># Hacker Rank (www.hackerrank.com)
# Kaprekar Numbers
# author: <NAME>
def kaprekar_numbers(x):
l = str(x*x)
return x == int(l[:len(l)/2] or 0) + int(l[len(l)/2:])
list_kaprekar = [str(x) for x in xrange(int(raw_input()), int(raw_input())+1) if kaprekar_numbers(x)]
if len(list_kaprekar) != 0:
print(" ".join(list_kaprekar))
else:
print("INVALID RANGE")<file_sep>// Hacker Rank (www.hackerrank.com)
// Library Fine
// author: <NAME>
returned = list(raw_input().split())
taken = list(raw_input().split())
fine = 0
if(int(returned[2])-int(taken[2])>0):
fine = 10000
if(int(returned[1])-int(taken[1])>0 and (int(returned[2])-int(taken[2]))==0):
fine=500*(int(returned[1])-int(taken[1]))
if ((int(returned[0])-int(taken[0]))>0 and (int(returned[1])-int(taken[1]))==0 and (int(returned[2])-int(taken[2]))==0):
fine = 15*(int(returned[0])-int(taken[0]))
print fine
<file_sep>// Hacker Rank (www.hackerrank.com)
// Merge two sorted linked lists
// author: <NAME>
Node MergeLists(Node list1, Node list2) {
// This is a "method-only" submission.
// You only need to complete this method
Node result = null;
if(list1 == null) {
return list2;
}
else if(list2 == null) {
return list1;
}
if(list1.data <=list2.data) {
result = list1;
result.next = MergeLists(list1.next,list2);
}
else {
result = list2;
result.next = MergeLists(list2.next,list1);
}
return result;
}
<file_sep># Hacker Rank (www.hackerrank.com)
# Chocolate Feast
# author: <NAME>
T = int(raw_input())
for i in range (0,T):
dollars,chock_price,wrap_change = [int(x) for x in raw_input().split(' ')]
answer = 0
# write code to compute answer
chocks = wrapper = dollars/chock_price #counting the number of chocks(wrappers) can be bought
while (wrapper>=wrap_change):
change = wrapper/wrap_change #change wrappers to chocks
chocks +=change #add them to total
wrapper %=wrap_change #how many wrappers left after change
wrapper +=change #add wrappers left after change and new chocko wrappers
print chocks
<file_sep># Hacker Rank (www.hackerrank.com)
# Maximizing XOR
# author: <NAME>
def maxXor( l, r):
max = 0
for i in xrange(l,r+1):
for j in xrange(l,r+1):
if(max<(i^j)):
max = i^j
return max
_l = int(raw_input());
_r = int(raw_input());
res = maxXor(_l, _r);
print(res)
<file_sep># Hacker Rank (www.hackerrank.com)
# Sherlock and Moving Tiles
# author: <NAME>
import math
L,s1,s2 = [int(i) for i in raw_input().split()]
Q = int(raw_input())
for i in xrange(Q):
q = int(raw_input())
l = math.sqrt(2*q)
res = abs(math.sqrt(2*math.pow(L,2))-l)/(abs(s1-s2))
print format(res, '10.22f') <file_sep># Hacker Rank (www.hackerrank.com)
# Is Fibo
# author: <NAME>
from math import *
for _ in range(int(raw_input())):
n = int(raw_input())
root1 = sqrt(5 * n**2 + 4)
root2 = sqrt(5 * n**2 - 4)
isFibo = root1 % 1 == 0 or root2 % 1 == 0
if(isFibo):
print "IsFibo"
else:
print "IsNotFibo"<file_sep># Hacker Rank (www.hackerrank.com)
# Identify Smith Numbers
# author: <NAME>
n = int(raw_input())
j = 2
total = 0
x=[int(i) for i in str(n)]
sumX = sum(x)
while n!=1:
if(n%j==0):
n = n / j
if(j>9):
o=[int(i) for i in str(j)]
sumO = sum(o)
total = total+sumO
else:
total = total + j
else:
j = j + 1
if (total == sumX):
print "1"<file_sep>// Hacker Rank (www.hackerrank.com)
// Find the Median
// author: <NAME>
t = input()
ar = [int(i) for i in raw_input().split()]
ar = sorted(ar)
median = ar[t/2]
print median
<file_sep>// Hacker Rank (www.hackerrank.com)
// Grid Challenge
// author: <NAME>
t = input()
possibility = 0
for i in range(t):
n = input()
for j in range(n):
ar = list(raw_input())
ar = sorted(ar)
first = ar[0]
if(first >= last):
possibility = 1
last = ar[n-1]
<file_sep>// Hacker Rank (www.hackerrank.com)
// Quicksort 1 - Partition
// author: <NAME>
t= input()
list_ = [int(i) for i in raw_input().split()]
list1 = []
list2 = []
p = list_[0]
for j in list_:
if (j < p):
list1.append(j)
else:
list2.append(j)
print' '.join(map(str, list1))+" "+' '.join(map(str, list2))
<file_sep># Hacker Rank (www.hackerrank.com)
# Service Lane
# author: <NAME>
## Version 1.0
N,T = [int(x) for x in raw_input().split()]
list = [int(x) for x in raw_input().split()]
for l in xrange(T):
i,j = [int(y) for y in raw_input().split()]
smallest = 3
for k in xrange(i, j+1):
if(list[k]<smallest):
smallest = list[k]
print smallest
## Version 2.0 (efficient)
entry = raw_input().split()
N = int(entry[0])
T = int(entry[1])
list = [int(x) for x in raw_input().split()]
for x in xrange(T):
l = raw_input().split()
i = int(l[0])
j = int(l[1])
print min(list[i:j+1])<file_sep># Hacker Rank (www.hackerrank.com)
# Marble Cut
# author: <NAME>
t = int(raw_input())
for i in range(t):
l,b = (int(l) for l in raw_input().split(' '))
if(abs(l*b)%3==0):
print "YES"
else:
print "NO", abs((l*b)%3)<file_sep># Hacker Rank (www.hackerrank.com)
# Connecting Towns
# author: <NAME>
t = int(raw_input())
for i in xrange(t):
n = int(raw_input())
list_ = list(map(int,raw_input().split()))
res = 1
for j in xrange(n-1):
res = res * list_[j]
print res%1234567
<file_sep># Hacker Rank (www.hackerrank.com)
# Make it Anagram
# author: <NAME>
from collections import Counter
def anagram(a,b):
dict_a = Counter(a)
dict_b = Counter(b)
return sum([abs(dict_a[i]- dict_b[i]) for i in set(a) | set(b)])
if __name__ == '__main__':
a = raw_input()
b = raw_input()
print anagram(a,b)<file_sep>// Hacker Rank (www.hackerrank.com)
// Insert a node at the head of a linked list
// author: <NAME>
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
}
*/
// This is a "method-only" submission.
// You only need to complete this method.
Node Insert(Node head,int x) {
Node newHead = new Node();
newHead.data = x;
newHead.next = null;
newHead.next = head;
head = newHead;
return head;
}
<file_sep># Hacker Rank (www.hackerrank.com)
# The Time in Words
# author: <NAME>
time_words = {"one":1,"two":2,"three":3,'four':4,"five":5,"six":6,"seven":7,'eight':8,"nine":9,"ten":10,
"eleven":11,'twelve':12,"thirteen":13,"fourteen":14,"quarter":15,'sixteen':16,"seventeen":17,
"eighteen":18,'nineteen':19,"twenty":20,"twenty one":21,"twenty two":22,"twenty three":23,
"twenty four":24,"twenty five":25,"twenty six":26,"twenty seven":27,"twenty eight":28, "twenty nine":29,"half":30}
H = int(raw_input())
M = int(raw_input())
m,h = M,H
hour = ''
minutes = ''
if (M > 30):
m = 60 - m
h = h+1
for k,v in time_words.iteritems():
if(v == h):
hour = '' + k
for k,v in time_words.iteritems():
if (v == m):
minutes = ''+k
if (M == 0):
print hour+" o' clock"
elif (M <= 15):
print 'quarter past '+ hour
elif (M == 30):
print minutes+' past '+ hour
elif (M == 45):
print minutes+' to '+ hour
elif (M <=14 or M <= 29 ):
print minutes+' minutes past '+ hour
else:
print minutes+' minutes to '+ hour
<file_sep># Hacker Rank (www.hackerrank.com)
# Angry Professor
# author: <NAME>
T = int(raw_input())
list = []
for i in xrange(T):
entry = raw_input().split()
N = int(entry[0])
K = int(entry[1])
count = 0
list = [int(x) for x in raw_input().split()]
for j in xrange(N):
if(list[j]<=0):
count = count +1
if (count<K):
print "YES"
else:
print "NO"
<file_sep># Hacker Rank (www.hackerrank.com)
# Filling Jars
# author: <NAME>
n,m = (int(i) for i in raw_input().split())
total = 0
for j in range(m):
a,b,k = (int(i) for i in raw_input().split())
total = (b-a+1)*k
print (total/n)
<file_sep>// Hacker Rank (www.hackerrank.com)
// Closest_Numbers
// author: <NAME>
t= input()
ar = [int(i) for i in raw_input().split()]
ar = sorted(ar)
new_ar = []
smallest = abs(ar[0]-ar[1])
for i in range(1,t-2):
if (abs(ar[i]-ar[i+1]) < smallest):
new_ar = []
smallest = abs(ar[i]-ar[i+1])
new_ar.append(ar[i])
new_ar.append(ar[i+1])
elif (abs(ar[i]-ar[i+1]) == smallest):
new_ar.append(ar[i])
new_ar.append(ar[i+1])
else:
continue
print ' '.join(map(str,new_ar))<file_sep># Hacker Rank (www.hackerrank.com)
# Sherlock and Squares
# author: <NAME>
import math
t = int(raw_input())
for i in xrange(t):
start,end = [int(i) for i in raw_input().split()]
first = int(math.sqrt(start))
if (first*first<start):
first=first+1
second = int(math.sqrt(end))
if(first<=second):
print second-first+1
else:
print 0
<file_sep>// Hacker Rank (www.hackerrank.com)
// Diagonal Difference
// author: <NAME>
t = int(raw_input())
sum1=sum2=0
for k in range(t):
list_ = [int(i) for i in raw_input().split()]
first, second = list_[k], list_[len(list_)-k-1]
sum1+=first
sum2+=second
print abs(sum1-sum2) | c1eb2869557afe24ff525c08bc6f724b01c809ee | [
"Java",
"Python"
] | 46 | Python | NurbekSakiev/HackerRank | 25bd99126a4017690f0689bbe7481229902150c2 | 05cfbbdc37641859654224ba3a50ab8eaaa1f3da |
refs/heads/master | <repo_name>karthik9319/Preparation<file_sep>/practise/test.py
import pandas as pd
df = pd.read_csv('CPU_Util_.csv')
df['TimeStamp'] = pd.to_datetime(df['Time (GMT)'])
df['Hr'] = [x. hour for x in df['TimeStamp']]
df.drop(['TimeStamp'], axis=1)
print("Mean of KPI Value: ",df.groupby('Hr').mean())
x = df.groupby('Hr').min()
# print(x['KPI Value'])
y = df.groupby('Hr').max()
print("Min of KPI Value: ",x['KPI Value'])
print("Max of KPI Value: ", y['KPI Value'])<file_sep>/README.md
# Preparation
Practise of Hands-on Machine Learning with Scikit-Learn, Keras & Tensorflow
| cbdc1794218dc368171eebecaf3a4e38385e3d9c | [
"Markdown",
"Python"
] | 2 | Python | karthik9319/Preparation | 8b7d2b428c412194e552371ba69f4c940b9ff735 | 0e96c7f8fd4affd1b73417f59a870bb213d27638 |
refs/heads/master | <repo_name>ShubhamD32/Flashcards<file_sep>/task/src/flashcards/Main.java
package flashcards;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
class Card {
private Map<String,String> map = new LinkedHashMap<>();
private Map<String,Integer> mistakeMap = new LinkedHashMap<>();
List<String> loggerList = new ArrayList<>();
static private int hardestNumber;
public Card(Map<String,String> map) {
this.map = map;
}
public void addElement () {
Scanner scanner = new Scanner(System.in);
System.out.println("The card:");
addToLogger("The card:");
String card = scanner.nextLine();
addToLogger(card);
if (map.containsKey(card)) {
System.out.println("The card \"" + card + "\" already exists.");
addToLogger("The card \"" + card + "\" already exists.");
}
System.out.println("The definition of the card:");
addToLogger("The definition of the card:");
String definition = scanner.nextLine();
addToLogger(definition);
if (map.containsValue(definition)) {
System.out.println("The definition \"" + definition + "\" already exists.");
addToLogger("The definition \"" + definition + "\" already exists.");
}
map.put(card, definition);
mistakeMap.put(card, 0);
System.out.println("The pair (\"" + card + "\":\"" + definition + "\") has been added.");
addToLogger("The pair (\"" + card + "\":\"" + definition + "\") has been added.");
}
public void removeElement () {
Scanner scanner = new Scanner(System.in);
System.out.println("The card:");
addToLogger("The card:");
String card = scanner.nextLine();
addToLogger(card);
if (!map.containsKey(card)) {
System.out.println("Can't remove \"" + card + "\": there is no such card");
addToLogger("Can't remove \"" + card + "\": there is no such card");
} else {
map.remove(card);
mistakeMap.remove(card);
System.out.println("The card has been removed.");
addToLogger("The card has been removed.");
}
}
public void exportFile () {
Scanner scanner = new Scanner(System.in);
System.out.println("File name:");
addToLogger("File name:");
String fileName = scanner.nextLine();
addToLogger(fileName);
String filePath = "./" + fileName;
int counter = 0;
File file = new File(filePath);
try (FileWriter fileWriter = new FileWriter(file)){
for (Map.Entry<String,String> entry : map.entrySet()) {
fileWriter.write(entry.getKey());
fileWriter.write("\n");
fileWriter.write(entry.getValue());
fileWriter.write("\n");
mistakeWriter(fileWriter, entry.getKey());
fileWriter.write("\n");
counter++;
}
} catch (IOException e) {
System.out.println("The file could not be created.");
addToLogger("The file could not be created.");
}
System.out.println(counter + " cards have been saved");
addToLogger(counter + " cards have been saved");
}
public void mistakeWriter(FileWriter fileWriter, String string) {
try {
fileWriter.write(Integer.toString(mistakeMap.get(string)));
} catch (IOException e) {
System.out.println("The file could not be created.");
addToLogger("The file could not be created.");
}
}
public void importFile () {
Scanner scanner = new Scanner(System.in);
System.out.println("File name:");
addToLogger("File name:");
String fileName = scanner.nextLine();
addToLogger(fileName);
String filePath = "./" + fileName;
File file = new File(filePath);
int fileLineCounter = 0;
try {
Scanner fileScanner = new Scanner(file);
fileScanner.useDelimiter("\\s+!\\n");
while (fileScanner.hasNext()) {
String card = fileScanner.nextLine();
String definition = fileScanner.nextLine();
int mistakes = Integer.parseInt(fileScanner.nextLine());
if (map.containsKey(card)) {
map.replace(card, definition);
fileLineCounter++;
} else {
map.put(card, definition);
fileLineCounter++;
}
if (!mistakeMap.containsKey(card)) {
mistakeMap.put(card, mistakes);
} else {
mistakeMap.replace(card, mistakes);
}
}
if (fileLineCounter == 1) {
System.out.println(fileLineCounter + " card has been loaded.");
addToLogger(fileLineCounter + " card has been loaded.");
} else {
System.out.println(fileLineCounter + " cards have been loaded.");
addToLogger(fileLineCounter + " cards have been loaded.");
}
} catch (FileNotFoundException e ) {
System.out.println("File not found.");
addToLogger("File not found.");
}
}
public Map<String,Integer> getMistakeMap() {
return mistakeMap;
}
public void ask () {
Map<String,String> reverseMap = new LinkedHashMap<>();
for (Map.Entry<String,String> entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.println("How many times to ask?");
addToLogger("How many times to ask?");
int numberOfTries = Integer.parseInt(scanner.nextLine());
addToLogger(Integer.toString(numberOfTries));
ArrayList<String> arrayList = new ArrayList<>(map.keySet());
int arrayListSize = arrayList.size();
for (int i = 0; i < numberOfTries; i++) {
int randomSelector = random.nextInt(arrayListSize);
System.out.println("Print the definition \"" + arrayList.get(randomSelector) + "\":");
addToLogger("Print the definition \"" + arrayList.get(randomSelector) + "\":");
String askedString = arrayList.get(randomSelector);
//System.out.println("Asked string is : " + askedString);
String checkString = scanner.nextLine();
addToLogger(checkString);
String answerString = map.get(arrayList.get(randomSelector));
if (checkString.equalsIgnoreCase(answerString)) {
System.out.println("Correct answer.");
addToLogger("Correct answer.");
} else if (reverseMap.containsKey(checkString)) {
if (!mistakeMap.containsKey(askedString)) {
mistakeMap.put(askedString, 1);
} else {
mistakeMap.replace(askedString, mistakeMap.get(askedString) + 1);
}
System.out.println("Wrong answer. The correct one is \"" + map.get(askedString) + "\", you've just written the definition of \"" + reverseMap.get(checkString) + "\"");
addToLogger("Wrong answer. The correct one is \"" + map.get(askedString) + "\", you've just written the definition of \"" + reverseMap.get(checkString) + "\"");
} else {
if (!mistakeMap.containsKey(askedString)) {
mistakeMap.put(askedString, 1);
} else {
mistakeMap.replace(askedString, mistakeMap.get(askedString) + 1);
}
System.out.println("Wrong answer. The correct one is \"" + map.get(reverseMap.get(answerString)) + "\"");
addToLogger("Wrong answer. The correct one is \"" + map.get(reverseMap.get(answerString)) + "\"");
}
}
}
public void getHardest() {
List<String> hardestCards = new ArrayList<>();
if (mistakeMap.isEmpty()) {
System.out.println("There are no cards with errors");
addToLogger("There are no cards with errors");
} else {
hardestCards = getLargestStrings();
if ((mistakeMap.get(hardestCards.get(0)) == 0)) {
System.out.println("There are no cards with errors");
addToLogger("There are no cards with errors");
} else if (hardestCards.size() == 1) {
System.out.println("The hardest card is \"" + hardestCards.get(0) + "\"." + " You have " + mistakeMap.get(hardestCards.get(0)) + " errors answering it.");
addToLogger("The hardest card is \"" + hardestCards.get(0) + "\"." + " You have " + mistakeMap.get(hardestCards.get(0)) + " errors answering it.");
} else {
System.out.print("\"The hardest cards are\"" );
addToLogger("\"The hardest cards are" );
for (int i = 0; i < hardestCards.size(); i++) {
System.out.print(" \"" + hardestCards.get(i) + "\",");
System.out.print("\n");
addToLogger(" \"" + hardestCards.get(i) + "\",");
addToLogger("\n");
}
System.out.print(" \"" + hardestCards.get(hardestCards.size()) + "\". You have " + mistakeMap.get(hardestCards.get(0)) + " errors answering it.");
//addToLogger(" \"" + hardestCards.get(hardestCards.size() - 1) + "\". You have " + mistakeMap.get(hardestCards.get(0)) + " errors answering it.");
}
/*System.out.println(hardestCards);
System.out.println("Count -> " + mistakeMap.get(hardestCards.get(0)));*/
}
//System.out.println("SHUBHAM ->" + mistakeMap.get(hardestCards.get(0)));
}
private List<String> getLargestStrings() {
List<String> list = new ArrayList<String>();
int max = Collections.max(mistakeMap.values());
if (mistakeMap.size() == 0) {
list.clear();
return list;
} else {
for (Map.Entry<String, Integer> entry : mistakeMap.entrySet()) {
if (entry.getValue() == max) {
list.add(entry.getKey());
max = entry.getValue();
}
}
hardestNumber = max;
return list;
}
}
/* public int returnHardestNumber() {
*//*return mistakeMap.get();*//*
}*/
void resetStatistics() {
for (Map.Entry<String,Integer> entry : mistakeMap.entrySet()) {
mistakeMap.replace(entry.getKey(), 0);
}
System.out.println("Card statistics has been reset.");
addToLogger("Card statistics has been reset.");
}
void addToLogger(String string) {
loggerList.add(string);
}
/*void displayLoggerList() {
System.out.println(loggerList);
}*/
void writeLog() {
Scanner scanner = new Scanner(System.in);
System.out.println("File name:");
addToLogger("File name:");
String filename = scanner.nextLine();
addToLogger(filename);
String filePath = "./" + filename;
File file = new File(filePath);
try (FileWriter fileWriter = new FileWriter(file)) {
for (String string : loggerList) {
fileWriter.write(string);
fileWriter.write("\n");
}
} catch (IOException e) {
System.out.println("Error writing to file");
addToLogger("Error writing to file");
}
System.out.println("The log has been saved.");
addToLogger("The log has been saved.");
}
void fileReadArgs (String fileNameArgs) {
String fileName = fileNameArgs;
addToLogger(fileName);
String filePath = "./" + fileName;
File file = new File(filePath);
int fileLineCounter = 0;
try {
Scanner fileScanner = new Scanner(file);
fileScanner.useDelimiter("\\s+!\\n");
while (fileScanner.hasNext()) {
String card = fileScanner.nextLine();
String definition = fileScanner.nextLine();
int mistakes = Integer.parseInt(fileScanner.nextLine());
if (map.containsKey(card)) {
map.replace(card, definition);
fileLineCounter++;
} else {
map.put(card, definition);
fileLineCounter++;
}
if (!mistakeMap.containsKey(card)) {
mistakeMap.put(card, mistakes);
} else {
mistakeMap.replace(card, mistakes);
}
}
if (fileLineCounter == 1) {
System.out.println(fileLineCounter + " card has been loaded.");
addToLogger(fileLineCounter + " card has been loaded.");
} else {
System.out.println(fileLineCounter + " cards have been loaded.");
addToLogger(fileLineCounter + " cards have been loaded.");
}
} catch (FileNotFoundException e ) {
System.out.println("File not found.");
addToLogger("File not found.");
}
}
void fileWriteArgs(String fileNameArgs) {
String fileName = fileNameArgs;
addToLogger(fileName);
String filePath = "./" + fileName;
int counter = 0;
File file = new File(filePath);
try (FileWriter fileWriter = new FileWriter(file)){
if (map.size() == 0) {
System.out.println("0 cards have been saved.");
}
for (Map.Entry<String,String> entry : map.entrySet()) {
fileWriter.write(entry.getKey());
fileWriter.write("\n");
fileWriter.write(entry.getValue());
fileWriter.write("\n");
mistakeWriter(fileWriter, entry.getKey());
fileWriter.write("\n");
counter++;
}
} catch (IOException e) {
System.out.println("The file could not be created.");
addToLogger("The file could not be created.");
}
System.out.println(counter + " cards have been saved");
addToLogger(counter + " cards have been saved");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String,String> map = new LinkedHashMap<>();
Card card = new Card(map);
for (int i = 0; i < args.length-1; i++) {
if ("-import".equals(args[i])) {
card.fileReadArgs(args[++i]);
}
}
System.out.println("Input the action (add, remove, import, export, ask, exit, log, hardest card, reset stats):");
card.addToLogger("Input the action (add, remove, import, export, ask, exit, log, hardest card, reset stats):");
String inputString = scanner.nextLine();
card.addToLogger(inputString);
while (!"exit".equalsIgnoreCase(inputString)) {
switch (inputString.toLowerCase()) {
case "add" :
card.addElement();
break;
case "remove" :
card.removeElement();
break;
case "import" :
card.importFile();
break;
case "export" :
card.exportFile();
break;
case "ask" :
card.ask();
break;
case "hardest card" :
card.getHardest();
break;
case "reset stats" :
card.resetStatistics();
break;
case "log" :
card.writeLog();
break;
}
System.out.println("Input the action (add, remove, import, export, ask, exit, log, hardest card, reset stats):");
card.addToLogger("Input the action (add, remove, import, export, ask, exit, log, hardest card, reset stats):");
inputString = scanner.nextLine();
card.addToLogger(inputString);
}
System.out.println("Bye bye!");
for (int i = 0; i < args.length-1; i++) {
if ("-export".equals(args[i])) {
card.fileWriteArgs(args[++i]);
}
}
card.addToLogger("Bye bye!");
}
}
| 57f5fbff435d0c7d7f73d788063220f7bc832073 | [
"Java"
] | 1 | Java | ShubhamD32/Flashcards | 26226eae698b1004e44ef4056e544e60eb3a71d9 | 7f7eeaf9ac9cafde1eb8deec5290b9d53c246568 |
refs/heads/master | <repo_name>vasilysmolin/laravel-blog<file_sep>/public/admin/custom/blog/blogPostEdit.js
$(document).ready(function () {
CKEDITOR.replace('editor');
});<file_sep>/public/admin/custom/users/usersAllList.js
$(document).ready(function () {
$('.jsAdminUsersMastersParserActive').on('click', function () {
$.ajax({
method: 'POST',
url: '/admin/ajaxAdminUsersMastersParserActive',
data: {
_token: token
}
}).done(function (response) {
if (response.success === true) {
console.log(123);
}
});
});
});
<file_sep>/public/admin/js/custom/unique.js
$(document).ready(function () {
var alias = $('.js-unique-nickname');
var phone = $('.js-unique-phone');
// var userID = $('#userID').data('user');
var addressID = $('#addressID').data('address');
function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); }
function isEnglish(n) { return /-?[А-Яа-яйё]/.test(n); }
$('.js-unique-nickname').on('keyup', function () {
if (alias.length > 0) {
if(isNumber(alias.val())){
$('.js-unique-nickname').next().css('display', 'block');
$('.js-unique-nickname').next().text('Никнейм должен содержать латинские буквы');
$('.js-unique-nickname').css('border', '1px solid #c9302c');
$('.jsUnique').attr('disabled', 'disabled');
}else{
if(isEnglish(alias.val())) {
console.log(1);
$('.js-unique-nickname').next().css('display', 'block');
$('.js-unique-nickname').next().text('Никнейм не должен содержать русские буквы');
$('.js-unique-nickname').css('border', '1px solid #c9302c');
$('.jsUnique').attr('disabled', 'disabled');
}else{
$('.js-unique-nickname').next().css('display', 'none');
$('.js-unique-nickname').css('border', '1px solid #E3E3E3');
$('.jsUnique').removeAttr('disabled');
uniqueForm(alias, 'nickname');
}
}
}
return false;
});
$('.js-unique-phone').on('keyup', function () {
if (phone.length > 0) {
$('.bb-input__error').css('display', 'none');
$('.js-unique-nickname').css('border', '1px solid #E3E3E3');
$('.jsUnique').removeAttr('disabled');
uniqueForm(phone, 'phone');
}
return false;
});
$('.jsAdminTagControl').on('keyup', function () {
var $error = $(this).next();
var $btn = $error.closest('form').find('button');
$.ajax({
method: 'POST',
url: '/admin/ajaxUniqueTagSetting',
data: {
tag: $(this).val(),
settingID: $('.jsAdminTagSettingID').val(),
_token: token
}
}).done(function (response) {
if (response.success == false) {
$error.css({'display': 'block'});
$btn.attr('disabled', 'disabled');
} else {
$error.css({'display': 'none'});
$btn.removeAttr('disabled');
}
});
});
function uniqueForm(alias, type) {
$.ajax({
method: 'POST',
url: '/admin/ajaxAdminValidate',
data: {
type: type,
alias: alias.val(),
addressID: addressID,
_token: token
}
}).done(function (response) {
if(response.phone === true ){
if (response.success === true) {
$('.js-unique-phone').next().css('display', 'none');
$('.js-unique-phone').css('border', '1px solid #E3E3E3');
$('.jsUnique').removeAttr('disabled');
}
if (response.success === false) {
$('.js-unique-phone').next().css('display', 'block');
$('.js-unique-phone').next().text('телефон занят');
$('.js-unique-phone').css('border', '1px solid #c9302c');
$('.jsUnique').attr('disabled', 'disabled');
}
} else if(response.nickname === true){
if (response.success === true) {
$('.js-unique-nickname').next().css('display', 'none');
$('.js-unique-nickname').css('border', '1px solid #E3E3E3');
$('.jsUnique').removeAttr('disabled');
}
if (response.success === false) {
if($('.js-unique-nickname').val().length>0){
$('.js-unique-nickname').next().css('display', 'block');
$('.js-unique-nickname').next().text('никнайм не уникальный');
$('.js-unique-nickname').css('border', '1px solid #c9302c');
$('.jsUnique').attr('disabled', 'disabled');
}
}
}
});
}
});
<file_sep>/public/admin/js/custom/custom.js
$(document).ready(function () {
if($(".js-select-differents").length > 0){
$(".js-select-differents").select2();
}
if($('.select2').length > 0) {
$('.select2').select2();
}
if($('.select2-multiple').length > 0) {
$('.select2-multiple').select2();
}
if ($('.js-select-progress-change-event').length > 0) {
$('.js-select-progress-change-event').on('change',function(){
const $this = $(this);
const value = $this.val();
const $profileTR = $this.closest('tr').children()[0];
const profileID = $($profileTR).html().trim();
if(value.length){
$.ajax({
method:'POST',
url:'/admin/ajaxChangeUserStatus',
data:{
status:value,
profileID:profileID,
_token: token
}
}).done((response)=>{
$this.css('color',response.color);
});
}
});
}
if($('.js-phone-activate').length > 0){
$('.js-phone-activate').on('change',function(){
const $this = $(this);
const value = $this.val();
const userTR = $this.closest('tr').children()[0];
const userID = $(userTR).html().trim();
$.ajax({
method:'POST',
url:'/admin/ajaxChangePhoneActive',
data:{
userID: userID,
phoneActive: value,
_token:token
}
}).done((response)=>{
})
});
}
if($('.js-address-catalog').length > 0){
$('.js-address-catalog').on('change',function(){
const $this = $(this);
const value = $this.val();
const addressID = $(this).data('id');
const userTR = $this.closest('tr').children()[0];
// const addressID = $(userTR).html().trim();
$.ajax({
method:'POST',
url:'/admin/ajaxChangeAddressCatalog',
data:{
addressID: addressID,
catalog: value,
_token:token
}
}).done((response)=>{
})
});
}
if ($('.js-select-progress-change-event-user').length > 0) {
$('.js-select-progress-change-event-user').on('change',function(){
const value = $(this).val();
console.log(value);
const $this = $(this);
const $userTR = $(this).closest('tr').children()[0];
const profileID = $($userTR).html().trim();
if(value.length){
$.ajax({
method:'POST',
url:'/admin/ajaxChangeUserStatus',
data:{
status:value,
userID:profileID,
_token: token
}
}).done((response)=>{
$this.css('color',response.color);
// console.log(response);
});
}
});
}
// Change user consultant
let consultantSelect = '.js-select-user-consultant';
if ($(consultantSelect).length > 0) {
$(consultantSelect).on('change', function() {
let consultantID = $(this).val();
let $userTR = $(this).closest('tr').children()[0];
let userID = $($userTR).html().trim();
if (consultantID.length){
$.ajax({
method:'POST',
url:'/admin/ajaxUserChangeConsultant',
data:{
consultantID: consultantID,
userID: userID,
_token: token
}
});
}
});
}
// Change active status
if ($('.js-change-parameter-phone').length > 0) {
$('.js-change-parameter-phone').on('change', function () {
var param;
var field = $(this).data('field');
var itemID = $(this).data('id');
var table = $(this).data('table');
$(this).is(':checked') ? param = 1 : null;
$.ajax({
method: 'POST',
url: '/admin/ajaxChangePhoneActiveStatus',
data: {
itemID: itemID,
param: param,
field: field,
table: table,
_token: token
}
});
});
}
$('.js-review-user__address').on('change', function () {
var userID = $(this).val();
$.ajax({
method: 'POST',
url: '/admin/ajaxGetAddress',
data: {
userID: userID,
_token: token
}
}).done(function (response) {
if (response.success === true) {
var addressID = $('#addressID');
addressID.empty();
addressID.html(response.html);
}
});
return false;
});
if ($('#jsServiceSelect').length > 0) {
$(document).on('change', '#jsServiceSelect', function (e) {
var _this = $(this);
var _thisVal = _this.val();
var value = [];
if (_thisVal !== null) {
if (_thisVal.length > 0) {
for (var i = 0; i < _thisVal.length; i++) {
if (i + 1 === _thisVal.length) {
value += _thisVal[i];
} else {
value += _thisVal[i] + ', ';
}
}
}
} else {
value = " ";
}
$('#jsServiceInput').val(value);
});
}
if ($('.jsCatServiceSelect').length > 0) {
$(document).on('change', '.jsCatServiceSelect', function (e) {
var _this = $(this);
$.ajax({
method: 'POST',
url: '/admin/ajaxGetCatServiceSelect',
data: {
catServicesID: _this.val(),
_token: token
}
}).done(function (response) {
if (response.success === true) {
var addressID = $('#addressID');
$('#jsServiceInput').val('').trigger("change");
$('#jsServiceSelect').html(response.html);
$('#jsServiceSelect').select2();
$('#jsServiceSelect').val('').trigger("change");
}
});
});
}
function colorSelect(e) {
function build($select) {
var html = '';
var listItems = '';
var span = '<span>выберите цвет</span>';
$select.find('option').each(function() {
listItems += ''+
'<li style="background:'+$(this).attr('data-color')+'" data-colorVal="'+$(this).attr('data-color')+'" data-color="'+$(this).val()+'">'+
'<span>'+$(this).text()+'</span>'+
'</li>'
;
if ($(this).attr('selected')) {
span = '<span>'+$(this).attr('data-color')+'<span style="background:'+$(this).attr('data-color')+'"></span></span>';
}
});
html = ''+
'<div class="color-select">'+
span +
'<ul>'+listItems+'</ul>'+
'</div>'
;
return html;
}
$(e).each(function() {
var $this = $(this);
$this.hide();
$this.after(build($this));
});
};
$(document).on('click', '.color-select > span', function() {
$(this).siblings('ul').toggle();
});
$(document).on('click', '.color-select li', function() {
var $this = $(this);
var color = $this.attr('data-colorVal');
var colorID = $this.attr('data-color');
var colorText = $this.find('span').text();
var $value = $this.parents('.color-select').find('span:first');
var $select = $this.parents('.color-select').prev('select');
$value.text(colorText);
$value.append('<span style="background:'+color+'"></span>');
$this.parents('ul').hide();
$select.val(colorID);
})
;
if($('.jsColorSelect').length) {
colorSelect($('.jsColorSelect'));
}
var settingsAddField = '.jsAdminSettingsAddField';
var settingsDeleteField = '.jsAdminSettingsDeleteField';
if ($(settingsAddField).length) {
$(document).on('click', settingsAddField, function () {
var $this = $(this);
$.ajax({
method: 'POST',
url: '/admin/ajaxSettingsAddNewField',
data: {
countAddField: $('.jsAdminSettingsAddFieldBlocks').length,
_token: token
}
}).done(function (response) {
if (response.success === true) {
$this.closest('.form-group').before(response.html);
}
});
});
$(document).on('click', settingsDeleteField, function () {
var $this = $(this);
$this.closest('.form-group').remove();
});
}
});
<file_sep>/app/Http/Controllers/GetEmailController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\GetEmailRequest;
use App\Models\GetEmail;
class GetEmailController extends Controller
{
public function email(GetEmailRequest $request) {
$getEmail = new GetEmail();
$getEmail->email = $request->input('email');
$getEmail->save();
return redirect()->route('email-success');
}
}
<file_sep>/public/admin/custom/users/usersEdit.js
$(document).ready(function () {
$('#js-users-roles-type-select').on('change', function () {
$.ajax({
method: 'POST',
url: '/admin/ajaxUsersTakeRolesByType',
data: {
typeID: $(this).val(),
_token: token
}
}).done(function (response) {
if (response.success === true) {
$('#js-users-roles-select').html(response.html)
}
});
});
$('#js-users-roles-city-select').on('change', function () {
$.ajax({
method: 'POST',
url: '/admin/ajaxUsersTakeRolesByCity',
data: {
cityID: $(this).val(),
_token: token
}
}).done(function (response) {
if (response.success === true) {
$('#js-users-roles-districts-select').html(response.htmlDis)
}
if (response.success === true) {
$('#js-users-roles-metro-select').html(response.htmlMetro)
}
});
});
// $('.js-time-mask').mask("+7 (999) 999-99-99");
//Accordeon (admin)
$('.js-bb-accordeon').find('.bb-accordeon__item').find('.bb-accordeon__title').on('click', function () {
if ($(this).parent().hasClass('is-open')) {
$(this).parent().removeClass('is-open').find('.bb-accordeon__content').css('display', 'none');
} else {
$(this).parent().addClass('is-open').find('.bb-accordeon__content').removeAttr('style');
}
});
$('.js-service-check__div').on('click', function () {
var _this = $(this);
if (!_this.hasClass('is-checked')) {
_this.addClass('is-checked');
_this.children('input.active').attr( "value", 1 );
} else {
_this.removeClass('is-checked');
_this.children('input.active').attr( "value", 0 );
}
});
$('.js-label-active').on('click', function () {
var _this = $(this);
if(!_this.parent('.js-service-check__div').hasClass('is-checked')){
_this.parent('.js-service-check__div').addClass('is-checked');
_this.prev('.active').attr( "value", 1 );
} else {
_this.parents('.js-service-check__div').removeClass('is-checked');
_this.prev('.active').attr( "value", 0 );
}
});
var inputElement = $('.js-service-input');
inputElement.on('input', function () {
$(this).parent().removeClass('is-invalid');
if ($(this).val() === '') {
$(this).parent().addClass('is-invalid');
}
});
inputElement.on('change', function () {
var _this = $(this);
var price;
var time;
if (_this.hasClass('js-i-time')) {
if (_this.val() !== '' && _this.parent().prev().children('.js-i-price').val() !== '') {
price = _this.parent().prev().children('.js-i-price').val();
time = _this.val();
}
}
if (_this.hasClass('js-i-price')) {
if (_this.val() !== '' && _this.parent().next().children('.js-i-time').val() !== '') {
price = _this.val();
time = _this.parent().next().children('.js-i-time').val();
}
}
});
$('.service-item__field').on('click', function () {
var _this = $(this);
if (_this.find('.js-service-input').attr('readonly')) {
_this.parent('.service-item').children('.js-service-check__div').addClass('is-checked');
_this.find('.js-service-input').removeAttr('readonly', '');
_this.parent('.service-item').find('#active').attr( "value", 1 );
}
});
// Map
if ($('.js-cabinet__map').length > 0) {
ymaps.ready(initCabinetMap);
}
if ($('.jsGeoMap').length > 0) {
$(document).on('keyup', '.jsGeoMap', function () {
geoMap($(this).val(), null, null);
});
}
if ($('#jsCategoriesSelect').length > 0) {
$(document).on('change', '#jsCategoriesSelect', function () {
var _this = $(this);
var _thisVal = _this.val();
var value = [];
if (_thisVal !== null) {
if (_thisVal.length > 0) {
for (var i = 0; i < _thisVal.length; i++) {
if (i + 1 === _thisVal.length) {
value += _thisVal[i];
} else {
value += _thisVal[i] + ', ';
}
}
}
} else {
value = " ";
}
$('#jsCategoriesInput').val(value);
});
}
$('.select2').select2();
if ($("#select-profile").val() != '') {
const URIString = document.documentURI;
const dividedString = URIString.split('/');
$.ajax({
url: '/admin/ajaxGetUserDepartments',
type: 'POST',
data: {
_token: token,
userID: dividedString[dividedString.length - 1] // ID пользователя, полученное из адресной строки
}
}).done(function(response) {
$(".select-department-holder").html(response.html);
$("#select-department").select2();
});
}
$("#select-profile").on("change", function(e) {
$.ajax({
url: '/admin/ajaxGetUserDepartmentsByDepartmentId',
type: 'POST',
data: {
_token: token,
departmentID: $("#select-profile").val()
}
}).done(function(response) {
$(".select-department-holder").html(response.html);
$("#select-department").select2();
})
})
});
var balloon = {
iconLayout: 'default#image',
iconImageHref: '/client/files/icons/svg/map-pin.svg',
iconImageSize: [30, 42],
iconImageOffset: [-3, -42]
};
function initCabinetMap() {
var myMap;
var myPlaceMark;
var coordXInput = $('#latitude');
var coordYInput = $('#longitude');
var coordX;
var coordY;
if (coordXInput.val() === '' && coordYInput.val() === '') {
coordX = 55.742909;
coordY = 37.6275;
} else {
coordX = coordXInput.val();
coordY = coordYInput.val();
}
myMap = new ymaps.Map('card-map', {
center: [coordX, coordY],
zoom: 17
});
myPlaceMark = new ymaps.Placemark([coordX, coordY], {}, balloon);
myMap.events.add('click', function (e) {
var coords = e.get('coords');
coordXInput.val(coords[0]);
coordYInput.val(coords[1]);
myMap.geoObjects.remove(myPlaceMark);
myPlaceMark = new ymaps.Placemark([coords[0], coords[1]], {}, balloon);
myMap.geoObjects.add(myPlaceMark);
});
// myMap.behaviors.disable(['scrollZoom']);
myMap.controls.remove('typeSelector');
myMap.geoObjects.add(myPlaceMark);
$('.js-profile-contact__city').on('change', function () {
var cityID = $(this).val();
$.ajax({
method: 'POST',
url: '/ajaxGetMetroOrDistrict',
data: {
cityID: cityID,
_token: token
}
}).done(function (response) {
if (response.success === true) {
// myMap.setCenter([response.coordY, response.coordX], 13);
var type = response.type;
var metroBlock = $('.js-profile-contact__metro-block');
var districtBlock = $('.js-profile-contact__district-block');
var select;
if (type === 'metro') {
metroBlock.removeClass('is-hidden');
districtBlock.addClass('is-hidden');
select = $('.js-profile-contact__metro');
}
if (type === 'district') {
districtBlock.removeClass('is-hidden');
metroBlock.addClass('is-hidden');
select = $('.js-profile-contact__district');
}
if (type === '') {
districtBlock.addClass('is-hidden');
metroBlock.addClass('is-hidden');
} else {
var data = JSON.parse(response.html);
var arrData = [{'id': 0, 'text': 'Не выбран'}];
$.each(data, function (key, name) {
arrData.push({'id': key, 'text': name});
});
select.html('').select2({data: arrData});
}
var street = $('.js-profile-contact__home').val();
var number = $('.js-profile-contact__number').val();
if(street === ""){
street = null;
}
if(number === ""){
number = null;
}
geoMap(response.cityName, street, number);
}
});
return false;
});
$(document).on('keyup', '.js-profile-contact__home', function () {
var city = $('.js-profile-contact__city').find("option:selected").text();
var number = $('.js-profile-contact__number').val();
if(number === ""){
number = null;
}
geoMap(city, $(this).val(), number);
});
$(document).on('keyup', '.js-profile-contact__number', function () {
var city = $('.js-profile-contact__city').find("option:selected").text();
var street = $('.js-profile-contact__home').val();
if(street === ""){
street = null;
}
geoMap(city, street, $(this).val());
});
}
function geoMap(city, street, number) {
var myGeocoder = "";
if (city !== null && street !== null && number !== null) {
myGeocoder = ymaps.geocode(city+', '+street+', '+number);
} else if (city !== null && street !== null) {
myGeocoder = ymaps.geocode(city+', '+street);
} else if (city !== null) {
myGeocoder = ymaps.geocode(city);
} else {
myGeocoder = ymaps.geocode('Москва');
}
var myMap;
var myPlaceMark;
var coordX;
var coordY;
myGeocoder.then(
function (res) {
var coords = res.geoObjects.get(0).geometry.getCoordinates();
myGeocoder.then(
function (res) {
$('#card-map').html('');
coordX = coords[0];
coordY = coords[1];
myMap = new ymaps.Map('card-map', {
center: [coordX, coordY],
zoom: 17
});
$('#coordX').attr('value', coordX);
$('#coordY').attr('value', coordY);
myPlaceMark = new ymaps.Placemark([coordX, coordY], {}, balloon);
myMap.geoObjects.add(myPlaceMark);
myMap.events.add('click', function (e) {
var coords = e.get('coords');
$('#coordX').attr('value', coords[0]);
$('#coordY').attr('value', coords[1]);
myMap.geoObjects.remove(myPlaceMark);
myPlaceMark = new ymaps.Placemark([coords[0], coords[1]], {}, balloon);
myMap.geoObjects.add(myPlaceMark);
});
}
);
}
);
}
<file_sep>/app/Http/Requests/GetEmailRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class GetEmailRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => 'required|unique:get_emails,email|email:rfc,dns',
];
}
public function messages()
{
return [
'email.email' => 'Ой, видимо, вы ошиблись — такого адреса почты не существует.',
'email.unique' => 'Ой, а такой адрес почты уже кто-то оставил.',
'email.required' => 'Ой, а вы забыли написать свой адрес почты.',
];
}
}
<file_sep>/public/admin/custom/auth.js
$(document).ready(function() {
$('.jsMpAdminAuth').parsley();
}); | 031ad7b55b81b9ab3b24052263acb08afaeae959 | [
"JavaScript",
"PHP"
] | 8 | JavaScript | vasilysmolin/laravel-blog | 980f82450f61c56cbe17db7b16c4d00969499838 | d88d9b2319d5687a26af3830ca48bba1390de042 |
refs/heads/master | <repo_name>lukasz-kaniowski/spring-mongo-rabbitmq<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lukaszkaniowski</groupId>
<artifactId>spring-mongo-rabbitmq</artifactId>
<version>1.0</version>
<name>spring-mongo-rabbitmq</name>
<packaging>war</packaging>
<properties>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.springframework.mobile-version>1.0.0.RELEASE</org.springframework.mobile-version>
<org.aspectj-version>1.6.9</org.aspectj-version>
<org.slf4j-version>1.6.1</org.slf4j-version>
<log4j-version>1.2.16</log4j-version>
<javax.servlet.api-version>2.5</javax.servlet.api-version>
<javax.servlet.jsp-version>2.1</javax.servlet.jsp-version>
<javax.servlet.jstl-version>1.2</javax.servlet.jstl-version>
<spring-integration-core.version>2.1.3.RELEASE</spring-integration-core.version>
<maven-jetty-plugin.version>6.1.26</maven-jetty-plugin.version>
<spring-data-mongodb.version>1.0.2.RELEASE</spring-data-mongodb.version>
<sitemesh.version>2.4.2</sitemesh.version>
<spring-data-redis.version>1.0.1.RELEASE</spring-data-redis.version>
</properties>
<dependencies>
<!-- CloudFoundry -->
<dependency>
<groupId>org.cloudfoundry</groupId>
<artifactId>cloudfoundry-runtime</artifactId>
<version>0.8.1</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-core</artifactId>
<version>${spring-integration-core.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId>
<version>${org.springframework.mobile-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring-data-mongodb.version}</version>
</dependency>
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring-data-redis.version}</version>
</dependency>
<!-- Aspect J -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
<scope>runtime</scope>
</dependency>
<!-- Jackson JSON Processor -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.1</version>
</dependency>
<!-- Joda Time Library -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6.2</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${javax.servlet.api-version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${javax.servlet.jsp-version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${javax.servlet.jstl-version}</version>
</dependency>
<!-- Sitemesh -->
<dependency>
<groupId>opensymphony</groupId>
<artifactId>sitemesh</artifactId>
<version>${sitemesh.version}</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<version>2.0M7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring</finalName>
<plugins>
<!-- With this you can start the server by doing mvn jetty:run -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${maven-jetty-plugin.version}</version>
<configuration>
<scanIntervalSeconds>3</scanIntervalSeconds>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>org.springframework.maven.milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project><file_sep>/README.md
spring-mongo-rabbitmq
=====================
[](http://secure.travis-ci.org/lukasz-kaniowski/spring-mongo-rabbitmq)
Sample spring application with mongo and rabbitmq.
This app is live on cloudfoundry [link to app][2]
## MongoDb - Spring Data
* Model mapping
* Map Reduce example
* Spring data repository (with custom repository methods)
* Use of mongo template
Check junit tests [PersonRepositoryTest][1]
## Redis - Spring Data
* RedisTemplate usage
* Redis: Value, List, Counters
* Publish Subscribe Events
Check junit tests [RedisRepositoryTest][5] and [RedisPublisherTest][6]
## Frontend
* Spring mvc
* i18n
* Layouts with [sitemesh][3]
* Styling using [Twitter Bootstrap][4]
[1]: spring-mongo-rabbitmq/blob/master/src/test/java/com/lkan/sample/mongo/repository/PersonRepositoryTest.java
[2]: http://ukasz-spring.cloudfoundry.com/
[3]: http://wiki.sitemesh.org/display/sitemesh/Home
[4]: http://twitter.github.com/bootstrap/
[5]: spring-mongo-rabbitmq/blob/master/src/test/java/com/lkan/sample/redis/RedisRepositoryTest.java
[6]: spring-mongo-rabbitmq/blob/master/src/test/java/com/lkan/sample/redis/RedisPublisherTest.java
<file_sep>/src/main/java/com/lkan/sample/redis/RedisRepository.java
package com.lkan.sample.redis;
import com.lkan.sample.mongo.repository.Person;
import java.util.List;
/**
* Repository for redis
*
* @author <NAME>
*/
public interface RedisRepository {
/**
* Saves value for given key
*
* @param key
* @param value
*/
void save(String key, String value);
/**
* Get value for key
*
* @param key
* @return
*/
String get(String key);
/**
* Get current value of counter
*
* @return
*/
Long getOperationCount();
/**
* Clears counter
*/
void clearCounter();
/**
* Save msg on list for key 'pub_sub_msg'
*
* @param msg
*/
void saveMessage(String msg);
/**
* Get list for key 'pub_sub_msg'
*
* @return
*/
List<String> getMessages();
/**
* Clears redis database
*/
void flushDb();
}
<file_sep>/src/main/java/com/lkan/sample/mongo/builder/PersonBuilder.java
package com.lkan.sample.mongo.builder;
import com.lkan.sample.mongo.repository.Person;
import com.lkan.sample.mongo.repository.Pet;
public class PersonBuilder {
private String name;
private final Person person;
public PersonBuilder() {
person = new Person();
}
public static PersonBuilder aPerson() {
return new PersonBuilder();
}
public PersonBuilder withName(String name) {
person.setName(name);
return this;
}
public PersonBuilder withAge(int age) {
person.setAge(age);
return this;
}
public PersonBuilder withPet(Pet pet){
person.addPet(pet);
return this;
}
public Person build() {
return person;
}
}<file_sep>/src/main/java/com/lkan/sample/mongo/mapReduce/MapReduceResult.java
package com.lkan.sample.mongo.mapReduce;
import java.util.HashMap;
/**
* TODO lkan; javadoc
*
* @author <NAME>
*/
public class MapReduceResult extends HashMap {
}
<file_sep>/src/main/resources/mapReduce/petsMap.js
function () {
this.pets.forEach(
function(z) {
emit(z.type, { count:1 });
}
)
}<file_sep>/src/main/java/com/lkan/sample/mongo/mapReduce/ValueObject.java
package com.lkan.sample.mongo.mapReduce;
import java.util.HashMap;
/**
* TODO lkan; javadoc
*
* @author <NAME>
*/
public class ValueObject {
private String id;
private HashMap value;
public String getId() {
return id;
}
public HashMap getValue() {
return value;
}
public void setValue(HashMap value) {
this.value = value;
}
@Override
public String toString() {
return "ValueObject [id=" + id + ", value=" + value + "]";
}
}
<file_sep>/src/main/resources/messages_pl.properties
navbar.home=Dom
home.title=Home
mongo.title=MongoDB with Spring Data
navbar.mongo=MongoDB
<file_sep>/src/main/java/com/lkan/sample/mongo/repository/PersonRepository.java
package com.lkan.sample.mongo.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
/**
* Person repository
*
* @author <NAME>
*/
public interface PersonRepository extends MongoRepository<Person, String>, PersonRepositoryCustom {
Person findByName(String name);
@Query("{ 'name' : ?0 }")
List<Person> findQueryExample(String name);
}
<file_sep>/src/main/resources/messages.properties
navbar.home=Home
navbar.lang=Language
navbar.lang.en=English
navbar.lang.pl=Polski
navbar.mongo=MongoDB
home.title=Home
mongo.title=MongoDB with Spring Data
<file_sep>/src/main/java/com/lkan/sample/mongo/repository/PersonRepositoryCustom.java
package com.lkan.sample.mongo.repository;
import com.lkan.sample.mongo.mapReduce.MapReduceResult;
import java.util.List;
/**
* TODO lkan; javadoc
*
* @author <NAME>
*/
public interface PersonRepositoryCustom {
List<Person> complicatedSearch();
MapReduceResult countPetsForPeopleOlderThan(int age);
}
<file_sep>/src/main/java/com/lkan/sample/home/HomeController.java
package com.lkan.sample.home;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* TODO lkan; javadoc
*
* @author <NAME>
*/
@Controller
@RequestMapping("/")
public class HomeController {
@RequestMapping(method = RequestMethod.GET)
public String show(ModelMap model) {
return "/home";
}
@RequestMapping(value = "/mu-40e93541-db42b8f5-36bd0540-dcbf7834", method = RequestMethod.GET)
@ResponseBody
public String blitz_io(ModelMap model) {
return "42";
}
}
<file_sep>/src/main/java/com/lkan/sample/redis/RedisMessageListener.java
package com.lkan.sample.redis;
import org.springframework.beans.factory.annotation.Autowired;
/**
* TODO lkan; javadoc
*
* @author <NAME>
*/
public class RedisMessageListener {
@Autowired
private RedisRepository redisRepository;
public void handleMessage(String msg) {
redisRepository.saveMessage(msg);
}
}
<file_sep>/src/main/java/com/lkan/sample/redis/RedisRepositoryImpl.java
package com.lkan.sample.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* TODO lkan; javadoc
*
* @author <NAME>
*/
@Repository
public class RedisRepositoryImpl implements RedisRepository {
private static final String PUB_SUB_MSG = "pub_sub_msg";
private final StringRedisTemplate stringRedisTemplate;
private final ValueOperations<String, String> valueOps;
private final RedisAtomicLong counter;
@Autowired
public RedisRepositoryImpl(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
valueOps = stringRedisTemplate.opsForValue();
counter = new RedisAtomicLong("counter", stringRedisTemplate.getConnectionFactory());
}
@Override
public void save(String key, String value) {
valueOps.set(key, value);
counter.incrementAndGet();
}
@Override
public String get(String key) {
return valueOps.get(key);
}
@Override
public Long getOperationCount() {
return counter.get();
}
@Override
public void clearCounter() {
counter.set(0L);
}
@Override
public void saveMessage(String msg) {
stringRedisTemplate.opsForList().leftPush(PUB_SUB_MSG, msg);
}
@Override
public void flushDb() {
stringRedisTemplate.getConnectionFactory().getConnection().flushDb();
}
@Override
public List<String> getMessages() {
return stringRedisTemplate.opsForList().range(PUB_SUB_MSG, 0, -1);
}
}
<file_sep>/src/test/java/com/lkan/sample/redis/RedisPublisherTest.java
package com.lkan.sample.redis;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.fest.assertions.api.Assertions.assertThat;
/**
* TODO lkan; javadoc
*
* @author <NAME>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring/appServlet/redis.xml")
public class RedisPublisherTest {
@Autowired
private RedisPublisher redisService;
@Autowired
private RedisRepository redisRepository;
@Before
public void setup() {
redisRepository.flushDb();
}
@Test
public void shouldPublishMsgWithoutError() throws Exception {
redisService.publish("Some message!");
Thread.sleep(10); //wait for asynchronous call to finish
assertThat(redisRepository.getMessages().size()).isEqualTo(1);
assertThat(redisRepository.getMessages().get(0)).isEqualTo("Some message!");
}
}
<file_sep>/src/main/java/com/lkan/sample/mongo/MongoController.java
package com.lkan.sample.mongo;
import com.lkan.sample.mongo.repository.Person;
import com.lkan.sample.mongo.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
/**
* Controller for mongo
*
* @author <NAME>
*/
@Controller
@RequestMapping("/mongo/")
public class MongoController {
@Autowired
PersonRepository personRepository;
@RequestMapping(method = RequestMethod.GET)
public String show(ModelMap model) {
List<Person> all = personRepository.findAll();
model.addAttribute("people", all);
return "mongo";
}
@RequestMapping(method = RequestMethod.POST)
public String addPerson(@ModelAttribute Person person, Model model, BindingResult result) {
personRepository.save(person);
return "redirect:/mongo/";
}
@RequestMapping(method = RequestMethod.GET, value = "clearDb")
public String clearDb(ModelMap model) {
personRepository.deleteAll();
List<Person> all = personRepository.findAll();
model.addAttribute("people", all);
return "peopleList";
}
}
| 6ad15a9f28da8fe6e0db27d057873692f76d7dc1 | [
"Markdown",
"JavaScript",
"Maven POM",
"INI",
"Java"
] | 16 | Maven POM | lukasz-kaniowski/spring-mongo-rabbitmq | 44fbd4b6d363c00eea11c98cbafdfa7208e9406b | f7b9e3e6568f2a3255765401cf2d13d2aa21f237 |
refs/heads/master | <repo_name>abhishek-shigavan/Flip_Coin_Simulation<file_sep>/flipCoinSimulator.sh
#!/bin/bash -x
isHead=0
isTail=1
headCounter=0
tailCounter=0
gameCounter=0
winCounter=21
afterEqualMargin=2
equalCountPosition=0
for((i=0; i<=41; i++))
do
((gameCounter++))
coinSimulator=$(($RANDOM%2))
if [ $coinSimulator -eq $isHead ]
then
((headCounter++))
headCounter=$headCounter
else
((tailCounter++))
tailCounter=$tailCounter
fi
margin=$(($headCounter - $tailCounter))
margin=${margin#-}
if [ $gameCounter -eq 1 ]
then
continue
elif [ $headCounter -eq $winCounter -o $tailCounter -eq $winCounter ]
then
break
elif [ $headCounter -eq $tailCounter ]
then
equalCountPosition=$gameCounter
elif [ $equalCountPosition -eq 0 ]
then
continue
elif [ $gameCounter -gt $equalCountPosition -a $margin -eq $afterEqualMargin ]
then
break
fi
done
if [ $headCounter -gt $tailCounter ]
then
echo " Head is the Winner "
echo " Winning Margin : $margin "
elif [ $tailCounter -gt $headCounter ]
then
echo " Tail is the Winner "
echo " Winning Margin : $margin "
fi
| 277749525d4ca5d27f4231e6bdeba41d54219310 | [
"Shell"
] | 1 | Shell | abhishek-shigavan/Flip_Coin_Simulation | 006802c9035ff638f30957ae701ae47efd774f1f | ae2aa73aa25d72ceaef0ba8c75c848f4ea8c5b63 |
refs/heads/master | <file_sep>package main
import (
"github.com/ocelot93/gofirst/003-packages/cat"
)
func main() {
cat.Hello()
cat.Meow("meow")
}<file_sep>package main
import (
"fmt"
)
type Human interface {
Speak()
}
type Person struct {
Name string
Age int
}
func (p *Person) Speak() {
fmt.Println("Hello")
}
func saySomething(h Human) {
h.Speak()
}
func main() {
p1 := Person{"Ilya", 25}
saySomething(&p1) //need to specify a pointer here for code to work properly
p1.Speak()
}
<file_sep>package cat
import "fmt"
func Hello() {
fmt.Println("Hello from cat")
}
func Meow(a string) {
fmt.Printf("%s\n", a)
}<file_sep>package main
import (
"net"
"log"
"fmt"
"bufio"
)
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
go HandleFunc(conn)
}
}
func HandleFunc(conn net.Conn) {
name := conn.RemoteAddr().String()
fmt.Printf("%+v just joined the network\n", name)
conn.Write([]byte("Hello," + name + ", my dear nigga" + "\n\r"))
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
text := scanner.Text()
if text == "Exit" {
conn.Write([]byte("Goodbye\n\r"))
break
} else if text != "" {
conn.Write([]byte("You have just enetered this:" + text + "\n\r"))
}
}
} | 82bed8d385732554ecb35393443dd70530b4b541 | [
"Go"
] | 4 | Go | ocelot93/gofirst | d8bb2df9ca441cc7cb86a21b25b7a3b6f0d69c19 | e59e985df2355d6347be404be73f586e87f63034 |
refs/heads/master | <repo_name>xalfonso/perfilac1.0<file_sep>/Perfilac/visual/Administrar Usuarios.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Perfilac.servicio;
using Perfilac.dominio;
namespace Perfilac.visual
{
public partial class Administrar_Usuarios : Form
{
public Administrar_Usuarios(Service servicio)
{
InitializeComponent();
this.servicio = servicio;
actualizarListadoUsuario();
}
private Boolean agregarUser;
public Boolean AgregarUser
{
get { return agregarUser; }
set { agregarUser = value; }
}
private Boolean modificarUser;
public Boolean ModificarUser
{
get { return modificarUser; }
set { modificarUser = value; }
}
private Service servicio;
public Service Servicio
{
get { return servicio; }
set { servicio = value; }
}
private void actualizarListadoUsuario()
{
listBox1.Items.Clear();
listBox1.Items.AddRange(servicio.listarUsuarios().ToArray());
}
private void button1_Click(object sender, EventArgs e)
{
}
private void Administrar_Usuarios_Load(object sender, EventArgs e)
{
}
private void seleccionarUsuario()
{
if (listBox1.SelectedIndex != -1)
{
Usuario user = (Usuario)listBox1.SelectedItem;
textBox1.Text = user.PrimerNombre;
textBox2.Text = user.SegundoNombre;
textBox3.Text = user.PrimerApellido;
textBox4.Text = user.SegundoApellido;
textBox5.Text = user.User;
textBox6.Text = user.Pass;
textBox7.Text = user.Pass;
textBox8.Text = user.Id.ToString();
}
}
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
seleccionarUsuario();
}
private void button2_Click(object sender, EventArgs e)
{
textBox7.Visible = false;
label8.Visible = false;
textBox7.Clear();
button3.Text = "Modificar";
listBox1.SelectedIndex = -1;
modificarUser = false;
if (agregarUser)
{
Boolean validacion = false;
String mensaje = "";
if (textBox1.Text.Length < 1 || textBox3.Text.Length < 1 || textBox4.Text.Length < 1 || textBox5.Text.Length < 1 || textBox6.Text.Length<1)
{
validacion = true;
mensaje = ", No debe haber campos vacios exceptuado el Segundo Nombre";
}
if (textBox5.Text.Length < 4 || textBox6.Text.Length < 7)
{
validacion = true;
mensaje += ", el usuario debe tener más de 3 caracteres y las contraseña más de 6.";
}
if (!validacion)
{
Usuario nuevoUser = new Usuario(textBox5.Text, textBox6.Text, textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
servicio.salvarUsuario(nuevoUser);
actualizarListadoUsuario();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
//-----------------------
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
button2.Text = "Agregar";
agregarUser = false;
}
else
{
MessageBox.Show("Verifique los datos"+mensaje+"", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
//----------------------------
textBox1.ReadOnly = false;
textBox2.ReadOnly = false;
textBox3.ReadOnly = false;
textBox4.ReadOnly = false;
textBox5.ReadOnly = false;
textBox6.ReadOnly = false;
agregarUser = true;
button2.Text = "Agregar!";
}
}
private void button3_Click(object sender, EventArgs e)
{
button2.Text = "Agregar";
agregarUser = false;
if (listBox1.SelectedIndex != -1)
{
if (modificarUser)
{
Boolean validacion = false;
String mensaje = "";
if (textBox1.Text.Length < 1 || textBox3.Text.Length < 1 || textBox4.Text.Length < 1 || textBox5.Text.Length < 1 || textBox6.Text.Length < 1)
{
validacion = true;
mensaje = ", No debe haber campos vacios exceptuado el Segundo Nombre";
}
if (textBox5.Text.Length < 4 || textBox6.Text.Length < 7)
{
validacion = true;
mensaje += ", el usuario debe tener más de 3 caracteres y las contraseña más de 6";
}
if (textBox6.Text != textBox7.Text)
{
validacion = true;
mensaje += "; las contraseñas deben coincidir.";
}
if (!validacion)
{
Usuario nuevoUser = new Usuario(textBox5.Text, textBox6.Text, textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
nuevoUser.Id = int.Parse(textBox8.Text);
servicio.modificarUsuario(nuevoUser);
actualizarListadoUsuario();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
//-----------------------
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
textBox7.Visible = false;
label8.Visible = false;
button3.Text = "Modificar";
modificarUser = false;
}
else
{
MessageBox.Show("Verifique los datos" + mensaje + "", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
//textBox1.Clear();
//textBox2.Clear();
//textBox3.Clear();
//textBox4.Clear();
//textBox5.Clear();
//textBox6.Clear();
//----------------------------
textBox1.ReadOnly = false;
textBox2.ReadOnly = false;
textBox3.ReadOnly = false;
textBox4.ReadOnly = false;
textBox5.ReadOnly = false;
textBox6.ReadOnly = false;
textBox7.Visible = true;
label8.Visible = true;
modificarUser = true;
button3.Text = "Modificar!";
}
}
else
MessageBox.Show("Debe seleccionar el usuario", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void button1_Click_1(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
if (MessageBox.Show("Se eliminará el usuario seleccionado, ¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
this.servicio.eliminarUsuario(int.Parse(textBox8.Text));
actualizarListadoUsuario();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
}
}
else
MessageBox.Show("Debe seleccionar el usuario", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void button3_Click_1(object sender, EventArgs e)
{
button2.Text = "Agregar";
agregarUser = false;
if (listBox1.SelectedIndex != -1)
{
if (modificarUser)
{
Boolean validacion = false;
String mensaje = "";
if (textBox1.Text.Length < 1 || textBox3.Text.Length < 1 || textBox4.Text.Length < 1 || textBox5.Text.Length < 1 || textBox6.Text.Length < 1)
{
validacion = true;
mensaje = ", No debe haber campos vacios exceptuado el Segundo Nombre";
}
if (textBox5.Text.Length < 4 || textBox6.Text.Length < 7)
{
validacion = true;
mensaje += ", el usuario debe tener más de 3 caracteres y las contraseña más de 6";
}
if (textBox6.Text != textBox7.Text)
{
validacion = true;
mensaje += "; las contraseñas deben coincidir.";
}
if (!validacion)
{
Usuario nuevoUser = new Usuario(textBox5.Text, textBox6.Text, textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
nuevoUser.Id = int.Parse(textBox8.Text);
servicio.modificarUsuario(nuevoUser);
actualizarListadoUsuario();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
//-----------------------
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
textBox7.Visible = false;
label8.Visible = false;
button3.Text = "Modificar";
modificarUser = false;
}
else
{
MessageBox.Show("Verifique los datos" + mensaje + "", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
//textBox1.Clear();
//textBox2.Clear();
//textBox3.Clear();
//textBox4.Clear();
//textBox5.Clear();
//textBox6.Clear();
//----------------------------
textBox1.ReadOnly = false;
textBox2.ReadOnly = false;
textBox3.ReadOnly = false;
textBox4.ReadOnly = false;
textBox5.ReadOnly = false;
textBox6.ReadOnly = false;
textBox7.Visible = true;
label8.Visible = true;
modificarUser = true;
button3.Text = "Modificar!";
}
}
else
MessageBox.Show("Debe seleccionar el usuario", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}<file_sep>/README.md
# perfilac1.0
Project for perfilac company (1.0)
<file_sep>/Perfilac/dominio/Usuario.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class Usuario:EntidadPersistente
{
public Usuario(String user,String pass,String primerNombre,String segundoNombre,String primerApellido,String segundoApellido)
{
this.user = user;
this.pass = <PASSWORD>;
this.primerNombre = primerNombre;
this.segundoNombre = segundoNombre;
this.primerApellido = primerApellido;
this.segundoApellido = segundoApellido;
}
private String user;
public String User
{
get { return user; }
set { user = value; }
}
private String pass;
public String Pass
{
get { return pass; }
set { pass = value; }
}
private String primerNombre;
public String PrimerNombre
{
get { return primerNombre; }
set { primerNombre = value; }
}
private String segundoNombre;
public String SegundoNombre
{
get { return segundoNombre; }
set { segundoNombre = value; }
}
private String primerApellido;
public String PrimerApellido
{
get { return primerApellido; }
set { primerApellido = value; }
}
private String segundoApellido;
public String SegundoApellido
{
get { return segundoApellido; }
set { segundoApellido = value; }
}
public override string ToString()
{
return (this.user == null ? "" : this.user + " ");
}
}
}
<file_sep>/Perfilac/dominio/Cliente.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class Cliente:EntidadPersistente
{
private String codigo;
public String Codigo
{
get { return codigo; }
set { codigo = value; }
}
private String nombre;
public String Nombre
{
get { return nombre; }
set { nombre = value; }
}
private String contrato;
public String Contrato
{
get { return contrato; }
set { contrato = value; }
}
private String direccion;
public String Direccion
{
get { return direccion; }
set { direccion = value; }
}
private List<PersonaCliente> comerciales;
public List<PersonaCliente> Comerciales
{
get { return comerciales; }
set { comerciales = value; }
}
private String cuentaCUC;
public String CuentaCUC
{
get { return cuentaCUC; }
set { cuentaCUC = value; }
}
private String cuentaCUP;
public String CuentaCUP
{
get { return cuentaCUP; }
set { cuentaCUP = value; }
}
public Cliente(String codigo, String nombre, String contrato, String direccion, List<PersonaCliente> comerciales, String cuentaCUP, String cuentaCUC): base()
{
this.codigo = codigo;
this.nombre = nombre;
this.contrato = contrato;
this.direccion = direccion;
this.comerciales = comerciales;
this.cuentaCUP = cuentaCUP;
this.cuentaCUC = cuentaCUC;
}
public override string ToString()
{
return this.nombre;
}
}
}
<file_sep>/Perfilac/origen datos/DaoConecction.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Odbc;
using System.Data.Common;
namespace Perfilac.origen_datos
{
public class DaoConecction
{
static private OdbcConnection conexion;
//static private String cadenaConexion = "Driver={Microsoft Access Driver (*.mdb)};" + "Dbq=C:\\Documents and Settings\\ealfonso\\Mis documentos\\Codigo Perfilac\\Perfilac\\BD\\Perfilac.mdb;Uid=Eduardo;Pwd=Eduardo;";
static private String cadenaConexion = "Driver={Microsoft Access Driver (*.mdb)};" + "Dbq=..\\..\\..\\BD\\Perfilac.mdb;Uid=Eduardo;Pwd=<PASSWORD>;";
public OdbcConnection getConexion()
{
//if (conexion == null)
// conexion = new OdbcConnection(cadenaConexion);
conexion = new OdbcConnection(cadenaConexion);
return conexion;
}
}
}
<file_sep>/Perfilac/dao/NomencladorDao.cs
using System;
using System.Collections.Generic;
using System.Text;
using Perfilac.dominio;
using Perfilac.origen_datos;
using System.Data.Common;
using System.Data.Odbc;
using System.Data.SqlClient;
namespace Perfilac.dao
{
public class NomencladorDao:DaoGenerico
{
public NomencladorDao():base()
{
}
public List<TipoProducto> obtenerTiposProductos()
{
OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = conect.CreateCommand();
//SqlCommand comand1 = conect.CreateCommand();
command.CommandText = "Select id,nombre from NTipo;";
List<TipoProducto> result = new List<TipoProducto>();
try
{
conect.Open();
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
TipoProducto nuevo = new TipoProducto((String)reader["nombre"]);
nuevo.Id = int.Parse(reader["id"].ToString());
result.Add(nuevo);
}
reader.Close();
conect.Close();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
public List<TipoEnchape> obtenerTiposEnchapes()
{
OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = conect.CreateCommand();
command.CommandText = "Select id,nombre from NTipoEnchape;";
List<TipoEnchape> result = new List<TipoEnchape>();
try
{
conect.Open();
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
TipoEnchape nuevo = new TipoEnchape((String)reader["nombre"]);
nuevo.Id = int.Parse(reader["id"].ToString());
result.Add(nuevo);
}
reader.Close();
conect.Close();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
}
}
<file_sep>/Perfilac/dominio/PersonaCliente.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class PersonaCliente:EntidadPersistente
{
private String primerNombre;
public String PrimerNombre
{
get { return primerNombre; }
set { primerNombre = value; }
}
private String segundoNombre;
public String SegundoNombre
{
get { return segundoNombre; }
set { segundoNombre = value; }
}
private String primerApellido;
public String PrimerApellido
{
get { return primerApellido; }
set { primerApellido = value; }
}
private String segundoApellido;
public String SegundoApellido
{
get { return segundoApellido; }
set { segundoApellido = value; }
}
private String ci;
public String CI
{
get { return ci; }
set { ci = value; }
}
private String telefono;
public String Telefono
{
get { return telefono; }
set { telefono = value; }
}
private String cargo;
public String Cargo
{
get { return cargo; }
set { cargo = value; }
}
private Cliente cliente;
public Cliente Cliente
{
get { return cliente; }
set { cliente = value; }
}
public PersonaCliente(String primerNombre,String segundoNombre,String primerApellido,String segundoApellido,String ci,String telefono,String cargo):base()
{
this.primerNombre = primerNombre;
this.segundoNombre = segundoNombre;
this.primerApellido = primerApellido;
this.segundoApellido = segundoApellido;
this.ci = ci;
this.telefono = telefono;
this.cargo = cargo;
}
public String nombreCompleto()
{
return (this.primerNombre == null ? "" : this.primerNombre + " ") + (this.segundoNombre == null ? "" : this.segundoNombre + " ") + (this.primerApellido == null ? "" : this.primerApellido + " ") + (this.segundoApellido == null ? "" : this.segundoApellido);
}
public override string ToString()
{
return (this.primerNombre == null ? "" : this.primerNombre + " ") + (this.segundoNombre == null ? "" : this.segundoNombre + " ") + (this.primerApellido == null ? "" : this.primerApellido + " ") + (this.segundoApellido == null ? "" : this.segundoApellido);
}
}
}
<file_sep>/Perfilac/dominio/Producto.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class Producto:EntidadPersistente
{
private String codigo;
public String Codigo
{
get { return codigo; }
set { codigo = value; }
}
private String descripcion;
public String Descripcion
{
get { return descripcion; }
set { descripcion = value; }
}
private int noFicha;
public int NoFicha
{
get { return noFicha; }
set { noFicha = value; }
}
private double precioCUP;
public double PrecioCUP
{
get { return precioCUP; }
set { precioCUP = value; }
}
private double precioCUC;
public double PrecioCUC
{
get { return precioCUC; }
set { precioCUC = value; }
}
private String suministrador;
public String Suministrador
{
get { return suministrador; }
set { suministrador = value; }
}
private String color;
public String Color
{
get { return color; }
set { color = value; }
}
private TipoProducto tipo;
public TipoProducto Tipo
{
get { return tipo; }
set { tipo = value; }
}
private TipoEnchape enchape;
public TipoEnchape Enchape
{
get { return enchape; }
set { enchape = value; }
}
public Producto(String codigo,String descripcion,int noFicha,double precioCUC,double precioCUP,String suministrador,String color,TipoEnchape enchape,TipoProducto tipo):base()
{
this.codigo = codigo;
this.descripcion = descripcion;
this.noFicha = noFicha;
this.precioCUC = precioCUC;
this.precioCUP = precioCUP;
this.suministrador = suministrador;
this.color = color;
this.tipo = tipo;
this.enchape = enchape;
}
public Producto()
: base()
{
this.codigo = "";
this.descripcion = "";
this.noFicha = -1;
this.precioCUC = 0;
this.precioCUP = 0;
this.suministrador = "";
this.color = "";
this.tipo = new TipoProducto();
this.enchape = new TipoEnchape();
}
}
}
<file_sep>/Perfilac/visual/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Perfilac.visual;
namespace Perfilac
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Opacity += 0.02;
if (this.Opacity == 1)
{
timer1.Stop();
Principal ddk = new Principal(this);
ddk.Show();
this.Visible = false;
}
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
}
}<file_sep>/Perfilac/dao/DaoGenerico.cs
using System;
using System.Collections.Generic;
using System.Text;
using Perfilac.origen_datos;
using System.Data.Odbc;
namespace Perfilac.dao
{
public class DaoGenerico
{
protected DaoConecction daoConection;
public DaoConecction DaoConection
{
get { return daoConection; }
set { daoConection = value; }
}
protected OdbcConnection conec;
public OdbcConnection Conect
{
get { return conec; }
set { conec = value; }
}
protected OdbcTransaction transaction;
public OdbcTransaction Transaction
{
get { return transaction; }
set { transaction = value; }
}
public DaoGenerico()
{
this.daoConection = new DaoConecction();
}
}
}
<file_sep>/Perfilac/reportes/InformePrueba.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.reportes
{
public class InformePrueba
{
private String nombre;
public String Nombre
{
get { return nombre; }
set { nombre = value; }
}
private int edad;
public int Edad
{
get { return edad; }
set { edad = value; }
}
public InformePrueba()
{
this.edad = 23;
this.nombre = "<NAME>";
}
}
}
<file_sep>/Perfilac/dao/UsuarioDao.cs
using System;
using System.Collections.Generic;
using System.Text;
using Perfilac.dominio;
using System.Data.Common;
using System.Data.Odbc;
namespace Perfilac.dao
{
public class UsuarioDao:DaoGenerico
{
public List<Usuario> listarUsuarios()
{
this.Conect = daoConection.getConexion();
this.Conect.Open();
OdbcCommand command = this.Conect.CreateCommand();
this.Transaction = this.Conect.BeginTransaction();
command.Transaction = this.Transaction;
command.CommandText = "Select * from TUsuario";
List<Usuario> listUsuarios = new List<Usuario>();
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
Usuario usuario = new Usuario(reader["usuario"].ToString(), reader["pass"].ToString(), reader["primerNombre"].ToString(), reader["segundoNombre"].ToString(), reader["primerApellido"].ToString(), reader["segundoApellido"].ToString());
usuario.Id = (int)reader["id"];
listUsuarios.Add(usuario);
}
reader.Close();
this.Transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
this.Conect.Close();
return listUsuarios;
}
public void eliminarUsuario(int idUsuario)
{
this.Conect = daoConection.getConexion();
this.Conect.Open();
OdbcCommand command = this.Conect.CreateCommand();
this.Transaction = this.Conect.BeginTransaction();
command.Transaction = this.Transaction;
command.CommandText = "DELETE FROM TUsuario WHERE TUsuario.id="+idUsuario+";";
try
{
OdbcDataReader rea = command.ExecuteReader();
Console.WriteLine(command.CommandText);
rea.Close();
this.Transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
this.Conect.Close();
}
public void modificarUsuario(Usuario usuario)
{
this.Conect = daoConection.getConexion();
this.Conect.Open();
OdbcCommand command = this.Conect.CreateCommand();
this.Transaction = this.Conect.BeginTransaction();
command.Transaction = this.Transaction;
command.CommandText = "UPDATE TUsuario SET TUsuario.primerNombre = '" + usuario.PrimerNombre + "', TUsuario.segundoNombre = '" + usuario.SegundoNombre + "', TUsuario.primerApellido = '" + usuario.PrimerApellido + "', TUsuario.segundoApellido = '" + usuario.SegundoApellido + "', TUsuario.usuario = '" + usuario.User + "', TUsuario.pass = '" + usuario.Pass + "' WHERE TUsuario.id=" + usuario.Id + ";";
try
{
OdbcDataReader rea = command.ExecuteReader();
Console.WriteLine(command.CommandText);
rea.Close();
this.Transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
this.Conect.Close();
}
public void salvarUsuario(Usuario usuario)
{
this.Conect = daoConection.getConexion();
this.Conect.Open();
OdbcCommand command = this.Conect.CreateCommand();
this.Transaction = this.Conect.BeginTransaction();
command.Transaction = this.Transaction;
command.CommandText = "insert into TUsuario(usuario,pass,primerNombre,segundoNombre,primerApellido,segundoApellido) values('" + usuario.User + "','" + usuario.Pass + "','" + usuario.PrimerNombre + "','" + usuario.SegundoNombre + "','" + usuario.PrimerApellido + "','" + usuario.SegundoApellido + "')";
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
reader.Close();
this.Transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
this.Conect.Close();
}
}
}
<file_sep>/Perfilac/dao/ProductoDao.cs
using System;
using System.Collections.Generic;
using System.Text;
using Perfilac.origen_datos;
using System.Data.Common;
using System.Data.Odbc;
using Perfilac.dominio;
namespace Perfilac.dao
{
public class ProductoDao:DaoGenerico
{
public ProductoDao():base()
{
}
public List<Producto> consultarPorParametros(String codigo, int noFicha, TipoProducto tipo, TipoEnchape enchape)
{
String cadena = "SELECT TProducto.*,NTipo.id, NTipo.nombre as tipoProducto,NTipoEnchape.id,NTipoEnchape.nombre as tipoEnchape FROM ((TProducto INNER JOIN NTipo ON NTipo.id = TProducto.tipo) inner join NTipoEnchape on TProducto.enchape = NTipoEnchape.id) Where TProducto.id <> -1 ";
//String cadena = "SELECT TProducto.* FROM ((TProducto INNER JOIN NTipo ON NTipo.id = TProducto.tipo) inner join NTipoEnchape on TProducto.enchape = NTipoEnchape.id) Where TProducto.tipo = " + tipo.Id + " and TProducto.enchape = " + enchape.Id + " ";
if (tipo != null)
cadena += "and TProducto.tipo = " + tipo.Id + "";
if (enchape != null)
cadena += "and TProducto.enchape = " + enchape.Id + "";
if (codigo != "")
cadena += "and TProducto.codigo like '" + codigo + "%'";
if (noFicha != -1)
cadena += "and TProducto.noFicha like '"+ noFicha + "%'";
OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = conect.CreateCommand();
List<Producto> result = new List<Producto>();
command.CommandText = cadena;
try
{
conect.Open();
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
TipoEnchape tEnchape = new TipoEnchape((String)reader["tipoEnchape"]);
TipoProducto tProducto = new TipoProducto((String)reader["tipoProducto"]);
Producto nuevo = new Producto((String)reader["codigo"], (String)reader["descripcion"], int.Parse(reader["noFicha"].ToString()), double.Parse(reader["precioCUC"].ToString()), double.Parse(reader["precioCUP"].ToString()), (String)reader["suministrador"], (String)reader["color"],tEnchape,tProducto);
nuevo.Id = int.Parse(reader["id"].ToString());
result.Add(nuevo);
}
reader.Close();
conect.Close();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
public void salvarProducto (Producto producto)
{
OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = conect.CreateCommand();
command.CommandText = "insert into TProducto(codigo,enchape,tipo,descripcion,noFicha,precioCUP,precioCUC,suministrador,color) values('" + producto.Codigo + "','" + producto.Enchape.Id + "','" + producto.Tipo.Id + "','" + producto.Descripcion + "','" + producto.NoFicha + "','" + producto.PrecioCUP + "','" + producto.PrecioCUC + "','" + producto.Suministrador + "','" + producto.Color + "');";
conect.Open();
OdbcTransaction tx = conect.BeginTransaction();
command.Transaction = tx;
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
tx.Commit();
reader.Close();
conect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
tx.Rollback();
}
}
}
}
<file_sep>/Perfilac/dao/ClienteDao.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data.Odbc;
using Perfilac.dominio;
namespace Perfilac.dao
{
public class ClienteDao:DaoGenerico
{
public ClienteDao():base()
{
}
public List<PersonaCliente> obtenerPersonasClientes(Cliente cliente)
{
String cadena = "SELECT * from TPersonaCliente Where TPersonaCliente.cliente ="+ cliente.Id +"";
OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = conect.CreateCommand();
command.CommandText = cadena;
List<PersonaCliente> result = new List<PersonaCliente>();
try
{
conect.Open();
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
PersonaCliente nuevo = new PersonaCliente(reader["primerNombre"].ToString(), reader["segundoNombre"].ToString(), reader["primerApellido"].ToString(), reader["segundoApellido"].ToString(), reader["ci"].ToString(), reader["telefono"].ToString(), reader["cargo"].ToString());
nuevo.Id = int.Parse(reader["id"].ToString());
result.Add(nuevo);
}
reader.Close();
conect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
return result;
}
public List<Cliente> obtenerTodosClientes()
{
String cadena = "SELECT * from TCliente";
OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = conect.CreateCommand();
command.CommandText = cadena;
List<Cliente> result = new List<Cliente>();
try
{
conect.Open();
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
Cliente nuevo = new Cliente(reader["codigo"].ToString(), reader["nombre"].ToString(), reader["contrato"].ToString(), reader["direccion"].ToString(), null, reader["cuentaCUP"].ToString(), reader["cuentaCUC"].ToString());
nuevo.Id = int.Parse(reader["id"].ToString());
result.Add(nuevo);
}
reader.Close();
conect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
return result;
}
private void salvarPersonaCliente(PersonaCliente personaCliente)
{
//OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = this.Conect.CreateCommand();
command.CommandText = "insert into TPersonaCliente(primerNombre,segundoNombre,primerApellido,segundoApellido,cliente,ci,telefono,cargo) values('" + personaCliente.PrimerNombre + "','" + personaCliente.SegundoNombre + "','" + personaCliente.PrimerApellido + "','" + personaCliente.SegundoApellido + "','" + personaCliente.Cliente.Id + "','" + personaCliente.CI + "','" + personaCliente.Telefono + "','" + personaCliente.Cargo + "');";
//OdbcTransaction tx = conect.BeginTransaction();
command.Transaction = this.Transaction;
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
//tx.Commit();
reader.Close();
//conect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
}
public void salvarClienteCompleto(Cliente cliente)
{
this.Conect = daoConection.getConexion();
this.Conect.Open();
OdbcCommand command = this.Conect.CreateCommand();
this.Transaction = this.Conect.BeginTransaction();
salvarCliente(cliente);
int idCliente = 0;
command.CommandText = "Select max(id) from TCliente";
command.Transaction = this.Transaction;
try
{
idCliente = int.Parse(command.ExecuteScalar().ToString());
Console.WriteLine(command.CommandText);
//reader.ToString();
//int a = reader.FieldCount;
//idCliente = int.Parse(reader[1].ToString());
//while (reader.Read())
//{
// idCliente = int.Parse(reader[0].ToString());
//}
//reader.Close();
//conect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
foreach (PersonaCliente var in cliente.Comerciales)
{
var.Cliente.Id = idCliente;
salvarPersonaCliente(var);
}
this.Transaction.Commit();
this.Conect.Close();
}
private void salvarCliente(Cliente cliente)
{
//OdbcConnection conect = daoConection.getConexion();
OdbcCommand command = this.Conect.CreateCommand();
command.CommandText = "insert into TCliente(codigo,nombre,contrato,direccion,cuentaCUP,cuentaCUC) values('" + cliente.Codigo + "','" + cliente.Nombre + "','" + cliente.Contrato + "','" + cliente.Direccion + "','" + cliente.CuentaCUP + "','" + cliente.CuentaCUC + "');";
//conect.Open();
//OdbcTransaction tx = conect.BeginTransaction();
command.Transaction = this.Transaction;
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
//tx.Commit();
reader.Close();
//conect.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
}
}
}
<file_sep>/Perfilac/dominio/EmpresaPerfilac.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class EmpresaPerfilac
{
private List<Producto> productos;
public List<Producto> Productos
{
get { return productos; }
set { productos = value; }
}
private List<Cliente> listCliente;
public List<Cliente> ListCliente
{
get { return listCliente; }
set { listCliente = value; }
}
private List<Venta> listVenta;
public List<Venta> ListaVenta
{
get { return listVenta; }
set { listVenta = value; }
}
private String numeroCuentaAcreedorMN;
public String NumeroCuentaAcreedorMN
{
get { return numeroCuentaAcreedorMN; }
set { numeroCuentaAcreedorMN = value; }
}
private String numeroCuentaAcreedorCUC;
public String NumeroCuentaAcreedorCUC
{
get { return numeroCuentaAcreedorCUC; }
set { numeroCuentaAcreedorCUC = value; }
}
public EmpresaPerfilac()
{
this.productos = new List<Producto>();
this.listCliente = new List<Cliente>();
}
}
}
<file_sep>/Perfilac/visual/AgregarProductoVenta.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Perfilac.dominio;
namespace Perfilac.visual
{
public partial class AgregarProductoVenta : Form
{
public AgregarProductoVenta()
{
InitializeComponent();
this.productoVender = new ProductoVenta();
}
private ProductoVenta productoVender;
public ProductoVenta ProductoVender
{
get { return productoVender; }
set { productoVender = value; }
}
public void mostrarCampos(String codigo,String noFicha,String descripcion,String suministrador,String color,String precioCUP,String precioCUC,String tipo,String enchape,String id)
{
textBox1.Text = codigo;
textBox2.Text = noFicha;
textBox7.Text = descripcion;
textBox12.Text = suministrador;
textBox13.Text = color;
textBoxTipo.Text = precioCUP;
textBoxEnchape.Text = precioCUC;
textBoxCUP.Text = tipo;
textBoxCUC.Text = enchape;
textBox11.Text = id;
}
private void button1_Click(object sender, EventArgs e)
{
double ancho = 0;
double alto = 0;
int cant = 0;
Boolean error = false;
try
{
ancho = double.Parse(textBox6.Text);
}
catch (Exception)
{
label11.Visible = true;
error = true;
}
try
{
alto = double.Parse(textBox5.Text);
}
catch (Exception)
{
label12.Visible = true;
error = true;
}
try
{
cant = int.Parse(textBox8.Text);
}
catch (Exception)
{
label13.Visible = true;
error = true;
}
if (!error)
{
productoVender = new ProductoVenta();
productoVender.Ancho = ancho;
productoVender.Alto = alto;
productoVender.Cant = cant;
productoVender.Id = -1;
productoVender.Prod = new Producto(textBox1.Text, textBox7.Text, int.Parse(textBox2.Text),double.Parse(textBoxCUC.Text), double.Parse(textBoxCUP.Text), textBox12.Text, textBox13.Text, new TipoEnchape(textBoxEnchape.Text), new TipoProducto(textBoxTipo.Text));
productoVender.Prod.Id = int.Parse(textBox11.Text);
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("Existen campos que estan incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}<file_sep>/Perfilac/visual/Principal.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Perfilac.dominio;
using Perfilac.servicio;
using Perfilac.dao;
using Perfilac.reportes;
using System.Globalization;
namespace Perfilac.visual
{
public partial class Principal : Form
{
private Service servicio;
public Service Servicio
{
get { return servicio; }
set { servicio = value; }
}
private Form1 formPrincipal;
private List<Producto> listProductoFactura;
public List<Producto> ListProductoFactura
{
get { return listProductoFactura; }
set { listProductoFactura = value; }
}
private List<ProductoVenta> listProductosVenta;
public List<ProductoVenta> ListProductoV
{
get { return listProductosVenta; }
set { listProductosVenta = value; }
}
private Boolean clienteSelecionado;
public Boolean ClienteSelecionado
{
get { return clienteSelecionado; }
set { clienteSelecionado = value; }
}
private TipoVenta tipoVenta;
public TipoVenta TipoVent
{
get { return tipoVenta; }
set { tipoVenta = value; }
}
public Principal(Form1 formPrincipal)
{
InitializeComponent();
servicio = new Service();
this.formPrincipal = formPrincipal;
}
private void Principal_Load(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
label17.Visible = false;
label16.Visible = false;
label15.Visible = false;
int numeroFicha = 0;
double precioCUC = 0.0;
double precioCUP = 0.0;
Boolean error = false;
try
{
numeroFicha = int.Parse(textBox2.Text);
}
catch (Exception)
{
label17.Visible = true;
error = true;
}
try
{
precioCUC = double.Parse(textBox3.Text);
}
catch (Exception)
{
label15.Visible = true;
error = true;
}
try
{
precioCUP = double.Parse(textBox4.Text);
}
catch (Exception)
{
label16.Visible = true;
error = true;
}
if (!error)
{
TipoProducto tipo = (TipoProducto)comboBox1.SelectedItem;
TipoEnchape enchape = (TipoEnchape)comboBox2.SelectedItem;
String codigo = textBox1.Text;
String color = textBox5.Text;
String suministrador = textBox6.Text;
String descripcion = textBox7.Text;
Producto nuevoProducto = new Producto(codigo, descripcion, numeroFicha, precioCUC, precioCUP, suministrador, color, enchape, tipo);
this.servicio.salvarProducto(nuevoProducto);
limpiarVisualProducto();
MessageBox.Show("Se ha insertado satisfactoriamente la ficha con código: " + precioCUC + " y " + precioCUP, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Existen campos que estan incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void insertarFichaToolStripMenuItem1_Click(object sender, EventArgs e)
{
groupBox3.Visible = false;
groupBox1.Visible = true;
groupBox2.Visible = false;
comboBox1.Items.Clear();
comboBox1.Items.AddRange(servicio.obtenerTiposProducto().ToArray());
comboBox1.SelectedIndex = 0;
comboBox2.Items.Clear();
comboBox2.Items.AddRange(servicio.obtenerTiposEnchape().ToArray());
comboBox2.SelectedIndex = 0;
}
private void limpiarVisualProducto()
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
label17.Visible = false;
label16.Visible = false;
label15.Visible = false;
comboBox1.SelectedIndex = 0;
comboBox2.SelectedIndex = 0;
}
private void button2_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Si continua se perderan los datos.¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
limpiarVisualProducto();
}
}
private void verFichaToolStripMenuItem_Click(object sender, EventArgs e)
{
if (groupBox1.Visible || groupBox3.Visible)
{
if (MessageBox.Show("¿Desea conservar los datos que no haya guardado de la vista actual?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
limpiarVisualProducto();
}
}
groupBox3.Visible = false;
groupBox1.Visible = false;
groupBox2.Visible = true;
label14.Visible = false;
comboBox3.Items.Clear();
TipoProducto tipoVacio = new TipoProducto("Todos");
tipoVacio.Id = -1;
comboBox3.Items.Add(tipoVacio);
comboBox3.Items.AddRange(servicio.obtenerTiposProducto().ToArray());
comboBox3.SelectedIndex = 0;
comboBox4.Items.Clear();
TipoEnchape enchapoVacio = new TipoEnchape("Todos");
enchapoVacio.Id = -1;
comboBox4.Items.Add(enchapoVacio);
comboBox4.Items.AddRange(servicio.obtenerTiposEnchape().ToArray());
comboBox4.SelectedIndex = 0;
//List<Producto> listProducto = this.servicio.consultarProducto();
//dataGridView1.RowCount = listProducto.Count+1;
//for (int i = 0; i < listProducto.Count; i++)
//{
// dataGridView1[0, i].Value = listProducto[i].Codigo;
// dataGridView1[1, i].Value = listProducto[i].NoFicha;
// dataGridView1[2, i].Value = listProducto[i].Descripcion;
// dataGridView1[3, i].Value = listProducto[i].Tipo.ToString();
// dataGridView1[4, i].Value = listProducto[i].Enchape.ToString();
// dataGridView1[5, i].Value = listProducto[i].PrecioCUP;
// dataGridView1[6, i].Value = listProducto[i].PrecioCUC;
//}
}
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void salirToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Está a punto de cerrar la aplicación. ¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
formPrincipal.Close();
}
}
private void prefacturaToolStripMenuItem_Click(object sender, EventArgs e)
{
if (groupBox1.Visible)
{
if (MessageBox.Show("¿Desea conservar los datos que no haya guardado de la vista actual?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
limpiarVisualProducto();
}
}
groupBox1.Visible = false;
groupBox2.Visible = false;
groupBox3.Visible = true;
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.Value = DateTime.Now;
label46.Visible = false;
comboBox6.Items.Clear();
TipoProducto tipoVacio = new TipoProducto("Todos");
tipoVacio.Id = -1;
comboBox6.Items.Add(tipoVacio);
comboBox6.Items.AddRange(servicio.obtenerTiposProducto().ToArray());
comboBox6.SelectedIndex = 0;
comboBox5.Items.Clear();
TipoEnchape enchapoVacio = new TipoEnchape("Todos");
enchapoVacio.Id = -1;
comboBox5.Items.Add(enchapoVacio);
comboBox5.Items.AddRange(servicio.obtenerTiposEnchape().ToArray());
comboBox5.SelectedIndex = 0;
this.listProductosVenta = new List<ProductoVenta>();
this.TipoVent = TipoVenta.prefactura;
actualizarListadoClientes();
}
private void button6_Click(object sender, EventArgs e)
{
Boolean error = false;
if (!clienteSelecionado)
{
MessageBox.Show("Debe seleccionar permanentemente la persona cliente de la factura", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
error = true;
}
if (this.listProductosVenta.Count == 0)
{
MessageBox.Show("Debe seleccionar las fichas de la factura", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
error = true;
}
if (!error)
{
PersonaCliente personaSelecionada = (PersonaCliente)listBox2.Items[listBox2.SelectedIndex];
Cliente clienteSeleccionado = (Cliente)listBox1.Items[listBox1.SelectedIndex];
List<ProductoVenta> produstosVender = new List<ProductoVenta>();
DateTime fecha = dateTimePicker1.Value;
Perfilac.dominio.Venta vet = new Perfilac.dominio.Venta(clienteSeleccionado, personaSelecionada, fecha, produstosVender, TipoVent);
List<Ingreso> listPagos = new List<Ingreso>();
foreach (Object var in listBox3.Items)
{
Ingreso nuevo = (Ingreso)var;
nuevo.Client = clienteSeleccionado;
nuevo.Venta = vet;
listPagos.Add(nuevo);
}
vet.ImportePagado = listPagos;
foreach (DataGridViewRow row in dataGridView3.Rows)
{
if (row.Cells[0].Value != null)
{
Producto nuevo = new Producto();
nuevo.Id = int.Parse(row.Cells[14].Value.ToString());
ProductoVenta nuevoProductoVenta = new ProductoVenta();
nuevoProductoVenta.Prod = nuevo;
nuevoProductoVenta.Ancho = double.Parse(row.Cells[7].Value.ToString());
nuevoProductoVenta.Alto = double.Parse(row.Cells[8].Value.ToString());
nuevoProductoVenta.Cant = int.Parse(row.Cells[9].Value.ToString());
nuevoProductoVenta.Vent = vet;
produstosVender.Add(nuevoProductoVenta);
}
}
try
{
int id = servicio.salvarVenta(vet);
MessageBox.Show("La Factura se ha insertado correctamente", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
imprimirVenta(id);
limpiarDatosFactura();
}
catch (Exception exep)
{
MessageBox.Show(exep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void actualizarListadoClientes()
{
listBox1.Items.Clear();
listBox1.Items.AddRange(this.servicio.obtenerClientes().ToArray());
}
private void nuevoClienteToolStripMenuItem_Click(object sender, EventArgs e)
{
Nuevo_Cliente formNuevoCliente = new Nuevo_Cliente(this.servicio);
if (formNuevoCliente.ShowDialog() == DialogResult.OK)
{
if (groupBox3.Visible)
actualizarListadoClientes();
}
}
private void operacionesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void textBox8_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void groupBox3_Enter(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
Cliente clienteSeleccionado = (Cliente)listBox1.Items[listBox1.SelectedIndex];
label26.Text = clienteSeleccionado.Nombre;
label31.Text = clienteSeleccionado.Codigo;
textBox13.Text = clienteSeleccionado.Direccion;
label33.Text = clienteSeleccionado.Contrato;
label42.Text = clienteSeleccionado.CuentaCUP;
label43.Text = clienteSeleccionado.CuentaCUC;
listBox2.Items.Clear();
listBox2.Items.AddRange(clienteSeleccionado.Comerciales.ToArray());
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
PersonaCliente personaSelecionada = (PersonaCliente)listBox2.Items[listBox2.SelectedIndex];
label30.Text = personaSelecionada.nombreCompleto();
label34.Text = personaSelecionada.Cargo;
label36.Text = personaSelecionada.CI;
label38.Text = personaSelecionada.Telefono;
}
private void limpiarDatosFactura()
{
//fecha
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.Value = DateTime.Now;
//Cliente
abilitarSeleccionarCliente();
abilitarSeleccionarPersonaCliente();
//Pagos
listBox3.Items.Clear();
//Producto
comboBox6.SelectedIndex = 0;
comboBox5.SelectedIndex = 0;
textBox10.Clear();
textBox11.Clear();
dataGridView2.Rows.Clear();
dataGridView3.Rows.Clear();
this.listProductosVenta = new List<ProductoVenta>();
}
private void button4_Click(object sender, EventArgs e)
{
Boolean error = false;
if (!clienteSelecionado)
{
MessageBox.Show("Debe seleccionar permanentemente la persona cliente de la factura", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
error = true;
}
if (this.listProductosVenta.Count == 0)
{
MessageBox.Show("Debe seleccionar las fichas de la factura", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
error = true;
}
if (!error)
{
PersonaCliente personaSelecionada = (PersonaCliente)listBox2.Items[listBox2.SelectedIndex];
Cliente clienteSeleccionado = (Cliente)listBox1.Items[listBox1.SelectedIndex];
List<ProductoVenta> produstosVender = new List<ProductoVenta>();
DateTime fecha = dateTimePicker1.Value;
Perfilac.dominio.Venta vet = new Perfilac.dominio.Venta(clienteSeleccionado, personaSelecionada, fecha, produstosVender, TipoVent);
List<Ingreso> listPagos = new List<Ingreso>();
foreach (Object var in listBox3.Items)
{
Ingreso nuevo = (Ingreso)var;
nuevo.Client = clienteSeleccionado;
nuevo.Venta = vet;
listPagos.Add(nuevo);
}
vet.ImportePagado = listPagos;
foreach (DataGridViewRow row in dataGridView3.Rows)
{
if (row.Cells[0].Value != null)
{
Producto nuevo = new Producto();
nuevo.Id = int.Parse(row.Cells[14].Value.ToString());
ProductoVenta nuevoProductoVenta = new ProductoVenta();
nuevoProductoVenta.Prod = nuevo;
nuevoProductoVenta.Ancho = double.Parse(row.Cells[7].Value.ToString());
nuevoProductoVenta.Alto = double.Parse(row.Cells[8].Value.ToString());
nuevoProductoVenta.Cant = int.Parse(row.Cells[9].Value.ToString());
nuevoProductoVenta.Vent = vet;
produstosVender.Add(nuevoProductoVenta);
}
}
try
{
servicio.salvarVenta(vet);
MessageBox.Show("La Factura se ha insertado correctamente", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
limpiarDatosFactura();
}
catch (Exception exep)
{
MessageBox.Show(exep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void button7_Click(object sender, EventArgs e)
{
}
private void button7_Click_1(object sender, EventArgs e)
{
if (button10.Visible)
{
PagoCliente formPago = new PagoCliente();
if (formPago.ShowDialog() == DialogResult.OK)
{
listBox3.Items.Add(formPago.TipoPagoCliente);
}
}
else
MessageBox.Show("Debe seleccionar permanentemente la persona que efectúa el pago", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button5_Click(object sender, EventArgs e)
{
//MessageBox.Show(dataGridView2.SelectedRows[0].Cells[0].Value.ToString());
}
private void pruebaToolStripMenuItem_Click(object sender, EventArgs e)
{
groupBox3.Visible = false;
groupBox1.Visible = true;
groupBox2.Visible = false;
groupBox4.Visible = false;
comboBox1.Items.Clear();
comboBox1.Items.AddRange(servicio.obtenerTiposProducto().ToArray());
comboBox1.SelectedIndex = 0;
comboBox2.Items.Clear();
comboBox2.Items.AddRange(servicio.obtenerTiposEnchape().ToArray());
comboBox2.SelectedIndex = 0;
}
private void comboBox2_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("Debe seleccionar un valor", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Handled = true;
return;
}
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("Debe seleccionar un valor", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Handled = true;
return;
}
private void comboBox3_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("Debe seleccionar un valor", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Handled = true;
return;
}
private void comboBox4_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("Debe seleccionar un valor", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Handled = true;
return;
}
private void comboBox3_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Boolean error = false;
label14.Visible = false;
int noFicha = 0;
if (textBox9.Text.Length != 0)
{
try
{
noFicha = int.Parse(textBox9.Text);
}
catch (Exception)
{
error = true;
label14.Visible = true;
MessageBox.Show("Existen campos que estan incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
noFicha = -1;
if (!error)
{
String codigo = textBox8.Text;
TipoEnchape enchape = (TipoEnchape)comboBox4.SelectedItem;
if (enchape.Id == -1)
enchape = null;
TipoProducto tipo = (TipoProducto)comboBox3.SelectedItem;
if (tipo.Id == -1)
tipo = null;
List<Producto> listProducto = servicio.consultarProductosPorParametros(codigo, noFicha, tipo, enchape);
dataGridView1.RowCount = listProducto.Count + 1;
for (int i = 0; i < listProducto.Count; i++)
{
dataGridView1[0, i].Value = listProducto[i].Codigo;
dataGridView1[1, i].Value = listProducto[i].NoFicha;
dataGridView1[2, i].Value = listProducto[i].Descripcion;
dataGridView1[3, i].Value = listProducto[i].Suministrador;
dataGridView1[4, i].Value = listProducto[i].Color;
dataGridView1[5, i].Value = listProducto[i].Tipo.ToString();
dataGridView1[6, i].Value = listProducto[i].Enchape.ToString();
dataGridView1[7, i].Value = listProducto[i].PrecioCUP;
dataGridView1[8, i].Value = listProducto[i].PrecioCUC;
}
}
}
private void ingresosToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void button8_Click(object sender, EventArgs e)
{
Boolean error = false;
label46.Visible = false;
int noFicha = 0;
if (textBox10.Text.Length != 0)
{
try
{
noFicha = int.Parse(textBox10.Text);
}
catch (Exception)
{
error = true;
label46.Visible = true;
MessageBox.Show("Existen campos que estan incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
noFicha = -1;
if (!error)
{
String codigo = textBox11.Text;
TipoEnchape enchape = (TipoEnchape)comboBox5.SelectedItem;
if (enchape.Id == -1)
enchape = null;
TipoProducto tipo = (TipoProducto)comboBox6.SelectedItem;
if (tipo.Id == -1)
tipo = null;
listProductoFactura = servicio.consultarProductosPorParametros(codigo, noFicha, tipo, enchape);
dataGridView2.RowCount = listProductoFactura.Count + 1;
for (int i = 0; i < listProductoFactura.Count; i++)
{
dataGridView2[0, i].Value = listProductoFactura[i].Codigo;
dataGridView2[1, i].Value = listProductoFactura[i].NoFicha;
dataGridView2[2, i].Value = listProductoFactura[i].Descripcion;
dataGridView2[3, i].Value = listProductoFactura[i].Suministrador;
dataGridView2[4, i].Value = listProductoFactura[i].Color;
dataGridView2[5, i].Value = listProductoFactura[i].Tipo.ToString();
dataGridView2[6, i].Value = listProductoFactura[i].Enchape.ToString();
dataGridView2[7, i].Value = listProductoFactura[i].PrecioCUP;
dataGridView2[8, i].Value = listProductoFactura[i].PrecioCUC;
dataGridView2[9, i].Value = listProductoFactura[i].Id;
}
}
}
private void dataGridView2_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
Boolean existe = false;
if (dataGridView3.Rows.Count > 1)
{
foreach (DataGridViewRow row in dataGridView3.Rows)
{
if (row.Cells[0].Value != null && row.Cells[0].Value.ToString().Equals(dataGridView2.SelectedRows[0].Cells[0].Value))
{
existe = true;
break;
}
}
}
if (!existe)
{
AgregarProductoVenta formAgregarProductoVenta = new AgregarProductoVenta();
formAgregarProductoVenta.mostrarCampos(dataGridView2.SelectedRows[0].Cells[0].Value.ToString(), dataGridView2.SelectedRows[0].Cells[1].Value.ToString(), dataGridView2.SelectedRows[0].Cells[2].Value.ToString(), dataGridView2.SelectedRows[0].Cells[3].Value.ToString(), dataGridView2.SelectedRows[0].Cells[4].Value.ToString(), dataGridView2.SelectedRows[0].Cells[5].Value.ToString(), dataGridView2.SelectedRows[0].Cells[6].Value.ToString(), dataGridView2.SelectedRows[0].Cells[7].Value.ToString(), dataGridView2.SelectedRows[0].Cells[8].Value.ToString(), dataGridView2.SelectedRows[0].Cells[9].Value.ToString());
if (formAgregarProductoVenta.ShowDialog() == DialogResult.OK)
{
ProductoVenta productoVentaEscogido = formAgregarProductoVenta.ProductoVender;
dataGridView3.RowCount++;
dataGridView3[0, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.Codigo;
dataGridView3[1, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.NoFicha;
dataGridView3[2, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.Descripcion;
dataGridView3[3, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.Suministrador;
dataGridView3[4, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.Color;
dataGridView3[5, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.Tipo.Nombre;
dataGridView3[6, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.Enchape.Nombre;
dataGridView3[7, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Ancho;
dataGridView3[8, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Alto;
dataGridView3[9, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Cant;
dataGridView3[10, dataGridView3.RowCount - 2].Value = productoVentaEscogido.precioCUC();
dataGridView3[11, dataGridView3.RowCount - 2].Value = productoVentaEscogido.ImporteCUC();
dataGridView3[12, dataGridView3.RowCount - 2].Value = productoVentaEscogido.precioCUP();
dataGridView3[13, dataGridView3.RowCount - 2].Value = productoVentaEscogido.ImporteCUP();
dataGridView3[14, dataGridView3.RowCount - 2].Value = productoVentaEscogido.Prod.Id;
this.listProductosVenta.Add(productoVentaEscogido);
}
}
else
MessageBox.Show("Ya existe una ficha con este número", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void dataGridView3_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (MessageBox.Show("Se eliminará el producto de la factura o prefactura actual.¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.listProductosVenta.RemoveAt(dataGridView3.SelectedRows[0].Index);
dataGridView3.Rows.Remove(dataGridView3.SelectedRows[0]);
}
}
private void desabilitarSeleccionarCliente()
{
listBox1.Enabled = false;
button9.Visible = true;
}
private void abilitarSeleccionarCliente()
{
listBox1.Enabled = true;
button9.Visible = false;
}
private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyValue == 13)
desabilitarSeleccionarCliente();
}
private void button9_Click(object sender, EventArgs e)
{
if (listBox3.Items.Count > 0)
{
if (MessageBox.Show("Si continua se perderán los datos de pago realizado por la persona, ¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
abilitarSeleccionarCliente();
abilitarSeleccionarPersonaCliente();
listBox3.Items.Clear();
}
}
else
{
abilitarSeleccionarCliente();
abilitarSeleccionarPersonaCliente();
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listBox1.SelectedIndex != -1)
desabilitarSeleccionarCliente();
}
private void desabilitarSeleccionarPersonaCliente()
{
listBox2.Enabled = false;
button10.Visible = true;
clienteSelecionado = true;
}
private void abilitarSeleccionarPersonaCliente()
{
listBox2.Enabled = true;
button10.Visible = false;
clienteSelecionado = false;
}
private void listBox2_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
desabilitarSeleccionarPersonaCliente();
desabilitarSeleccionarCliente();
}
}
private void listBox2_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyValue == 13)
{
desabilitarSeleccionarPersonaCliente();
desabilitarSeleccionarCliente();
}
}
private void button10_Click(object sender, EventArgs e)
{
if (listBox3.Items.Count > 0)
{
if (MessageBox.Show("Si continua se perderán los datos de pago realizado por la persona, ¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
abilitarSeleccionarPersonaCliente();
listBox3.Items.Clear();
}
}
else
abilitarSeleccionarPersonaCliente();
}
private void facturaToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void groupBox4_Enter(object sender, EventArgs e)
{
}
private void datosToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void clienteToolStripMenuItem_Click(object sender, EventArgs e)
{
Nuevo_Cliente formNuevoCliente = new Nuevo_Cliente(this.servicio);
if (formNuevoCliente.ShowDialog() == DialogResult.OK)
{
if (groupBox3.Visible)
actualizarListadoClientes();
}
}
private void reporteClienToolStripMenuItem_Click(object sender, EventArgs e)
{
ReporteClientes infor = new ReporteClientes();
String selection = "{TCliente.id} <> -1";
VisorDeInforme visor = new VisorDeInforme(infor, selection);
visor.ShowDialog(this);
}
private void consultarFichasToolStripMenuItem_Click(object sender, EventArgs e)
{
if (groupBox1.Visible || groupBox3.Visible)
{
if (MessageBox.Show("¿Desea conservar los datos que no haya guardado de la vista actual?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
limpiarVisualProducto();
}
}
groupBox3.Visible = false;
groupBox1.Visible = false;
groupBox4.Visible = false;
groupBox2.Visible = true;
label14.Visible = false;
comboBox3.Items.Clear();
TipoProducto tipoVacio = new TipoProducto("Todos");
tipoVacio.Id = -1;
comboBox3.Items.Add(tipoVacio);
comboBox3.Items.AddRange(servicio.obtenerTiposProducto().ToArray());
comboBox3.SelectedIndex = 0;
comboBox4.Items.Clear();
TipoEnchape enchapoVacio = new TipoEnchape("Todos");
enchapoVacio.Id = -1;
comboBox4.Items.Add(enchapoVacio);
comboBox4.Items.AddRange(servicio.obtenerTiposEnchape().ToArray());
comboBox4.SelectedIndex = 0;
//List<Producto> listProducto = this.servicio.consultarProducto();
//dataGridView1.RowCount = listProducto.Count+1;
//for (int i = 0; i < listProducto.Count; i++)
//{
// dataGridView1[0, i].Value = listProducto[i].Codigo;
// dataGridView1[1, i].Value = listProducto[i].NoFicha;
// dataGridView1[2, i].Value = listProducto[i].Descripcion;
// dataGridView1[3, i].Value = listProducto[i].Tipo.ToString();
// dataGridView1[4, i].Value = listProducto[i].Enchape.ToString();
// dataGridView1[5, i].Value = listProducto[i].PrecioCUP;
// dataGridView1[6, i].Value = listProducto[i].PrecioCUC;
//}
}
private void ventaToolStripMenuItem_Click(object sender, EventArgs e)
{
if (groupBox1.Visible)
{
if (MessageBox.Show("¿Desea conservar los datos que no haya guardado de la vista actual?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
limpiarVisualProducto();
}
}
groupBox3.Text = "Nueva Prefactura";
groupBox4.Visible = false;
groupBox1.Visible = false;
groupBox2.Visible = false;
groupBox3.Visible = true;
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.Value = DateTime.Now;
label46.Visible = false;
comboBox6.Items.Clear();
TipoProducto tipoVacio = new TipoProducto("Todos");
tipoVacio.Id = -1;
comboBox6.Items.Add(tipoVacio);
comboBox6.Items.AddRange(servicio.obtenerTiposProducto().ToArray());
comboBox6.SelectedIndex = 0;
comboBox5.Items.Clear();
TipoEnchape enchapoVacio = new TipoEnchape("Todos");
enchapoVacio.Id = -1;
comboBox5.Items.Add(enchapoVacio);
comboBox5.Items.AddRange(servicio.obtenerTiposEnchape().ToArray());
comboBox5.SelectedIndex = 0;
this.listProductosVenta = new List<ProductoVenta>();
this.TipoVent = TipoVenta.prefactura;
actualizarListadoClientes();
}
private void facturaToolStripMenuItem_Click_1(object sender, EventArgs e)
{
groupBox4.Visible = true;
groupBox1.Visible = false;
groupBox2.Visible = false;
groupBox3.Visible = false;
}
private void consultarClientesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void button12_Click(object sender, EventArgs e)
{
if (groupBox1.Visible)
{
if (MessageBox.Show("¿Desea conservar los datos que no haya guardado de la vista actual?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
limpiarVisualProducto();
}
}
groupBox3.Text = "Nueva Factura";
groupBox4.Visible = false;
groupBox1.Visible = false;
groupBox2.Visible = false;
groupBox3.Visible = true;
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.Value = DateTime.Now;
label46.Visible = false;
comboBox6.Items.Clear();
TipoProducto tipoVacio = new TipoProducto("Todos");
tipoVacio.Id = -1;
comboBox6.Items.Add(tipoVacio);
comboBox6.Items.AddRange(servicio.obtenerTiposProducto().ToArray());
comboBox6.SelectedIndex = 0;
comboBox5.Items.Clear();
TipoEnchape enchapoVacio = new TipoEnchape("Todos");
enchapoVacio.Id = -1;
comboBox5.Items.Add(enchapoVacio);
comboBox5.Items.AddRange(servicio.obtenerTiposEnchape().ToArray());
comboBox5.SelectedIndex = 0;
this.listProductosVenta = new List<ProductoVenta>();
this.TipoVent = TipoVenta.factura;
actualizarListadoClientes();
}
private void reportesFichasToolStripMenuItem_Click(object sender, EventArgs e)
{
ReporteClientes infor = new ReporteClientes();
String selection = "";
VisorDeInforme visor = new VisorDeInforme(infor, selection);
visor.ShowDialog(this);
}
private void reporteToolStripMenuItem_Click(object sender, EventArgs e)
{
ReporteVenta infor = new ReporteVenta();
String selection = "{TVenta.Id} = 22 and {TCliente.Id}={TVenta.cliente} and {TPersonaCliente.id} = {TVenta.comercial} and {TProductoVenta.venta} = {TVenta.id} and {TProducto.id} = {TProductoVenta.producto}";
VisorDeInforme visor = new VisorDeInforme(infor, selection);
visor.ShowDialog(this);
}
private void imprimirVenta(int id)
{
ReporteVenta infor = new ReporteVenta();
String selection = "{TVenta.Id} = " + id + " and {TCliente.Id}={TVenta.cliente} and {TPersonaCliente.id} = {TVenta.comercial} and {TProductoVenta.venta} = {TVenta.id} and {TProducto.id} = {TProductoVenta.producto}";
VisorDeInforme visor = new VisorDeInforme(infor, selection);
visor.ShowDialog(this);
}
private void insertarUsuariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Administrar_Usuarios form = new Administrar_Usuarios(this.servicio);
form.Show();
}
private void button11_Click(object sender, EventArgs e)
{
//DateTimeFormatInfo dfi = new DateTimeFormatInfo();
////dfi.MonthDayPattern = "MM-MMMM, ddd-dddd";
//dfi.ShortDatePattern = "dd/MM/yyyy";
//string fechas = dateTimePicker2.Value.ToString(dfi);
//dfi.ShortDatePattern = "dd - MM - yyyy";
//fechas += "\n\n" + dateTimePicker2.Value.ToString(dfi);
//dfi.ShortDatePattern = "MM/dd/yyyy HH:mm";
//fechas += "\n\n" + dateTimePicker2.Value.ToString(dfi);
//MessageBox.Show(fechas);
List<Venta> result = servicio.consultarVentas(0, dateTimePicker2.Value, dateTimePicker3.Value);
dataGridView4.RowCount = result.Count + 1;
for (int i = 0; i < result.Count; i++)
{
dataGridView4[0, i].Value = i+1;
dataGridView4[1, i].Value = result[i].Fecha;
dataGridView4[2, i].Value = result[i].Cliente.Nombre;
dataGridView4[3, i].Value = result[i].Comercial.nombreCompleto();
dataGridView4[4, i].Value = result[i].ImporteCUCTotal();
dataGridView4[5, i].Value = result[i].ImporteCUPTotal();
}
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
}
private void Principal_FormClosed(object sender, FormClosedEventArgs e)
{
formPrincipal.Close();
}
}
}<file_sep>/Perfilac/visual/PagoCliente.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Perfilac.dominio;
namespace Perfilac.visual
{
public partial class PagoCliente : Form
{
private Ingreso pagoCliente;
public Ingreso TipoPagoCliente
{
get { return pagoCliente; }
set { pagoCliente = value; }
}
public PagoCliente()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label2.Visible = false;
try
{
double importe = double.Parse(textBox1.Text);
String cheque = textBox2.Text;
TipoMoneda moneda = new TipoMoneda();
moneda = (TipoMoneda)Enum.Parse(typeof(TipoMoneda), comboBox1.Text);
this.pagoCliente = new Ingreso(importe,cheque,moneda);
this.DialogResult = DialogResult.OK;
}
catch (Exception)
{
label2.Visible = true;
MessageBox.Show("Existen campos que estan incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
label2.Visible = false;
this.DialogResult = DialogResult.Cancel;
}
}
}<file_sep>/Perfilac/dao/VentaDao.cs
using System;
using System.Collections.Generic;
using System.Text;
using Perfilac.origen_datos;
using System.Data.Common;
using System.Data.Odbc;
using Perfilac.dominio;
using System.Globalization;
namespace Perfilac.dao
{
public class VentaDao : DaoGenerico
{
public VentaDao():base()
{
}
private List<ProductoVenta> listProductoVenta(int idventa)
{
//Este metodo depende de que se haya abierto una conexion en consultarVentas
OdbcCommand command = this.Conect.CreateCommand();
command.CommandText = "SELECT TProductoVenta.*,TProducto.precioCUC,TProducto.precioCUP FROM TProducto INNER JOIN TProductoVenta ON TProducto.Id = TProductoVenta.producto WHERE (((TProductoVenta.venta)="+idventa+"))";
List<ProductoVenta> listProductoVenta = new List<ProductoVenta>();
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
Producto product = new Producto();
product.PrecioCUC = double.Parse(reader["precioCUC"].ToString());
product.PrecioCUP = double.Parse(reader["precioCUP"].ToString());
ProductoVenta productVenta = new ProductoVenta();
productVenta.Alto = double.Parse(reader["alto"].ToString());
productVenta.Ancho = double.Parse(reader["ancho"].ToString());
productVenta.Cant = (int)reader["cantidad"];
productVenta.Prod = product;
listProductoVenta.Add(productVenta);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return listProductoVenta;
}
public List<Venta> consultarVentas(int tipo,DateTime fechaInicio,DateTime fechaFin)
{
this.Conect = daoConection.getConexion();
this.Conect.Open();
OdbcCommand command = this.Conect.CreateCommand();
String formato = "\"dd/mm/aaaa\"";
command.CommandText = "SELECT TVenta.*, TCliente.nombre AS client, TPersonaCliente.primerNombre, TPersonaCliente.segundoNombre, TPersonaCliente.primerApellido, TPersonaCliente.segundoApellido FROM (TVenta INNER JOIN TCliente ON TVenta.cliente = TCliente.id) INNER JOIN TPersonaCliente ON (TPersonaCliente.Id = TVenta.comercial) AND (TCliente.Id = TPersonaCliente.cliente) where (((TVenta.tipo)=0) AND ((TVenta.fecha) Between # " + fechaInicio.Month + "/" + fechaInicio.Day + "/" + fechaInicio.Year + "# And # " + fechaFin.Month + "/" + fechaFin.Day + "/" + fechaFin.Year + " #))";
List<Venta> listVenta = new List<Venta>();
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
while (reader.Read())
{
Cliente cliente = new Cliente("",(String)reader["client"],"","",null,"","");
PersonaCliente personaCliente = new PersonaCliente((String)reader["primerNombre"], (String)reader["segundoNombre"], (String)reader["primerApellido"], (String)reader["segundoApellido"], "", "", "");
TipoVenta tVenta = new TipoVenta();
if (tipo == 1)
tVenta = TipoVenta.factura;
Venta venta = new Venta(cliente, personaCliente, (DateTime)reader["fecha"], null, tVenta);
venta.Id = (int)reader["id"];
//TipoProducto tProducto = new TipoProducto((String)reader["tipoProducto"]);
//Producto nuevo = new Producto((String)reader["codigo"], (String)reader["descripcion"], int.Parse(reader["noFicha"].ToString()), double.Parse(reader["precioCUC"].ToString()), double.Parse(reader["precioCUP"].ToString()), (String)reader["suministrador"], (String)reader["color"], tEnchape, tProducto);
//nuevo.Id = int.Parse(reader["id"].ToString());
venta.ListProductoVenta = listProductoVenta(venta.Id);
listVenta.Add(venta);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(command.CommandText);
Console.WriteLine(ex.Message);
}
this.Conect.Close();
return listVenta;
}
public int salvarVentaCompleta(Venta venta)
{
this.Conect = daoConection.getConexion();
this.Conect.Open();
OdbcCommand command = this.Conect.CreateCommand();
this.Transaction = this.Conect.BeginTransaction();
salvarVenta(venta);
int idVenta = 0;
command.CommandText = "Select max(id) from TVenta";
command.Transaction = this.Transaction;
try
{
idVenta = int.Parse(command.ExecuteScalar().ToString());
Console.WriteLine(command.CommandText);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
foreach (ProductoVenta var in venta.ListProductoVenta)
{
var.Vent.Id = idVenta;
salvarVentasProductos(var);
}
foreach (Ingreso var in venta.ImportePagado)
{
var.Venta.Id = idVenta;
salvarVentasPagos(var);
}
this.Transaction.Commit();
this.Conect.Close();
return idVenta;
}
private void salvarVentasPagos(Ingreso ingreso)
{
//Este metodo depende de que se haya abierto una conexion en salvarVentaCompleta
OdbcCommand command = this.Conect.CreateCommand();
command.CommandText = "insert into TIngreso(venta,ingreso,cheque,moneda,cliente) values('" + ingreso.Venta.Id + "','" + ingreso.Importe + "','" + ingreso.Cheque + "','" + ingreso.Moneda.ToString() + "','" + ingreso.Client.Id + "')";
command.Transaction = this.Transaction;
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
}
private void salvarVentasProductos(ProductoVenta productoVenta)
{
OdbcCommand command = this.Conect.CreateCommand();
command.CommandText = "insert into TProductoVenta(cantidad,venta,producto,ancho,alto) values('" + productoVenta.Cant + "','" + productoVenta.Vent.Id + "','" + productoVenta.Prod.Id + "','" + productoVenta.Ancho + "','" + productoVenta.Alto + "')";
command.Transaction = this.Transaction;
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
}
public void salvarVenta(Venta venta)
{
OdbcCommand command = this.Conect.CreateCommand();
command.CommandText = "insert into TVenta(cliente,comercial,fecha,tipo) values('" + venta.Cliente.Id + "','" + venta.Comercial.Id + "','" + venta.Fecha + "','" + (int)venta.TipoVenta + "')";
command.Transaction = this.Transaction;
try
{
OdbcDataReader reader = command.ExecuteReader();
Console.WriteLine(command.CommandText);
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.Transaction.Rollback();
}
}
}
}
<file_sep>/Perfilac/servicio/Service.cs
using System;
using System.Collections.Generic;
using System.Text;
using Perfilac.dominio;
using Perfilac.dao;
namespace Perfilac.servicio
{
public class Service
{
private EmpresaPerfilac emp;
public EmpresaPerfilac Emp
{
get { return emp; }
set { emp = value; }
}
private ProductoDao daoProducto;
public ProductoDao DaoProducto
{
get { return daoProducto; }
set { daoProducto = value; }
}
private UsuarioDao daoUsuario;
public UsuarioDao DaoUsuario
{
get { return daoUsuario; }
set { daoUsuario = value; }
}
private NomencladorDao daoNomenclador;
public NomencladorDao DaoNomenclador
{
get { return daoNomenclador; }
set { daoNomenclador = value; }
}
private ClienteDao daoCliente;
public ClienteDao DaoCliente
{
get { return daoCliente; }
set { daoCliente = value; }
}
private VentaDao daoVenta;
public VentaDao DaoVenta
{
get { return daoVenta; }
set { daoVenta = value; }
}
public void salvarProducto(Producto producto)
{
this.DaoProducto.salvarProducto(producto);
}
public List<TipoEnchape> obtenerTiposEnchape()
{
return this.daoNomenclador.obtenerTiposEnchapes();
}
public List<TipoProducto> obtenerTiposProducto()
{
return this.daoNomenclador.obtenerTiposProductos();
}
public List<Producto> consultarProductosPorParametros(String codigo, int noFicha, TipoProducto tipo, TipoEnchape enchape)
{
return this.DaoProducto.consultarPorParametros(codigo, noFicha, tipo, enchape);
}
public List<Producto> consultarProducto()
{
return this.emp.Productos;
}
public void salvarCliente(Cliente cliente)
{
this.DaoCliente.salvarClienteCompleto(cliente);
}
public int salvarVenta(Venta venta)
{
return DaoVenta.salvarVentaCompleta(venta);
}
public List<Cliente> obtenerClientes()
{
List<Cliente> result = this.daoCliente.obtenerTodosClientes();
foreach (Cliente var in result)
{
var.Comerciales = obtenerPersonasClientes(var);
}
return result;
}
public List<PersonaCliente> obtenerPersonasClientes(Cliente cliente)
{
return this.daoCliente.obtenerPersonasClientes(cliente);
}
public List<Venta> consultarVentas(int tipo, DateTime fechaInicio, DateTime fechaFin)
{
return daoVenta.consultarVentas(tipo, fechaInicio, fechaFin);
}
public void salvarUsuario(Usuario user)
{
this.daoUsuario.salvarUsuario(user);
}
public void eliminarUsuario(int idUsuario)
{
this.DaoUsuario.eliminarUsuario(idUsuario);
}
public void modificarUsuario(Usuario usuario)
{
this.daoUsuario.modificarUsuario(usuario);
}
public List<Usuario> listarUsuarios()
{
return this.daoUsuario.listarUsuarios();
}
public Service()
{
this.emp = new EmpresaPerfilac();
this.daoProducto = new ProductoDao();
this.daoNomenclador = new NomencladorDao();
this.daoCliente = new ClienteDao();
this.daoVenta = new VentaDao();
this.daoUsuario = new UsuarioDao();
}
}
}
<file_sep>/Perfilac/dominio/Ingreso.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class Ingreso:EntidadPersistente
{
private Venta vent;
public Venta Venta
{
get { return vent; }
set { vent = value; }
}
private Cliente client;
public Cliente Client
{
get { return client; }
set { client = value; }
}
private double importe;
public double Importe
{
get { return importe; }
set { importe = value; }
}
private String cheque;
public String Cheque
{
get { return cheque; }
set { cheque = value; }
}
private TipoMoneda moneda;
public TipoMoneda Moneda
{
get { return moneda; }
set { moneda = value; }
}
public Ingreso(double importe,String cheque,TipoMoneda moneda):base()
{
this.cheque = cheque;
this.importe = importe;
this.moneda = moneda;
}
public override string ToString()
{
return this.cheque + " "+this.importe+"$ "+""+moneda.ToString();
}
}
}
<file_sep>/Perfilac/dominio/ProductoVenta.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class ProductoVenta:EntidadPersistente
{
private int cant;
public int Cant
{
get { return cant; }
set { cant = value; }
}
private double ancho;
public double Ancho
{
get { return ancho; }
set { ancho = value; }
}
private double alto;
public double Alto
{
get { return alto; }
set { alto = value; }
}
private Producto prod;
public Producto Prod
{
get { return prod; }
set { prod = value; }
}
private Venta vent;
public Venta Vent
{
get { return vent; }
set { vent = value; }
}
public ProductoVenta():base()
{
this.cant = 0;
this.ancho = 0;
this.alto = 0;
this.prod = null;
this.vent = null;
}
public double metrosCuadrado()
{
return (this.ancho / 1000) * (this.alto / 1000)*this.cant;
}
public double precioCUP()
{
return this.prod.PrecioCUP * this.metrosCuadrado() / this.cant;
}
public double precioCUC()
{
return this.prod.PrecioCUC * this.metrosCuadrado() / this.cant;
}
public decimal ImporteCUC()
{
double imp = this.precioCUC() * this.cant;
decimal numero = decimal.Parse(imp.ToString());
return Math.Round(numero, 2);
}
public decimal ImporteCUP()
{
double imp = this.precioCUP() * this.cant;
decimal numero = decimal.Parse(imp.ToString());
return Math.Round(numero, 2);
}
}
}
<file_sep>/Perfilac/visual/Nuevo Cliente.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Perfilac.dominio;
using Perfilac.servicio;
namespace Perfilac.visual
{
public partial class Nuevo_Cliente : Form
{
public Nuevo_Cliente(Service servicio)
{
InitializeComponent();
this.servicio = servicio;
this.listPersonaCliente = new List<PersonaCliente>();
}
private Service servicio;
public Service Servicio
{
get { return servicio; }
set { servicio = value; }
}
private Cliente nuevoCliente;
public Cliente NuevoCliente
{
get { return nuevoCliente; }
set { nuevoCliente = value; }
}
private List<PersonaCliente> listPersonaCliente;
public List<PersonaCliente> ListPersonaCliente
{
get { return listPersonaCliente; }
set { listPersonaCliente = value; }
}
private void button4_Click(object sender, EventArgs e)
{
groupBox1.Visible = true;
groupBox2.Visible = false;
}
private void limpiarDatosPersonaAutorizada()
{
textBox7.Clear();
textBox8.Clear();
textBox10.Clear();
textBox9.Clear();
textBox12.Clear();
textBox11.Clear();
}
private void actualizarListadoPersonasAutorizadas()
{
listBox1.Items.Clear();
listBox1.Items.AddRange(this.listPersonaCliente.ToArray());
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void Nuevo_Cliente_Load(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
}
private void button2_Click_1(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
String nombre = textBox1.Text;
String contrato = textBox2.Text;
String codigo = textBox3.Text;
String cuentaCUP = textBox4.Text;
String cuentaCUC = textBox5.Text;
String direccion = textBox6.Text;
if (this.listPersonaCliente.Count > 0)
{
this.nuevoCliente = new Cliente(codigo, nombre, contrato, direccion, this.listPersonaCliente, cuentaCUP, cuentaCUC);
foreach (PersonaCliente var in this.listPersonaCliente)
{
var.Cliente = nuevoCliente;
}
this.servicio.salvarCliente(nuevoCliente);
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("Debe adicionar al menos una persona responsable", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void limpiarDatosCliente()
{
textBox7.Clear();
textBox8.Clear();
textBox10.Clear();
textBox9.Clear();
textBox11.Clear();
textBox12.Clear();
textBox13.Clear();
}
private void button1_Click_2(object sender, EventArgs e)
{
String primerNombre = textBox7.Text;
String segundoNombre = textBox8.Text;
String primerApellido = textBox10.Text;
String segundoApellido = textBox9.Text;
String cargo = textBox11.Text;
String carnet = textBox12.Text;
String telefono = textBox13.Text;
PersonaCliente nuevaPersonaCliente = new PersonaCliente(primerNombre, segundoNombre, primerApellido, segundoApellido, carnet, telefono,cargo);
this.ListPersonaCliente.Add(nuevaPersonaCliente);
actualizarListadoPersonasAutorizadas();
limpiarDatosCliente();
groupBox2.Visible = true;
groupBox1.Visible = false;
}
private void button2_Click_2(object sender, EventArgs e)
{
groupBox2.Visible = true;
groupBox1.Visible = false;
}
private void button3_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
if (MessageBox.Show("Se eliminará el elemento selecionado, ¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.ListPersonaCliente.RemoveAt(listBox1.SelectedIndex);
actualizarListadoPersonasAutorizadas();
}
}
else
MessageBox.Show("Debe seleccionar el elemento a eliminar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
}
}
}<file_sep>/Perfilac/visual/VisorDeInforme.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Perfilac.reportes;
namespace Perfilac.visual
{
public partial class VisorDeInforme : Form
{
public VisorDeInforme(Object report,String selection)
{
InitializeComponent();
crystalReportViewer1.ReportSource = report;
crystalReportViewer1.SelectionFormula = selection;
}
}
}<file_sep>/Perfilac/dominio/TipoVenta.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public enum TipoVenta
{
prefactura,factura
}
}
<file_sep>/Perfilac/dominio/Venta.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class Venta:EntidadPersistente
{
private List<ProductoVenta> listProductoVenta;
public List<ProductoVenta> ListProductoVenta
{
get { return listProductoVenta; }
set { listProductoVenta = value; }
}
private Cliente cliente;
public Cliente Cliente
{
get { return cliente; }
set { cliente = value; }
}
private PersonaCliente comercial;
public PersonaCliente Comercial
{
get { return comercial; }
set { comercial = value; }
}
private DateTime fecha;
public DateTime Fecha
{
get { return fecha; }
set { fecha = value; }
}
private List<Ingreso> importePagado;
public List<Ingreso> ImportePagado
{
get { return importePagado; }
set { importePagado = value; }
}
private TipoVenta tipoVenta;
public TipoVenta TipoVenta
{
get { return tipoVenta; }
set { tipoVenta = value; }
}
public decimal ImporteCUCTotal()
{
decimal importeTotal = 0;
foreach (ProductoVenta var in this.listProductoVenta)
{
importeTotal += var.ImporteCUC();
}
return importeTotal;
}
public decimal ImporteCUPTotal()
{
decimal importeTotal = 0;
foreach (ProductoVenta var in this.listProductoVenta)
{
importeTotal += var.ImporteCUP();
}
return importeTotal;
}
public Venta(Cliente cliente, PersonaCliente comercial, DateTime fecha,List<ProductoVenta> listProductoVenta,TipoVenta tipoVenta)
: base()
{
this.cliente = cliente;
this.comercial = comercial;
this.fecha = fecha;
this.listProductoVenta = listProductoVenta;
this.tipoVenta = tipoVenta;
}
}
}
<file_sep>/Perfilac/dominio/EntidadPersistente.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public class EntidadPersistente
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
public EntidadPersistente()
{
this.id = -1;
}
}
}
<file_sep>/Perfilac/dominio/TipoMoneda.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Perfilac.dominio
{
public enum TipoMoneda
{
CUP,CUC
}
}
| 63839f83422997f2a01d88db7efbad25ca69c59b | [
"Markdown",
"C#"
] | 28 | C# | xalfonso/perfilac1.0 | 4b14a2f5272cb4ab7dc10bbdab35f23868a75c0f | 6ad56e20d56bda001eaf04691d1cd9b1ace6da4b |
refs/heads/master | <repo_name>LonelyDrifter/ts_study_demo<file_sep>/module/a.ts
namespace A {
export const aName = 'aName';
}<file_sep>/app.ts
// // 基本数据类型
// // let num = 25;
// // num = 2;
// // 不能储存非原有的类型数据
// // ts 原型
// let num = 25;
// // 等同于
// // let num : number = 25;
// // let boolean = true;
// let boolean: boolean = true;
// let string: string = '123';
// let anything: any = '123';
// anything = 456;
// // 数组 元组 枚举
// let names: Array<string> = ['1', '2']; // 等同于 let names: string [] = ['1', '2'];
// let ages: Array<number> = [1, 2] // 等同于 let ages: number [] = [1, 2];
// let any: Array<any> = [1, '2'] // 等同于 let any: any [] = [1, '2'];
// // 元组
// let list: [ number, string] = [ 1, '1'] // 每个位置的元素类型要对应上
// // 枚举 enum
// enum Color {
// black,
// yellow,
// red
// }
// let myColor: Color = Color.black;
// console.log(myColor);
// // 函数
// // 函数的相关类型
// // 返回值类型
// function retunValue (): number {
// return 123;
// }
// console.log(retunValue());
// // 空
// function sayHello (): void {
// console.log('hello')
// }
// // 参数类型
// function sumValue(value1: number, value2: number) : number {
// return value1 + value2; // 如果两个参数中有一个不是数值,返回NaN;
// };
// console.log(sumValue(1,2));
// // 函数类型
// let myFunc: (a: number, b: number) => number;
// // myFunc = sayHello;
// myFunc = sumValue;
// // object & type
// let objectOne = {
// name: '小小',
// age: 12
// }
// // 会报错
// // objectOne = { }
// // Type '{}' is missing the following properties from type '{ name: string; age: number; }': name, agets(2739)
// // 错误
// // let objectTwo : {name: string, age: number} = {
// // name: 12, // 不能将类型“number”分配给类型“string”。ts(2322) app.ts(74, 18): The expected type comes from property 'name' which is declared here on type '{ name: string; age: number; }'
// // age: '12' //不能将类型“string”分配给类型“number”。ts(2322)
// // }
// // 正确
// let objectTwo : {name: string, age: number} = {
// name: '小小',
// age: 12
// }
// // 复杂对象类型
// let complex: {data: number[], myFunc: (item: number) => number[]} = {
// data: [1, 2, 3],
// myFunc: function(item: number):number[] {
// this.data.push(item);
// return this.data;
// }
// }
// // type 生成类型,用于多个对象都用一个
// type MyType = {data: number[], myFunc: (item: number) => number[]};
// let complex1: MyType = {
// data: [1, 2, 3],
// myFunc: function(item: number):number[] {
// this.data.push(item);
// return this.data;
// }
// }
// // union type
// let unionType : number | string | boolean = 12;
// unionType = '12';
// unionType = true;
// // unionType = [1, 2] // 不能将类型“number[]”分配给类型“string | number | boolean”。不能将类型“number[]”分配给类型“string”
// // 检查类型
// let checkType = 10;
// if (typeof checkType == "number") {
// // 类型的名字要用引号引起来
// console.log('number')
// }
// // null 和 undefined
// let myNull = 1;
// // myNull = null; // 不能将类型“null”分配给类型“number”, 但将严格模式禁用掉就可以了,tsconfig.json 中 "strict": true 变为 false 即可。
// // never never类型是任何类型的子类型,也可以赋值给任何类型;然而,没有类型是never 的子类型或可以赋值给never类型(除了never 本身之外)。即使any也不可以赋值给never。通常表现为抛出异常或无法执行到终止点(例如无限循环)
// let x: never;
// // x = 123; // 不能将类型“123”分配给类型“never”。
// // never 的应用场景 抛出异常
// function error(messages: string): never {
// throw new Error(messages);
// }
// // 死循环
// function loop(): never {
// while(true) { }
// }
// let y : number;
// y = (() => {
// throw new Error('error');
// })();<file_sep>/class.ts
// class 类(属性,方法)
class Person {
public name: string; // public 公用的
protected gender: string = '男'; // protected 受保护的 当前类和继承的子类使用
private age: number = 27; // private 私有的 当前类可以使用
// 构造函数
constructor (name: string, public username: string) {
// this.name 内部 name 外部传来的
this.name = name;
this.username = username;
// this.gender = gender; // 属性“gender”受保护,只能在类“Person”及其子类中访问。
}
public pringAge(age: number) {
this.age = age;
// console.log(this.age);
}
public pringName(name: string) {
this.name = name;
console.log(this.name);
}
private setGender (gender: string) {
this.gender = this.gender
}
}
const person = new Person('小刘', '小李');
// console.log(person.name, person.username);
person.pringAge(30);
// 创建子类 Student 继承 Person
class Student extends Person {
constructor(name: string, username: string){
super(name, username);
}
// 重写父类方法
public pringName(name: string) {
this.name = name + '123';
console.log(this.name);
}
}
const Mr_L = new Student('小刘', '小李');
Mr_L.pringName('哈哈');<file_sep>/generic.ts
// 泛型 Generic
// 在函数中使用泛型
function identify(arg: any) {
return arg
};
console.log(identify(20));
// 根据传递的类型,自动对应类型
function identify1<T>(arg: T): T {
return arg
};
// 明确类型
console.log(identify1<string>('20'));
// 交给ts 推断类型
console.log(identify(20));
// 在接口中使用泛型
interface GenericInterface {
<T>(arg: T): T;
}
// 或
interface GenericInterfaceOne<T> {
(arg: T): T;
}
function identify2<T>(arg: T): T {
return arg
};
let myIdentify: GenericInterface = identify2;
let myIdentifyOne: GenericInterfaceOne<number | string> = identify2;
// 明确类型
console.log(myIdentify<string>('myIdentify'));
// 交给ts 推断类型
console.log(myIdentify(30));
// 或
// 明确类型
console.log(myIdentifyOne('myIdentifyOne')); // 在let myIdentifyOne: GenericInterfaceOne<number | string> = identify2; 指定完了
// 交给ts 推断类型
console.log(myIdentifyOne(40));
// 为泛型添加约束
// 指定参数属性
function getLength<T extends { length: any }>(obj: T): any {
return obj.length;
}
const obj = {
name: 'obj',
age: 25,
length: 10
}
console.log(getLength(obj));
// 指定类型
function getLengthOne<T extends number>(obj: T): any {
return obj;
}
const obj1 = 25
console.log(getLengthOne(obj1));
// 泛型应用在calss中
class CountNumber<T>{
number1: T;
number2: T;
constructor (num1: T, num2: T) {
this.number1 = num1;
this.number2 = num2;
}
calcalate () :number {
// return this.number1 + this.number2; // Operator '+' cannot be applied to types 'T' and 'T'.
return +this.number1 / +this.number2; // + 用于解析 ts 识别的, 用于计算
}
}
const countnumber = new CountNumber<number>(100, 200);
const countnumber1 = new CountNumber<string>('100', '200');
console.log(countnumber.calcalate())
console.log(countnumber1.calcalate())<file_sep>/class_set_get.ts
// class set get 修饰词 用于隔离私有属性 和 公开属性
// class 静态属性和方法
class PersonOne {
private _name: string = 'PersonOne_name';
// 静态属性 可直接调用
static specialty: string = '唱歌';
// 静态方法
static getSpecialty () :string {
return this.specialty;
}
// 私有属性赋值
set setName (value: string) {
this._name = value;
}
// 私有属性取值
get getName () {
return this._name;
}
}
let personone = new PersonOne();
console.log(personone.getName);
personone.setName = 'personone_name';
console.log(personone.getName);
console.log(PersonOne.specialty);
console.log(PersonOne.getSpecialty());<file_sep>/interface.ts
// interface 接口
interface PeopleInterface {
name: string,
age: number, // : 必传
sex?: string, // ?: 可选
readonly salary: number, // 只读,不能修改
[propName: string]: any, // [propName: string] 代表可以给任何名字
greet():void
}
// interface 可以继承 type 不能继承
type People1 = { name: string, age: number };
let people: PeopleInterface = {
name: '小刘',
age: 25,
salary: 10000,
ids: [1, 2, 3],
greet() {
console.log('谢谢!');
}
}
// people.salary = 1000; //Cannot assign to 'salary' because it is a read-only property.
function printPeople(people: PeopleInterface){
console.log(`我叫${people.name},${people.age}岁,我的工作是${people.salary}`)
}
printPeople(people)
people.greet();
interface StudentInterface {
id: number,
course: string
}
// 创建类 可以实现多个接口
class NewPeople implements PeopleInterface, StudentInterface{
name: string = 'newPeople';
age: number = 25;
salary: number = 50000;
greet() {
console.log('Hello newPeople')
};
id: number = 1;
course: string = 'IT'
}
// interface 接口的继承
interface Employee extends PeopleInterface {
work: string
}
// 实体要有子类的属性也要有父类的属性
const employee : Employee = {
name: '继承PeopleInterface的Employee接口的实体',
age: 25,
salary: 100000,
greet() {
console.log('employee')
},
work: '前端开发'
}
console.log(employee);<file_sep>/generic.js
"use strict";
// 泛型 Generic
// 在函数中使用泛型
function identify(arg) {
return arg;
}
;
console.log(identify(20));
// 根据传递的类型,自动对应类型
function identify1(arg) {
return arg;
}
;
// 明确类型
console.log(identify1('20'));
// 交给ts 推断类型
console.log(identify(20));
function identify2(arg) {
return arg;
}
;
var myIdentify = identify2;
var myIdentifyOne = identify2;
// 明确类型
console.log(myIdentify('myIdentify'));
// 交给ts 推断类型
console.log(myIdentify(30));
// 或
// 明确类型
console.log(myIdentifyOne('myIdentifyOne')); // 在let myIdentifyOne: GenericInterfaceOne<number | string> = identify2; 指定完了
// 交给ts 推断类型
console.log(myIdentifyOne(40));
// 为泛型添加约束
// 指定参数属性
function getLength(obj) {
return obj.length;
}
var obj = {
name: 'obj',
age: 25,
length: 10
};
console.log(getLength(obj));
// 指定类型
function getLengthOne(obj) {
return obj;
}
var obj1 = 25;
console.log(getLengthOne(obj1));
// 泛型应用在calss中
var CountNumber = /** @class */ (function () {
function CountNumber(num1, num2) {
this.number1 = num1;
this.number2 = num2;
}
CountNumber.prototype.calcalate = function () {
return this.number1 + this.number2; // + 用于解析 ts 识别的, 用于计算
};
return CountNumber;
}());
var countnumber = new CountNumber(100, 200);
var countnumber1 = new CountNumber('100', '200');
console.log(countnumber.calcalate());
console.log(countnumber1.calcalate());
<file_sep>/class_set_get.js
"use strict";
// class set get 修饰词 用于隔离私有属性 和 公开属性
// class 静态属性和方法
var PersonOne = /** @class */ (function () {
function PersonOne() {
this._name = 'PersonOne_name';
}
// 静态方法
PersonOne.getSpecialty = function () {
return this.specialty;
};
Object.defineProperty(PersonOne.prototype, "setName", {
// 私有属性赋值
set: function (value) {
this._name = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PersonOne.prototype, "getName", {
// 私有属性取值
get: function () {
return this._name;
},
enumerable: true,
configurable: true
});
// 静态属性 可直接调用
PersonOne.specialty = '唱歌';
return PersonOne;
}());
var personone = new PersonOne();
console.log(personone.getName);
personone.setName = 'personone_name';
console.log(personone.getName);
console.log(PersonOne.specialty);
console.log(PersonOne.getSpecialty());
<file_sep>/README.md
#### 用于练习ts的例子
包含:
* 基本数据类型
* 数组、元组、枚举类型
* 函数类型
* 对象类型和type
* never和null
* 类,类的属性和方法
* 类的继承
* set/get/static
* 命名空间namespace
* 命名空间文件拆分
* 多重命名空间及引入文件
* module的使用
* interface接口的用法
* 接口的继承及类的实现
* 泛型Generic的函数应用
* 泛型Generic的类应用
<file_sep>/namespace.js
"use strict";
// namespace : 命名空间 内部的属性方法要让外部获取到 需要加export
// const PI = 1;
// console.log(MyMath.sumvalue(5, 10));
// console.log(MyMath.calcCircle(8));
// console.log(PI);
// console.log(MyMath.PI);
// tsc --outfile namespace.js sumvalue.ts namespace_path.ts namespace.ts 注意合并顺序
// /// 在ts 中代表引入文件
/// <reference path= "sumvalue.ts"/>
/// <reference path= "namespace_path.ts"/>
// tsc namespace.ts --outFile namespace.js
// 多重命名空间
var OneSpace;
(function (OneSpace) {
var TwoSpace;
(function (TwoSpace) {
TwoSpace.a = 'TwoSpace中的a';
})(TwoSpace = OneSpace.TwoSpace || (OneSpace.TwoSpace = {}));
})(OneSpace || (OneSpace = {}));
console.log(OneSpace.TwoSpace.a);
<file_sep>/namespace.ts
// namespace : 命名空间 内部的属性方法要让外部获取到 需要加export
// const PI = 1;
// console.log(MyMath.sumvalue(5, 10));
// console.log(MyMath.calcCircle(8));
// console.log(PI);
// console.log(MyMath.PI);
// tsc --outfile namespace.js sumvalue.ts namespace_path.ts namespace.ts 注意合并顺序
// /// 在ts 中代表引入文件
/// <reference path= "sumvalue.ts"/>
/// <reference path= "namespace_path.ts"/>
// tsc namespace.ts --outFile namespace.js
// 多重命名空间
namespace OneSpace {
export namespace TwoSpace {
export const a = 'TwoSpace中的a';
}
}
console.log(OneSpace.TwoSpace.a);<file_sep>/module/b.ts
namespace B {
export const bName = 'bName';
}<file_sep>/class.js
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// class 类(属性,方法)
var Person = /** @class */ (function () {
// 构造函数
function Person(name, username) {
this.username = username;
this.gender = '男'; // protected 受保护的 当前类和继承的子类使用
this.age = 27; // private 私有的 当前类可以使用
// this.name 内部 name 外部传来的
this.name = name;
this.username = username;
// this.gender = gender; // 属性“gender”受保护,只能在类“Person”及其子类中访问。
}
Person.prototype.pringAge = function (age) {
this.age = age;
// console.log(this.age);
};
Person.prototype.pringName = function (name) {
this.name = name;
console.log(this.name);
};
Person.prototype.setGender = function (gender) {
this.gender = this.gender;
};
return Person;
}());
var person = new Person('小刘', '小李');
// console.log(person.name, person.username);
person.pringAge(30);
// 创建子类 Student 继承 Person
var Student = /** @class */ (function (_super) {
__extends(Student, _super);
function Student(name, username) {
return _super.call(this, name, username) || this;
}
// 重写父类方法
Student.prototype.pringName = function (name) {
this.name = name + '123';
console.log(this.name);
};
return Student;
}(Person));
var Mr_L = new Student('小刘', '小李');
Mr_L.pringName('哈哈');
<file_sep>/namespace_path.js
"use strict";
var MyMath;
(function (MyMath) {
MyMath.PI = 3.14;
function calcCircle(value) {
return value * MyMath.PI;
}
MyMath.calcCircle = calcCircle;
})(MyMath || (MyMath = {}));
<file_sep>/app.js
"use strict";
// // 基本数据类型
// // let num = 25;
// // num = 2;
// // 不能储存非原有的类型数据
// // ts 原型
// let num = 25;
// // 等同于
// // let num : number = 25;
// // let boolean = true;
// let boolean: boolean = true;
// let string: string = '123';
// let anything: any = '123';
// anything = 456;
// // 数组 元组 枚举
// let names: Array<string> = ['1', '2']; // 等同于 let names: string [] = ['1', '2'];
// let ages: Array<number> = [1, 2] // 等同于 let ages: number [] = [1, 2];
// let any: Array<any> = [1, '2'] // 等同于 let any: any [] = [1, '2'];
// // 元组
// let list: [ number, string] = [ 1, '1'] // 每个位置的元素类型要对应上
// // 枚举 enum
// enum Color {
// black,
// yellow,
// red
// }
// let myColor: Color = Color.black;
// console.log(myColor);
// // 函数
// // 函数的相关类型
// // 返回值类型
// function retunValue (): number {
// return 123;
// }
// console.log(retunValue());
// // 空
// function sayHello (): void {
// console.log('hello')
// }
// // 参数类型
// function sumValue(value1: number, value2: number) : number {
// return value1 + value2; // 如果两个参数中有一个不是数值,返回NaN;
// };
// console.log(sumValue(1,2));
// // 函数类型
// let myFunc: (a: number, b: number) => number;
// // myFunc = sayHello;
// myFunc = sumValue;
// // object & type
// let objectOne = {
// name: '小小',
// age: 12
// }
// // 会报错
// // objectOne = { }
// // Type '{}' is missing the following properties from type '{ name: string; age: number; }': name, agets(2739)
// // 错误
// // let objectTwo : {name: string, age: number} = {
// // name: 12, // 不能将类型“number”分配给类型“string”。ts(2322) app.ts(74, 18): The expected type comes from property 'name' which is declared here on type '{ name: string; age: number; }'
// // age: '12' //不能将类型“string”分配给类型“number”。ts(2322)
// // }
// // 正确
// let objectTwo : {name: string, age: number} = {
// name: '小小',
// age: 12
// }
// // 复杂对象类型
// let complex: {data: number[], myFunc: (item: number) => number[]} = {
// data: [1, 2, 3],
// myFunc: function(item: number):number[] {
// this.data.push(item);
// return this.data;
// }
// }
// // type 生成类型,用于多个对象都用一个
// type MyType = {data: number[], myFunc: (item: number) => number[]};
// let complex1: MyType = {
// data: [1, 2, 3],
// myFunc: function(item: number):number[] {
// this.data.push(item);
// return this.data;
// }
// }
// // union type
// let unionType : number | string | boolean = 12;
// unionType = '12';
// unionType = true;
// // unionType = [1, 2] // 不能将类型“number[]”分配给类型“string | number | boolean”。不能将类型“number[]”分配给类型“string”
// // 检查类型
// let checkType = 10;
// if (typeof checkType == "number") {
// // 类型的名字要用引号引起来
// console.log('number')
// }
// // null 和 undefined
// let myNull = 1;
// // myNull = null; // 不能将类型“null”分配给类型“number”, 但将严格模式禁用掉就可以了,tsconfig.json 中 "strict": true 变为 false 即可。
// // never never类型是任何类型的子类型,也可以赋值给任何类型;然而,没有类型是never 的子类型或可以赋值给never类型(除了never 本身之外)。即使any也不可以赋值给never。通常表现为抛出异常或无法执行到终止点(例如无限循环)
// let x: never;
// // x = 123; // 不能将类型“123”分配给类型“never”。
// // never 的应用场景 抛出异常
// function error(messages: string): never {
// throw new Error(messages);
// }
// // 死循环
// function loop(): never {
// while(true) { }
// }
// let y : number;
// y = (() => {
// throw new Error('error');
// })();
| e3e0cc7021880bce62d8a511562f65749316d8e2 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 15 | TypeScript | LonelyDrifter/ts_study_demo | a9625a292df58e729798c17a2cbcb176a200254d | bcb486dbbdd033c61965956de657e76ca09eab9c |
refs/heads/master | <file_sep>use block_cryptography_rust::hashing::sha256_hash;
use block_cryptography_rust::signing::verify_data;
use ring::signature::Signature;
use ring::digest::Digest;
pub type Username = String;
pub type PublicKey = [u8; 32];
pub type Hash = Digest;
pub type Seal = Signature;
pub struct Transaction {
to: Username,
from: Username,
amount: f32,
sender_seal: Signature,
reciever_seal: Signature
}
impl Transaction {
pub fn new(to: Username, from: Username, amount: f32, sender_seal: Seal, reciever_seal: Seal) -> Self {
Transaction {
to: to,
from: from,
amount: amount,
sender_seal: sender_seal,
reciever_seal: reciever_seal
}
}
pub fn to(&self) -> &Username {
&self.to
}
pub fn from(&self) -> &Username {
&self.from
}
pub fn amount(&self) -> &f32 {
&self.amount
}
pub fn sender_seal(&self) -> &Seal {
&self.sender_seal
}
pub fn receiver_seal(&self) -> &Seal {
&self.reciever_seal
}
pub fn hash(&self) -> Hash {
sha256_hash(format!("{}{}{}", &self.to, &self.from, &self.amount).as_bytes())
}
pub fn check(&self, sender_key: &PublicKey, reciever_key: &PublicKey) -> bool {
verify_data(sender_key, format!("{:?}", self.hash()).as_bytes(), self.sender_seal) && verify_data(reciever_key, format!("{:?}", self.hash()).as_bytes(), self.reciever_seal)
}
}<file_sep>use ring::digest::Digest;
use ring::signature::Signature;
pub type Hash = Digest;
pub type Seal = Signature;
pub type Username = String;
pub type PublicKey = [u8; 32];<file_sep>use std::collections::HashMap;
pub type Username = String;
pub type PublicKey = [u8; 32];
fn add_user(key_map: &mut HashMap<Username, PublicKey>, username: Username, key: PublicKey) -> Option<()> {
match key_map.insert(username, key) {
Some(_) => { Some(()) },
None => { None }
}
}
fn get_user<'a>(key_map: &'a HashMap<Username, PublicKey>, username: &'a Username) -> Option<&'a PublicKey> {
key_map.get(username)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let mut map = std::collections::HashMap::<Username, PublicKey>::new();
add_user(&mut map, "Jake".to_string(), [0 as u8; 32]);
get_user(&map, &"Jake".to_string());
}
} | 9b0c999d41636121ebea1925d5d259db09a5c3cc | [
"Rust"
] | 3 | Rust | jweir136/single_miner_coin | 4576fccb3a2a4d502a3995fae2e45554660675d8 | 42d5087504a1577f9944087adb0d7fb8c8ec44b9 |
refs/heads/master | <file_sep>def current_age_for_birth_year(birth_year)
2016-(birth_year)
end
| 5f1b737e9f39643c8a2b2093dbdbb2eb7084eedb | [
"Ruby"
] | 1 | Ruby | jmpann/intro-to-tdd-rspec-and-learn-web-1116 | b82b25c7e63b24c09517bb251e9d1317872b3cb1 | c240bf38de0769b35b4c58dbebd951ebdc6f21cb |
refs/heads/master | <repo_name>BCITbridgeproject/springmass<file_sep>/animate.py
#import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import os
matplotlib.rcParams['interactive'] = False
aggregate = 5
start_time = 0
x_max = 0
if not os.path.exists("output/plots"):
os.makedirs("output/plots")
f = open("output/displacements.csv", "r")
t = []
x = []
eof = False
buf = f.readline()
line = buf.split(",")
masses = len(line) - 1
for i in range(0, masses):
x.append([])
while eof == False:
buf = f.readline()
if buf == "":
eof = True
else:
line = buf.split(",")
t.append(float(line[0]))
for i in range(0, masses):
x[i].append(float(line[i + 1]))
f = open("output/car_displacements.csv", "r")
car_x = []
eof = False
buf = f.readline()
line = buf.split(",")
while eof == False:
buf = f.readline()
if buf == "":
eof = True
else:
line = buf.split(",")
car_x.append(float(line[1]))
f.close()
t = t[start_time:]
for i in range(0, masses):
x[i] = x[i][start_time:]
for i in range(0, masses):
i_x_max = np.max(np.abs(x[i]))
if i_x_max > x_max:
x_max = i_x_max
x_max *= 1.05
for i in range(0, int(len(t) / aggregate)):
print("frame: " + str(i + 1) + "/" + str(int(len(t) / aggregate)))
plt.clf()
values = []
for j in range(0, masses):
values.append(x[j][i * aggregate])
plt.plot(range(0, masses), values)
if (car_x[i * aggregate] < masses):
plt.plot(car_x[i * aggregate], values[int(round(car_x[i * aggregate]))], 'ro')
#plt.plot(range(0, masses), values, 'ro')
plt.text(0, x_max * 1.05, "t = " + str(t[i * aggregate]))
plt.axis([0, masses - 1, -x_max, x_max])
plt.savefig("output/plots/" + str(i).zfill(5) + ".png")<file_sep>/springmass.py
import numpy
import scipy.integrate
import random
import math
import time
import os.path
import config as cfg
import pylab
# c-style structure definitions for holding data
class SimulationParameters:
period_length = None
stop_time = None
points = None
timestep = None
t = None
system = None
initial_conditions = None
car_force = None
car_amplitudes = None
car_velocity = None
car_cross_periods = None
class SimulationResults:
solution = None
x = None
v = None
a = None
car_x = None
fft = None
fft_frequencies = None
fft_magnitudes = None
fft_time = None
fft_time_frequencies = None
fft_time_magnitudes = None
# utility function
def randomize(base_value, variance):
return base_value + base_value * variance * (random.random() - random.random())
# Initialization functions
def calculateParameters():
parameters = SimulationParameters()
parameters.period_length = 2 * math.pi / math.sqrt(cfg.stiffness_base_value * 2 / cfg.mass_base_value)
parameters.stop_time = cfg.periods * parameters.period_length # value of t that the simulation ends at
parameters.points = int(round(cfg.periods * parameters.period_length * cfg.sample_rate)) # how many points to solve for
parameters.timestep = parameters.stop_time / parameters.points
parameters.t = numpy.linspace(0.0, parameters.stop_time, parameters.points)
parameters.system = createSystem()
parameters.initial_conditions = createInitialConditions()
parameters.car_velocity = randomize(cfg.car_velocity_base_value, cfg.car_velocity_variance)
parameters.car_cross_periods = cfg.nodes / parameters.car_velocity
parameters.car_force = randomize(cfg.car_force_base_value, cfg.car_force_variance)
parameters.car_amplitudes = []
for i in range(0, 100):
parameters.car_amplitudes.append(random.random() - random.random())
return parameters
def createInitialConditions():
w = numpy.zeros(cfg.nodes * 2 + 1)
return w
def createSystem():
mass_matrix = numpy.zeros((cfg.nodes, cfg.nodes))
for i in range(0, cfg.nodes):
mass_matrix[i][i] = randomize(cfg.mass_base_value, cfg.mass_variance)
stiffness_values = []
for i in range(0, cfg.nodes + 1):
stiffness_values.append(randomize(cfg.stiffness_base_value, cfg.stiffness_variance))
stiffness_matrix = numpy.zeros((cfg.nodes, cfg.nodes))
stiffness_matrix[0][0] = stiffness_values[0] + stiffness_values[1]
for i in range(0, cfg.nodes - 1):
stiffness_matrix[i][i] = stiffness_values[i] + stiffness_values[i + 1]
stiffness_matrix[i][i + 1] = -stiffness_values[i + 1]
stiffness_matrix[i + 1][i] = -stiffness_values[i + 1]
stiffness_matrix[i + 1][i + 1] = stiffness_values[i + 1] + stiffness_values[i + 2]
damping_values = []
for i in range(0, cfg.nodes + 1):
damping_values.append(randomize(cfg.damping_base_value, cfg.damping_variance))
damping_matrix = numpy.zeros((cfg.nodes, cfg.nodes))
damping_matrix[0][0] = damping_values[0] + damping_values[1]
for i in range(0, cfg.nodes - 1):
damping_matrix[i][i] = damping_values[i] + damping_values[i + 1]
damping_matrix[i][i + 1] = -damping_values[i + 1]
damping_matrix[i + 1][i] = -damping_values[i + 1]
damping_matrix[i + 1][i + 1] = damping_values[i + 1] + damping_values[i + 2]
restoring_force_matrix = numpy.dot(numpy.linalg.inv(mass_matrix), -stiffness_matrix)
damping_force_matrix = numpy.dot(numpy.linalg.inv(mass_matrix), -damping_matrix)
system = numpy.vstack((numpy.hstack((numpy.zeros((cfg.nodes, cfg.nodes)), numpy.identity(cfg.nodes))), numpy.hstack((restoring_force_matrix, damping_force_matrix))))
system = numpy.vstack((system, numpy.zeros(cfg.nodes * 2)))
car = numpy.zeros(((cfg.nodes * 2) + 1, 1))
car[len(car) - 1] = 1
system = numpy.hstack((system, car))
return system
# Simulation functions
def runSimulation(parameters):
result = SimulationResults()
result.solution = scipy.integrate.odeint(theFunction, parameters.initial_conditions, parameters.t, args=(parameters,))
result.x = []
result.v = []
result.a = []
for i in range(1, cfg.sensors + 1):
result.x.append([])
result.v.append([])
result.a.append([])
n = float(cfg.nodes) / (float(cfg.sensors) + 1)
si = int(i * n)
for j in range(0, parameters.points):
x = result.solution[j][si]
result.x[i - 1].append(x)
result.v[i - 1].append(result.solution[j][cfg.nodes + si])
accelerations = theFunction(result.solution[j], parameters.t[j], parameters)
result.a[i - 1].append(accelerations[cfg.nodes + si])
result.car_x = []
for i in range(0, parameters.points):
result.car_x.append(result.solution[i][len(result.solution[0]) - 1])
result.fft = []
for i in range(0, cfg.sensors):
result.fft.append(numpy.fft.rfft(result.a[i]))
result.fft_frequencies = []
for i in range(0, len(result.fft[0])):
result.fft_frequencies.append(cfg.sample_rate * float(i) / float(parameters.points))
result.fft_magnitudes = []
for i in range(0, cfg.sensors):
result.fft_magnitudes.append([])
for j in range(0, len(result.fft[0])):
result.fft_magnitudes[i].append(math.sqrt(result.fft[i][j].real ** 2 + result.fft[i][j].imag ** 2))
result.fft_time = []
for i in range(0, cfg.fft_time_bins):
result.fft_time.append([])
for j in range(0, cfg.sensors):
result.fft_time[i].append([])
begin = i * (parameters.points / cfg.fft_time_bins)
end = (i + 1) * (parameters.points / cfg.fft_time_bins)
result.fft_time[i][j] = numpy.fft.rfft(result.a[j][begin:end])
result.fft_time_frequencies = []
for i in range(0, len(result.fft_time[0][0])):
result.fft_time_frequencies.append(cfg.sample_rate * float(i) / float(parameters.points / cfg.fft_time_bins))
result.fft_time_magnitudes = []
for i in range(0, cfg.fft_time_bins):
result.fft_time_magnitudes.append([])
for j in range(0, cfg.sensors):
result.fft_time_magnitudes[i].append([])
for k in range(0, len(result.fft_time[i][j])):
result.fft_time_magnitudes[i][j].append(math.sqrt(result.fft_time[i][j][k].real ** 2 + result.fft_time[i][j][k].imag ** 2))
return result
def getCarVelocity(t, parameters):
sinsum = 0
for i in range(0, len(parameters.car_amplitudes)):
sinsum += parameters.car_amplitudes[i] * math.sin(i * (2 * math.pi / parameters.stop_time) * t)
return parameters.car_velocity + sinsum * parameters.car_velocity * cfg.car_velocity_driving_variance
def theFunction(conditions, t, parameters):
car_x = conditions[len(conditions) - 1]
f = numpy.dot(parameters.system, conditions)
f[len(f) - 1] = getCarVelocity(t, parameters)
if math.floor(car_x) < cfg.nodes:
f[cfg.nodes + math.floor(car_x)] -= parameters.car_force * (1 - (car_x - math.floor(car_x)))
if math.ceil(car_x) < cfg.nodes:
f[cfg.nodes + math.ceil(car_x)] -= parameters.car_force * (1 - (math.ceil(car_x) - car_x))
return f
# Output functions
def writeToFile(filename, variable_names, data):
f = open(filename, "w")
f.write(variable_names[0])
for i in range(1, len(variable_names)):
f.write("," + variable_names[i])
f.write("\n")
for i in range(0, len(data[0])):
f.write(str(data[0][i]))
for j in range(1, len(data)):
f.write("," + str(data[j][i]))
f.write("\n")
f.close()
def getOutputFilename(output_name):
if cfg.output_overwrite:
return "output/" + output_name + ".csv"
else:
count = 0
while True:
filename = "output/" + output_name + str(count) + ".csv"
if os.path.isfile(filename) == False:
return filename
else:
count += 1
def outputData(result, parameters):
if not os.path.exists("output"):
os.makedirs("output")
if cfg.output_displacements:
variable_names = ["t"]
for i in range(0, cfg.sensors):
variable_names.append("x" + str(i + 1))
writeToFile(getOutputFilename("displacements"), variable_names, numpy.vstack((parameters.t, result.x)))
if cfg.output_velocities:
variable_names = ["t"]
for i in range(0, cfg.sensors):
variable_names.append("v" + str(i + 1))
writeToFile(getOutputFilename("velocities"), variable_names, numpy.vstack((parameters.t, result.v)))
if cfg.output_accelerations:
variable_names = ["t"]
for i in range(0, cfg.sensors):
variable_names.append("a" + str(i + 1))
writeToFile(getOutputFilename("accelerations"), variable_names, numpy.vstack((parameters.t, result.a)))
if cfg.output_fft:
variable_names = ["freq"]
for i in range(0, cfg.sensors):
variable_names.append("mag" + str(i + 1))
writeToFile(getOutputFilename("fft"), variable_names, numpy.vstack((result.fft_frequencies, result.fft_magnitudes)))
if cfg.output_fft_time:
variable_names = ["freq"]
for i in range(0, cfg.sensors):
variable_names.append("mag" + str(i + 1))
for i in range(0, cfg.fft_time_bins):
filename = "fft_time_b" + str(i) + "s"
writeToFile(getOutputFilename(filename), variable_names, numpy.vstack((result.fft_time_frequencies, result.fft_time_magnitudes[i])))
if cfg.output_car_displacements:
variable_names = ["t", "x"]
writeToFile(getOutputFilename("car_displacements"), variable_names, numpy.vstack((parameters.t, result.car_x)))
# Display functions
def displayData(result, parameters):
if cfg.display_fft_time == True:
pylab.figure()
for i in range(0, cfg.fft_time_bins):
pylab.plot(result.fft_time_frequencies, result.fft_time_magnitudes[i][cfg.sensors / 2])
if cfg.display_animation == True:
pylab.figure()
pylab.ion()
pylab.axis([0, cfg.sensors - 1, numpy.amin(result.x), numpy.amax(result.x)])
x = numpy.linspace(0, cfg.sensors, cfg.sensors)
car_x = 0
car_y = 0
y = numpy.zeros(cfg.sensors)
line, = pylab.plot(x, y)
car, = pylab.plot(car_x, car_y, 'rs')
for i in pylab.arange(0, parameters.points / cfg.animation_aggregate_frames):
for j in range(0, cfg.sensors):
y[j] = result.x[j][i * cfg.animation_aggregate_frames]
line.set_ydata(y)
car.set_xdata(result.solution[i * cfg.animation_aggregate_frames][len(result.solution[0]) - 1])
pylab.draw()
pylab.pause(0.033)
# Nothing to see here
def main():
random.seed()
for i in range(0, cfg.simulations):
print("Simulation " + str(i + 1) + "/" + str(cfg.simulations))
parameters = calculateParameters()
result = runSimulation(parameters)
outputData(result, parameters)
displayData(result, parameters)
if __name__ == "__main__":
main()<file_sep>/config.py
simulations = 1 # number of simulations to run
nodes = 100 # number of nodes (masses)
sensors = nodes # cannot be more than the number of nodes!
periods = 100 # number of periods to simulate
sample_rate = 1 # highest frequency is less than 0.5
mass_base_value = 1.0
mass_variance = 0 # how much the mass of each node can vary, 0.1 = +/- 10%
stiffness_base_value = 1.0
stiffness_variance = 0
damping_base_value = 1.0
damping_variance = 0
car_force_base_value = 1.0 # the downwards acceleration the car exerts on the nodes
car_force_variance = 0
car_velocity_base_value = 1.0
car_velocity_variance = 0.0
car_velocity_driving_variance = 0.0 # how much the car's velocity varies as it drives across
fft_time_bins = 5 # how many bins to seperate the simulation into time-wise
output_overwrite = True # if false, write to a new file instead of overwriting
output_displacements = True
output_velocities = True
output_accelerations = True
output_fft = True
output_fft_time = True
output_car_displacements = True
display_animation = False
display_fft_time = False
animation_aggregate_frames = 20<file_sep>/Makefile
animation:
python animate.py
ffmpeg -r 20 -i output/plots/%5d.png output/animation.mp4
clean:
rm -rf output
rm config.pyc
<file_sep>/plot.py
import matplotlib.pyplot as plt
filename = "output/fft_time_b0s0.csv"
f = open(filename, "r")
data = []
eof = False
buf = f.readline()
line = buf.split(",")
columns = len(line)
for i in range(0, columns):
data.append([])
while eof == False:
buf = f.readline()
if buf == "":
eof = True
else:
line = buf.split(",")
for i in range(0, columns):
data[i].append(float(line[i]))
points = len(data[0])
for i in range(1, columns):
plt.plot(data[0], data[i])
plt.show()
f.close() | 500dd7e2ae6aeffc26184882ae1e7a30bf0643c4 | [
"Python",
"Makefile"
] | 5 | Python | BCITbridgeproject/springmass | 1827149d27b24fa9f42aea10405f21a7fa134952 | 1b6f55737d0f7f1cfdc3b8732ce00935e0f211c4 |
refs/heads/master | <repo_name>kswider/Lsystems<file_sep>/Assets/Scripts/Simulation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
/// <summary>
/// Class responsible for simulating L-Systems
/// </summary>
[Serializable]
public class Simulation
{
[SerializeField]
public List<Atom> currState;
[SerializeField]
public List<Production> productions;
[SerializeField]
public SerializableDictionary dictionary;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="currState">Starting string exported to format of List of Atoms</param>
/// <param name="productions">List of defined productions</param>
/// <param name="dictionary">Dictionary used to translating atoms to commands</param>
public Simulation(List<Atom> currState, List<Production> productions, SerializableDictionary dictionary)
{
this.currState = currState;
this.productions = productions;
this.dictionary = dictionary;
}
public Simulation(int egNum)
{
if (egNum == 1)
{
currState = new List<Atom> { new Atom('F', new List<double>()) };
Production p1 = new Production(
new List<Rule> { new Rule("true") },
'F',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('F', new List<Equation>()),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('+', new List<Equation>()),
new FutureAtom('F', new List<Equation>()),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('F', new List<Equation>()),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('-', new List<Equation>()),
new FutureAtom('F', new List<Equation>()),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('F', new List<Equation>()) },
1.0) });
productions = new List<Production>();
productions.Add(p1);
dictionary = new SerializableDictionary();
dictionary.Add('F', new FutureCommand("Forward", new List<Equation> { new Equation("10.0") }));
dictionary.Add('+', new FutureCommand("Rotate U", new List<Equation> { new Equation("26.0") }));
dictionary.Add('-', new FutureCommand("Rotate U", new List<Equation> { new Equation("-26.0") }));
dictionary.Add('[', new FutureCommand("Push position", new List<Equation>()));
dictionary.Add(']', new FutureCommand("Pull position", new List<Equation>()));
}
else if (egNum == 2)
{
currState = new List<Atom> { new Atom('X', new List<double>()) };
Production p1 = new Production(
new List<Rule> { new Rule("true") },
'X',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('F', new List<Equation>()),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('+', new List<Equation>()),
new FutureAtom('X', new List<Equation>()),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('-', new List<Equation>()),
new FutureAtom('X', new List<Equation>()),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('F', new List<Equation>()),
new FutureAtom('F', new List<Equation>()), },
1.0) });
Production p2 = new Production(
new List<Rule> { new Rule("true") },
'F',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('F', new List<Equation>()),
new FutureAtom('F', new List<Equation>()), },
1.0) });
productions = new List<Production>();
productions.Add(p1);
productions.Add(p2);
dictionary = new SerializableDictionary();
dictionary.Add('F', new FutureCommand("Forward", new List<Equation> { new Equation("10.0") }));
dictionary.Add('+', new FutureCommand("Rotate U", new List<Equation> { new Equation("26.0") }));
dictionary.Add('-', new FutureCommand("Rotate U", new List<Equation> { new Equation("-26.0") }));
dictionary.Add('[', new FutureCommand("Push position", new List<Equation>()));
dictionary.Add(']', new FutureCommand("Pull position", new List<Equation>()));
dictionary.Add('X', new FutureCommand("Do nothing", new List<Equation>()));
}
else if (egNum == 3)
{
currState = new List<Atom> { new Atom('X', new List<double> { 20.0 }) };
Production p1 = new Production(
new List<Rule> { new Rule("true") },
'X',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('F', new List<Equation> { new Equation("t0") }),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('+', new List<Equation>()),
new FutureAtom('X', new List<Equation> { new Equation("t0") }),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('-', new List<Equation>()),
new FutureAtom('X', new List<Equation> { new Equation("t0") }),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('F', new List<Equation> { new Equation("t0") }),
new FutureAtom('F', new List<Equation> { new Equation("t0") }), },
1.0) });
Production p2 = new Production(
new List<Rule> { new Rule("true") },
'F',
new List<SimpleProduction> {
new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('F', new List<Equation> { new Equation("t0") }),
new FutureAtom('F', new List<Equation> { new Equation("t0") }), },
0.5),
new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('F', new List<Equation> { new Equation("t0/2") }),},
0.5),
});
productions = new List<Production>();
productions.Add(p1);
productions.Add(p2);
dictionary = new SerializableDictionary();
dictionary.Add('F', new FutureCommand("Forward", new List<Equation> { new Equation("t0") }));
dictionary.Add('+', new FutureCommand("Rotate U", new List<Equation> { new Equation("26.0") }));
dictionary.Add('-', new FutureCommand("Rotate U", new List<Equation> { new Equation("-26.0") }));
dictionary.Add('[', new FutureCommand("Push position", new List<Equation>()));
dictionary.Add(']', new FutureCommand("Pull position", new List<Equation>()));
dictionary.Add('X', new FutureCommand("Do nothing", new List<Equation>()));
}
else if (egNum == 4)
{
currState = new List<Atom> { new Atom('!', new List<double>() { 0.8 }), new Atom('F', new List<double>() { 1.6 }), new Atom('/', new List<double>() { 45 }), new Atom('A', new List<double>()) };
Production p1 = new Production(
new List<Rule> { new Rule("true") },
'A',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('!', new List<Equation>() {new Equation("0.8") }),
new FutureAtom('F', new List<Equation>() {new Equation("0.4") }),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('&', new List<Equation>() {new Equation("36") }),
new FutureAtom('F', new List<Equation>() {new Equation("0.4") }),
new FutureAtom('A', new List<Equation>()),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('/', new List<Equation>() {new Equation("180") }),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('&', new List<Equation>() {new Equation("36") }),
new FutureAtom('F', new List<Equation>() {new Equation("0.4") }),
new FutureAtom('A', new List<Equation>()),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('/', new List<Equation>() {new Equation("252") }),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('&', new List<Equation>() {new Equation("36")}),
new FutureAtom('F', new List<Equation>() {new Equation("0.4") }),
new FutureAtom('A', new List<Equation>()),
new FutureAtom(']', new List<Equation>()) },
1.0)});
Production p2 = new Production(
new List<Rule> { new Rule("true") },
'F',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('F', new List<Equation>() {new Equation("t0*1.070") }) },
1.0) });
Production p3 = new Production(
new List<Rule> { new Rule("true") },
'!',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('!', new List<Equation>() {new Equation("t0*1.732") }) },
1.0) });
productions = new List<Production>();
productions.Add(p1);
productions.Add(p2);
productions.Add(p3);
dictionary = new SerializableDictionary();
dictionary.Add('F', new FutureCommand("Forward", new List<Equation> { new Equation("t0") }));
dictionary.Add('!', new FutureCommand("Change width", new List<Equation> { new Equation("t0") }));
dictionary.Add('+', new FutureCommand("Rotate U", new List<Equation> { new Equation("t0") }));
dictionary.Add('-', new FutureCommand("Rotate U2", new List<Equation> { new Equation("t0") }));
dictionary.Add('|', new FutureCommand("Rotate U", new List<Equation> { new Equation("180") }));
dictionary.Add('[', new FutureCommand("Push position", new List<Equation>()));
dictionary.Add(']', new FutureCommand("Pull position", new List<Equation>()));
dictionary.Add('$', new FutureCommand("Dollar rotation", new List<Equation>()));
dictionary.Add('&', new FutureCommand("Rotate L", new List<Equation> { new Equation("t0") }));
dictionary.Add('^', new FutureCommand("Rotate L2", new List<Equation> { new Equation("t0") }));
dictionary.Add('\\', new FutureCommand("Rotate H", new List<Equation> { new Equation("t0") }));
dictionary.Add('/', new FutureCommand("Rotate H2", new List<Equation> { new Equation("t0") }));
}
else if (egNum == 5)
{
currState = new List<Atom> { new Atom('A', new List<double> { 1, 10 }) };
//variables used in productions
double r1 = 0.9;
double r2 = 0.6;
double a0 = 45;
double a2 = 45;
if (Scenes.Parameters != null)
{
foreach (KeyValuePair<string, double> parameter in Scenes.Parameters)
{
switch (parameter.Key)
{
case "r1":
r1 = parameter.Value;
break;
case "r2":
r2 = parameter.Value;
break;
case "a0":
a0 = parameter.Value;
break;
case "a2":
a2 = parameter.Value;
break;
}
}
}
double d = 137.5;
double wr = 0.707;
Production p1 = new Production(
new List<Rule> { new Rule("true") },
'A',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('!', new List<Equation> {new Equation("t1") }),
new FutureAtom('F', new List<Equation>{ new Equation("t0") }),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('&', new List<Equation>{ new Equation(String.Format("{0:0.000}", a0)) }),
new FutureAtom('B', new List<Equation>{ new Equation("t0 * " + String.Format("{0:0.000}", r1)), new Equation("t1 * " + String.Format("{0:0.000}",wr)) }),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('/', new List<Equation> { new Equation(String.Format("{0:0.000}", d)) }),
new FutureAtom('A', new List<Equation> { new Equation("t0 * " + String.Format("{0:0.000}", r1)), new Equation("t1 *" + String.Format("{0:0.000}", wr)) }) },
1.0)});
Production p2 = new Production(
new List<Rule> { new Rule("true") },
'B',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('!', new List<Equation> {new Equation("t1") }),
new FutureAtom('F', new List<Equation>{ new Equation("t0") }),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('-', new List<Equation> { new Equation(String.Format("{0:0.000}", a2)) }),
new FutureAtom('$', new List<Equation>()),
new FutureAtom('C', new List<Equation>{ new Equation("t0 * " + String.Format("{0:0.000}",r1)), new Equation("t1 * " + String.Format("{0:0.000}", wr)) }),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('C', new List<Equation>{ new Equation("t0 * " + String.Format("{0:0.000}", r1)), new Equation("t1 * " + String.Format("{0:0.000}", wr)) }) },
1.0)});
Production p3 = new Production(
new List<Rule> { new Rule("true") },
'C',
new List<SimpleProduction> { new SimpleProduction(
new List<FutureAtom> {
new FutureAtom('!', new List<Equation> {new Equation("t1") }),
new FutureAtom('F', new List<Equation>{ new Equation("t0") }),
new FutureAtom('[', new List<Equation>()),
new FutureAtom('+', new List<Equation> { new Equation(String.Format("{0:0.000}", a0)) }),
new FutureAtom('$', new List<Equation>()),
new FutureAtom('B', new List<Equation>{ new Equation("t0 * " + String.Format("{0:0.000}", r2)), new Equation("t1 * " + String.Format("{0:0.000}", wr)) }),
new FutureAtom(']', new List<Equation>()),
new FutureAtom('B', new List<Equation>{ new Equation("t0 * " + String.Format("{0:0.000}", r1)), new Equation("t1 * " + String.Format("{0:0.000}", wr)) }) },
1.0)});
productions = new List<Production>();
productions.Add(p1);
productions.Add(p2);
productions.Add(p3);
dictionary = new SerializableDictionary();
dictionary.Add('F', new FutureCommand("Forward", new List<Equation> { new Equation("t0") }));
dictionary.Add('!', new FutureCommand("Change width", new List<Equation> { new Equation("t0") }));
dictionary.Add('+', new FutureCommand("Rotate U", new List<Equation> { new Equation("t0") }));
dictionary.Add('-', new FutureCommand("Rotate U2", new List<Equation> { new Equation("t0") }));
dictionary.Add('|', new FutureCommand("Rotate U", new List<Equation> { new Equation("180") }));
dictionary.Add('[', new FutureCommand("Push position", new List<Equation>()));
dictionary.Add(']', new FutureCommand("Pull position", new List<Equation>()));
dictionary.Add('$', new FutureCommand("Dollar rotation", new List<Equation>()));
dictionary.Add('&', new FutureCommand("Rotate L", new List<Equation> { new Equation("t0") }));
dictionary.Add('^', new FutureCommand("Rotate L2", new List<Equation> { new Equation("t0") }));
dictionary.Add('\\', new FutureCommand("Rotate H", new List<Equation> { new Equation("t0") }));
dictionary.Add('/', new FutureCommand("Rotate H2", new List<Equation> { new Equation("t0") }));
}
else if (egNum == 6)
{
currState = Scenes.StartingSequence;
productions = Scenes.Productions;
if (Scenes.Dictionary != null)
dictionary = Scenes.Dictionary;
else
{
dictionary = new SerializableDictionary();
dictionary.Add('F', new FutureCommand("Forward", new List<Equation> { new Equation("t0") }));
dictionary.Add('!', new FutureCommand("Change width", new List<Equation> { new Equation("t0") }));
dictionary.Add('+', new FutureCommand("Rotate U", new List<Equation> { new Equation("t0") }));
dictionary.Add('-', new FutureCommand("Rotate U2", new List<Equation> { new Equation("t0") }));
dictionary.Add('|', new FutureCommand("Rotate U", new List<Equation> { new Equation("180") }));
dictionary.Add('[', new FutureCommand("Push position", new List<Equation>()));
dictionary.Add(']', new FutureCommand("Pull position", new List<Equation>()));
dictionary.Add('$', new FutureCommand("Dollar rotation", new List<Equation>()));
dictionary.Add('&', new FutureCommand("Rotate L", new List<Equation> { new Equation("t0") }));
dictionary.Add('^', new FutureCommand("Rotate L2", new List<Equation> { new Equation("t0") }));
dictionary.Add('\\', new FutureCommand("Rotate H", new List<Equation> { new Equation("t0") }));
dictionary.Add('/', new FutureCommand("Rotate H2", new List<Equation> { new Equation("t0") }));
}
}
else
{
currState = null;
productions = null;
dictionary = null;
}
}
/// <summary>
/// Generates List of Atom from String with proper pattern
/// </summary>
/// <param name="atomStr">String representation of 'state' e.g. A(1,2,3)B(4)C(5)DF</param>
/// <returns>Result List of Atom or empty List if string is not valid </returns>
public static List<Atom> GenerateStateFromSting(String state)
{
List<Atom> ret = new List<Atom>();
String pattern = @".(\([0-9]+(\.[0-9]*)?(,[0-9]+(\.[0-9]*)?)*\))?";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = regex.Match(state);
while (m.Success)
{
Group g1 = m.Groups[0];
ret.Add(Atom.GenerateAtomFromString(g1.ToString()));
m = m.NextMatch();
}
return ret;
}
/// <summary>
/// Generates List of FutureAtom from String with proper pattern
/// </summary>
/// <param name="atomStr">String representation of 'future state' e.g. A(t1,t2)B(5)CD(t3-1)</param>
/// <returns>Result List of FutureAtom or empty List if string is not valid </returns>
public static List<FutureAtom> GenerateFutureStateFromSting(String state)
{
List<FutureAtom> ret = new List<FutureAtom>();
for(int i = 0; i < state.Length; i++)
{
if(i != state.Length-1 && state[i+1] == '(')
{
int length = 2;
int parentesisCount = 1;
int start = i;
for(int j = i+2; parentesisCount != 0; j++)
{
if(j >= state.Length) return new List<FutureAtom>();
if (state[j] == '(') parentesisCount++;
else if (state[j] == ')') parentesisCount--;
length++;
i = j;
}
ret.Add(FutureAtom.GenerateFutureAtomFromString(state.Substring(start, length)));
} else
{
ret.Add(FutureAtom.GenerateFutureAtomFromString(state.Substring(i,1)));
}
}
return ret;
}
/// <summary>
/// Method aplying productions to current state of the system n times
/// </summary>
/// <param name="n">Defines how many steps of productions will be done</param>
public void evaluate(int n)
{
for(int i = 0; i < n; i++)
{
List<Atom> nextState = new List<Atom>();
foreach (Atom currStateAtom in currState)
{
Boolean hasPassed = false;
foreach (Production prod in productions)
{
if (prod.passesGuards(currStateAtom))
{
foreach(Atom nextAtom in currStateAtom.apply(prod))
{
nextState.Add(nextAtom);
}
hasPassed = true;
break;
}
}
if (!hasPassed) nextState.Add(currStateAtom);
}
currState = nextState;
}
}
/// <summary>
/// Method for translating current state of system to list of commands
/// </summary>
/// <returns></returns>
public List<Command> translate()
{
List<Command> ret = new List<Command>();
foreach (Atom atom in currState)
{
Debug.Log(atom.GetLetter());
FutureCommand listing = dictionary.GetOrElse(atom.GetLetter(),new FutureCommand("do nothing",new List<Equation>()));
ret.Add(listing.evaluate(atom.GetParameters()));
}
return ret;
}
}
<file_sep>/Assets/Scripts/Rule.cs
using System;
using NCalc;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Class representing a rule which can be evaluated to boolean value
/// </summary>
[Serializable]
public class Rule
{
[UnityEngine.SerializeField]
private String rule;
/// <summary>
/// Default Constructor
/// </summary>
/// <param name="pattern">Pattern representing rule. Result of equation must be double. Variables must be represented by t0,t1...t9 </param>
public Rule(String pattern)
{
rule = pattern;
}
/// <summary>
/// Method that applies variables from list to rule and evaluates its value
/// </summary>
/// <param name="t">List of parameters. Position in list matches parameter number. Its imoprtant to keep list length equal to largest parameter number (e.g. t9 -> List.Count() == 9 )</param>
/// <returns>Evaluated boolean value</returns>
public Boolean apply(List<Double> t)
{
String replacedPattern = rule;
int i = 0;
foreach (Double param in t)
{
String strParam = "t" + i.ToString();
replacedPattern = replacedPattern.Replace(strParam, param.ToString());
i++;
}
Expression e = new Expression(replacedPattern);
return (Boolean) e.Evaluate();
}
}
<file_sep>/Assets/Scripts/Command.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Class representing command recognized by drawing classes
/// </summary>
[Serializable]
public class Command
{
[UnityEngine.SerializeField]
private string commandName;
public string GetCommandName()
{
return commandName;
}
[UnityEngine.SerializeField]
private List<double> parameters;
public List<double> GetParameters()
{
return parameters;
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="commandName">String representing command (must be recognized by drawer classes)</param>
/// <param name="parameters">Parameters that might be applied to the command e.g. "rotate" 90</param>
public Command(string commandName, List<double> parameters)
{
this.commandName = commandName;
this.parameters = parameters;
}
}
<file_sep>/Assets/Scripts/Menu/MenuManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MenuManager : MonoBehaviour {
[SerializeField]
private Button inputMenuButton;
[SerializeField]
private Button chooseSimulationMenuButton;
[SerializeField]
private Button exitButton;
// Use this for initialization
void Start () {
inputMenuButton.onClick.AddListener(delegate { StartCoroutine(Scenes.Load("menu2")); });
chooseSimulationMenuButton.onClick.AddListener(delegate { StartCoroutine(Scenes.Load("menu3")); });
exitButton.onClick.AddListener(delegate { Application.Quit(); });
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Assets/Scripts/FutureCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Something that may become Command
/// </summary>
[Serializable]
public class FutureCommand
{
[UnityEngine.SerializeField]
private string commandName;
public string GetCommandName()
{
return commandName;
}
[UnityEngine.SerializeField]
private List<Equation> equations;
public List<Equation> GetEquations()
{
return equations;
}
public FutureCommand(string commandName, List<Equation> equations)
{
this.commandName = commandName;
this.equations = equations;
}
public Command evaluate(List<Double> args)
{
List<Double> nParameters = new List<double>();
if (commandName.Equals("Forward") && args.Count() < 1) return new Command(commandName, new List<Double>(new Double[] { 1.0 }));
else if (commandName.Equals("Rotate U") && args.Count() < 1) return new Command(commandName, new List<Double>(new Double[] { 90.0 }));
else if (commandName.Equals("Rotate U2") && args.Count() < 1) return new Command(commandName, new List<Double>(new Double[] { 90.0 }));
else if (commandName.Equals("Rotate L") && args.Count() < 1) return new Command(commandName, new List<Double>(new Double[] { 90.0 }));
else if (commandName.Equals("Rotate L2") && args.Count() < 1) return new Command(commandName, new List<Double>(new Double[] { 90.0 }));
else if (commandName.Equals("Rotate H") && args.Count() < 1) return new Command(commandName, new List<Double>(new Double[] { 90.0 }));
else if (commandName.Equals("Rotate H2") && args.Count() < 1) return new Command(commandName, new List<Double>(new Double[] { 90.0 }));
else
{
foreach (Equation eq in GetEquations())
{
nParameters.Add(eq.apply(args));
}
return new Command(GetCommandName(), nParameters);
}
}
}
<file_sep>/Assets/Scripts/SerializableDictionary.cs
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class SerializableDictionary : Dictionary<Char, FutureCommand>, ISerializationCallbackReceiver
{
[UnityEngine.SerializeField]
private List<Char> keys = new List<Char>();
[UnityEngine.SerializeField]
private List<FutureCommand> values = new List<FutureCommand>();
// save the dictionary to lists
public void OnBeforeSerialize()
{
keys.Clear();
values.Clear();
foreach (KeyValuePair<Char, FutureCommand> pair in this)
{
keys.Add(pair.Key);
values.Add(pair.Value);
}
}
// load dictionary from lists
public void OnAfterDeserialize()
{
this.Clear();
if (keys.Count != values.Count)
throw new System.Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable."));
for (int i = 0; i < keys.Count; i++)
this.Add(keys[i], values[i]);
}
public FutureCommand GetOrElse(Char letter, FutureCommand fc)
{
try
{
FutureCommand listing = this[letter];
return listing;
}
catch (KeyNotFoundException)
{
FutureCommand listing = new FutureCommand("Do nothing", new List<Equation>());
return listing;
}
}
}<file_sep>/Assets/Scripts/Scenes.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public static class Scenes
{
public static int SimulationNumber { get; set; }
public static Dictionary<char, string> Rules { get; set; }
public static List<Atom> StartingSequence { get; set; }
public static int Steps { get; set; }
public static Dictionary<string, double> Parameters { get; set; }
public static List<Production> Productions { get; set; }
public static SerializableDictionary Dictionary { get; set; }
public static int DrawingApproach { get; set; }
public static float WidthDecreaseRate { get; set; }
public static IEnumerator Load(string sceneName)
{
AsyncOperation async = SceneManager.LoadSceneAsync(sceneName);
while (!async.isDone)
{
yield return null;
}
}
public static IEnumerator LoadAdditive(string sceneName)
{
AsyncOperation async = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
while (!async.isDone)
{
yield return null;
}
}
public static IEnumerator LoadAdditiveGoThroughEachStep(string sceneName,double timeBetweenFrames)
{
int repeat = Scenes.Steps;
for (int i = 1; i <= repeat; i++)
{
Scenes.Steps = i;
AsyncOperation async = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
while (!async.isDone)
{
yield return null;
}
if(i<repeat)
GameObject.Find("Canvas/GoBackButton").SetActive(false);
if (i>1)
SceneManager.UnloadSceneAsync("main");
yield return new WaitForSeconds((float)timeBetweenFrames);
}
}
}<file_sep>/Assets/Scripts/Menu/MenuManager3.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MenuManager3 : MonoBehaviour {
[SerializeField]
private Button simulation1Button;
[SerializeField]
private Button simulation2Button;
[SerializeField]
private Button simulation3Button;
[SerializeField]
private Button goBackButton;
[SerializeField]
private Canvas canvas;
private Animator cameraAnimator;
// Use this for initialization
void Start() {
goBackButton.onClick.AddListener(delegate { SceneManager.LoadScene("menu"); });
simulation1Button.onClick.AddListener(delegate { StartDrawing(1); });
simulation2Button.onClick.AddListener(delegate { StartDrawing(2); });
simulation3Button.onClick.AddListener(delegate { StartDrawing(3); });
cameraAnimator = GameObject.Find("Main Camera").GetComponent<Animator>();
}
void Update()
{
//Stopping Camera Animation
if (Input.GetKeyDown(KeyCode.P))
{
if (cameraAnimator.enabled)
cameraAnimator.enabled = false;
else
cameraAnimator.enabled = true;
}
}
void StartDrawing(int treeNumber)
{
Scenes.Parameters = new Dictionary<string, double>();
switch (treeNumber)
{
case 1:
Scenes.Parameters.Add("r1", 0.9);
Scenes.Parameters.Add("r2", 0.6);
Scenes.Parameters.Add("a0", 45);
Scenes.Parameters.Add("a2", 45);
Scenes.DrawingApproach = 1;
Scenes.WidthDecreaseRate = 0.707f;
canvas.enabled = false;
Scenes.SimulationNumber = 5;
Scenes.Steps = 10;
StartCoroutine(Scenes.LoadAdditive("main"));
break;
case 2:
Scenes.Parameters.Add("r1", 0.9);
Scenes.Parameters.Add("r2", 0.9);
Scenes.Parameters.Add("a0", 45);
Scenes.Parameters.Add("a2", 45);
Scenes.DrawingApproach = 1;
Scenes.WidthDecreaseRate = 0.707f;
canvas.enabled = false;
Scenes.SimulationNumber = 5;
Scenes.Steps = 10;
StartCoroutine(Scenes.LoadAdditiveGoThroughEachStep("main", 3));
break;
case 3:
Scenes.DrawingApproach = 0;
canvas.enabled = false;
Scenes.SimulationNumber = 4;
Scenes.Steps = 6;
StartCoroutine(Scenes.LoadAdditiveGoThroughEachStep("main", 3));
break;
}
}
}
<file_sep>/Assets/Scripts/Menu/MenuManager2.cs
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine.SceneManagement;
using SFB;
using System.Collections;
//using UnityEditor;
//using System.Runtime.InteropServices;
public class MenuManager2 : MonoBehaviour
{
/* TODO
[DllImport("user32.dll")]
private static extern void SaveFileDialog();
[DllImport("user32.dll")]
private static extern void OpenFileDialog();
*/
[SerializeField]
private UnityEngine.UI.Button goBackButton;
[SerializeField]
private Canvas canvas;
[SerializeField]
private InputField startingSequenceInputField;
[SerializeField]
private InputField stepsInputField;
[SerializeField]
private UnityEngine.UI.Button startButton;
[SerializeField]
private UnityEngine.UI.Button addNextProductionButton;
[SerializeField]
private UnityEngine.UI.Button loadDictionary;
[SerializeField]
private UnityEngine.UI.Button loadFromJsonButton;
[SerializeField]
private UnityEngine.UI.Button saveToJsonButton;
[SerializeField]
private GameObject productionsGrid;
[SerializeField]
private GameObject production;
[SerializeField]
private GameObject after;
[SerializeField]
private Toggle cyllinderToggle;
[SerializeField]
private Toggle coneToggle;
[SerializeField]
private InputField coneInputField;
[SerializeField]
private Toggle lastStateToggle;
[SerializeField]
private Toggle smoothAnimationToggle;
[SerializeField]
private InputField timeBetweenFramesInputField;
private Animator cameraAnimator;
private List<GameObject> productions;
// Use this for initialization
private Material material;
void Start()
{
goBackButton.onClick.AddListener(delegate { SceneManager.LoadScene("menu"); });
productions = new List<GameObject>();
addNextProductionButton.onClick.AddListener(delegate { AddNextProduction(); });
startButton.onClick.AddListener(StartSimulation);
loadDictionary.onClick.AddListener(LoadDictionary);
loadFromJsonButton.onClick.AddListener(LoadFromJson);
saveToJsonButton.onClick.AddListener(SaveToJson);
cameraAnimator = GameObject.Find("Main Camera").GetComponent<Animator>();
}
void Update()
{
if (cyllinderToggle.isOn)
coneInputField.interactable = false;
else
coneInputField.interactable = true;
if (lastStateToggle.isOn)
timeBetweenFramesInputField.interactable = false;
else
timeBetweenFramesInputField.interactable = true;
//Stopping Camera Animation
if (Input.GetKeyDown(KeyCode.P))
{
if (cameraAnimator.enabled)
cameraAnimator.enabled = false;
else
cameraAnimator.enabled = true;
}
}
private void LoadDictionary()
{
String path = StandaloneFileBrowser.OpenFilePanel("Load Dictionary for your Lsystem", "", "json", false)[0];
String myJson;
if (path.Length != 0)
{
Scenes.Dictionary = new SerializableDictionary();
myJson = File.ReadAllText(path);
JObject json = JObject.Parse(myJson);
JArray entries = JArray.Parse(json["Dictionary"].ToString());
foreach (JObject entry in entries)
{
String letter = entry["Letter"].ToString();
Debug.Log(letter);
String command = entry["Command"].ToString();
Debug.Log(command);
JArray arguments = JArray.Parse(entry["Arguments"].ToString());
List<Equation> equations = new List<Equation>();
foreach(String argument in arguments.Select(a => (string)a).ToList<String>())
{
equations.Add(new Equation(argument));
Debug.Log(argument);
}
Scenes.Dictionary.Add(letter[0], new FutureCommand(command, equations));
}
}
}
private void SaveToJson()
{
String path = StandaloneFileBrowser.SaveFilePanel("Save Lsystem to JSON file", "", "MyLsystem.json", "json");
if (path.Length != 0)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter();
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.WriteStartObject();
writer.WritePropertyName("Starting sequence");
writer.WriteValue(startingSequenceInputField.text);
writer.WritePropertyName("Steps");
writer.WriteValue(stepsInputField.text);
writer.WritePropertyName("Productions");
writer.WriteStartArray();
foreach(GameObject prod in productions)
{
writer.WriteStartObject();
writer.WritePropertyName("Before");
writer.WriteValue(prod.transform.Find("Header/Before/BeforeInputField").GetComponent<InputField>().text[0]);
writer.WritePropertyName("Guard");
writer.WriteValue(prod.transform.Find("Header/Guard/GuardInputField").GetComponent<InputField>().text);
writer.WritePropertyName("Afters");
writer.WriteStartArray();
foreach (Transform afterGameObject in prod.GetComponentsInChildren<Transform>().Where(t => t.name == "After(Clone)"))
{
writer.WriteStartObject();
writer.WritePropertyName("Probability");
writer.WriteValue(afterGameObject.Find("Probability/ProbabilityInputField").GetComponent<InputField>().text);
writer.WritePropertyName("State");
writer.WriteValue(afterGameObject.Find("State/StateInputField").GetComponent<InputField>().text);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
}
writer.WriteEndArray();
}
File.WriteAllText(path, sw.ToString());
}
}
private void LoadFromJson()
{
String path = StandaloneFileBrowser.OpenFilePanel("Select JSON file containing Lsystem", "", "json", false)[0];
String myJson;
if (path.Length != 0)
{
myJson = File.ReadAllText(path);
DeleteAllProductions();
JObject json = JObject.Parse(myJson);
startingSequenceInputField.text = json["Starting sequence"].ToString();
stepsInputField.text = json["Steps"].ToString();
JArray productions = JArray.Parse(json["Productions"].ToString());
foreach(JObject jprod in productions)
{
GameObject prodGO = AddNextProduction(jprod["Before"].ToString(), jprod["Guard"].ToString());
JArray afters = JArray.Parse(jprod["Afters"].ToString());
foreach(JObject jafter in afters)
{
GameObject newAfter = Instantiate(after, prodGO.transform.Find("AftersGrid"));
Button deleteButton = newAfter.transform.Find("DeleteButton").GetComponent<Button>();
deleteButton.onClick.AddListener(delegate { DeleteAfter(newAfter); });
newAfter.transform.Find("Probability/ProbabilityInputField").GetComponent<InputField>().text = jafter["Probability"].ToString();
newAfter.transform.Find("State/StateInputField").GetComponent<InputField>().text = jafter["State"].ToString();
}
}
}
}
private void DeleteAllProductions()
{
foreach(GameObject prod in productions)
{
Destroy(prod);
}
productions = new List<GameObject>();
}
private GameObject AddNextProduction(String before = "", String guard = "")
{
GameObject newProduction = Instantiate(production, productionsGrid.transform);
productions.Add(newProduction);
Button deleteButton = newProduction.transform.Find("Header/DeleteButton").GetComponent<Button>();
deleteButton.onClick.AddListener(delegate { DeleteProduction(newProduction); });
Button addNextAfterButton = newProduction.transform.Find("Header/AddNextAfterButton").GetComponent<Button>();
addNextAfterButton.onClick.AddListener(delegate { addNextAfter(newProduction); });
newProduction.transform.Find("Header/Before/BeforeInputField").GetComponent<InputField>().text = before;
newProduction.transform.Find("Header/Guard/GuardInputField").GetComponent<InputField>().text = guard;
return newProduction;
}
private void DeleteProduction(GameObject newProduction)
{
productions.Remove(newProduction);
Destroy(newProduction);
}
private void addNextAfter(GameObject newProduction)
{
GameObject newAfter = Instantiate(after, newProduction.transform.Find("AftersGrid"));
Button deleteButton = newAfter.transform.Find("DeleteButton").GetComponent<Button>();
deleteButton.onClick.AddListener(delegate { DeleteAfter(newAfter); });
}
private void DeleteAfter(GameObject newAfter)
{
Destroy(newAfter);
}
private void StartSimulation()
{
canvas.enabled = false;
PassParamtersFromInputs();
Scenes.SimulationNumber = 6;
if(lastStateToggle.isOn)
StartCoroutine(Scenes.LoadAdditive("main"));
else
StartCoroutine(Scenes.LoadAdditiveGoThroughEachStep("main",Double.Parse(timeBetweenFramesInputField.text)));
}
private void PassParamtersFromInputs()
{
Scenes.StartingSequence = Simulation.GenerateStateFromSting(startingSequenceInputField.text);
Scenes.Steps = Int32.Parse(stepsInputField.text);
Scenes.Productions = new List<Production>();
foreach (GameObject productionGameObject in productions)
{
char before = productionGameObject.transform.Find("Header/Before/BeforeInputField").GetComponent<InputField>().text[0];
List<Rule> guards = new List<Rule> { new Rule(productionGameObject.transform.Find("Header/Guard/GuardInputField").GetComponent<InputField>().text) };
List<SimpleProduction> simpleProductions = new List<SimpleProduction>();
foreach (Transform afterGameObject in productionGameObject.GetComponentsInChildren<Transform>().Where(t => t.name == "After(Clone)"))
{
String afterString = afterGameObject.Find("State/StateInputField").GetComponent<InputField>().text;
double probability = Double.Parse(afterGameObject.Find("Probability/ProbabilityInputField").GetComponent<InputField>().text);
simpleProductions.Add(new SimpleProduction(Simulation.GenerateFutureStateFromSting(afterString), probability));
}
Scenes.Productions.Add(new Production(guards, before, simpleProductions));
}
if (cyllinderToggle.isOn)
{
Scenes.DrawingApproach = 0;
}
else
{
Scenes.DrawingApproach = 1;
Scenes.WidthDecreaseRate = (float)Double.Parse(coneInputField.text);
}
}
}
<file_sep>/Assets/Scripts/Equation.cs
using System;
using NCalc;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
/// <summary>
/// Class used to evaluate values of equations given in string format
/// </summary>
[Serializable]
public class Equation
{
[SerializeField]
public String equation;
/// <summary>
/// Default Constructor
/// </summary>
/// <param name="pattern">Pattern representing equation. Result of equation must be double. Variables must be represented by t0,t1...t9 </param>
public Equation(String pattern)
{
equation = pattern;
}
/// <summary>
/// Method that applies variables from list to equation and evaluates its value
/// </summary>
/// <param name="t">List of parameters. Position in list matches parameter number. Its imoprtant to keep list length equal to largest parameter number (e.g. t9 -> List.Count() == 9 )</param>
/// <returns>Evaluated double value</returns>
public Double apply(List<Double> t)
{
String replacedPattern = equation;
int i = 0;
foreach (Double param in t)
{
String strParam = "t" + i.ToString();
replacedPattern = replacedPattern.Replace(strParam, String.Format("{0:0.000}", param));
i++;
}
Debug.Log(replacedPattern);
Expression e = new Expression(replacedPattern);
return Convert.ToDouble(e.Evaluate());
}
}<file_sep>/Assets/Scripts/SimpleProduction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Class representing simple production. Never used as stand alone class (only applied to Production)
/// </summary>
[Serializable]
public class SimpleProduction
{
[UnityEngine.SerializeField]
private List<FutureAtom> after;
public List<FutureAtom> GetAfter()
{
return after;
}
[UnityEngine.SerializeField]
private double probability;
public double GetProbability()
{
return probability;
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="after">FutreAtom that will be produced by this Production</param>
/// <param name="probability">Probabbility of applying this production. Its impotant to keep sum of probabilities of simpleproductions with smae before and guard equal to 1.0</param>
public SimpleProduction(List<FutureAtom> after, Double probability)
{
this.after = after;
this.probability = probability;
}
}<file_sep>/Assets/Scripts/TurtleController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Linq;
public class TurtleController : MonoBehaviour
{
private Material material;
private Vector3 lastPosition;
private Vector3 newPosition;
private float scale;
private Orientation orientation;
private float delta;
private static Dictionary<char, string> parameters;
[SerializeField]
private Button goBackButton;
/* it was used for 2D trees
private Vector3 direction;
private int count;
private LineRenderer lineRenderer;
*/
// Use this for initialization
void Start()
{
goBackButton.onClick.AddListener(goBackToMenu);
// parameters initialization
lastPosition = new Vector3(0, 0, 0);
Stack<Vector3> positionStack = new Stack<Vector3>();
Stack<Orientation> orientationStack = new Stack<Orientation>();
Stack<float> scaleStack = new Stack<float>();
scale = 1;
orientation = new Orientation();
material = Resources.Load("Materials/Barks/bark02", typeof(Material)) as Material;
/* it was used for 2D trees
private Orientation orientation;
direction = new Vector3(0,1,0);
count = 0;
lineRenderer = new LineRenderer();
Stack<LineRenderer> _lineRendererStack = new Stack<LineRenderer>();
*/
//Atom a = new Atom('A', new List<double> { 2.0, 4.9 });
//Debug.Log("JSON: " + JsonUtility.ToJson(a).ToString());
// Creating sentence to draw
Simulation sim = new Simulation(Scenes.SimulationNumber);
sim.evaluate(Scenes.Steps);
List <Command> commands = sim.translate();
foreach (Command command in commands)
{
switch (command.GetCommandName())
{
// 3D
case "Forward":
newPosition = lastPosition;
newPosition += orientation.H * ((float)command.GetParameters()[0] * 2);
DrawLine(lastPosition, newPosition);
lastPosition = newPosition;
// TODO
//orientation.RotationCorrection(lastPosition);
break;
case "Rotate U":
delta = (float)command.GetParameters()[0];
orientation.RotateU(delta);
break;
case "Rotate U2":
delta = -(float)command.GetParameters()[0];
orientation.RotateU(delta);
break;
case "Rotate L":
delta = (float)command.GetParameters()[0];
orientation.RotateL(delta);
break;
case "Rotate L2":
delta = -(float)command.GetParameters()[0];
orientation.RotateL(delta);
break;
case "Rotate H":
delta = (float)command.GetParameters()[0];
orientation.RotateH(delta);
break;
case "Rotate H2":
delta = -(float)command.GetParameters()[0];
orientation.RotateH(delta);
break;
case "Dollar rotation":
orientation.DollarRotation();
break;
case "Push position":
positionStack.Push(lastPosition);
orientationStack.Push(new Orientation(orientation));
scaleStack.Push(scale);
break;
case "Pull position":
lastPosition = positionStack.Pop();
orientation = orientationStack.Pop();
scale = scaleStack.Pop();
break;
case "Change width":
scale = (float)command.GetParameters()[0] / 10;
break;
}
/* 2D
switch (command.CommandName)
{
case "Forward":
lineRenderer.positionCount++;
count++;
DrawLine(count);
break;
case "Rotate X":
break;
case "Rotate left":
gamma = (float)command.parameters[0];
direction = Quaternion.Euler(0, 0, delta) * direction;
break;
case "Rotate right":
gamma = (float)command.parameters[0];
direction = Quaternion.Euler(0, 0, -delta) * direction;
break;
case "Push position":
lineRendererStack.Push(lineRenderer);
countStack.Push(count);
positionStack.Push(lastPosition);
directionStack.Push(direction);
count = 0;
Material material = _lineRenderer.material;
GameObject branch = new GameObject("Branch");
branch.transform.position = lastPosition;
lineRenderer = branch.AddComponent<LineRenderer>();
lineRenderer.material = material;
lineRenderer.startWidth = .05f;
lineRenderer.endWidth = .05f;
lineRenderer.positionCount = 1;
lineRenderer.SetPosition(count, lastPosition);
break;
case "Pull position":
lineRenderer = lineRendererStack.Pop();
count = countStack.Pop();
lastPosition = positionStack.Pop();
direction = directionStack.Pop();
break;
}
*/
}
}
private void goBackToMenu()
{
GameObject.Find("MenuCanvas").GetComponent<Canvas>().enabled = true;
SceneManager.UnloadSceneAsync("main");
}
/* 2D
private void DrawLine(int index)
{
newPosition = lastPosition;
newPosition += direction;
lineRenderer.SetPosition(index, newPosition);
lastPosition = newPosition;
}
*/
private void DrawLine(Vector3 lastPosition, Vector3 newPosition)
{
// Cylinder approach
if (Scenes.DrawingApproach == 0)
{
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder.transform.parent = gameObject.transform;
cylinder.GetComponent<MeshRenderer>().material = material;
float distance = Vector3.Distance(newPosition, lastPosition);
Vector3 newScale = cylinder.transform.localScale;
newScale.y = distance / 2;
newScale.x = scale;
newScale.z = scale;
cylinder.transform.localScale = newScale;
cylinder.transform.position = Vector3.Lerp(lastPosition, newPosition, 0.5f);
cylinder.transform.up = newPosition - lastPosition;
}
// Cone approach
else
{
GameObject cone = CreateCone.Create(1, scale, scale * Scenes.WidthDecreaseRate);
cone.transform.parent = gameObject.transform;
cone.GetComponent<MeshRenderer>().material = material;
Vector3 newScale = cone.transform.localScale;
newScale.y = Vector3.Distance(lastPosition, newPosition);
cone.transform.localScale = newScale;
cone.transform.position = lastPosition;
cone.transform.up = newPosition - lastPosition;
}
}
}
<file_sep>/Assets/Scripts/Orientation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class Orientation
{
public Vector3 H { get; private set; }
public Vector3 L { get; private set; }
public Vector3 U { get; private set; }
public Orientation()
{
H = new Vector3(0, 1, 0);
L = new Vector3(-1, 0, 0);
U = new Vector3(0, 0, -1);
}
public Orientation(Orientation o)
{
H = o.H;
L = o.L;
U = o.U;
}
public void RotateU(float delta)
{
H = Quaternion.AngleAxis(-delta, U) * H;
L = Quaternion.AngleAxis(-delta, U) * L;
}
public void RotateL(float delta)
{
H = Quaternion.AngleAxis(-delta, L) * H;
U = Quaternion.AngleAxis(-delta, L) * U;
}
public void RotateH(float delta)
{
L = Quaternion.AngleAxis(delta, H) * L;
U = Quaternion.AngleAxis(delta, H) * U;
}
public void DollarRotation()
{
Vector3 V = new Vector3(0, 1, 0);
L = Vector3.Scale(V, H) / Vector3.Scale(V, H).magnitude;
U = Vector3.Scale(H, L);
}
/*TODO
public void RotationCorrection(Vector3 startingPoint)
{
float alfa = 0.40f * Vector3.Magnitude(Vector3.Scale(H, new Vector3(-0.61f, 0.77f, -0.19f)));
H = Quaternion.AngleAxis(alfa, H) * H;
}
*/
}
<file_sep>/Assets/Scripts/Atom.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
/// <summary>
/// Simple class representing atom in l-system state
/// </summary>
[Serializable]
public class Atom
{
[UnityEngine.SerializeField]
private char letter;
public char GetLetter()
{
return letter;
}
[UnityEngine.SerializeField]
private List<double> parameters;
public List<double> GetParameters()
{
return parameters;
}
public void SetParameters(List<double> value)
{
parameters = value;
}
/// <summary>
/// Generates Atom from String with proper pattern
/// </summary>
/// <param name="atomStr">String representation of atom e.g. A(12,3.4,5)</param>
/// <returns>Result Atom or null if pattern doesnt match the string</returns>
public static Atom GenerateAtomFromString(String atomStr)
{
Debug.Log(atomStr);
String pattern = @"^.(\([0-9]+(\.[0-9]+)?(,[0-9]+(\.[0-9]*)?)*\))?$";
Regex regex = new Regex(pattern, RegexOptions.None);
Match m = regex.Match(atomStr);
if (atomStr.Length == 1)
{
return new Atom(atomStr[0], new List<double>());
}
else if (m.Success)
{
Group g1 = m.Groups[0];
Group g2 = m.Groups[1];
//Atom letter
CaptureCollection cc1 = g1.Captures;
Capture letter = cc1[0];
//Atom args
List<Double> nParams = new List<Double>();
CaptureCollection cc2 = g2.Captures;
Capture c2 = cc2[0];
String pattern2 = @"[0-9]+(\.[0-9]+)?";
Regex regex2 = new Regex(pattern2, RegexOptions.IgnoreCase);
Match m2 = regex2.Match(c2.ToString());
while (m2.Success)
{
Group g3 = m2.Groups[0];
CaptureCollection cc3 = g3.Captures;
for (int l = 0; l < cc3.Count; l++)
{
Capture c3 = cc3[l];
nParams.Add(Convert.ToDouble(c3.ToString()));
}
m2 = m2.NextMatch();
}
return new Atom(letter.ToString()[0], nParams);
}
else
{
return null;
}
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="letter">Letter used to define atom</param>
/// <param name="parameters">List of arguments applied to atom</param>
public Atom(char letter, List<double> parameters)
{
this.letter = letter;
SetParameters(parameters);
}
/// <summary>
/// Method that changes atom according to given producton
/// </summary>
/// <param name="p">Production which will be applied to atom. It' important to check if atom passesGuard of Production before applying production to atom</param>
/// <returns>Atoms created by the Production p</returns>
public List<Atom> apply(Production p)
{
return p.getAfter(GetParameters());
}
}
<file_sep>/README.md
# Lsystems #
## Description ##
Application made for generating trees using L-systems rules. It was created as a project for Modelling and Simulation of Systems course at AGH University.
Whole documentation of project is available in Polish in document "Symulacje L-systems.pdf".
## How to run application ##
If you want to check our application, you have to:
1. Work on Windows OS.
2. Download compiled version of application available in release section.
3. Run lsystems.exe.
4. Have fun of creating your trees!
There are some premade rules for creating trees in json files so you can load them in app to see how rules should be made.
We will be happy if you try our application and give us some feedback about it.
Screenshots from app:





<file_sep>/Assets/Scripts/FutureAtom.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
/// <summary>
/// Something that may become Atom
/// </summary>
[Serializable]
public class FutureAtom
{
[UnityEngine.SerializeField]
private char letter;
public char GetLetter()
{
return letter;
}
[UnityEngine.SerializeField]
private List<Equation> equations;
public List<Equation> GetEquations()
{
return equations;
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="letter">Letter used to define atom.</param>
/// <param name="equations">List of equations. According to them we can evaluate new Atom.</param>
public FutureAtom(char letter, List<Equation> equations)
{
this.letter = letter;
this.equations = equations;
}
/// <summary>
/// Generates FutureAtom from String with proper pattern
/// </summary>
/// <param name="atomStr">String representation of future atom e.g. A(t1,t2+5.4,5)</param>
/// <returns>Result FutureAtom or null if pattern doesnt match the string</returns>
public static FutureAtom GenerateFutureAtomFromString(String atomStr)
{
if ((atomStr.Length > 1 && atomStr[1] == '(' && atomStr.Last() == ')'))
{
String[] equationsStrArray = atomStr.Substring(2, atomStr.Length - 3).Split(',');
List<Equation> nParams = new List<Equation>();
for (int i = 0; i < equationsStrArray.Length; i++)
{
nParams.Add(new Equation(equationsStrArray[i]));
}
return new FutureAtom(atomStr[0], nParams);
}
else if (atomStr.Length == 1)
{
return new FutureAtom(atomStr[0], new List<Equation>());
}
else return null;
}
/// <summary>
/// Method evaluating new Atom
/// </summary>
/// <param name="args">Arguments that will be passed to Equations to evaluate new Atom parameters</param>
/// <returns>created Atom</returns>
public Atom evaluate(List<Double> args)
{
List<Double> nParameters = new List<double>();
for (int i = 0; i < GetEquations().Count(); i++)
{
nParameters.Add(GetEquations()[i].apply(args));
}
return new Atom(this.GetLetter(), nParameters);
}
}
<file_sep>/Assets/Scripts/Production.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
/// <summary>
/// Class representing production with features such as probability, guard and parameters.
/// </summary>
[Serializable]
public class Production
{
[UnityEngine.SerializeField]
private List<Rule> guards;
public List<Rule> GetGuards()
{
return guards;
}
[UnityEngine.SerializeField]
private char before;
public char GetBefore()
{
return before;
}
[UnityEngine.SerializeField]
private List<SimpleProduction> after;
public List<SimpleProduction> GetAfter()
{
return after;
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="guards">Defines rules when atom can or can not be applied to production</param>
/// <param name="before">Defines letter by which we recognize atoms that can be applied to production</param>
/// <param name="after">Defines list of possible results of productions. Sum of probabilities in this lists must be equal to 1.0</param>
public Production(List<Rule> guards, char before, List<SimpleProduction> after)
{
this.guards = guards;
this.before = before;
this.after = after;
}
/// <summary>
/// Method returning effect of production
/// </summary>
/// <param name="parameters">parameters of atom applied to production</param>
/// <returns>List of Atoms produced by this porduction</returns>
public List<Atom> getAfter(List<Double> parameters)
{
System.Random random = new System.Random();
Double randDouble = random.NextDouble();
Double acc = 0;
List<Atom> ret = new List<Atom>();
for (int i=0; i < GetAfter().Count; i++)
{
acc += GetAfter()[i].GetProbability();
if(randDouble <= acc)
{
foreach(FutureAtom nAtom in GetAfter()[i].GetAfter())
{
ret.Add(nAtom.evaluate(parameters));
}
return ret;
}
}
return ret;
}
/// <summary>
/// Method for checking if Atom can be applied to production
/// </summary>
/// <param name="atom">Atom to check</param>
/// <returns>true if atom can be applied to production, false otherwise</returns>
public Boolean passesGuards(Atom atom)
{
Boolean isOK = false;
Debug.Log(atom.GetLetter());
for(int i=0; i < GetGuards().Count(); i++)
{
if (atom.GetLetter() == GetBefore() && GetGuards()[i].apply(atom.GetParameters()))
{
isOK = true;
}
}
return isOK;
}
} | 356b42df7c6d770027e594aa4a72ae15f1aa7db4 | [
"Markdown",
"C#"
] | 17 | C# | kswider/Lsystems | 37db6707eb52ab7ab26ef0c7d6a7714aa9953381 | 0d154c5ccf1fac0bae97ad7f8ae957f1fac3721d |
refs/heads/master | <repo_name>ras756un/Triviagame<file_sep>/assets/javascript/app.js
//timer
var timer = 50;
//score keeping
var currentQuestion = 0; var correctAns; var incorrectAns; var userAns; var seconds; var time; var answered;
var gameQuestions = [q1 = {
question: "What is the name of the mouse that Jon wants Garfield to eat?",
choices: ["Levi", "Davy", "Derek", "Lewis"],
answer: 3
}, q2 = {
question: "What is the name of the vet?",
choices: ["<NAME>", "<NAME>", "<NAME>", "<NAME>"],
answer: 3
}, q3 = {
question: "What song does Odie dance to at the dog show?",
choices: ["<NAME>", "Who Let the Dogs Out", "Holla", "I Feel Good"],
answer: 1
}, q4 = {
question: "Where is the train going that Garfield first changes the path of?",
choices: ["Los Angeles", "Seattle", "Boston", "New York"],
answer: 2
}];
function countTime() {
timer = 20;
$("#timeLeft").html("<h5>Time remaining: " + timer + "</h5>");
time = setInterval(displayTime, 1000);
}
function displayTime() {
timer--;
$("#timeLeft").html("<h5>Time remaining: " + timer + "</h5>");
if(timer < 1){
clearInterval(timer);
throw new Error("Times Up");
}
}
function displayQuesiton() {
countTime();
if (currentQuestion = 0){
$("#questions").html("<h5> "+ gameQuestions[currentQuestion].question + "</h5>");
//call to displayChoices function to display choices.
}
else if (currentQuestion < 4){
currentQuestion++;
$("#questions").html("<h5> "+ gameQuestions[currentQuestion].question + "</h5>");
//call to displayChoices function to display choices.
}
else {
gameOver();
}
}
function displayChoices() {
//code to display choices goes here.
//loop and/or use .each method on the objects within the array.
}
function startGame() {
console.log("Game has started.");
displayQuesiton();
}
function newGame() {
currentQuestion = 0;
correctAns = 0;
incorrectAns = 0;
startGame();
}
function gameOver() {
alert("Game is over.")
}
$(document).ready(function () {
$(".gif").on("click", function () {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
setTimeout(function () {
$(".gif").remove();
$("#catStart").remove();
}, 1600);
setTimeout(function () {
startGame();
},
1700);
});
});
| f20b769dfdded006ebeba6ca9ea8db8d0d269b13 | [
"JavaScript"
] | 1 | JavaScript | ras756un/Triviagame | 04a9834f2e752c583ebb1b89327ae5c19bb7fe6f | 99d2a4c49f5b59d85c2e33a2bfdaf3a87d58395e |
refs/heads/master | <repo_name>ariel-diaz/study-group<file_sep>/study-groups-server/src/App.js
import React, {Component} from "react";
import {BrowserRouter, Switch, Route, Redirect} from "react-router-dom";
import connect from "unstated-connect";
import {Pane} from "evergreen-ui";
import NavBar from "./ui/NavBar";
import Search from "./modules/group/screens/Search";
import List from "./modules/group/screens/List";
import Create from "./modules/group/screens/Create";
import Details from "./modules/group/screens/Details";
import Login from "./modules/user/screens/Login";
import Profile from "./modules/user/screens/Profile";
import UniversityContainer from "./modules/universities/container";
import UserContainer from "./modules/user/container";
class App extends Component {
async componentDidMount() {
const {
containers: [university, user],
} = this.props;
await university.fetch();
await user.restore();
}
render() {
return (
<BrowserRouter>
<Switch>
<Route component={Login} path="/login" />
<Route
render={({history}) => (
<Pane width="100%">
<NavBar history={history} />
<Switch>
<Route exact component={Search} path="/groups" />
<Route component={List} path="/my-groups" />
<Route component={Create} path="/groups/create" />
<Route component={Details} path="/groups/:id" />
<Route component={Profile} path="/profile" />
<Redirect to="/login" />
</Switch>
</Pane>
)}
/>
</Switch>
</BrowserRouter>
);
}
}
export default connect([UniversityContainer, UserContainer])(App);
<file_sep>/study-groups-server/server.js
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
next();
});
const urlDb = "mongodb://studyadmin:<EMAIL>:45043/study-groups";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
mongoose.connect(urlDb);
const db = mongoose.connection;
const users = new mongoose.Schema({
id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
password: <PASSWORD>,
university: String,
career: String,
avatar: String
});
const groups = new mongoose.Schema({
id: Number,
owner: Number,
description: String,
title: String,
datetime: String,
university: String,
assignment: String,
professor: String,
limit: Number,
participants: [],
location: String
});
const universities = new mongoose.Schema({
id: mongoose.Schema.Types.ObjectId,
description: String,
assignments: []
});
let UnisDb = mongoose.model('Universities', universities);
let GroupsDb = mongoose.model('Groups', groups);
let UsersDb = mongoose.model('Users', users);
db.on('error', console.log.bind(console, "connection error:"));
db.once('open', () => {
console.log("Conectada a la db");
});
app.use(express.static(path.join(__dirname, "build")));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "build/index.html"));
});
app.post('/api/login', (req, res) => {
let body = req.body;
UsersDb.findOne( {email: body.email} , (err , usuarioDb) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error al buscar usuario',
errors: err
});
}
if (!usuarioDb) {
return res.status(400).json({
ok: false,
mensaje: 'Credenciales incorrectas - email',
errors: err
});
}
if(body.password !== usuarioDb.password) {
return res.status(400).json({
ok: false,
mensaje: 'Credenciales incorrectas - password',
errors: err
});
}
usuarioDb.password = "xD";
res.status(200).json({
usuarioDb
});
});
});
app.get('/api/users', (req, res) => {
UsersDb.find({})
.exec(
(err, users) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: "Error",
errors: err
});
}
res.status(200).json({
users
});
}
)
});
app.post('/api/users', (req, res) => {
const body = req.body;
let user = new UsersDb({
name: body.name,
email: body.email,
password: <PASSWORD>,
university: body.university,
career: body.career,
avatar: body.avatar
});
user.save((err, resp) => {
if (err) {
return res.status(400).json(
{
ok: false,
mensaje: "Error al crear universidad",
errors: err
}
);
}
res.status(201).json({
resp
});
});
});
app.get('/api/Universities', (req, res) => {
UnisDb.find({})
.exec(
(err, universities) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: "Error",
errors: err
});
}
res.status(200).json({
universities
});
}
)
});
app.post('/api/Universities', (req, res) => {
let body = req.body;
var university = new UnisDb({
description: body.description,
assignment: body.assignments
});
university.save((err, resp) => {
if (err) {
return res.status(400).json(
{
ok: false,
mensaje: "Error al crear universidad",
errors: err
}
);
}
res.status(201).json({
resp
});
})
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Listening port", port);
});<file_sep>/study-groups-server/src/containers.js
const requireAll = ctx =>
ctx
.keys()
.map(ctx)
.map(m => m.default)
.filter(Boolean);
export default requireAll(
require.context("./modules", true, /containers\.js$/)
).map(Container => new Container());
<file_sep>/study-groups-server/src/modules/group/screens/Details.js
/* eslint-disable */
import type {Container} from "unstated";
import React, {Component} from "react";
import connect from "unstated-connect";
import styled from "styled-components";
import {Pane, Text, Button, toaster} from "evergreen-ui";
import GroupContainer from "../container";
import UserContainer from "../../user/container";
import { formatDistance, format } from 'date-fns'
import {es} from 'date-fns/locale'
type Props = {
containers: Array<Container>,
};
const Wrapper = styled.section`
display: flex;
flex-direction: column;
width: 100%;
justify-content: center;
align-items: center;
min-height: 100vh;
padding-top: 24px;
.side-info {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
height: 120%;
margin-top: -100px;
max-width: 210px;
.university-image {
width: 185px;
height: 185px;
border-radius: 100%;
margin-bottom: 20px;
img {
width: 100%;
height: 100%;
object-fit: contain;
border-radius: 100%;
}
}
button {
width: 80%;
justify-content: center;
align-items: center;
height: 50px;
font-weight: bold;
font-size: 16px;
letter-spacing: 1.22px;
text-align: center;
text-transform: uppercase;
}
.participants {
display: flex;
flex-direction: row;
justify-content: flex-start;
width: 100%;
margin-top: 7px;
height: 30px;
.participant {
width: 30px;
height: 30px;
border-radius: 15px;
background: #c5bdbd;
margin: 0 5px;
animation: fadeIn 0.3s;
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0px);
}
}
}
}
.lugar-title {
display: block;
margin-top: 20px;
}
p {
font-size: 16px;
color: #000000;
letter-spacing: 0.42px;
text-align: center;
line-height: 22px;
font-weight: bold;
margin-top: 0;
}
}
.main-content {
margin-left: 55px;
height: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
h1 {
margin: 0;
font-weight: normal;
font-size: 2rem;
}
span.sub-text {
margin-bottom: 17px;
}
p {
margin-top: 0;
font-size: 16px;
color: #000000;
letter-spacing: 0.42px;
line-height: 22px;
}
.map {
width: 100%;
height: 209px;
margin-top: 20px;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
}
.sub-text {
opacity: 0.52;
text-transform: uppercase;
font-weight: bold;
font-size: 16px;
color: #000000;
letter-spacing: 0.42px;
text-align: center;
}
`;
const defaultDescription =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sapien mauris, dapibus eu efficitur et, pharetra eget mauris. Pellentesque condimentum, arcu nec gravida pellentesque, nibh dolor scelerisque massa, ut ullamcorper lectus magna vel sapien.";
class DetailsScreen extends Component {
props: Props;
state = {
joined: false,
};
async componentDidMount() {
const {
containers: [group],
match,
} = this.props;
await group.fetch(match.params.id);
console.log("test", this.props.containers[1]);
// TODO: traer data de los participantes
}
isJoined = () => {
const {
containers: [group, user]
} = this.props
return group.state.selected.participants.some(participant => participant === user.state.profile.id)
}
joinGroup = () => {
const {
containers: [group, user],
match,
} = this.props;
toaster.closeAll()
const groupId = group.state.selected.id
console.log('isJoined', this.isJoined())
if (!this.isJoined()) {
console.log('lets join')
group.join(user.state.profile)
toaster.success('Te uniste a este grupo de estudio con éxito')
} else {
console.log('chau')
group.leave(user.state.profile.id)
toaster.notify('Saliste del grupo')
}
}
render() {
const {
containers: [group],
} = this.props;
const groupData = group.state.selected;
if (groupData) {
const {limit, participants, title, assignment, description, datetime} = groupData;
const date = new Date(datetime)
const distance = formatDistance(new Date(), date, { locale: es })
const joined = this.state.joined;
return (
<Wrapper>
<Pane
elevation={1}
float="left"
width='80%'
maxWidth={764}
minHeight={515}
padding={42}
margin={24}
display="flex"
justifyContent="space-between"
alignItems="flex-start"
display="flex"
elevation={1}
flexDirection="row"
background='#fafafa'
borderRadius={6}
>
<div className="side-info">
<div className="university-image">
<img
alt="UBA"
src="https://www.dc.uba.ar/Trash/eventos/icpc/2009/images/uba_logo.jpg"
/>
</div>
<Button onClick={this.joinGroup}
appearance={!this.isJoined() && 'primary'}
intent={!this.isJoined() ? 'success' : 'danger'}
marginBottom={20}
>
{!this.isJoined() ? "Unirse" : "Salir"}
</Button>
<span className="sub-text">
QUEDAN {limit - participants.length} LUGARES
</span>
<div className="participants">
{participants.map(participant => (
<div key={participant} className="participant" />
))}
</div>
<span className="sub-text lugar-title">LUGAR Y HORA</span>
<p>
Biblioteca de la FADU <br />
{date.toLocaleString('es-ES')}
</p>
</div>
<div className="main-content">
<h1>{title}</h1>
<span className="sub-text">
{groupData.class || "clase x"} - en {distance}
</span>
<p>{description || defaultDescription}</p>
<div className="map">
<img
alt=""
src={require('../../../assets/map.png')}
/>
</div>
</div>
</Pane>
</Wrapper>
);
}
return "";
}
}
export default connect([GroupContainer, UserContainer])(DetailsScreen);
<file_sep>/study-groups-server/src/modules/group/screens/Create.js
// @flow
import type {Container} from "unstated";
import React from "react";
import {
Pane,
Button,
Heading,
TextInputField,
SelectField,
toaster,
} from "evergreen-ui";
import {Form, FormItem} from "react-local-form";
import connect from "unstated-connect";
import Wrapper from "../../../ui/Container";
import UniversityContainer from "../../universities/container";
import UserContainer from "../../user/container";
import GroupContainer from "../container";
type Props = {
containers: Array<Container>,
history: any,
};
const CreateScreen = ({
containers: [university, group, user],
history,
}: Props) => (
<Pane appearance="tint1" height="100%" padding={24} width="100%">
<Wrapper>
<Heading color="white" marginY="24px" size={900}>
Crear grupo
</Heading>
<Form
render={({values, errors}) => {
const universities = university.state.list;
const selectedUniversity = universities.find(
_university => _university.id === values.university
);
return (
<Pane backgroundColor="white" elevation={1} padding={24}>
<FormItem
name="title"
rules={[value => !value && "Este campo es requerido"]}
validate={["mount", "change"]}
>
<TextInputField required label="Título" />
</FormItem>
<FormItem name="description" validate={["mount", "change"]}>
<TextInputField label="Descripción" type="text" />
</FormItem>
<FormItem
name="limit"
rules={[value => !value && "Este campo es requerido"]}
validate={["mount", "change"]}
>
<TextInputField required label="Plazas" type="number" />
</FormItem>
<FormItem
name="location"
rules={[value => !value && "Este campo es requerido"]}
validate={["mount", "change"]}
>
<TextInputField required label="Ubicación" />
</FormItem>
<FormItem
name="datetime"
rules={[value => !value && "Este campo es requerido"]}
validate={["mount", "change"]}
>
<TextInputField
required
label="Horario"
type="datetime-local"
/>
</FormItem>
<FormItem
name="university"
rules={[value => !value && "Este campo es requerido"]}
validate={["mount", "change"]}
>
<SelectField required label="Universidad">
<option disabled value="">
Seleccione una universidad
</option>
{universities.map(_university => (
<option key={_university.id} value={_university.id}>
{_university.id}
</option>
))}
</SelectField>
</FormItem>
{selectedUniversity && (
<FormItem
name="assignment"
rules={[value => !value && "Este campo es requerido"]}
validate={["mount", "change"]}
>
<SelectField required label="Materia">
<option disabled value="">
Seleccione una universidad
</option>
{selectedUniversity.assignments.map(assignment => (
<option key={assignment} value={assignment}>
{assignment}
</option>
))}
</SelectField>
</FormItem>
)}
<Button
disabled={Boolean(errors.length)}
isLoading={group.state.syncing}
type="submit"
>
Crear
</Button>
</Pane>
);
}}
values={{
university: "",
assignment: "",
participants: [user.state.profile],
}}
onSubmit={async ({values}) => {
const data = await group.create(values);
toaster.success("Tu grupo fue creado");
history.push(`/groups/${data.id}`);
}}
/>
</Wrapper>
</Pane>
);
export default connect([UniversityContainer, GroupContainer, UserContainer])(
CreateScreen
);
<file_sep>/study-groups-server/src/modules/universities/resources.js
import axios from "axios";
const URL = "/api/universities";
export default {
fetch: () => axios(URL).then(result => {
console.log(result);
return result.data;
}),
};
<file_sep>/study-groups-server/build/precache-manifest.6c0998bc7ea1aa8a2bc80dd496b9f2e6.js
self.__precacheManifest = [
{
"revision": "c699099ed7cd4c983eb8846ffa1e18f8",
"url": "/static/media/map.c699099e.png"
},
{
"revision": "b99a43efbc3db63c80c9abeafb669bea",
"url": "/static/media/logo.b99a43ef.svg"
},
{
"revision": "d568dca52b9e562bd37a736c57623d33",
"url": "/static/media/logo-white.d568dca5.svg"
},
{
"revision": "229c360febb4351a89df",
"url": "/static/js/runtime~main.229c360f.js"
},
{
"revision": "c571fa799755e879f270",
"url": "/static/js/main.c571fa79.chunk.js"
},
{
"revision": "815732a5e2c4075ce8ac",
"url": "/static/js/1.815732a5.chunk.js"
},
{
"revision": "c571fa799755e879f270",
"url": "/static/css/main.4e4db873.chunk.css"
},
{
"revision": "d868236cdd9ed07c90333d25e5ca508d",
"url": "/index.html"
}
];<file_sep>/study-groups-server/src/ui/NavBar.js
import React from "react";
import {Pane, Heading, Avatar, Popover, Position, Menu} from "evergreen-ui";
import {Link} from "react-router-dom";
import Container from "./Container";
const NavBar = ({history}) => (
<Pane backgroundColor="#111c27" height="70px" width="100%">
<Container height="100%">
<Pane
alignItems="center"
display="flex"
height="100%"
justifyContent="space-between"
>
<Heading alignItems='center' display='flex' color="white" fontSize="30px">
<img style={{
height: '25px',
marginRight: '10px'
}} src={require('../assets/logo-white.svg')} alt=""/>
<Link to="/groups">Stoodi</Link>
</Heading>
<Pane alignItems="center" display="flex">
<Popover
content={
<Menu>
<Menu.Group>
<Menu.Item
icon="plus"
onSelect={() => {
history.push("/groups/create");
}}
>
Agregar grupo
</Menu.Item>
<Menu.Item
icon="list"
onSelect={() => {
history.push("/my-groups");
}}
>
Mis grupos
</Menu.Item>
<Menu.Item
icon="user"
onSelect={() => {
history.push("/profile");
}}
>
Perfil
</Menu.Item>
</Menu.Group>
<Menu.Divider />
<Menu.Group>
<Menu.Item
icon="cross"
intent="danger"
onSelect={() => {
history.push("/login");
}}
>
Salir
</Menu.Item>
</Menu.Group>
</Menu>
}
position={Position.BOTTOM_RIGHT}
>
<Avatar
name=""
size={30}
src="https://pbs.twimg.com/profile_images/756196362576723968/6GUgJG4L_400x400.jpg"
/>
</Popover>
</Pane>
</Pane>
</Container>
</Pane>
);
export default NavBar;
<file_sep>/study-groups-server/src/modules/universities/container.js
import {Container} from "unstated";
import api from "./resources";
export default class UniversityContainer extends Container {
state = {
list: [],
};
async fetch() {
const list = await api.fetch();
console.log(list);
this.setState({list});
}
}
<file_sep>/study-groups-server/src/modules/group/resources.js
import axios from "axios";
const URL = "/api/groups";
export default {
search: (university, assignment) =>
axios(
`${URL}?university_like=${university}&assignment_like=${assignment}`
).then(resp => resp.data),
fetch: id => axios(`${URL}/${id}`).then(resp => resp.data),
create: data =>
axios({
data,
url: URL,
method: "POST",
}).then(resp => resp.data),
update: data =>
axios({
data,
url: URL,
method: "PATCH",
}),
};
<file_sep>/study-groups-server/src/ui/Container.js
import React from "react";
import Box from "ui-box";
const Container = props => <Box marginX="auto" maxWidth="960px" {...props} />;
export default Container;
<file_sep>/study-groups-server/src/modules/user/screens/Profile.js
import React from "react";
import {Subscribe} from "unstated";
import UserContainer from "../container";
const ProfileScreen = () => (
<Subscribe to={[UserContainer]}>
{user => {
console.log("user: ", user);
return <div>{`<ProfileScreen />`}</div>;
}}
</Subscribe>
);
export default ProfileScreen;
<file_sep>/study-groups-server/model.js
const mongoose = require("mongoose");
const users = new mongoose.Schema({
id: Number,
name: String,
email: String,
password: <PASSWORD>,
university: String,
career: String,
avatar: String
});
const universities = new mongoose.Schema({
id: String,
assignments: []
});
const groups = new mongoose.Schema({
id: Number,
owner: Number,
description: String,
title: String,
datetime: String,
university: String,
assignment: String,
professor: String,
limit: Number,
participants: [],
location: String
});
| c93481e480f704b3e7e8a1dcb21de0669cdf2817 | [
"JavaScript"
] | 13 | JavaScript | ariel-diaz/study-group | 40d337d3bb8634de44a586785b90ac76940c09a4 | 3191eac071ad183a61850a4028318f21b66e421d |
refs/heads/master | <file_sep>const TeleBot = require('telebot');
const bot = new TeleBot({
token: process.env.TELEGRAM_BOT_TOKEN,
usePlugins: ['askUser'],
});
module.exports = bot;
<file_sep>const lists = require('../models/lists')
// /about
module.exports = (bot) => {
bot.on('/lists', (msg) => {
const chatId = msg.chat.id;
lists.getAll().then(lists => {
const text = JSON.stringify(lists);
return bot.sendMessage(chatId, text, {
replyMarkup: bot.keyboard([
['/list_add', '/list_remove', '/person_add']
], {resize: true, once: true})
});
})
});
}
<file_sep>require('dotenv').config()
const bot = require('./modules/telegram');
require('./actions/start')(bot);
require('./actions/me')(bot);
require('./actions/about')(bot);
require('./actions/lists')(bot);
require('./actions/list_add')(bot);
require('./actions/list_remove')(bot);
require('./actions/person_add')(bot);
// bot.on(/^\/person_add (.+)\s(.+)$/, (msg, props) => {
// const listName = props.match[1];
// const personName = props.match[1];
// console.log('msg', msg);
// return msg.reply.text('list!')
// });
bot.start();
<file_sep># Peoplefull Telegram Bot
- Lists & People
- Lists "Customers", "Students", "Employees", "Friends", etc
- List settings: Remind to ping not offen 20 days
- Reminder to ping + Button "Done", and right after next candidate
- Limit daily pings to 10
<file_sep>// /about
module.exports = (bot, db) => {
let newPerson = {};
bot.on('/person_add', (msg) => {
const id = msg.from.id;
db.collection('lists').find({}).toArray((err, docs) => {
const lists = docs;
return bot.sendMessage(id, 'To which list new person should be added?', {
ask: 'person-add-list',
replyMarkup: bot.keyboard([
lists.map(list => list.name)
], {resize: true, once: false})
});
});
});
// Ask person add list name event
bot.on('ask.person-add-list', (msg) => {
const id = msg.from.id;
const name = msg.text;
newPerson.list = name;
// Ask user age
return bot.sendMessage(id, `What is name of person?`, {
ask: 'person-add-name',
});
});
// Ask person add name event
bot.on('ask.person-add-name', (msg) => {
const id = msg.from.id;
const name = msg.text;
newPerson.name = name;
// db.collection('lists').findOne({
// name: newPerson.list
// })
// Ask user age
return bot.sendMessage(id, `Person ${JSON.stringify(newPerson)}`);
});
}
<file_sep>module.exports = (bot) => {
bot.on('/about', (msg) => {
const id = msg.chat.id;
let text = '👱 This bot is powered by TeleBot library ' +
'https://github.com/kosmodrey/telebot Go check the source code!';
return bot.sendMessage(id, text, {
replyMarkup: bot.keyboard([
['/lists', '/today', '/me']
], {resize: true, once: true})
});
});
}
<file_sep>module.exports = (bot) => {
bot.on('/start', (msg, propse) => {
const replyMarkup = bot.keyboard([
['/lists', '/about']
], {resize: true, once: false});
return bot.sendMessage(msg.chat.id,
'👱 Use commands: /lists and /about', {replyMarkup}
);
});
}
<file_sep>module.exports = (bot, db) => {
bot.on('/list_remove', (msg, propse) => {
const id = msg.from.id;
// Ask list name
return bot.sendMessage(id, 'Type name of list?', {ask: 'list-remove-name'});
});
// Ask list name event
bot.on('ask.list-remove-name', (msg) => {
const id = msg.from.id;
const name = msg.text;
db.collection('lists').deleteOne({
name,
});
// Ask user age
return bot.sendMessage(id, `Removed a list "${name}"!`);
});
};
<file_sep>const mongo = require('../modules/mongo');
const getAll = () => {
const db = mongo.getInstance()
return new Promise((resolve, reject) => {
db.collection('lists').find({}).toArray((err, docs) => {
if (err) return reject(err);
const lists = docs;
resolve(lists)
})
})
}
module.exports = {
getAll,
}
<file_sep>module.exports = (bot, db) => {
bot.on('/list_add', (msg, propse) => {
const id = msg.from.id;
// Ask list name
return bot.sendMessage(id, 'What is list name?', {ask: 'list-add-name'});
});
// Ask list name event
bot.on('ask.list-add-name', (msg) => {
const id = msg.from.id;
const name = msg.text;
db.collection('lists').insertOne({
name,
people: []
});
// Ask user age
return bot.sendMessage(id, `Added a list "${name}"!`);
});
};
<file_sep>const lists = require('../models/lists')
module.exports = (bot) => {
bot.on('/me', (msg) => {
const id = msg.chat.id;
let text = '👱 You have:\n2 lists:\n- asd\n- alkjsd';
return bot.sendMessage(id, text, {
replyMarkup: bot.keyboard([
['/lists', '/lists_add', '/today', '/me']
], {resize: true, once: true})
});
});
}
| 833fb4dcfb8461dfa686de9e71fce76fd4e48314 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | itspoma/peoplefull-telegram-bot | 53ba8aeb14224d68405e7d699a302a54dc12ad14 | bfdc92f1e1c6e4a5b8762b377f454294abcce9c3 |
refs/heads/master | <file_sep>package com.marlabs.springDemo.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.marlabs.springDemo.domains.Book;
import com.marlabs.springDemo.services.BookService;
@Controller
public class BookController {
@Autowired
BookService bs = new BookService();
@GetMapping("/books")
public String list(Model mode) {
List<Book> books = bs.findAllBooks();
mode.addAttribute("books", books);
return "books";
}
@PostMapping("/books")
public String post(Book book) {
bs.addBook(book);
return "redirect:/books";
}
@GetMapping("/books/{id}")
public String details(@PathVariable long id, Model mode) {
Book book = bs.findOneBook(id);
mode.addAttribute("book", book);
return "book";
}
@GetMapping("/books/addbook")
public String addBook(Model mode) {
mode.addAttribute("book", new Book());
return "addBook";
}
@GetMapping("/books/addbook/{id}")
public String editBook(@PathVariable long id, Model mode) {
Book book = bs.findOneBook(id);
mode.addAttribute("book", book);
return "addBook";
}
@DeleteMapping("/books/delete/{id}")
public String deleteBook(@PathVariable long id, final RedirectAttributes ra) {
bs.deleteBook(id);
ra.addFlashAttribute("message", "Deleted");
return "redirect:/books";
}
}
<file_sep>package com.marlabs.springDemo;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import com.marlabs.springDemo.domains.Book;
import com.marlabs.springDemo.services.BookService;
public class Test4Post {
@Mock
BookService bs;
// BookRepository br;
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Before
public void setUp() {
}
@Test
public void testPost() {
Book b1 = new Book("Java", "YYQ", "1234");
// Book b2 = mock(Book.class);
List<Book> bb = new ArrayList<Book>();
bb.add(b1);
// bb.add(b2);
when(bs.findByName("YYQ")).thenReturn(bb);
assertEquals(bs.findByName("YYQ"), bb);
verify(bs).findByName("YYQ");
System.out.println(bb);
}
// public List<Book> findByName(String name) {
// return bookService.findByName(name);
// }
}
| 84ff6935760c6e0d6fd7be8f6e16d3b916557e98 | [
"Java"
] | 2 | Java | Yan19910828/springDemo | 423d9949b04967ca02926347ebe152a993337972 | 598adf43c2671e8327ab8a76a6f38192007c205d |
refs/heads/master | <repo_name>ciec20151104699/2018-09<file_sep>/a ➕b/a ➕b/main.swift
//
// main.swift
// a ➕b
//
// Created by sq on 2018/9/19.
// Copyright © 2018年 sq. All rights reserved.
//
import Foundation
print("Hello, World!")
var a=78
var b=78
var c=a+b
print(c)
| b54c0f3ad9606475f0670ee92c3c58b318d6b3ac | [
"Swift"
] | 1 | Swift | ciec20151104699/2018-09 | d12f7c35de7661aee20ed5983243e40be14461b7 | 6651b80626b8c130220af6a8003ce58c148f78e6 |
refs/heads/main | <file_sep>const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:127.0.0.1/supermarket',{useNewUrlParser: true});
const db = mongoose.connection;
const Produto = require(("../model/Produto"));
db.on('error', (error) => {
console.log("Conexao nao estabelecida");
});
db.once('open', () => {
console.log('Conexao realizada com sucesso');
});
module.exports = {
getOneProduto (id){
return Produto.find({_id: id});
},
getAllProdutos (){
return Produto.find({});
},
deleteProduto (id){
return Produto.deleteOne({_id: id});
},
updateProduto (produto){
console.log(produto);
return Produto.findByIdAndUpdate({_id: produto.id}, produto, {upsert: true, new: true});
}
}<file_sep>const express = require("express");
const mongoDbService = require("../service/mongoDbService");
const server = express();
server.use(express.json());
const hostName = "localhost";
const port = "3000";
server.listen(port, hostName, () => {
console.log(`Example app listening at http://${hostName}:${port}/`);
})
server.get('/products', (req, res) => {
mongoDbService.getAllProdutos().then((result) =>{
if(result){
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(JSON.stringify(result));
}
}).catch((err) =>{
console.log(err);
});
});
server.get('/products/:id', (req, res) => {
mongoDbService.getOneProduto(req.params.id).then((result) =>{
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
console.log(result);
res.end(JSON.stringify(result));
});
});
server.post('/products', (req, res) => {
mongoDbService.updateProduto(req.body).then((result) =>{
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
console.log(result);
res.end(JSON.stringify(result));
});
});
server.put('/products/:id', (req, res) => {
mongoDbService.updateProduto(req.body).then((result) =>{
if(result){
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(JSON.stringify(result));
}
}).catch((err) =>{
console.log(err);
});
});
server.delete('/products/:id', (req, res) => {
mongoDbService.deleteProduto(req.params.id).then((result) =>{
if(result){
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(JSON.stringify(result));
}
}).catch((err) =>{
console.log(err);
});
});
| a3963c4ebba841abfb8d333eee67cd845f9b26e4 | [
"JavaScript"
] | 2 | JavaScript | Beatrizluc/AtividadePraticaNodeJs | 8053dc8f3b46c802bcf75f6f78486d541a050bb5 | 402d12ae3731d8094a1688a77d59941e2dcb76fb |
refs/heads/master | <repo_name>itungxp/react-native-demo<file_sep>/App/js/components/Toolbar.js
import React from 'react'
import {View, TouchableOpacity, Text} from 'react-native'
import {Icon} from 'react-native-elements'
import AppEventEmitter from './AppEventEmitter'
import css from './Style'
class Toolbar extends React.Component {
open() {
AppEventEmitter.emit('menu.click');
}
render() {
const self = this;
return (
<View style={{flexDirection:'row',alignItems:'center'}}>
<TouchableOpacity onPress={self.open} style={css.iconPadding}>
<Icon onPress={self.open} name='view-headline' style={[css.imageIcon, css.iconHome]}/>
</TouchableOpacity>
<View style={css.toolbarTitleView}>
<Text style={css.toolbarTitle}>{this.props.name}</Text>
</View>
</View>
)
}
}
module.exports = Toolbar;
<file_sep>/App/js/components/Style.js
import React, {StyleSheet, Dimensions, PixelRatio} from "react-native";
const {width, height, scale} = Dimensions.get("window"),
vw = width / 100,
vh = height / 100,
vmin = Math.min(vw, vh),
vmax = Math.max(vw, vh);
export default StyleSheet.create({
iconPadding: {
padding: 10,
paddingTop: 25
},
imageIcon: {
"width": 14,
"height": 14
},
iconHome: {
"width": 20,
"marginLeft": -4
},
toolbarTitleView: {
"position": "absolute",
"top": 27,
"left": 0,
"width": width - 160,
"marginLeft": 80,
"marginRight": 80,
"alignItems": "center"
},
toolbarTitle: {
"color": "#494949",
"fontSize": 16,
"alignSelf": "center"
},
loginBtn : {
marginTop: 50
}
});
<file_sep>/App/js/App.js
import React from 'react'
import {View, StyleSheet} from 'react-native'
import {SideMenu, List, ListItem, Icon} from 'react-native-elements'
import {Router, Scene, Actions, ActionConst} from 'react-native-router-flux'
import AppEventEmitter from './components/AppEventEmitter'
import Login from './Login'
import Form from './Form'
import ListView from './Form'
import Card from './Form'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {toggled: false}
}
toggleSideMenu() {
this.setState({
toggled: !this.state.toggled
})
}
componentDidMount() {
AppEventEmitter.addListener('menu.click', () => this.toggleSideMenu());
}
render() {
const list = [
{title: 'Form', icon: 'content-paste', action: Actions.form},
{title: 'List', icon: 'list', action: Actions.list},
{title: 'Cards', icon: 'business', action: Actions.card},
{title: 'Logout', icon: 'person', action: Actions.login}];
// SideMenu takes a React Native element as a prop for the actual Side Menu
const MenuComponent = (
<View style={{flex: 1, backgroundColor: '#ededed', justifyContent: 'center'}}>
<List containerStyle={{marginBottom: 20}}>
{
list.map((item, i) => (
<ListItem
onPress={() =>{ item.action(); this.toggleSideMenu();} }
key={i}
title={item.title}
leftIcon={{name: item.icon}}
/>
))
}
</List>
</View>
);
const scenes = Actions.create(
<Scene key="root">
<Scene key="login" component={Login} title="Login" type={ActionConst.RESET}/>
<Scene key="form" component={Form} title="Form" type={ActionConst.RESET}/>
<Scene key="list" component={ListView} title="List View" type={ActionConst.RESET}/>
<Scene key="card" component={Card} title="Card" type={ActionConst.RESET}/>
</Scene>
);
return (
<SideMenu
menuPosition="left"
MenuComponent={MenuComponent}
toggled={this.state.toggled}>
<Router hideNavBar={true} scenes={scenes} />
</SideMenu>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFF',
}
});
module.exports = App;
<file_sep>/App/js/Login.js
import React, {Component} from 'react'
import {View, StyleSheet, Text} from 'react-native'
import css from './components/Style'
import {FormLabel, FormInput, Button} from 'react-native-elements'
import {Actions} from 'react-native-router-flux'
class Login extends React.Component {
render() {
return (
<View style={styles.container}>
<FormLabel>Name</FormLabel>
<FormInput placeholder="Username or email" onChangeText={(text) => this.setState({username: text})}/>
<FormLabel>Password</FormLabel>
<FormInput placeholder="Password" secureTextEntry={true}/>
<Button title="Login"
onPress={() => Actions.form({username: this.state.username})}
buttonStyle={css.loginBtn} backgroundColor="#2196F3"/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
}
});
module.exports = Login;
| f60e9459c3617a91b8b09a6bef2315abb727f6d7 | [
"JavaScript"
] | 4 | JavaScript | itungxp/react-native-demo | 0fec4d9cac804a8194b9db1f3a2b99e44d9f8fd6 | a4bf003ed517aad6bc427ad17353eb317879d7f0 |
refs/heads/master | <file_sep># WSP Lesson / StableNYC
Web server class project to familiarize with HTML, CSS, and JavaScript. I made this a mockup of a landing page for a personal project I am developing.
<br/><br/>
## Dev Setup
To run you need to execute the following in the terminal:
1. If setting up for the first time on a machine:
```
$flutter login
$flutter init
```
2. Each time running:
```
$flutter serve --only functions,hosting
```
3. Open browser window and go to url: ```localhost/5001```
<br/>
<file_sep>const functions = require('firebase-functions'); //import this library/module
const express = require('express') // light req/resp framework
const app = express() //'app' handles all requests through http
const path = require('path') // this is for the warning requiring 'path.join()' in place of '+' to concatenate
exports.httpReq = functions.https.onRequest(app)
app.get('/', frontendHandler); // slash only is called a 'root request'
app.get('/b', backendHandler);
app.get('/home', frontendHandler);
app.get('/login', frontendHandler);
// request and response are provided by the Node.js framework
// request object: all info being sent from client computer web browser, likewise for response
function frontendHandler(request, response) {
response.sendFile(path.join(__dirname, '/spa/index.html')) // specifies absolute full path on this computer where the index.html is
}
function backendHandler(req, res) {
const n = Math.random(); // 0 ~ 1 (not including 1)
const num = Math.floor(n * 10); // 0 ~ 9 int
let s = 0;
s = 50 + 12;
let page = `
<h1>Your lucky number is ${num}</h1>
Sum is ${s}
`;
res.send(page)
}
// I'm adding this comment to test something about git<file_sep>function home_page() {
pageContent.innerHTML = `
<!-- Dropdown Menu -->
<div class="btn-group" style="padding-bottom: 32px;">
<button align="center" style="background-color: #000000; color:white; font-size:15px;" class="btn btn-secondary btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Get Started
</button>
<div class="dropdown-menu" aria-labelledby="dropdownmenu2">
<button class="dropdown-item" type="button"></button>
<button class="dropdown-item" type="button">Manhattan</button>
<button class="dropdown-item" type="button">Brooklyn</button>
<button class="dropdown-item" type="button">Queens</button>
<button class="dropdown-item" type="button">The Bronx</button>
<button class="dropdown-item" type="button">Staten Island</button>
<button class="dropdown-item" type="button">All NYC</button>
<button class="dropdown-item" type="button"></button>
<button class="dropdown-item" type="button">How It Works</button>
<button class="dropdown-item" type="button"></button>
<button href="login_page.js" class="dropdown-item" type="button">Login</button>
<button class="dropdown-item" type="button"></button>
</div>
</div>
<!-- Carousel -->
<div id="carouselExampleFade" class="carousel slide carousel-fade" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="images/manhattan-01.jpg" class="d-block w-100" alt="...">
<input type ="button" class="classic_button_next btn btn-primary btn-large" id="next_button" value="Next >>"/>
</div>
<div class="carousel-item">
<img src="images/brownstone-01.webp" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="images/manhattan-02.webp" class="d-block w-100" alt="...">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleFade" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleFade" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
`;
} | 18525b3e52a3741b6b7a6bc270ec38c2256b12a0 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | greyamex/wsp20-lesson1-creative | b3557d0f8cc4401d6a95322ed4185a8ba9af5be6 | a926971b5cea4646c1dc2ad29ead4e5986f711ca |
refs/heads/master | <repo_name>xuepd/printer-manager-cups<file_sep>/cache/cache.go
package cache
import (
"fmt"
"time"
"github.com/dgraph-io/badger/v2"
)
//Cache an expiring value store
type Cache map[string]time.Time
//Read returns the Cache from the given path, or an error if one occurred
func Read(path string) (Cache, error) {
db, err := badger.Open(badger.DefaultOptions(path).WithLogger(nil))
if err != nil {
return nil, fmt.Errorf("Unable to open db: %w", err)
}
defer db.Close()
cache := make(Cache)
if err = db.View(func(txn *badger.Txn) error {
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
if err := item.Value(func(v []byte) error {
t := new(time.Time)
err := t.UnmarshalBinary(v)
if err != nil {
return fmt.Errorf("Unable to unmarshal time: %w", err)
}
cache[string(item.Key())] = *t
return nil
}); err != nil {
return err
}
}
return nil
}); err != nil {
return nil, fmt.Errorf("Unable to read iterate through database: %w", err)
}
return cache, nil
}
//Write writes cache to the given path or returns an error if one occurred
func (cache Cache) Write(path string) error {
db, err := badger.Open(badger.DefaultOptions(path).WithLogger(nil))
if err != nil {
return fmt.Errorf("Unable to open db: %w", err)
}
defer db.Close()
return db.Update(func(txn *badger.Txn) error {
for id, t := range cache {
tb, err := t.MarshalBinary()
if err != nil {
return fmt.Errorf("Unable to marshal time: %w", err)
}
if err := txn.Set([]byte(id), tb); err != nil {
return fmt.Errorf("Unable to write to cache: %w", err)
}
}
return nil
})
}
//Purge removes the given ids from the cache at the given path, or returns an error if one occurred
func Purge(path string, ids []string) error {
db, err := badger.Open(badger.DefaultOptions(path).WithLogger(nil))
if err != nil {
return fmt.Errorf("Unable to open db: %w", err)
}
defer db.Close()
return db.Update(func(txn *badger.Txn) error {
for _, id := range ids {
if err := txn.Delete([]byte(id)); err != nil {
return fmt.Errorf("Unable to delete key: %w", err)
}
}
return nil
})
}
<file_sep>/user/user.go
package user
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"os"
)
//UtmpLocations specifies where to search for utmp files
var UtmpLocations = []string{"/var/run/utmp", "/run/utmp"}
//UtmpxLocations specifies where to search for utmpx files
var UtmpxLocations = []string{"/var/run/utmpx"}
const typeUser = 7
type utmp struct {
Type int16
_ [42]byte
Name [32]byte
_ [308]byte
}
type utmpx struct {
Name [256]byte
_ [40]byte
Type int16
_ [330]byte
}
func coalesce(items []string) []string {
set := make(map[string]struct{})
for _, i := range items {
set[i] = struct{}{}
}
coalesced := make([]string, 0, len(set))
for i := range set {
coalesced = append(coalesced, i)
}
return coalesced
}
func readUtmp(path string) ([]string, error) {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("Unable to open path %s: %w", path, err)
}
defer f.Close()
var usernames []string
for {
u := new(utmp)
if err := binary.Read(f, binary.LittleEndian, u); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("Unable to read: %w", err)
}
if u.Type == typeUser {
end := bytes.IndexByte(u.Name[:], 0)
usernames = append(usernames, string(u.Name[:end]))
}
}
return usernames, nil
}
func readUtmpx(path string) ([]string, error) {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("Unable to open path %s: %w", path, err)
}
defer f.Close()
var usernames []string
for {
u := new(utmpx)
if err := binary.Read(f, binary.LittleEndian, u); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("Unable to read: %w", err)
}
if u.Type == typeUser {
end := bytes.IndexByte(u.Name[:], 0)
usernames = append(usernames, string(u.Name[:end]))
}
}
return usernames, nil
}
//GetUsers returns the users currently signed in, or an error if one occurred
func GetUsers() ([]string, error) {
for _, path := range UtmpLocations {
usernames, err := readUtmp(path)
if err != nil {
if os.IsNotExist(err) {
continue
}
log.Println("WARN: Error reading utmp file:", err)
continue
}
return coalesce(usernames), nil
}
for _, path := range UtmpxLocations {
usernames, err := readUtmpx(path)
if err != nil {
if os.IsNotExist(err) {
continue
}
log.Println("WARN: Error reading utmpx file:", err)
continue
}
return coalesce(usernames), nil
}
return nil, errors.New("Unable to find utmp/utmpx file")
}
<file_sep>/main.go
package main
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/kelseyhightower/envconfig"
"github.com/korylprince/printer-manager-cups/control"
"github.com/korylprince/printer-manager-cups/cups"
)
func main() {
c := new(Config)
if err := envconfig.Process("", c); err != nil {
log.Fatalln("ERROR: Unable to process configuration:", err)
}
client, err := cups.New()
if err != nil {
log.Fatalln("ERROR: Unable to create CUPS client:", err)
}
con, err := control.New()
if err != nil {
log.Fatalln("ERROR: Unable to set up control socket:", err)
}
inputSync := make(chan []string)
inputClearCache := make(chan struct{})
inputListDrivers := make(chan struct{})
output := make(chan string)
con.Register(control.PacketTypeSync, func(p *control.Packet) *control.Packet {
users := make([]string, 0)
if p.Message == "" {
inputSync <- nil
} else {
if err = json.Unmarshal([]byte(p.Message), &users); err != nil {
log.Println("WARN: Unable to unmarshal users:", err)
return &control.Packet{Type: control.PacketTypeResponse, Message: fmt.Sprintf("Unable to unmarshal users: %v", err)}
}
inputSync <- users
}
return &control.Packet{Type: control.PacketTypeResponse, Message: <-output}
})
con.Register(control.PacketTypeClearCache, func(p *control.Packet) *control.Packet {
inputClearCache <- struct{}{}
return &control.Packet{Type: control.PacketTypeResponse, Message: <-output}
})
con.Register(control.PacketTypeListDrivers, func(p *control.Packet) *control.Packet {
inputListDrivers <- struct{}{}
return &control.Packet{Type: control.PacketTypeResponse, Message: <-output}
})
log.Println("INFO: Listening for commands on", con.Socket)
t := time.NewTimer(0)
for {
select {
case users := <-inputSync:
log.Println("INFO: Sync command received. Running sync")
if err := Sync(c, client, users); err != nil {
log.Println("WARN: Sync failed:", err)
output <- fmt.Sprintf("Sync failed: %v", err)
break
}
output <- "Sync completed successfully"
case <-inputClearCache:
log.Println("INFO: ClearCache command received. Clearing cache")
if err := ClearCache(c, client); err != nil {
log.Println("WARN: Clearing cache failed:", err)
output <- fmt.Sprintf("Clearing cache failed: %v", err)
break
}
client.ClearCache()
output <- "Cache cleared successfully"
case <-inputListDrivers:
log.Println("INFO: ListDrivers command received. Querying CUPS")
drivers, err := client.GetPPDs()
if err != nil {
log.Println("WARN: Querying CUPS failed:", err)
output <- fmt.Sprintf("Querying CUPS failed: %v", err)
break
}
buf, err := json.MarshalIndent(drivers, "", "\t")
if err != nil {
log.Println("WARN: Marshalling drivers failed:", err)
output <- fmt.Sprintf("Marshalling drivers failed: %v", err)
break
}
output <- string(buf)
case <-t.C:
if err := Sync(c, client, nil); err != nil {
log.Println("WARN: Sync failed:", err)
}
}
t.Stop()
t.Reset(c.SyncInterval)
}
}
<file_sep>/control/control.go
//go:generate stringer -type PacketType
package control
import (
"encoding/json"
"errors"
"fmt"
"log"
"net"
"os"
"sync"
)
type PacketType int
//SearchPaths will be searched for a valid directory to place the control socket
var SearchPaths = []string{"/var/run", "/run"}
const (
PacketTypeSync PacketType = iota
PacketTypeResponse
PacketTypeClearCache
PacketTypeListDrivers
)
//Packet represents a control packet
type Packet struct {
Type PacketType `json:"type"`
Message string `json:"msg"`
}
//GetSocket returns a control socket path, or an error if none exists
func GetSocket() (string, error) {
for _, path := range SearchPaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
return fmt.Sprintf("%s/printer-manager.sock", path), nil
}
}
return "", errors.New("Unable to find valid run directory")
}
//Listener listens for control Packets and runs registered handlers on them
type Listener struct {
Socket string
listener net.Listener
handlers map[PacketType]func(p *Packet) *Packet
handlersMu *sync.RWMutex
}
func (l *Listener) worker() {
for {
conn, err := l.listener.Accept()
if err != nil {
log.Println("WARN: Unable to accept control message:", err)
continue
}
d := json.NewDecoder(conn)
p := new(Packet)
if err = d.Decode(p); err != nil {
conn.Close()
log.Println("WARN: Unable to decode control message:", err)
continue
}
l.handlersMu.RLock()
f, ok := l.handlers[p.Type]
l.handlersMu.RUnlock()
if !ok || f == nil {
conn.Close()
log.Printf("WARN: Unregistered handler for PacketType: %s\n", p.Type.String())
continue
}
log.Printf("INFO: Running handler for control message: %s\n", p.Type.String())
go func() {
resp := f(p)
e := json.NewEncoder(conn)
if err = e.Encode(resp); err != nil {
conn.Close()
return
}
if err = conn.Close(); err != nil {
log.Println("WARN: Error closing conn:", err)
}
}()
}
}
//New returns a new Listener or an error if one occurred
func New() (*Listener, error) {
sock, err := GetSocket()
if err != nil {
return nil, fmt.Errorf("Unable to get socket: %w", err)
}
if err := os.Remove(sock); err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("Unable to remove old socket: %w", err)
}
l, err := net.Listen("unix", sock)
if err != nil {
return nil, fmt.Errorf("Unable to listen on %s: %w", sock, err)
}
if err = os.Chmod(sock, 0777); err != nil {
return nil, fmt.Errorf("Unable to set permissions for socket: %w", err)
}
lis := &Listener{Socket: sock,
listener: l,
handlers: make(map[PacketType]func(*Packet) *Packet),
handlersMu: new(sync.RWMutex),
}
go lis.worker()
return lis, nil
}
//Register registers the given handler for the given Packet type
func (l *Listener) Register(t PacketType, handler func(p *Packet) *Packet) {
l.handlersMu.Lock()
l.handlers[t] = handler
l.handlersMu.Unlock()
}
//Do sends the given control packet and returns the response, or an error if one occurred
func Do(p *Packet) (*Packet, error) {
sock, err := GetSocket()
if err != nil {
return nil, fmt.Errorf("Unable to get socket: %w", err)
}
conn, err := net.Dial("unix", sock)
if err != nil {
return nil, fmt.Errorf("Unable to dial %s: %w", sock, err)
}
e := json.NewEncoder(conn)
if err = e.Encode(p); err != nil {
conn.Close()
return nil, fmt.Errorf("Unable to encode packet: %w", err)
}
resp := new(Packet)
d := json.NewDecoder(conn)
if err = d.Decode(resp); err != nil {
conn.Close()
return nil, fmt.Errorf("Unable to decode response: %w", err)
}
if err = conn.Close(); err != nil {
return nil, fmt.Errorf("Error closing conn: %w", err)
}
return resp, nil
}
<file_sep>/httpapi/httpapi.go
package httpapi
import (
"encoding/json"
"fmt"
"net/http"
"github.com/korylprince/printer-manager-cups/cups"
)
const apiPath = "/users/%s/printers"
func GetPrinters(apiBase string, usernames []string) ([]*cups.Printer, error) {
printerSet := make(map[string]*cups.Printer)
for _, username := range usernames {
resp, err := http.Get(apiBase + fmt.Sprintf(apiPath, username))
if err != nil {
return nil, fmt.Errorf("Unable to query printers: %w", err)
}
if resp.StatusCode == http.StatusNotFound {
// skip unknown users
resp.Body.Close()
continue
}
printers := make([]*cups.Printer, 0)
d := json.NewDecoder(resp.Body)
if err := d.Decode(&printers); err != nil {
resp.Body.Close()
return nil, fmt.Errorf("Unable to decode response: %w", err)
}
resp.Body.Close()
for _, p := range printers {
printerSet[p.ID] = p
}
}
// coalesce printers
printers := make([]*cups.Printer, 0, len(printerSet))
for _, p := range printerSet {
printers = append(printers, p)
}
return printers, nil
}
<file_sep>/cmd/printer-manager/main.go
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/korylprince/printer-manager-cups/control"
)
func DoCommand(pkt *control.Packet) {
resp, err := control.Do(pkt)
if err != nil {
if strings.Contains(err.Error(), "connect: no such file or directory") {
fmt.Println("Control socket not found. Are you sure the server is running?")
} else {
fmt.Println("Unable to send command to server:", err)
}
os.Exit(1)
}
fmt.Println(resp.Message)
}
func usage() {
fmt.Printf("Usage: %s [command]:\nCommands:\n\tsync [usernames...]\tsyncs printers, optionally including usernames\n\tclear-cache\t\tclears printer cache\n\tlist-drivers\t\tlists drivers found by CUPS\n", os.Args[0])
os.Exit(1)
}
func main() {
if len(os.Args) < 2 {
usage()
}
switch os.Args[1] {
case "sync":
if len(os.Args) > 2 {
users := os.Args[2:len(os.Args)]
b, err := json.Marshal(users)
if err != nil {
fmt.Println("Unable to marshal users:", err)
os.Exit(1)
}
fmt.Print("Server returned: ")
DoCommand(&control.Packet{Type: control.PacketTypeSync, Message: string(b)})
} else {
fmt.Print("Server returned: ")
DoCommand(&control.Packet{Type: control.PacketTypeSync})
}
case "clear-cache":
fmt.Print("Server returned: ")
DoCommand(&control.Packet{Type: control.PacketTypeClearCache})
fmt.Println("You will probably want to run the sync command now")
case "list-drivers":
fmt.Println("Server returned:")
DoCommand(&control.Packet{Type: control.PacketTypeListDrivers})
default:
fmt.Println("Unknown command:", os.Args[1])
usage()
}
}
<file_sep>/sync.go
package main
import (
"fmt"
"log"
"strings"
"time"
"github.com/korylprince/printer-manager-cups/cache"
"github.com/korylprince/printer-manager-cups/cups"
"github.com/korylprince/printer-manager-cups/httpapi"
"github.com/korylprince/printer-manager-cups/user"
)
func Sync(config *Config, client *cups.Client, usernames []string) error {
log.Println("INFO: Starting sync")
// get users
allUsers, err := user.GetUsers()
if err != nil {
return fmt.Errorf("Unable to get users: %w", err)
}
// filter ignored users
var users []string
outerIgnored:
for _, u := range allUsers {
for _, i := range config.IgnoreUsers {
if u == i {
continue outerIgnored
}
}
users = append(users, u)
}
users = append(users, usernames...)
// force usernames to lowercase
if config.IgnoreUserCase {
for i, u := range users {
users[i] = strings.ToLower(u)
}
}
log.Println("INFO: Getting printers for:", strings.Join(users, ", "))
// get api printers
printers, err := httpapi.GetPrinters(config.APIBase, users)
if err != nil {
return fmt.Errorf("Unable to get API printers: %w", err)
}
log.Println("INFO: Got", len(printers), "printers from API")
// cache api printer ids
pCache, err := cache.Read(config.CachePath)
if err != nil {
return fmt.Errorf("Unable to read cache: %w", err)
}
for _, p := range printers {
pCache[p.ID] = time.Now().Add(config.CacheTime)
}
if err = pCache.Write(config.CachePath); err != nil {
return fmt.Errorf("Unable to update cache: %w", err)
}
errPrinters := make(map[string]*cups.Printer)
// sync api printers to cups
for _, p := range printers {
if err = client.AddOrModify(p); err != nil {
log.Printf("WARN: Unable to add or modify printer %s (%s): %v\n", p.ID, p.Hostname, err)
errPrinters[p.ID] = p
continue
}
log.Printf("INFO: Added/Modified printer: %s (%s)\n", p.ID, p.Hostname)
}
// get cups printers
cupsPrinters, err := client.GetPrinters()
if err != nil {
if !strings.Contains(err.Error(), "No destinations added.") {
return fmt.Errorf("Unable to get CUPS printers: %w", err)
}
}
log.Println("INFO: Got", len(cupsPrinters), "printers from CUPS")
// remove matching, unmanaged printers
for _, cp := range cupsPrinters {
for _, p := range printers {
// skip if same printer
if cp.ID == p.ID {
continue
}
// skip error printers
if _, ok := errPrinters[p.ID]; ok {
continue
}
// skip if doesn't match
if !strings.Contains(cp.Hostname, p.Hostname) {
continue
}
if err = client.Delete(cp); err != nil {
log.Printf("WARN: Unable to remove matched printer %s: %v\n", cp.ID, err)
continue
}
log.Printf("INFO: Removed matching printer %s (%s): matched %s (%s)\n", cp.ID, cp.Hostname, p.ID, p.Hostname)
}
}
// delete expired printers
var deleted []string
outerExpired:
for id, expiration := range pCache {
if !expiration.Before(time.Now()) {
continue
}
for _, cp := range cupsPrinters {
if id == cp.ID {
if err = client.Delete(cp); err != nil {
log.Printf("WARN: Unable to delete expired printer %s (%s): %v\n", cp.ID, cp.Hostname, err)
continue outerExpired
}
log.Printf("INFO: Deleted expired printer %s (%s)\n", cp.ID, cp.Hostname)
break
}
}
// printer deleted successfully or not found
deleted = append(deleted, id)
}
// get default printer
cupsDefault, err := client.GetDefault()
if err != nil {
log.Println("WARN: Unable to get default printer:", err)
}
// elect default printer
var def *cups.Printer
for _, p := range printers {
if p.ID == cupsDefault {
def = p
break
}
}
for _, p := range printers {
// skip error printers
if _, ok := errPrinters[p.ID]; ok {
continue
}
if def == nil || p.DefaultPriority > def.DefaultPriority {
def = p
}
}
// set default printer
if def != nil && def.ID != cupsDefault {
if err = client.SetDefault(def); err != nil {
log.Printf("WARN: Unable to set default printer to %s (%s): %v\n", def.ID, def.Hostname, err)
} else {
log.Printf("INFO: Set default printer to %s (%s)\n", def.ID, def.Hostname)
}
}
// purge expired printers from cache
if err = cache.Purge(config.CachePath, deleted); err != nil {
log.Println("WARN: Unable to purge cache:", err)
}
log.Println("INFO: Sync completed successfully")
return nil
}
func ClearCache(config *Config, client *cups.Client) error {
log.Println("INFO: Clearing cached printers")
// cache api printer ids
pCache, err := cache.Read(config.CachePath)
if err != nil {
return fmt.Errorf("Unable to read cache: %w", err)
}
// get cups printers
cupsPrinters, err := client.GetPrinters()
if err != nil {
if !strings.Contains(err.Error(), "No destinations added.") {
return fmt.Errorf("Unable to get CUPS printers: %w", err)
}
}
log.Println("INFO: Got", len(cupsPrinters), "printers from CUPS")
// delete expired printers
var deleted []string
outerExpired:
for id := range pCache {
for _, cp := range cupsPrinters {
if id == cp.ID {
if err = client.Delete(cp); err != nil {
log.Printf("WARN: Unable to delete expired printer %s (%s): %v\n", cp.ID, cp.Hostname, err)
continue outerExpired
}
log.Printf("INFO: Deleted expired printer %s (%s)\n", cp.ID, cp.Hostname)
break
}
}
// printer deleted successfully or not found
deleted = append(deleted, id)
}
// purge expired printers from cache
if err = cache.Purge(config.CachePath, deleted); err != nil {
log.Println("WARN: Unable to purge cache:", err)
}
log.Println("INFO: Cache cleared successfully")
return nil
}
<file_sep>/config.go
package main
import "time"
type Config struct {
APIBase string `required:"true"`
CachePath string `default:"/etc/printer-manager"`
CacheTime time.Duration `default:"336h"` // 14 days
SyncInterval time.Duration `default:"1h"`
IgnoreUsers []string `default:"root"`
IgnoreUserCase bool `default:"false"`
}
<file_sep>/cups/cups.go
package cups
import (
"errors"
"fmt"
"math/rand"
"os/exec"
"os/user"
"time"
"github.com/phin1x/go-ipp"
)
const DefaultCacheTimeout = time.Minute * 5
//Client is a CUPS client that connects over unix sockets
type Client struct {
client *ipp.IPPClient
adapter ipp.Adapter
CacheTimeout time.Duration
cache map[string]string
cacheTime time.Time
}
//New returns a new client or an error if one occurred
func New() (*Client, error) {
// set user field
user, err := user.Current()
if err != nil {
return nil, fmt.Errorf("Unable to lookup current user: %w", err)
}
adapter := ipp.NewSocketAdapter("localhost:631", false)
return &Client{
client: ipp.NewIPPClientWithAdapter(user.Username, adapter),
adapter: adapter,
CacheTimeout: DefaultCacheTimeout,
}, nil
}
func (c *Client) adminURL() string {
return c.adapter.GetHttpUri("admin", "")
}
func (c *Client) getPPDs() (map[string]string, error) {
r := ipp.NewRequest(ipp.OperationCupsGetPPDs, rand.Int31())
r.OperationAttributes[ipp.AttributeRequestedAttributes] = []string{"ppd-make-and-model", ipp.AttributePPDName}
resp, err := c.client.SendRequest(c.adminURL(), r, nil)
if err != nil {
return nil, fmt.Errorf("Unable to complete IPP request: %w", err)
}
ppds := make(map[string]string)
for _, a := range resp.PrinterAttributes {
if val := a["ppd-make-and-model"]; len(val) == 1 {
if val2 := a[ipp.AttributePPDName]; len(val2) == 1 {
ppds[(val[0].Value).(string)] = (val2[0].Value).(string)
}
}
}
return ppds, nil
}
//GetPPDs returns the a mapping of make-and-model to name for all PPDs installed or an error if one occurred
func (c *Client) GetPPDs() (map[string]string, error) {
if c.cache != nil && time.Since(c.cacheTime) < c.CacheTimeout {
return c.cache, nil
}
ppds, err := c.getPPDs()
if err != nil {
return nil, err
}
c.cache = ppds
c.cacheTime = time.Now()
return ppds, nil
}
//GetDefault returns the id of the default Printer or an error if one occurred
func (c *Client) GetDefault() (string, error) {
r := ipp.NewRequest(ipp.OperationCupsGetDefault, rand.Int31())
r.OperationAttributes[ipp.AttributeRequestedAttributes] = []string{ipp.AttributePrinterName}
resp, err := c.client.SendRequest(c.adminURL(), r, nil)
if err != nil {
return "", fmt.Errorf("Unable to complete IPP request: %w", err)
}
if len(resp.PrinterAttributes) != 1 {
return "", errors.New("Server did not return a default printer")
}
return (resp.PrinterAttributes[0][ipp.AttributePrinterName][0].Value).(string), nil
}
//CUPS hold CUPS-specific driver options
type CUPS struct {
DriverName []string `json:"driver_name"`
URITemplate string `json:"uri_template"`
DefaultPriority int `json:"default_priority"`
Options map[string]string `json:"options"`
Override struct {
Name string `json:"name"`
Location string `json:"location"`
} `json:"override"`
}
//Driver hold driver options
type Driver struct {
*CUPS `json:"cups"`
}
//Printer represents a CUPs printer
type Printer struct {
ID string `json:"id"`
Hostname string `json:"hostname"`
Name string `json:"name"`
Location string `json:"location"`
*Driver `json:"driver"`
}
func (p *Printer) GetName() string {
if p.Driver != nil && p.Driver.CUPS != nil && p.Driver.CUPS.Override.Name != "" {
return p.Driver.CUPS.Override.Name
}
return p.Name
}
func (p *Printer) GetLocation() string {
if p.Driver != nil && p.Driver.CUPS != nil && p.Driver.CUPS.Override.Location != "" {
return p.Driver.CUPS.Override.Location
}
return p.Location
}
//GetPrinters returns all the installed Printers or an error if one occurred
func (c *Client) GetPrinters() ([]*Printer, error) {
r := ipp.NewRequest(ipp.OperationCupsGetPrinters, rand.Int31())
r.OperationAttributes[ipp.AttributeRequestedAttributes] = []string{ipp.AttributePrinterName, ipp.AttributeDeviceURI, ipp.AttributePrinterInfo, ipp.AttributePrinterLocation}
resp, err := c.client.SendRequest(c.adminURL(), r, nil)
if err != nil {
return nil, fmt.Errorf("Unable to complete IPP request: %w", err)
}
printers := make([]*Printer, 0, len(resp.PrinterAttributes))
for _, a := range resp.PrinterAttributes {
p := new(Printer)
if val := a[ipp.AttributePrinterName]; len(val) == 1 {
p.ID = (val[0].Value).(string)
}
// we're returning full URI here instead of trying to parse out hostname
if val := a[ipp.AttributeDeviceURI]; len(val) == 1 {
p.Hostname = (val[0].Value).(string)
}
if val := a[ipp.AttributePrinterInfo]; len(val) == 1 {
p.Name = (val[0].Value).(string)
}
if val := a[ipp.AttributePrinterLocation]; len(val) == 1 {
p.Location = (val[0].Value).(string)
}
printers = append(printers, p)
}
return printers, nil
}
//AddOrModify creates or updates the Printer or returns an error if one occurred
func (c *Client) AddOrModify(p *Printer) error {
//find first matching PPD
ppds, err := c.GetPPDs()
if err != nil {
return fmt.Errorf("Unable to get PPDs: %w", err)
}
ppd := ""
for _, p := range p.DriverName {
if name, ok := ppds[p]; ok {
ppd = name
break
}
}
if ppd == "" {
return errors.New("No matching PPDs found")
}
r := ipp.NewRequest(ipp.OperationCupsAddModifyPrinter, rand.Int31())
r.OperationAttributes[ipp.AttributePrinterURI] = c.adapter.GetHttpUri("printers", p.ID)
r.OperationAttributes[ipp.AttributeDeviceURI] = fmt.Sprintf(p.URITemplate, p.Hostname)
r.OperationAttributes[ipp.AttributePPDName] = ppd
r.OperationAttributes[ipp.AttributePrinterInfo] = p.GetName()
r.OperationAttributes[ipp.AttributePrinterLocation] = p.GetLocation()
r.OperationAttributes[ipp.AttributePrinterIsAcceptingJobs] = true
r.OperationAttributes[ipp.AttributePrinterState] = ipp.PrinterStateIdle
if _, err := c.client.SendRequest(c.adminURL(), r, nil); err != nil {
return fmt.Errorf("Unable to add or modify printer: %w", err)
}
if len(p.Options) == 0 {
return nil
}
//use lpadmin to update options
options := []string{"-p", p.ID}
for k, v := range p.Options {
options = append(options, "-o", fmt.Sprintf("%s=%s", k, v))
}
cmd := exec.Command("lpadmin", options...)
if err := cmd.Run(); err != nil {
return fmt.Errorf("Unable to set printer options: %w", err)
}
return nil
}
//Delete deletes the Printer or returns an error if one occurred
func (c *Client) Delete(p *Printer) error {
r := ipp.NewRequest(ipp.OperationCupsDeletePrinter, rand.Int31())
r.OperationAttributes[ipp.AttributePrinterURI] = c.adapter.GetHttpUri("printers", p.ID)
_, err := c.client.SendRequest(c.adminURL(), r, nil)
if err != nil {
return fmt.Errorf("Unable to complete IPP request: %w", err)
}
return nil
}
//SetDefault sets the Printer as default or returns an error if one occurred
func (c *Client) SetDefault(p *Printer) error {
r := ipp.NewRequest(ipp.OperationCupsSetDefault, rand.Int31())
r.OperationAttributes[ipp.AttributePrinterURI] = c.adapter.GetHttpUri("printers", p.ID)
_, err := c.client.SendRequest(c.adminURL(), r, nil)
if err != nil {
return fmt.Errorf("Unable to complete IPP request: %w", err)
}
return nil
}
//ClearCache clears the clients PPD cache
func (c *Client) ClearCache() {
c.cache = nil
}
<file_sep>/go.mod
module github.com/korylprince/printer-manager-cups
go 1.14
require (
github.com/DataDog/zstd v1.4.8 // indirect
github.com/dgraph-io/badger/v2 v2.2007.2
github.com/dgraph-io/ristretto v0.0.3 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.3 // indirect
github.com/kelseyhightower/envconfig v1.4.0
github.com/phin1x/go-ipp v1.6.1-0.20210505080100-49bca931bb89
github.com/pkg/errors v0.9.1 // indirect
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 // indirect
golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6 // indirect
)
| 07e7ea9685b8a3e59da95d6e4c75f42f8afa0972 | [
"Go Module",
"Go"
] | 10 | Go | xuepd/printer-manager-cups | 953726aad1f8d6f039e85b4e2f2049121f6bdcc4 | 4bb2ce6b16e4f60b93465a54bf92f3fe8215bd8e |
refs/heads/master | <file_sep>/**
******************************************************************************
* @file stm32f4xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
*
* COPYRIGHT(c) 2018 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "stm32f4xx.h"
#include "stm32f4xx_it.h"
/* USER CODE BEGIN 0 */
uint8_t mode = 0;
uint8_t cnt1=0,cnt2=0,cnt3=0,cnt4=0,cnt5=0,cnt6=0;
signed char Gio1=20,Phut1=00,Gio2=20,Phut2=00;
signed char Gio3=20,Phut3=00,Gio4=20,Phut4=00;
signed char Gio5=20,Phut5=00,Gio6=20,Phut6=00;
signed char Gio7=20,Phut7=00,Gio8=20,Phut8=00;
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern I2C_HandleTypeDef hi2c1;
extern TIM_HandleTypeDef htim2;
extern UART_HandleTypeDef huart2;
/******************************************************************************/
/* Cortex-M4 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN HardFault_IRQn 1 */
/* USER CODE END HardFault_IRQn 1 */
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN MemoryManagement_IRQn 1 */
/* USER CODE END MemoryManagement_IRQn 1 */
}
/**
* @brief This function handles Pre-fetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN BusFault_IRQn 1 */
/* USER CODE END BusFault_IRQn 1 */
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN UsageFault_IRQn 1 */
/* USER CODE END UsageFault_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
HAL_SYSTICK_IRQHandler();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32F4xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32f4xx.s). */
/******************************************************************************/
int press_button(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
int Rvalue = 1;
int timming = 0;
if(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin) == 0)
{
while(1)
{
if(timming >= 0xff)
{
if(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin) != 0)
{
Rvalue = 0;
break;
}
}
timming++;
}
}
return Rvalue;
}
/**
* @brief This function handles EXTI line0 interrupt.
*/
void EXTI0_IRQHandler(void)
{
/* USER CODE BEGIN EXTI0_IRQn 0 */
/* USER CODE END EXTI0_IRQn 0 */
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
/* USER CODE BEGIN EXTI0_IRQn 1 */
//if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0)==0)
if(press_button(GPIOB, GPIO_PIN_0) == 0)
{
if(mode==5)
{
cnt4++;
if(cnt4>1)
{
cnt4=0;
}
}
if(mode == 1)
{
switch(cnt5)
{
case 1:
Gio1--;
if(Gio1<00)
Gio1=23;
break;
case 2:
Phut1--;
if(Phut1<00)
Phut1=59;
break;
case 3:
Gio2--;
if(Gio2<00)
Gio2=23;
break;
case 4:
Phut2--;
if(Phut2<00)
Phut2=59;
break;
case 5:
Gio3--;
if(Gio3<00)
Gio3=23;
break;
case 6:
Phut3--;
if(Phut3<00)
Phut3=59;
break;
case 7:
Gio4--;
if(Gio4<00)
Gio4=23;
break;
case 8:
Phut4--;
if(Phut4<00)
Phut4=59;
break;
case 9:
Gio5--;
if(Gio5<00)
Gio5=23;
break;
case 10:
Phut5--;
if(Phut5<00)
Phut5=59;
break;
case 11:
Gio6--;
if(Gio6<00)
Gio6=23;
break;
case 12:
Phut6--;
if(Phut6<00)
Phut6=59;
break;
case 13:
Gio7--;
if(Gio7<00)
Gio7=23;
break;
case 14:
Phut7--;
if(Phut7<00)
Phut7=59;
break;
case 15:
Gio8--;
if(Gio8<00)
Gio8=23;
break;
case 16:
Phut8--;
if(Phut8<00)
Phut8=59;
break;
default: break;
}
}
//else
// cnt5 = 0;
}
}
/**
* @brief This function handles EXTI line4 interrupt.
*/
void EXTI4_IRQHandler(void)
{
/* USER CODE BEGIN EXTI4_IRQn 0 */
/* USER CODE END EXTI4_IRQn 0 */
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_4);
/* USER CODE BEGIN EXTI4_IRQn 1 */
/* if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)
{
//while(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0){};
//HAL_Delay(200);
mode++;
if(mode>4)
mode=0;
//HAL_Delay(100);
}
*/
if(press_button(GPIOA, GPIO_PIN_4) == 0)
{
mode++;
if(mode > 5)
mode = 0;
}
/* USER CODE END EXTI4_IRQn 1 */
}
/**
* @brief This function handles EXTI line[9:5] interrupts.
*/
void EXTI9_5_IRQHandler(void)
{
/* USER CODE BEGIN EXTI9_5_IRQn 0 */
/* USER CODE END EXTI9_5_IRQn 0 */
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_5);
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_6);
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_7);
/* USER CODE BEGIN EXTI9_5_IRQn 1 */
//if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_5)==0)
if(press_button(GPIOA, GPIO_PIN_5) == 0)
{
if(mode == 1)
{
cnt5++;
if(cnt5 > 16)
cnt5 = 0;
}
//else cnt5 = 0;
if(mode==5)
{
cnt1++;
if(cnt1>1)
cnt1=0;
}
}
//if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_6)==0)
if(press_button(GPIOA, GPIO_PIN_6) == 0)
{
if(mode==5)
{
cnt2++;
if(cnt2>1)
cnt2=0;
}
}
//if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_7)==0)
if(press_button(GPIOA, GPIO_PIN_7) == 0)
{
if(mode==5)
{
cnt3++;
if(cnt3>1)
cnt3=0;
}
if(mode == 1)
{
switch(cnt5)
{
case 1:
Gio1++;
if(Gio1>23)
Gio1=0;
break;
case 2:
Phut1++;
if(Phut1>59)
Phut1=00;
break;
case 3:
Gio2++;
if(Gio2>23)
Gio2=0;
break;
case 4:
Phut2++;
if(Phut2>59)
Phut2=00;
break;
case 5:
Gio3++;
if(Gio3>23)
Gio3=0;
break;
case 6:
Phut3++;
if(Phut3>59)
Phut3=00;
break;
case 7:
Gio4++;
if(Gio4>23)
Gio4=0;
break;
case 8:
Phut4++;
if(Phut4>59)
Phut4=00;
break;
case 9:
Gio5++;
if(Gio5>23)
Gio5=0;
break;
case 10:
Phut5++;
if(Phut5>59)
Phut5=00;
break;
case 11:
Gio6++;
if(Gio6>23)
Gio6=0;
break;
case 12:
Phut6++;
if(Phut6>59)
Phut6=00;
break;
case 13:
Gio7++;
if(Gio7>23)
Gio7=0;
break;
case 14:
Phut7++;
if(Phut7>59)
Phut7=00;
break;
case 15:
Gio8++;
if(Gio8>23)
Gio8=0;
break;
case 16:
Phut8++;
if(Phut8>59)
Phut8=00;
break;
default: break;
}
}
//else cnt5 = 0;
}
}
/**
* @brief This function handles TIM2 global interrupt.
*/
void TIM2_IRQHandler(void)
{
/* USER CODE BEGIN TIM2_IRQn 0 */
/* USER CODE END TIM2_IRQn 0 */
HAL_TIM_IRQHandler(&htim2);
/* USER CODE BEGIN TIM2_IRQn 1 */
/* USER CODE END TIM2_IRQn 1 */
}
/**
* @brief This function handles I2C1 event interrupt.
*/
void I2C1_EV_IRQHandler(void)
{
/* USER CODE BEGIN I2C1_EV_IRQn 0 */
/* USER CODE END I2C1_EV_IRQn 0 */
HAL_I2C_EV_IRQHandler(&hi2c1);
/* USER CODE BEGIN I2C1_EV_IRQn 1 */
/* USER CODE END I2C1_EV_IRQn 1 */
}
/**
* @brief This function handles I2C1 error interrupt.
*/
void I2C1_ER_IRQHandler(void)
{
/* USER CODE BEGIN I2C1_ER_IRQn 0 */
/* USER CODE END I2C1_ER_IRQn 0 */
HAL_I2C_ER_IRQHandler(&hi2c1);
/* USER CODE BEGIN I2C1_ER_IRQn 1 */
/* USER CODE END I2C1_ER_IRQn 1 */
}
/**
* @brief This function handles USART2 global interrupt.
*/
void USART2_IRQHandler(void)
{
/* USER CODE BEGIN USART2_IRQn 0 */
/* USER CODE END USART2_IRQn 0 */
HAL_UART_IRQHandler(&huart2);
/* USER CODE BEGIN USART2_IRQn 1 */
/* USER CODE END USART2_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>#include "main.h"
void read_RTC()
{
aTxBuffer[0]=0;
I2C_WriteBuffer(hi2c1,(uint16_t)0xD0,1);
while(HAL_I2C_GetState(&hi2c1)!=HAL_I2C_STATE_READY);
I2C_ReadBuffer(hi2c1,(uint16_t)0xD0,7);
date = aTxBuffer[4];
date = RTC_ConvertFromDec(date);
month = aTxBuffer[5];
month = RTC_ConvertFromDec(month);
year = aTxBuffer[6];
year = RTC_ConvertFromDec(year);
day = aTxBuffer[3];
day = RTC_ConvertFromDec(day);
hour = aTxBuffer[2];
hour = RTC_ConvertFromDec(hour);
min = aTxBuffer[1];
min = RTC_ConvertFromDec(min);
sec = aTxBuffer[0];
sec = RTC_ConvertFromDec(sec);
}
void Set_Time_Bom()
{
char timedat[20];
LCD_Clear();
LCD_SetPos(0,0);
LCD_String("CAI DAT THOI GIAN");
LCD_SetPos(1,1);
LCD_String("Bom:");
LCD_SetPos(6,1);
sprintf(timedat,"%02d:%02d_%02d:%02d",Gio1,Phut1,Gio2,Phut2);
LCD_String(timedat);
HAL_Delay(500);
}
void Set_Time_Quat()
{
char timedat[20];
LCD_Clear();
LCD_SetPos(0,0);
LCD_String("CAI DAT THOI GIAN");
LCD_SetPos(0,1);
LCD_String("Quat:");
LCD_SetPos(6,1);
sprintf(timedat,"%02d:%02d_%02d:%02d",Gio3,Phut3,Gio4,Phut4);
LCD_String(timedat);
HAL_Delay(500);
}
void Set_Time_Den()
{
char timedat[20];
LCD_Clear();
LCD_SetPos(0,0);
LCD_String("CAI DAT THOI GIAN");
LCD_SetPos(1,1);
LCD_String("Den:");
LCD_SetPos(6,1);
sprintf(timedat,"%02d:%02d_%02d:%02d",Gio5,Phut5,Gio6,Phut6);
LCD_String(timedat);
HAL_Delay(500);
}
void Set_Time_Say()
{
char timedat[20];
LCD_Clear();
LCD_SetPos(0,0);
LCD_String("CAI DAT THOI GIAN");
LCD_SetPos(1,1);
LCD_String("Say:");
LCD_SetPos(6,1);
sprintf(timedat,"%02d:%02d_%02d:%02d",Gio7,Phut7,Gio8,Phut8);
LCD_String(timedat);
HAL_Delay(500);
}
void LCD_Auto_Time()
{
char timeBOM[20];
char timeQUAT[20];
char timeDEN[20];
char timeSAY[20];
LCD_Clear();
LCD_SetPos(0,0);
LCD_String("AUTO ");
LCD_String("Bom ");
sprintf(timeBOM,"%02d:%02d_%02d:%02d",Gio1,Phut1,Gio2,Phut2);
LCD_String(timeBOM);
LCD_SetPos(3,1);
LCD_String("Quat: ");
sprintf(timeQUAT,"%02d:%02d_%02d:%02d",Gio3,Phut3,Gio4,Phut4);
LCD_String(timeQUAT);
LCD_SetPos(4,2);
LCD_String("Den: ");
sprintf(timeDEN,"%02d:%02d_%02d:%02d",Gio5,Phut5,Gio6,Phut6);
LCD_String(timeDEN);
LCD_SetPos(4,3);
LCD_String("Say: ");
sprintf(timeSAY,"%02d:%02d_%02d:%02d",Gio7,Phut7,Gio8,Phut8);
LCD_String(timeSAY);
HAL_Delay(500);
}
void Write_SDCard()
{
if(f_mount(&SDFatFs,(TCHAR const*)SD_Path,0)!=FR_OK)
Error_Handler();
else
{
if(f_open(&MyFile,"Mytext.txt",FA_CREATE_ALWAYS|FA_WRITE)!=FR_OK)
Error_Handler();
else
{
res=f_lseek(&MyFile,f_tell(&MyFile)+f_size(&MyFile));
res=f_write(&MyFile,wtext,sizeof(wtext),(void*)&byteswritten);
f_close(&MyFile);
}
}
}
void Read_SDCard()
{
if(f_mount(&SDFatFs,(TCHAR const*)SD_Path,0)!=FR_OK)
Error_Handler();
else
{
if(f_open(&MyFile,"mywrite.txt",FA_READ)!=FR_OK)
Error_Handler();
else
{
res=f_read(&MyFile,rtext,sizeof(rtext),(void*)&bytesread);
if((bytesread==0)||(res!=FR_OK))
Error_Handler();
else
{
LCD_Clear();
LCD_SetPos(0,3);
rtext[bytesread]=0;
LCD_String((char*)rtext);
}
f_close(&MyFile);
}
}
}
void pos_str_LCD(int posx, int posy, char * st)
{
LCD_SetPos(posx, posy);
LCD_String(st);
}
void display_LCD(char * return_data, int buffer_uart, int point_start)
{
int i = 0;
for(i = 0; i < buffer_uart; i++)
{
return_data[i] = str_uart[i + point_start];
LCD_SendChar(return_data[i]);
}
}
void send_char_temperature(char *st)
{
LCD_SendChar(223);
LCD_String(st);
}
void display_st_LCD(char * st)
{
LCD_String(st);
}
void display_pos_LCD(int posx, int posy)
{
LCD_SetPos(posx, posy);
}
void display_sensor_LCD(char * st, int T_dat, int H_dat)
{
char dat_t[20],dat_h[20];
LCD_Clear();
pos_str_LCD(1,0,st);
pos_str_LCD(0,1,"ND: ");
display_LCD(buff_temp1, 2,6);
LCD_String(";");
display_LCD(buff_temp2, 2, 13);
send_char_temperature("C");
sprintf(dat_t,"%d",T_dat);
pos_str_LCD(15,1,dat_t);
send_char_temperature("C");
pos_str_LCD(0,2,"AM: ");
display_LCD(buff_humi1, 3,9);
display_st_LCD(";");
display_LCD(buff_humi2, 3, 16);
display_st_LCD("%");
sprintf(dat_h,"%d",H_dat);
pos_str_LCD(15,2,dat_h);
display_st_LCD("%");
pos_str_LCD(0,3,"AS: ");
display_LCD(buff_light, 5, 0);
LCD_String(" lux");
HAL_Delay(500);
}
void LCD_DK_TaiCho()
{
LCD_Clear();
pos_str_LCD(0,0, "MANUAL");
//anh sang
pos_str_LCD(8, 0, "AS:");
display_LCD(buff_light, 5, 0);
display_st_LCD(" lux");
//Nhiet do
display_pos_LCD(2,1);
display_LCD(buff_temp1, 2, 6);
display_st_LCD("_");
display_LCD(buff_temp2, 2, 13);
send_char_temperature("C");
//do am
display_pos_LCD(11,1);
display_LCD(buff_humi1, 3, 9);
display_st_LCD("_");
display_LCD(buff_humi2, 3, 16);
display_st_LCD("%");
pos_str_LCD(0, 2, "1:Quat hut");
pos_str_LCD(13, 2, "2:Den");
pos_str_LCD(0,3,"3:Phun Suong");
pos_str_LCD(13, 3, "4:Say");
HAL_Delay(500);
}
//string to uint
void strToUint()
{
// UART_Receive();
L=(str_uart[0]-48)*10000+(str_uart[1]-48)*1000+(str_uart[2]-48)*100+(str_uart[3]-48)*10+(str_uart[4]-48);
T1=(str_uart[6]-48)*10+(str_uart[7]-48);
H1=(str_uart[9]-48)*100+(str_uart[10]-48)*10+(str_uart[11]-48);
T2=(str_uart[13]-48)*10+(str_uart[14]-48);
H2=(str_uart[16]-48)*100+(str_uart[17]-48)*10+(str_uart[18]-48);
}
void InitialSoftwareProgram()
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_I2C1_Init();
MX_SDIO_SD_Init();
MX_FATFS_Init();
MX_TIM2_Init();
__HAL_UART_ENABLE_IT(&huart2,UART_IT_TC);
__HAL_UART_ENABLE_IT(&huart2,UART_IT_RXNE);
HAL_TIM_Base_Start_IT(&htim2);
//Write_SDCard();
LCD_ini();
LCD_Clear();
}
void blink_question_mask(int posx, int posy)
{
LCD_SetPos(posx,posy);
LCD_String("?");
HAL_Delay(300);
}
void which_setting(void * funcion_call, int posx, int posy)
{
void (*call_a_funcion_running)(void) = NULL;
call_a_funcion_running = funcion_call;
call_a_funcion_running();
blink_question_mask(posx, posy);
}
void setting_time(void)
{
switch(cnt5)
{
case 0:
LCD_Clear();
pos_str_LCD(0,0, "Setting TIME");
HAL_Delay(500);
break;
case 1:
which_setting(Set_Time_Bom,6,2);
break;
case 2:
which_setting(Set_Time_Bom,9,2);
break;
case 3:
which_setting(Set_Time_Bom,12,2);
break;
case 4:
which_setting(Set_Time_Bom,15,2);
break;
case 5:
which_setting(Set_Time_Quat,6,2);
break;
case 6:
which_setting(Set_Time_Quat,9,2);
break;
case 7:
which_setting(Set_Time_Quat,12,2);
break;
case 8:
which_setting(Set_Time_Quat,15,2);
break;
case 9:
which_setting(Set_Time_Den,6,2);
break;
case 10:
which_setting(Set_Time_Den,9,2);
break;
case 11:
which_setting(Set_Time_Den,12,2);
break;
case 12:
which_setting(Set_Time_Den,15,2);
break;
case 13:
which_setting(Set_Time_Say,6,2);
break;
case 14:
which_setting(Set_Time_Say,9,2);
break;
case 15:
which_setting(Set_Time_Say,12,2);
break;
case 16:
which_setting(Set_Time_Say,15,2);
break;
default: break;
}
}
void setting_auto_uto(void)
{
HAL_UART_Receive_IT(&huart2,(uint8_t *)str_uart,MAX_STRLEN);
display_sensor_LCD("ABUTO: G/D U TO", T1_dat, H1_dat);
strToUint();
//write_SD();
//HAL_TIM_PeriodElapsedCallback(&htim2);
//anh sang
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_9,GPIO_PIN_RESET); //tat den
if(T1>=T1_max || T2>=T1_max)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_SET); //bat quat hut
else if(T1==T1_dat || T2==T1_dat || T1>100 || T2>100)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_RESET); //tat quat hut
//nhiet do thap
if(T1<=T1_min || T2<=T1_min)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_10,GPIO_PIN_SET); //bat may say
else if(T1==T1_dat || T2==T1_dat || T2>100 || T1>100)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_10,GPIO_PIN_RESET); //tat may say
//do am cao
if(H1>=H1_max || H2>=H1_max)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_SET); //bat quat hut
else if(H1==H1_dat || H2==H1_dat || H1>100 || H2>100)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_RESET); //tat quat hut
//do am thap
if(H1<=H1_min || H2<=H1_min)
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12,GPIO_PIN_SET); //bat phun suong
else if(H1==H1_dat || H2==H1_dat || H1>100 || H2>100)
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12,GPIO_PIN_RESET); //tat phun suong
}
void setting_auto_quathe(void)
{
HAL_UART_Receive_IT(&huart2,(uint8_t *)str_uart,MAX_STRLEN);
display_sensor_LCD("AUTO: G/D QUA THE", T2_dat, H2_dat);
strToUint();
//write_SD();
//HAL_TIM_PeriodElapsedCallback(&htim2);
if(T1>=T2_max || T2>=T2_max)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_SET); //bat quat hut
else if(T1==T2_dat || T2==T2_dat || T1>100 || T2>100)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_RESET); //tat quat hut
//nhiet do thap
if(T1<=T2_min || T2<=T2_min)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_10,GPIO_PIN_SET); //bat may say
else if(T1==T2_dat || T2==T2_dat || T2>100 || T1>100)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_10,GPIO_PIN_RESET); //tat may say
//do am cao
if(H1>=H2_max || H2>=H2_max)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_SET); //bat quat hut
else if(H1==H2_dat || H2==H2_dat || H1>100 || H2>100)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_RESET); //tat quat hut
//do am thap
if(H1<=H2_min || H2<=H2_min)
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12,GPIO_PIN_SET); //bat phun suong
else if(H1==H2_dat || H2==H2_dat || H1>100 || H2>100)
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12,GPIO_PIN_RESET); //tat phun suong
//anh sang thap
if(L<=L2_min)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_9,GPIO_PIN_SET); //bat den
else
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_9,GPIO_PIN_RESET); //tat den
}
void setting_auto_timming(void)
{
LCD_Auto_Time();
}
void setting_manual(void)
{
HAL_UART_Receive_IT(&huart2,(uint8_t *)str_uart,MAX_STRLEN);
LCD_DK_TaiCho();
//write_SD();
//HAL_TIM_PeriodElapsedCallback(&htim2);
if(cnt1==1)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_SET); //bat quat hut
else
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_8,GPIO_PIN_RESET); //tat quat hut
if(cnt2==1)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_9,GPIO_PIN_SET); //bat den
else
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_9,GPIO_PIN_RESET); //tat den
if(cnt3==1)
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12,GPIO_PIN_SET); //bat phun suong
else
HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12,GPIO_PIN_RESET); //tat phun suong
if(cnt4==1)
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_10,GPIO_PIN_SET); //bat may say
else
HAL_GPIO_WritePin(GPIOE,GPIO_PIN_10,GPIO_PIN_RESET); //tat may say
}
void introduce(void)
{
HAL_UART_Receive_IT(&huart2,(uint8_t *)str_uart,MAX_STRLEN);
LCD_Clear();
//pos_str_LCD(0,0, "MENU");
//pos_str_LCD(0,1, "1:Che Do");
//pos_str_LCD(0,2, "2:Cai <NAME>");
pos_str_LCD(8,1, "HELLO");
pos_str_LCD(0,2, "Continue --> Press");
HAL_Delay(400);
}
void reset_value(void)
{
cnt1 = 0;
cnt2 = 0;
cnt3 = 0;
cnt4 = 0;
cnt5 = 0;
}
void mode_programing(int count)
{
switch(count)
{
case 0:
introduce();
reset_value();
break;
case 1:
setting_time();
break;
case 2:
setting_auto_uto();
break;
case 3:
setting_auto_quathe();
break;
case 4:
setting_auto_timming();
break;
case 5:
setting_manual();
break;
default: break;
}
}
int main(void)
{
InitialSoftwareProgram();
mode=0;
cnt1=0;
//Write_SDCard();
while (1)
{
mode_programing(mode);
}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==htim2.Instance)
{
cnt_timer++;
cnt_timer1++;
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance==huart2.Instance)
{
HAL_UART_Receive_IT(&huart2,(uint8_t *)str_uart,MAX_STRLEN);
HAL_UART_Transmit_IT(&huart2,(uint8_t *)str_uart,MAX_STRLEN);
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV4;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* I2C1 init function */
void MX_I2C1_Init(void)
{
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 100000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK)
{
Error_Handler();
}
}
/* SDIO init function */
void MX_SDIO_SD_Init(void)
{
hsd.Instance = SDIO;
hsd.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
hsd.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
hsd.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
hsd.Init.BusWide = SDIO_BUS_WIDE_1B;
hsd.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
hsd.Init.ClockDiv = 0;
}
/* TIM2 init function */
void MX_TIM2_Init(void)
{
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;
htim2.Instance = TIM2;
htim2.Init.Prescaler = 42000;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 119999;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_Base_Init(&htim2);
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig);
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig);
}
/* USART2 init function */
void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart2);
}
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
*/
void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
/*Configure GPIO pins : PA4 PA5 PA6 PA7 */
GPIO_InitStruct.Pin = GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : PB0 */
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : PE7 PE8 PE9 PE10 */
GPIO_InitStruct.Pin = GPIO_PIN_7|GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pin : PD12 */
GPIO_InitStruct.Pin = GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pins : D4_Pin D5_Pin D6_Pin D7_Pin */
GPIO_InitStruct.Pin = D4_Pin|D5_Pin|D6_Pin|D7_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/*Configure GPIO pins : RS_Pin EN_Pin */
GPIO_InitStruct.Pin = RS_Pin|EN_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_7|GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_12|D4_Pin|D5_Pin|D6_Pin
|D7_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, RS_Pin|EN_Pin, GPIO_PIN_RESET);
/* EXTI interrupt init*/
HAL_NVIC_SetPriority(EXTI0_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI0_IRQn);
HAL_NVIC_SetPriority(EXTI4_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI4_IRQn);
HAL_NVIC_SetPriority(EXTI9_5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
}
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler */
/* User can add his own implementation to report the HAL error return state */
while(1)
{
}
/* USER CODE END Error_Handler */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>#ifndef __main_H
#define __main_H
#ifdef __cplusplus
extern "C" {
#endif
#include "stm32f4xx_hal.h"
#include "fatfs.h"
#include "lcd.h"
#include "i2c.h"
#include "RTC.h"
I2C_HandleTypeDef hi2c1;
SD_HandleTypeDef hsd;
HAL_SD_CardInfoTypedef SDCardInfo;
TIM_HandleTypeDef htim2;
UART_HandleTypeDef huart2;
FATFS SDFatFs;
FIL MyFile;
FIL file_tam;
extern char SD_Path[4];
//UART_1
#define MAX_STRLEN 19
char buff_rx[MAX_STRLEN];
char buff_tx[MAX_STRLEN];
char str_uart[MAX_STRLEN]={0};
//Sensor
char buff_light[5];
char buff_temp1[2];
char buff_temp2[2];
char buff_humi1[3];
char buff_humi2[3];
//RTC
uint8_t aTxBuffer[8];
//uint8_t aRxBuffer[8];
uint8_t sec=0,min=0,hour=0,day=0,date=0,month=0,year=0;
extern signed char Gio1,Phut1,Gio2,Phut2;
extern signed char Gio3,Phut3,Gio4,Phut4;
extern signed char Gio5,Phut5,Gio6,Phut6;
extern signed char Gio7,Phut7,Gio8,Phut8;
//SD_Card
FRESULT res;
//uint8_t x=100;
uint32_t byteswritten,bytesread;
uint8_t wtext[]="Nha";
uint8_t rtext[100]={0};
//che do auto/manual
//uint8_t cnt=0,cnt1=0,cnt2=0;
uint8_t cnt_timer=0;
uint8_t cnt_timer1=0;
//che do u to
uint8_t T1_max=37,T1_min=33,T1_dat=35;
uint8_t H1_max=83,H1_min=77,H1_dat=80;
uint8_t L1_max=50,L1_min=20;
//che do qua the
uint8_t T2_max=32,T2_min=28,T2_dat=30;
uint8_t H2_max=87,H2_min=93,H2_dat=90;
uint8_t L2_max=50,L2_min=20;
uint8_t L,T1,H1,T2,H2;
char set_L1[20],set_L2[20];
extern uint8_t mode;
extern uint8_t cnt1;
extern uint8_t cnt2;
extern uint8_t cnt3;
extern uint8_t cnt4;
extern uint8_t cnt5;
extern uint8_t cnt6;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_I2C1_Init(void);
static void MX_SDIO_SD_Init(void);
static void MX_TIM2_Init(void);
void Error_Handler(void);
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart);
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
void strToUint(void);
void LCD_DK_TaiCho(void);
void LCD_TuDong_QuaThe(void);
void LCD_TuDong_UTo(void);
void Read_SDCard(void);
void Write_SDCard(void);
void read_RTC(void);
/*-------------------------*/
void send_char_temperature(char *st);
void display_LCD(char * return_data, int buffer_uart, int point_start);
void display_st_LCD(char * st);
void display_sensor_LCD(char * st, int T_dat, int H_dat);
void display_pos_LCD(int posx, int posy);
void InitialSoftwareProgram();
void blink_question_mask(int posx, int posy);
void which_setting(void * funcion_call, int posx, int posy);
void mode_programing(int count);
void setting_time(void);
void setting_auto_uto(void);
void setting_auto_quathe(void);
void setting_auto_timming(void);
void setting_manual(void);
void reset_value(void);
#ifdef __cplusplus
}
#endif
#endif /*__main_H */
| c4c4e4e274fc3be626fe82b6a0e3a4827e2415cb | [
"C"
] | 3 | C | MinhDinhTran/stm32f4-esp32 | 4b34a647970bdf99c1c2c6a7da55748dc81d68a8 | 562c74a0e2bcc2e356b1b2d4a8aea82347c960ca |
refs/heads/master | <repo_name>knackebrot/pvr.vuplus<file_sep>/src/enigma2/Admin.h
#pragma once
/*
* Copyright (C) 2005-2015 Team XBMC
* http://xbmc.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 2, 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 XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1335, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include <string>
#include <vector>
#include "libXBMC_pvr.h"
namespace enigma2
{
class Admin
{
public:
void SendPowerstate();
bool GetDeviceInfo();
PVR_ERROR GetDriveSpace(long long *iTotal, long long *iUsed, std::vector<std::string> &locations);
const std::string& GetServerName() const;
private:
unsigned int GetWebIfVersion(std::string versionString);
long long GetKbFromString(const std::string &stringInMbGbTb) const;
std::string m_strEnigmaVersion;
std::string m_strImageVersion;
std::string m_strWebIfVersion;
std::string m_strServerName = "Enigma2";
};
} //namespace enigma2<file_sep>/src/enigma2/Settings.h
#pragma once
#include "utilities/Logger.h"
#include <string>
#include "xbmc_addon_types.h"
class Vu;
namespace enigma2
{
static const std::string DEFAULT_HOST = "127.0.0.1";
static const int DEFAULT_CONNECT_TIMEOUT = 30;
static const int DEFAULT_STREAM_PORT = 8001;
static const int DEFAULT_WEB_PORT = 80;
static const int DEFAULT_UPDATE_INTERVAL = 2;
static const std::string DEFAULT_TSBUFFERPATH = "special://userdata/addon_data/pvr.vuplus";
static const int DEFAULT_NUM_GEN_REPEAT_TIMERS = 1;
enum class Timeshift
: int // same type as addon settings
{
OFF = 0,
ON_PLAYBACK,
ON_PAUSE
};
enum class PrependOutline
: int // same type as addon settings
{
NEVER = 0,
IN_EPG,
IN_RECORDINGS,
ALWAYS
};
class Settings
{
public:
/**
* Singleton getter for the instance
*/
static Settings& GetInstance()
{
static Settings settings;
return settings;
}
void ReadFromAddon();
ADDON_STATUS SetValue(const std::string &settingName, const void *settingValue);
//Connection
const std::string& GetHostname() const { return m_strHostname; }
int GetWebPortNum() const { return m_iPortWeb; }
bool GetUseSecureConnection() const { return m_bUseSecureHTTP; }
const std::string& GetUsername() const {return m_strUsername; }
const std::string& GetPassword() const { return m_strPassword; }
bool GetAutoConfigLiveStreamsEnabled() const { return m_bAutoConfig; }
int GetStreamPortNum() const { return m_iPortStream; }
bool UseSecureConnectionStream() const { return m_bUseSecureHTTPStream; }
bool UseLoginStream() const { return m_bUseLoginStream; }
//General
bool GetUseOnlinePicons() const { return m_bOnlinePicons; }
bool GetUsePiconsEuFormat() const { return m_bUsePiconsEuFormat; }
const std::string& GetIconPath() const { return m_strIconPath; }
int GetUpdateIntervalMins() const { return m_iUpdateInterval; }
//Channel & EPG
bool GetOneGroupOnly() const { return m_bOnlyOneGroup; }
const std::string& GetOneGroupName() const { return m_strOneGroup; }
bool GetZapBeforeChannelSwitch() const { return m_bZap; }
bool GetExtractExtraEpgInfo() const { return m_bExtractExtraEpgInfo; }
bool GetLogMissingGenreMappings() const { return m_bLogMissingGenreMappings; }
//Recordings and Timers
const std::string& GetRecordingPath() const { return m_strRecordingPath; }
bool GetRecordingsFromCurrentLocationOnly() const { return m_bOnlyCurrentLocation; }
bool GetKeepRecordingsFolders() const { return m_bKeepFolders; }
bool GetGenRepeatTimersEnabled() const { return m_bEnableGenRepeatTimers; }
int GetNumGenRepeatTimers() const { return m_iNumGenRepeatTimers; }
bool GetAutoTimersEnabled() const { return m_bEnableAutoTimers; }
bool GetAutoTimerListCleanupEnabled() const { return m_bAutomaticTimerlistCleanup; }
//Timeshift
const Timeshift& GetTimeshift() const { return m_timeshift; }
const std::string& GetTimeshiftBufferPath() const { return m_strTimeshiftBufferPath; }
bool IsTimeshiftBufferPathValid() const;
//Advanced
const PrependOutline& GetPrependOutline() const { return m_prependOutline; }
bool GetDeepStandbyOnAddonExit() const { return m_bSetPowerstate; }
int GetReadTimeoutSecs() const { return m_iReadTimeout; }
int GetStreamReadChunkSizeKb() const { return m_streamReadChunkSize; }
const std::string& GetConnectionURL() const { return m_connectionURL; }
unsigned int GetWebIfVersionAsNum() const { return m_webIfVersion; }
void SetWebIfVersionAsNum(unsigned int value) { m_webIfVersion = value; }
inline unsigned int GenerateWebIfVersionAsNum(unsigned int major, unsigned int minor, unsigned int patch)
{
return (major << 16 | minor << 8 | patch);
};
private:
Settings() = default;
Settings(Settings const &) = delete;
void operator=(Settings const &) = delete;
template <typename T>
ADDON_STATUS SetSetting(const std::string& settingName, const void* settingValue, T& currentValue, ADDON_STATUS returnValueIfChanged)
{
T newValue = *static_cast<const T*>(settingValue);
if (newValue != currentValue)
{
utilities::Logger::Log(utilities::LogLevel::LEVEL_NOTICE, "%s - Changed Setting '%s' from %d to %d", __FUNCTION__, settingName.c_str(), currentValue, newValue);
currentValue = newValue;
return returnValueIfChanged;
}
return ADDON_STATUS_OK;
};
ADDON_STATUS SetStringSetting(const std::string &settingName, const void* settingValue, std::string ¤tValue, ADDON_STATUS returnValueIfChanged);
//Connection
std::string m_strHostname = DEFAULT_HOST;
int m_iPortWeb = DEFAULT_WEB_PORT;
bool m_bUseSecureHTTP = false;
std::string m_strUsername = "";
std::string m_strPassword = "";
bool m_bAutoConfig = false;
int m_iPortStream = DEFAULT_STREAM_PORT;
bool m_bUseSecureHTTPStream = false;
bool m_bUseLoginStream = false;
//General
bool m_bOnlinePicons = true;
bool m_bUsePiconsEuFormat = false;
std::string m_strIconPath = "";
int m_iUpdateInterval = DEFAULT_UPDATE_INTERVAL;
//Channel & EPG
bool m_bOnlyOneGroup = false;
std::string m_strOneGroup = "";
bool m_bZap = false;
bool m_bExtractExtraEpgInfo = true;
bool m_bLogMissingGenreMappings = true;
//Recordings and Timers
std::string m_strRecordingPath = "";
bool m_bOnlyCurrentLocation = false;
bool m_bKeepFolders = false;
bool m_bEnableGenRepeatTimers = true;
int m_iNumGenRepeatTimers = DEFAULT_NUM_GEN_REPEAT_TIMERS;
bool m_bEnableAutoTimers = true;
bool m_bAutomaticTimerlistCleanup = false;
//Timeshift
Timeshift m_timeshift = Timeshift::OFF;
std::string m_strTimeshiftBufferPath = DEFAULT_TSBUFFERPATH;
//Advanced
PrependOutline m_prependOutline = PrependOutline::IN_EPG;
bool m_bSetPowerstate = false;
int m_iReadTimeout = 0;
int m_streamReadChunkSize = 0;
std::string m_connectionURL;
unsigned int m_webIfVersion;
//PVR Props
std::string m_szUserPath = "";
std::string m_szClientPath = "";
};
} //namespace enigma2
<file_sep>/src/enigma2/extract/ShowInfoExtractor.cpp
#include "ShowInfoExtractor.h"
using namespace enigma2;
using namespace enigma2::data;
using namespace enigma2::extract;
ShowInfoExtractor::ShowInfoExtractor()
: IExtractor()
{
episodeSeasonPatterns.emplace_back(
EpisodeSeasonPattern(MASTER_SEASON_EPISODE_PATTERN,
GET_SEASON_PATTERN, GET_EPISODE_PATTERN));
episodeSeasonPatterns.emplace_back(
EpisodeSeasonPattern(MASTER_EPISODE_PATTERN,
GET_EPISODE_PATTERN));
episodeSeasonPatterns.emplace_back(
EpisodeSeasonPattern(MASTER_YEAR_EPISODE_PATTERN,
GET_EPISODE_PATTERN));
episodeSeasonPatterns.emplace_back(
EpisodeSeasonPattern(MASTER_EPISODE_NO_PREFIX_PATTERN,
GET_EPISODE_NO_PREFIX_PATTERN));
yearPatterns.emplace_back(std::regex(GET_YEAR_PATTERN));
yearPatterns.emplace_back(std::regex(GET_YEAR_EPISODE_PATTERN));
}
ShowInfoExtractor::~ShowInfoExtractor(void)
{
}
void ShowInfoExtractor::ExtractFromEntry(BaseEntry &entry)
{
for (const auto& patternSet : episodeSeasonPatterns)
{
std::string masterText = GetMatchedText(entry.GetPlotOutline(), entry.GetPlot(), patternSet.masterRegex);
if (!masterText.empty())
{
if (patternSet.hasSeasonRegex && entry.GetSeasonNumber() == 0)
{
std::string seasonText = GetMatchTextFromString(masterText, patternSet.seasonRegex);
if (!seasonText.empty())
{
entry.SetSeasonNumber(atoi(seasonText.c_str()));
}
}
if (entry.GetEpisodeNumber() == 0)
{
std::string episodeText = GetMatchTextFromString(masterText, patternSet.episodeRegex);
if (!episodeText.empty())
{
entry.SetEpisodeNumber(atoi(episodeText.c_str()));
}
}
}
//Once we have at least an episode number we are done
if (entry.GetEpisodeNumber() != 0)
break;
}
for (const auto& pattern : yearPatterns)
{
std::string yearText = GetMatchedText(entry.GetPlotOutline(), entry.GetPlot(), pattern);
if (!yearText.empty() && entry.GetYear() == 0)
{
entry.SetYear(atoi(yearText.c_str()));
}
if (entry.GetYear() != 0)
break;
}
}<file_sep>/src/enigma2/extract/GenreExtractor.cpp
#include "GenreExtractor.h"
#include "libXBMC_pvr.h"
using namespace enigma2;
using namespace enigma2::data;
using namespace enigma2::extract;
using namespace enigma2::utilities;
GenreExtractor::GenreExtractor()
: IExtractor()
{
for (const auto& genreMapEntry : kodiKeyToGenreMap)
{
kodiGenreToKeyMap.insert({genreMapEntry.second, genreMapEntry.first});
}
genrePattern = std::regex(GENRE_PATTERN);
genreMajorPattern = std::regex(GENRE_MAJOR_PATTERN);
}
GenreExtractor::~GenreExtractor(void)
{
}
void GenreExtractor::ExtractFromEntry(BaseEntry &entry)
{
if (entry.GetGenreType() == 0)
{
const std::string genreText = GetMatchedText(entry.GetPlotOutline(), entry.GetPlot(), genrePattern);
if (!genreText.empty() && genreText != GENRE_RESERVED_IGNORE)
{
int combinedGenreType = GetGenreTypeFromText(genreText, entry.GetTitle());
if (combinedGenreType == EPG_EVENT_CONTENTMASK_UNDEFINED)
{
if (m_settings.GetLogMissingGenreMappings())
Logger::Log(LEVEL_NOTICE, "%s: Could not lookup genre using genre description string instead:'%s'", __FUNCTION__, genreText.c_str());
entry.SetGenreType(EPG_GENRE_USE_STRING);
entry.SetGenreDescription(genreText);
}
else
{
entry.SetGenreType(GetGenreTypeFromCombined(combinedGenreType));
entry.SetGenreSubType(GetGenreSubTypeFromCombined(combinedGenreType));
}
}
}
}
int GenreExtractor::GetGenreTypeFromCombined(int combinedGenreType)
{
return combinedGenreType & 0xF0;
}
int GenreExtractor::GetGenreSubTypeFromCombined(int combinedGenreType)
{
return combinedGenreType & 0x0F;
}
int GenreExtractor::GetGenreTypeFromText(const std::string &genreText, const std::string &showName)
{
int genreType = LookupGenreValueInMaps(genreText);
if (genreType == EPG_EVENT_CONTENTMASK_UNDEFINED)
{
if (m_settings.GetLogMissingGenreMappings())
Logger::Log(LEVEL_NOTICE, "%s: Tried to find genre text but no value: '%s', show - '%s'", __FUNCTION__, genreText.c_str(), showName.c_str());
std::string genreMajorText = GetMatchTextFromString(genreText, genreMajorPattern);
if (!genreMajorText.empty())
{
genreType = LookupGenreValueInMaps(genreMajorText);
if (genreType == EPG_EVENT_CONTENTMASK_UNDEFINED && m_settings.GetLogMissingGenreMappings())
Logger::Log(LEVEL_NOTICE, "%s: Tried to find major genre text but no value: '%s', show - '%s'", __FUNCTION__, genreMajorText.c_str(), showName.c_str());
}
}
return genreType;
}
int GenreExtractor::LookupGenreValueInMaps(const std::string &genreText)
{
int genreType = EPG_EVENT_CONTENTMASK_UNDEFINED;
auto genreMapSearch = genreMap.find(genreText);
if (genreMapSearch != genreMap.end())
{
genreType = genreMapSearch->second;
}
else
{
auto kodiGenreMapSearch = kodiGenreToKeyMap.find(genreText);
if (kodiGenreMapSearch != kodiGenreToKeyMap.end())
{
genreType = kodiGenreMapSearch->second;
}
}
return genreType;
}<file_sep>/src/enigma2/Settings.cpp
#include "Settings.h"
#include "../client.h"
#include "utilities/LocalizedString.h"
#include "p8-platform/util/StringUtils.h"
using namespace ADDON;
using namespace enigma2;
using namespace enigma2::utilities;
/***************************************************************************
* PVR settings
**************************************************************************/
void Settings::ReadFromAddon()
{
char buffer[1024];
buffer[0] = 0;
//Connection
if (XBMC->GetSetting("host", buffer))
m_strHostname = buffer;
else
m_strHostname = DEFAULT_HOST;
buffer[0] = 0;
if (!XBMC->GetSetting("webport", &m_iPortWeb))
m_iPortWeb = DEFAULT_WEB_PORT;
if (!XBMC->GetSetting("use_secure", &m_bUseSecureHTTP))
m_bUseSecureHTTP = false;
if (XBMC->GetSetting("user", buffer))
m_strUsername = buffer;
else
m_strUsername = "";
buffer[0] = 0;
if (XBMC->GetSetting("pass", buffer))
m_strPassword = buffer;
else
m_strPassword = "";
buffer[0] = 0;
if (!XBMC->GetSetting("autoconfig", &m_bAutoConfig))
m_bAutoConfig = false;
if (!XBMC->GetSetting("streamport", &m_iPortStream))
m_iPortStream = DEFAULT_STREAM_PORT;
if (!XBMC->GetSetting("use_secure_stream", &m_bUseSecureHTTPStream))
m_bUseSecureHTTPStream = false;
if (!XBMC->GetSetting("use_login_stream", &m_bUseLoginStream))
m_bUseLoginStream = false;
//General
if (!XBMC->GetSetting("onlinepicons", &m_bOnlinePicons))
m_bOnlinePicons = true;
if (!XBMC->GetSetting("usepiconseuformat", &m_bUsePiconsEuFormat))
m_bUsePiconsEuFormat = false;
if (XBMC->GetSetting("iconpath", buffer))
m_strIconPath = buffer;
else
m_strIconPath = "";
buffer[0] = 0;
if (!XBMC->GetSetting("updateint", &m_iUpdateInterval))
m_iUpdateInterval = DEFAULT_UPDATE_INTERVAL;
//Channels & EPG
if (!XBMC->GetSetting("onlyonegroup", &m_bOnlyOneGroup))
m_bOnlyOneGroup = false;
if (XBMC->GetSetting("onegroup", buffer))
m_strOneGroup = buffer;
else
m_strOneGroup = "";
buffer[0] = 0;
if (!XBMC->GetSetting("zap", &m_bZap))
m_bZap = false;
if (!XBMC->GetSetting("extracteventinfo", &m_bExtractExtraEpgInfo))
m_bExtractExtraEpgInfo = false;
if (!XBMC->GetSetting("logmissinggenremapping", &m_bLogMissingGenreMappings))
m_bLogMissingGenreMappings = false;
//Recording and Timers
if (XBMC->GetSetting("recordingpath", buffer))
m_strRecordingPath = buffer;
else
m_strRecordingPath = "";
buffer[0] = 0;
if (!XBMC->GetSetting("onlycurrent", &m_bOnlyCurrentLocation))
m_bOnlyCurrentLocation = false;
if (!XBMC->GetSetting("keepfolders", &m_bKeepFolders))
m_bKeepFolders = false;
if (!XBMC->GetSetting("enablegenrepeattimers", &m_bEnableGenRepeatTimers))
m_bEnableGenRepeatTimers = true;
if (!XBMC->GetSetting("numgenrepeattimers", &m_iNumGenRepeatTimers))
m_iNumGenRepeatTimers = DEFAULT_NUM_GEN_REPEAT_TIMERS;
if (!XBMC->GetSetting("enableautotimers", &m_bEnableAutoTimers))
m_bEnableAutoTimers = true;
if (!XBMC->GetSetting("timerlistcleanup", &m_bAutomaticTimerlistCleanup))
m_bAutomaticTimerlistCleanup = false;
//Timeshift
if (!XBMC->GetSetting("enabletimeshift", &m_timeshift))
m_timeshift = Timeshift::OFF;
if (XBMC->GetSetting("timeshiftbufferpath", buffer) && !std::string(buffer).empty())
m_strTimeshiftBufferPath = buffer;
else
m_strTimeshiftBufferPath = DEFAULT_TSBUFFERPATH;
buffer[0] = 0;
//Advanced
if (!XBMC->GetSetting("prependoutline", &m_prependOutline))
m_prependOutline = PrependOutline::IN_EPG;
if (!XBMC->GetSetting("setpowerstate", &m_bSetPowerstate))
m_bSetPowerstate = false;
if (!XBMC->GetSetting("readtimeout", &m_iReadTimeout))
m_iReadTimeout = 0;
if (!XBMC->GetSetting("streamreadchunksize", &m_streamReadChunkSize))
m_streamReadChunkSize = 0;
// Now that we've read all the settings construct the connection URL
// simply add user@pass in front of the URL if username/password is set
if ((m_strUsername.length() > 0) && (m_strPassword.length() > 0))
m_connectionURL = StringUtils::Format("%s:%s@", m_strUsername.c_str(), m_strPassword.c_str());
if (!m_bUseSecureHTTP)
m_connectionURL = StringUtils::Format("http://%s%s:%u/", m_connectionURL.c_str(), m_strHostname.c_str(), m_iPortWeb);
else
m_connectionURL = StringUtils::Format("https://%s%s:%u/", m_connectionURL.c_str(), m_strHostname.c_str(), m_iPortWeb);
}
ADDON_STATUS Settings::SetValue(const std::string &settingName, const void *settingValue)
{
//Connection
if (settingName == "host")
return SetStringSetting(settingName, settingValue, m_strHostname, ADDON_STATUS_NEED_RESTART);
else if (settingName == "webport")
return SetSetting<int>(settingName, settingValue, m_iPortWeb, ADDON_STATUS_NEED_RESTART);
else if (settingName == "use_secure")
return SetSetting<bool>(settingName, settingValue, m_bUseSecureHTTP, ADDON_STATUS_NEED_RESTART);
else if (settingName == "user")
return SetStringSetting(settingName, settingValue, m_strUsername, ADDON_STATUS_OK);
else if (settingName == "pass")
return SetStringSetting(settingName, settingValue, m_strPassword, ADDON_STATUS_OK);
else if (settingName == "autoconfig")
return SetSetting<bool>(settingName, settingValue, m_bAutoConfig, ADDON_STATUS_OK);
else if (settingName == "streamport")
return SetSetting<int>(settingName, settingValue, m_iPortStream, ADDON_STATUS_NEED_RESTART);
else if (settingName == "use_secure_stream")
return SetSetting<bool>(settingName, settingValue, m_bUseSecureHTTPStream, ADDON_STATUS_NEED_RESTART);
else if (settingName == "use_login_stream")
return SetSetting<bool>(settingName, settingValue, m_bUseLoginStream, ADDON_STATUS_NEED_RESTART);
//General
else if (settingName == "onlinepicons")
return SetSetting<bool>(settingName, settingValue, m_bOnlinePicons, ADDON_STATUS_NEED_RESTART);
else if (settingName == "usepiconseuformat")
return SetSetting<bool>(settingName, settingValue, m_bUsePiconsEuFormat, ADDON_STATUS_NEED_RESTART);
else if (settingName == "iconpath")
return SetStringSetting(settingName, settingValue, m_strIconPath, ADDON_STATUS_NEED_RESTART);
else if (settingName == "updateint")
return SetSetting<int>(settingName, settingValue, m_iUpdateInterval, ADDON_STATUS_OK);
//Channels & EPG
else if (settingName == "onlyonegroup")
return SetSetting<bool>(settingName, settingValue, m_bOnlyOneGroup, ADDON_STATUS_NEED_RESTART);
else if (settingName == "onegroup")
return SetStringSetting(settingName, settingValue, m_strOneGroup, ADDON_STATUS_NEED_RESTART);
else if (settingName == "zap")
return SetSetting<bool>(settingName, settingValue, m_bZap, ADDON_STATUS_OK);
else if (settingName == "extracteventinfo")
return SetSetting<bool>(settingName, settingValue, m_bExtractExtraEpgInfo, ADDON_STATUS_NEED_RESTART);
else if (settingName == "logmissinggenremapping")
return SetSetting<bool>(settingName, settingValue, m_bLogMissingGenreMappings, ADDON_STATUS_OK);
//Recordings and Timers
else if (settingName == "recordingpath")
return SetStringSetting(settingName, settingValue, m_strRecordingPath, ADDON_STATUS_NEED_RESTART);
else if (settingName == "onlycurrent")
return SetSetting<bool>(settingName, settingValue, m_bOnlyCurrentLocation, ADDON_STATUS_OK);
else if (settingName == "keepfolders")
return SetSetting<bool>(settingName, settingValue, m_bKeepFolders, ADDON_STATUS_OK);
else if (settingName == "enablegenrepeattimers")
return SetSetting<bool>(settingName, settingValue, m_bEnableAutoTimers, ADDON_STATUS_OK);
else if (settingName == "numgenrepeattimers")
return SetSetting<int>(settingName, settingValue, m_iNumGenRepeatTimers, ADDON_STATUS_OK);
else if (settingName == "enableautotimers")
return SetSetting<bool>(settingName, settingValue, m_bEnableAutoTimers, ADDON_STATUS_NEED_RESTART);
else if (settingName == "timerlistcleanup")
return SetSetting<bool>(settingName, settingValue, m_bAutomaticTimerlistCleanup, ADDON_STATUS_OK);
//Timeshift
else if (settingName == "enabletimeshift")
return SetSetting<Timeshift>(settingName, settingValue, m_timeshift, ADDON_STATUS_NEED_RESTART);
else if (settingName == "timeshiftbufferpath")
return SetStringSetting(settingName, settingValue, m_strTimeshiftBufferPath, ADDON_STATUS_OK);
//Advanced
else if (settingName == "prependoutline")
return SetSetting<PrependOutline>(settingName, settingValue, m_prependOutline, ADDON_STATUS_NEED_RESTART);
else if (settingName == "setpowerstate")
return SetSetting<bool>(settingName, settingValue, m_bSetPowerstate, ADDON_STATUS_OK);
else if (settingName == "readtimeout")
return SetSetting<int>(settingName, settingValue, m_iReadTimeout, ADDON_STATUS_NEED_RESTART);
else if (settingName == "streamreadchunksize")
return SetSetting<int>(settingName, settingValue, m_streamReadChunkSize, ADDON_STATUS_OK);
return ADDON_STATUS_OK;
}
ADDON_STATUS Settings::SetStringSetting(const std::string &settingName, const void* settingValue, std::string ¤tValue, ADDON_STATUS returnValueIfChanged)
{
const std::string strSettingValue = static_cast<const char*>(settingValue);
if (strSettingValue != currentValue)
{
Logger::Log(LEVEL_INFO, "%s - Changed Setting '%s' from %s to %s", __FUNCTION__, settingName.c_str(), currentValue.c_str(), strSettingValue.c_str());
currentValue = strSettingValue;
return returnValueIfChanged;
}
return ADDON_STATUS_OK;
}
bool Settings::IsTimeshiftBufferPathValid() const
{
return XBMC->DirectoryExists(m_strTimeshiftBufferPath.c_str());
}
<file_sep>/README.md
[](https://travis-ci.org/kodi-pvr/pvr.vuplus)
[](https://scan.coverity.com/projects/5120)
Enigma2 is a open source TV-receiver/DVR platform which Linux-based firmware (OS images) can be loaded onto many Linux-based set-top boxes (satellite, terrestrial, cable or a combination of these) from different manufacturers.
This addon leverage the OpenWebIf project: (https://github.com/E2OpenPlugins/e2openplugin-OpenWebif)
# Enigma2 PVR
VuPlus PVR client addon for [Kodi] (https://kodi.tv)
## Build instructions
### Linux
1. `git clone https://github.com/xbmc/xbmc.git`
2. `git clone https://github.com/kodi-pvr/pvr.vuplus.git`
3. `cd pvr.vuplus && mkdir build && cd build`
4. `cmake -DADDONS_TO_BUILD=pvr.vuplus -DADDON_SRC_PREFIX=../.. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=../../xbmc/addons -DPACKAGE_ZIP=1 ../../xbmc/cmake/addons`
5. `make`
##### Useful links
* [Kodi's PVR user support] (https://forum.kodi.tv/forumdisplay.php?fid=167)
* [Kodi's PVR development support] (https://forum.kodi.tv/forumdisplay.php?fid=136)
## Configuring the addon
### Connection
Within this tab the connection options need to be configured before it can be successfully enabled.
* **Enigma2 hostname or IP address**: The IP address or hostname of your enigma2 based settop box.
* **Web interface port**: The port used to connect to the web interface
* **Use secure HTTP (https)**: Use https to connect to the web interface
* **Username**: If the webinterface of the settop box is protected with a username / password combination this needs to be set in this option.
* **Password**: If the webinterface of the settop box is protected with a username / password combination this needs to be set in this option.
* **Enable automatic configuration for live streams**: When enabled the stream URL will be read from an M3U file. When disabled it is constructed based on the filename.
* **Streaming port**: This option defines the streaming port the settop box uses to stream live tv. The default is 8001 which should be fine if the user did not define a custom port within the webinterface.
Webinterface Port: This option defines the port that should be used to access the webinterface of the settop box.
### General
Within this tab general options are configured.
* **Fetch picons from web interface**: Fetch the picons straight from the Enigma 2 STB
* **Use picons.eu file formate**: Assume all picons files fetched from the STB start with `1_1_1_` and end with `_0_0_0`
* **Icon path**: In order to have Kodi display channel logos you have to copy the picons from your settop box onto your OpenELEC machine. You then need to specify this path in this property.
* **Update interval**: As the settop box can also be used to modify timers, delete recordings etc. and the settop box does not notify the Kodi installation, the addon needs to regularly check for updates (new channels, new/changed/deletes timers, deleted recordings, etc.) This property defines how often the addon checks for updates.
### Channels & EPG
Within this tab options that refer to channel and EPG data can be set.
* **Fetch only one TV bouquet**: If this option is set than only the channels that are in one specified TV bouquet will be loaded, instead of fetching all available channels in all available bouquets.
* **TV bouquet**: If the previous option has been enabled you need to specify the TV bouquet to be fetched from the settop box. Please not that this is the bouquet-name as shown on the settop box (i.e. "Favourites (TV)"). This setting is case-sensitive.
* **Zap before channelswitch (i.e. for Single Tuner boxes)**: When using the addon with a single tuner box it may be necessary that the addon needs to be able to zap to another channel on the settop box. If this option is enabled each channel switch in Kodi will also result in a channel switch on the settop box. Please note that "allow channel switching" needs to be enabled in the webinterface on the settop box.
* **Extract genre, season and episode info where possible**: Have kodi check the description fields in the EPG data and attempt to extrac
t genre, season and episode info where possible. Currently supports OTA, OpenTV and Rytec XMLTV EPG data for UK and Ireland channels. If y
ou would like to support other formats please raise an issue at the github project https://github.com/kodi-pvr/pvr.vuplus. Genre support s
pecificially requires the use of Rytec XMLTV Epg data. There is a CPU overhead to enabling this setting. After changing this option you wi
ll need to clear the EPG cache `Settings->PVR & Live TV->Guide->Clear cache` for it to take effect.
* **Log missing genre mappings**: If you would like missing genre mappings to be logged so you can report them enable this option. Note, any genres found that don't have a mapping will still be extracted and sent to Kodi as strings. Currently genres are extracted by looking for text between square brackets, e.g. [TV Drama]
### Recordings & Timers
* **Recording folder on receiver**: Per default the addon does not specify the recording folder in newly created timers, so the default set in the settop box will be used. If you want to specify a different folder (i.e. because you want all recordings scheduled via Kodi to be stored in a separate folder), then you need to set this option.
* **Use only the DVB boxes' current recording path**: If this option is not set the addon will fetch all available recordings from all configured paths from the STB. If this option is set then it will only list recordings that are stored within the "current recording path" on the settop box.
* **Keep folder structure for records**: If enabled do not specify a recording folder, when disabled (defaut), check if the recording is in it's own folder or in the root of the recording path
* **Enable generate repeat timers**: Repeat timers will display as timer rules. Enabling this will make Kodi generate regular timers to match the repeat timer rules so the UI can show what's scheduled and currently recording for each repeat timer.
* **Number of repeat timers to generate**: The number of Kodi PVR timers to generate.
* **Enable autotimers**: When this is enabled there are some settings required on the STB to enable linking of AutoTimers (Timer Rules) to Timers in the Kodi UI. On the STB enable the following options (note that this feature supports OpenWebIf 1.3.x and higher):
1. Hit `Menu` on the remote and go to `Timers->AutoTimers`
2. Hit `Menu` again and then select `6 Setup`
3. Set the following to option to `yes`
* `Include "AutoTimer" in tags`
* `Include AutoTimer name in tags`
* **Automatic timerlist cleanup**: If this option is set then the addon will send the command to delete completed timers from the STB after each update interval.
### Timeshift
* **Enable timeshift**: What timeshift option do you want. `Disabled`, only timeshift `On pause` or timeshift `On Playback`.
* **Timeshift buffer path**: The path used to store the timeshoft buffer. The default is the addon data folder in userdata
### Advanced
Within this tab more uncommon and advanced options can be configured.
* **Put outline (e.g. sub-title) before plot**: By default plot outline (short description on Enigma2) is not displayed in the UI. Can be
displayed in EPG, Recordings or both. After changing this option you will need to clear the EPG cache `Settings->PVR & Live TV->Guide->C
lear cache` for it to take effect.
* **Send deep standby command**: If this option is set then the addon will send the DeepStandby-Command to the settop box when Kodi will be closed (or the addon will be deactivated), causing the settop box to shutdown into DeepStandby.
* **Custom live TV timeout (0 to use default)**: The timemout to use when trying to read live streams
* **Stream read chunk size**: The chunk size used by Kodi for streams. Default 0 to leave it to Kodi to decide.<file_sep>/src/enigma2/extract/EpgEntryExtractor.cpp
#include "EpgEntryExtractor.h"
#include "GenreExtractor.h"
#include "ShowInfoExtractor.h"
using namespace enigma2;
using namespace enigma2::data;
using namespace enigma2::extract;
EpgEntryExtractor::EpgEntryExtractor()
: IExtractor()
{
m_extractors.emplace_back(new GenreExtractor());
m_extractors.emplace_back(new ShowInfoExtractor());
}
EpgEntryExtractor::~EpgEntryExtractor(void)
{
}
void EpgEntryExtractor::ExtractFromEntry(BaseEntry &entry)
{
for (auto& extractor : m_extractors)
{
extractor->ExtractFromEntry(entry);
}
}<file_sep>/src/enigma2/extract/EpgEntryExtractor.h
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "IExtractor.h"
namespace enigma2
{
namespace extract
{
class EpgEntryExtractor
: public IExtractor
{
public:
EpgEntryExtractor();
~EpgEntryExtractor(void);
void ExtractFromEntry(enigma2::data::BaseEntry &entry);
private:
std::vector<std::unique_ptr<IExtractor>> m_extractors;
};
} //namespace extract
} //namespace enigma2<file_sep>/src/enigma2/extract/GenreExtractor.h
#pragma once
#include "IExtractor.h"
#include <map>
#include <regex>
#include <string>
namespace enigma2
{
namespace extract
{
static const std::string GENRE_PATTERN = "^\\[([a-zA-Z /]{3}[a-zA-Z ./]+)\\][^]*";
static const std::string GENRE_MAJOR_PATTERN = "^([a-zA-Z /]{3,})\\.?.*";
static const std::string GENRE_RESERVED_IGNORE = "reserved";
class GenreExtractor
: public IExtractor
{
public:
GenreExtractor();
~GenreExtractor();
void ExtractFromEntry(enigma2::data::BaseEntry &entry);
private:
static int GetGenreTypeFromCombined(int combinedGenreType);
static int GetGenreSubTypeFromCombined(int combinedGenreType);
int GetGenreTypeFromText(const std::string &genreText, const std::string &showName);
int LookupGenreValueInMaps(const std::string &genreText);
std::regex genrePattern;
std::regex genreMajorPattern;
std::map<std::string, int> kodiGenreToKeyMap;
const std::map<int, std::string> kodiKeyToGenreMap
{
{0x00, "Undefined"},
//MOVIE/DRAMA
{0x10, "Movie/Drama"},
{0x11, "Detective/Thriller"},
{0x12, "Adventure/Western/War"},
{0x13, "Science Fiction/Fantasy/Horror"},
{0x14, "Comedy"},
{0x15, "Soap/Melodrama/Folkloric"},
{0x16, "Romance"},
{0x17, "Serious/Classical/Religious/Historical Movie/Drama"},
{0x18, "Adult Movie/Drama"},
//NEWS/CURRENT AFFAIRS
{0x20, "News/Current Affairs"},
{0x21, "News/Weather Report"},
{0x22, "News Magazine"},
{0x23, "Documentary"},
{0x24, "Discussion/Interview/Debate"},
//SHOW
{0x30, "Show/Game Show"},
{0x31, "Game Show/Quiz/Contest"},
{0x32, "Variety Show"},
{0x33, "Talk Show"},
//SPORTS
{0x40, "Sports"},
{0x41, "Special Event"},
{0x42, "Sport Magazine"},
{0x43, "Football"},
{0x44, "Tennis/Squash"},
{0x45, "Team Sports"},
{0x46, "Athletics"},
{0x47, "Motor Sport"},
{0x48, "Water Sport"},
{0x49, "Winter Sports"},
{0x4A, "Equestrian"},
{0x4B, "Martial Sports"},
//CHILDREN/YOUTH
{0x50, "Children's/Youth Programmes"},
{0x51, "Pre-school Children's Programmes"},
{0x52, "Entertainment Programmes for 6 to 14"},
{0x53, "Entertainment Programmes for 10 to 16"},
{0x54, "Informational/Educational/School Programme"},
{0x55, "Cartoons/Puppets"},
//MUSIC/BALLET/DANCE
{0x60, "Music/Ballet/Dance"},
{0x61, "Rock/Pop"},
{0x62, "Serious/Classical Music"},
{0x63, "Folk/Traditional Music"},
{0x64, "Musical/Opera"},
{0x65, "Ballet"},
//ARTS/CULTURE
{0x70, "Arts/Culture"},
{0x71, "Performing Arts"},
{0x72, "Fine Arts"},
{0x73, "Religion"},
{0x74, "Popular Culture/Traditional Arts"},
{0x75, "Literature"},
{0x76, "Film/Cinema"},
{0x77, "Experimental Film/Video"},
{0x78, "Broadcasting/Press"},
{0x79, "New Media"},
{0x7A, "Arts/Culture Magazines"},
{0x7B, "Fashion"},
//SOCIAL/POLITICAL/ECONOMICS
{0x80, "Social/Political/Economics"},
{0x81, "Magazines/Reports/Documentary"},
{0x82, "Economics/Social Advisory"},
{0x83, "Remarkable People"},
//EDUCATIONAL/SCIENCE
{0x90, "Education/Science/Factual"},
{0x91, "Nature/Animals/Environment"},
{0x92, "Technology/Natural Sciences"},
{0x93, "Medicine/Physiology/Psychology"},
{0x94, "Foreign Countries/Expeditions"},
{0x95, "Social/Spiritual Sciences"},
{0x96, "Further Education"},
{0x97, "Languages"},
//LEISURE/HOBBIES
{0xA0, "Leisure/Hobbies"},
{0xA1, "Tourism/Travel"},
{0xA2, "Handicraft"},
{0xA3, "Motoring"},
{0xA4, "Fitness & Health"},
{0xA5, "Cooking"},
{0xA6, "Advertisement/Shopping"},
{0xA7, "Gardening"},
//SPECIAL
{0xB0, "Special Characteristics"},
{0xB1, "Original Language"},
{0xB2, "Black & White"},
{0xB3, "Unpublished"},
{0xB4, "Live Broadcast"},
//USERDEFINED
{0xF0, "Drama"},
{0xF1, "Detective/Thriller"},
{0xF2, "Adventure/Western/War"},
{0xF3, "Science Fiction/Fantasy/Horror"},
//---- below currently ignored by XBMC see http://trac.xbmc.org/ticket/13627
{0xF4, "Comedy"},
{0xF5, "Soap/Melodrama/Folkloric"},
{0xF6, "Romance"},
{0xF7, "Serious/ClassicalReligion/Historical"},
{0xF8, "Adult"}
};
const std::map<std::string, int> genreMap
{
//MOVIE/DRAMA
{"General Movie/Drama", 0x10},
{"Movie", 0x10},
{"Film", 0x10},
{"Animated Movie/Drama", 0x10},
{"Thriller", 0x11},
{"Detective/Thriller", 0x11},
{"Action", 0x12},
{"Adventure", 0x12},
{"Adventure/War", 0x12},
{"Western", 0x12},
{"Gangster", 0x12},
{"Fantasy", 0x13},
{"Science Fiction", 0x13},
{"Family", 0x14},
{"Sitcom", 0x14},
{"Comedy", 0x14},
{"TV Drama. Comedy", 0x14},
{"Drama", 0x15},
{"Soap/Melodrama/Folkloric", 0x15},
{"TV Drama. Melodrama", 0x15},
{"TV Drama. Factual", 0x15},
{"TV Drama", 0x15},
{"TV Drama. Crime", 0x15},
{"TV Drama. Period", 0x15},
{"Romance", 0x16},
{"Medical Drama", 0x15},
{"Crime drama", 0x17},
{"Historical/Period Drama", 0x17},
{"Police/Crime Drama", 0x17},
//NEWS/CURRENT AFFAIRS
{"News", 0x20},
{"General News/Current Affairs", 0x20},
{"Documentary", 0x23},
{"Documentary. News", 0x23},
{"Discussion. News", 0x24},
//SHOW
{"Series", 0x30},
{"Show", 0x30},
{"Vets/Pets", 0x30},
{"Wildlife", 0x30},
{"Property", 0x30},
{"General Show/Game Show", 0x31},
{"Game Show", 0x31},
{"Challenge/Reality Show", 0x31},
{"Show. Variety Show", 0x32},
{"Variety Show", 0x32},
{"Entertainment", 0x32},
{"Miscellaneous", 0x32},
{"Talk Show", 0x33},
{"Show. Talk Show", 0x33},
//SPORTS
{"Sport", 0x40},
{"Live/Sport", 0x40},
{"General Sports", 0x40},
{"Football. Sports", 0x43},
{"Martial Sports", 0x4B},
{"Martial Sports. Sports", 0x4B},
{"Wrestling", 0x4B},
//CHILDREN/YOUTH
{"Children", 0x50},
{"Educational/Schools Programmes", 0x50},
{"Animation", 0x55},
{"Cartoons/Puppets", 0x55},
//MUSIC/BALLET/DANCE
{"Music", 0x60},
{"General Music/Ballet/Dance", 0x60},
{"Music. Folk", 0x63},
{"Musical", 0x64},
//ARTS/CULTURE
{"General Arts/Culture", 0x70},
{"Arts/Culture", 0x70},
{"Arts/Culture. Fine Arts", 0x72},
{"Religion", 0x73},
//SOCIAL/POLITICAL/ECONOMICS
{"Social/Political", 0x80},
{"Social/Political. Famous People", 0x83},
//EDUCATIONAL/SCIENCE
{"Education", 0x90},
{"Educational", 0x90},
{"History", 0x90},
{"Factual", 0x90},
{"General Education/Science/Factual Topics", 0x90},
{"Science", 0x90},
{"Educational. Nature", 0x91},
{"Environment", 0x91},
{"Technology", 0x92},
{"Computers/Internet/Gaming", 0x92},
//LEISURE/HOBBIES
{"Leisure", 0xA0},
{"Leisure. Lifestyle", 0xA0},
{"Travel", 0xA1},
{"Health", 0xA4},
{"Leisure. Health", 0xA4},
{"Medicine/Health", 0xA4},
{"Cookery", 0xA5},
{"Leisure. Cooking", 0xA5},
{"Leisure. Shopping", 0xA6},
{"Advertisement/Shopping", 0xA6},
{"Consumer", 0xA6},
//SPECIAL
//USERDEFINED
{"Factual Crime", 0xF1},
};
/*
Useful reference to Genres uses by Kodi PVR
EPG_EVENT_CONTENTMASK_UNDEFINED 0x00
EPG_EVENT_CONTENTMASK_MOVIEDRAMA 0x10
EPG_EVENT_CONTENTMASK_NEWSCURRENTAFFAIRS 0x20
EPG_EVENT_CONTENTMASK_SHOW 0x30
EPG_EVENT_CONTENTMASK_SPORTS 0x40
EPG_EVENT_CONTENTMASK_CHILDRENYOUTH 0x50
EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE 0x60
EPG_EVENT_CONTENTMASK_ARTSCULTURE 0x70
EPG_EVENT_CONTENTMASK_SOCIALPOLITICALECONOMICS 0x80
EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE 0x90
EPG_EVENT_CONTENTMASK_LEISUREHOBBIES 0xA0
EPG_EVENT_CONTENTMASK_SPECIAL 0xB0
EPG_EVENT_CONTENTMASK_USERDEFINED 0xF0
EPG_GENRE_USE_STRING 0x100
EPG_STRING_TOKEN_SEPARATOR ","
*/
};
} //namespace extract
} //namespace vuplus | d048840721c80558c1838f6c4aba3bf60054b08a | [
"Markdown",
"C++"
] | 9 | C++ | knackebrot/pvr.vuplus | 60aa65cf1d003efa08d53cb80d2aa5dbc4a4805e | d5d675a18a63b16398d2033c5782f71758e606cc |
refs/heads/main | <repo_name>denisignatoff/case_0006<file_sep>/js/main.js
// burder-menu
jQuery('.menuicon').on('click', function() {
jQuery(this).toggleClass('active')
jQuery('.header__contacts').toggleClass('active')
})
// phone-mask
jQuery('.form-inv__num').mask('+7 (999) 999-99-99')
// popup
function openPopup() {
jQuery('.popup__wrapper').css('display', 'flex')
jQuery('body').css('overflow', 'hidden')
}
function closePopup() {
jQuery('.popup__wrapper').css('display', 'none')
jQuery('body').css('overflow', 'auto')
}
jQuery('.open-popup').on('click', openPopup)
jQuery('.popup__close').on('click', closePopup)
jQuery('.popup__wrapper').on('click', function(e) {
if (e.target.classList.contains('popup__wrapper')) closePopup()
}) | ddbbc495bb76bd25e25d48d1e738b2662ed27d08 | [
"JavaScript"
] | 1 | JavaScript | denisignatoff/case_0006 | b30d69278024fb73a785ab0d478c9540d0604448 | 5ef4df7d70cd19691ac92bbfa69a6fc919ccf35d |
refs/heads/master | <file_sep>import {Avatar} from '@material-ui/core';
import { ChatOutlined, SendOutlined, ShareOutlined, ThumbUpAltOutlined } from '@material-ui/icons';
import React, {forwardRef} from 'react';
import InputOptions from './InputOptions';
import './Post.css';
const tempPost = ({name, description, message, photoUrl}, ref) => {
return <div ref = {ref} className="post">
<div className="post__header">
<Avatar src={photoUrl}> {name[0]} </Avatar>
<div className="post__info">
<h2>{name}</h2>
<p>{description}</p>
</div>
</div>
<div className="post__body">
{message}
</div>
<div className="post__buttons">
<InputOptions Icon={ThumbUpAltOutlined} title="Like" color="gray"></InputOptions>
<InputOptions Icon={ChatOutlined} title="Comment" color="gray"></InputOptions>
<InputOptions Icon={ShareOutlined} title="Share" color="gray"></InputOptions>
<InputOptions Icon={SendOutlined} title="Send" color="gray"></InputOptions>
</div>
</div>
}
const Post = forwardRef(tempPost);
export default Post
| c152cf19638f35aff2f82b5f1fd764a683ddee4b | [
"JavaScript"
] | 1 | JavaScript | aktiwari2287/linkedin-clone-anand | 6cc220a342f78e76cec12e1ac04e39188a09b74b | 5e0fc76daf65a279653796d7bdbb7596f872d2b3 |
refs/heads/master | <repo_name>d8815460/angelhack2017<file_sep>/tjwave-1/humix-conversation-module/config.js
module.exports = {
lang: 'cht', // 'en', 'cht' or 'chs'
'stt-engine': 'watson', // 'watson' or 'google',
'tts-engine': 'itri', // 'watson' or 'itri' or 'iflytek'
stt: {
watson: {
username: '5adba33a-c30c-41e9-8815-e9d8ce5d1788',
passwd: '<PASSWORD>'
},
google: {
username: '<EMAIL>',
passwd: '<PASSWORD>',
googleCredentialFile: 'client_secret_1054683840548-9bsup7sb2qrcrqr7gpket80kmabn417b.apps.googleusercontent.com.json', //the location of your google auth credential file.
googleProjectName: 'TOUCH', //the project name which create your credential file.
googleLan: 'cmn-Hant-TW', // en-Us or cmn-Hant-TW
}
},
tts: {
watson: {
username: '73be0fb1-2b24-4271-92df-715927358835',
passwd: '<PASSWORD>'
},
iflytek: {
appid: '<app_id>'
},
itri: {
username: 'chugo1014',
passwd: '<PASSWORD>',
speaker: 'TW_LIT_AKoan',
}
}
};
<file_sep>/linebot-server/server/conversation.js
const mqtt = require('mqtt')
const {
type, organizationId, deviceType, deviceId, username, password
} = require('../configs.js').mqtt
const clientId = [type, organizationId, deviceType, deviceId].join(':')
const iot_client = mqtt.connect('mqtt://'+organizationId+'.messaging.internetofthings.ibmcloud.com:1883', {
"clientId" : clientId,
"keepalive" : 30,
"username" : username,
"password" : <PASSWORD>
})
iot_client.on('connect', () => {
console.log('Client connected to IBM IoT Cloud.')
iot_client.subscribe('iot-2/cmd/+/fmt/json', (err, granted) => {
console.log('subscribed command, granted: '+ JSON.stringify(granted))
})
iot_client.publish('iot-2/evt/init/fmt/string', '{"text": "connected"}')
})
module.exports = iot_client<file_sep>/messenger-server/configs.js
module.exports = {
WEBHOOK:'/webhook',
VERIFY_TOKEN: '12345',
ACCESS_TOKEN: '<KEY>',//粉絲專頁存取權杖
CONVERSATION_URL: 'https://touch-bot-nodered.mybluemix.net/message',
SIMILARITY_URL: 'https://touch-bot-nodered.mybluemix.net/similarity'
} <file_sep>/linebot-server/server/linebot_alt.js
const LINEBot = require('line-messaging')
const http = require('http')
const conversation = require('./conversation')
const { CHANNEL_ID, CHANNEL_SECRET, CHANNEL_ACCESS_TOKEN, WEBHOOK } = require('../configs').linebot
const { MESSAGE } = LINEBot.Events
module.exports = app => {
const server = http.Server(app)
const bot = linebot(server)
app.use(bot.webhook(WEBHOOK));
const bot = LINEBot.create({
channelID: CHANNEL_ID,
channelSecret: CHANNEL_SECRET,
channelToken: CHANNEL_ACCESS_TOKEN
}, server)
bot.on( MESSAGE, (replyToken, message) => {
console.log(message)
})
return server
}
<file_sep>/messenger-server/index.js
const express = require('express')
const request = require('request')
const bodyParser = require('body-parser')
const botly = require('botly')
const { WEBHOOK, VERIFY_TOKEN, ACCESS_TOKEN, CONVERSATION_URL, SIMILARITY_URL } = require('./configs')
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
const bot = new botly({
verifyToken: VERIFY_TOKEN,
accessToken: ACCESS_TOKEN
})
let profiles = {}
const reply = (sender, message, data) => {
const payload = {
sender: sender,
message: message,
data: data
}
if (data.attachments && data.attachments.image) {
request.post({
url: SIMILARITY_URL,
body: JSON.stringify({ url: data.attachments.image[0] })
}, (res, req, body) => {
const data = JSON.parse(body)
const name = profiles[sender].first_name
const similar_images = data.similar_images
let elements = []
for (let i=0; i<3; i++) {
elements.push({
image_url: similar_images[i].metadata.url,
title: '藝人 : '+similar_images[i].image_file,
subtitle: '相似度 : '+similar_images[i].score,
item_url: similar_images[i].metadata.url,
buttons: [{
type: 'web_url',
title: '照片',
url: similar_images[i].metadata.url
}]
})
}
//只是送文字
bot.sendText({
id: sender,
text: '以下是這張照片的相似圖'
}, (e,d) => {
if (e) console.log('sendText error:', e)
else console.log('sendText callback:', d)
})
//送圖片+文字
bot.sendGeneric({
id: sender,
elements: elements
}, (e, d) => {
if (e) console.log('similarities error:', e)
else console.log('similarities callback:', d)
})
})
} else {
request.post({
url: CONVERSATION_URL,
body: JSON.stringify(payload)
}, (res, req, body) => {
const data = JSON.parse(body)
const name = profiles[sender].first_name
const type = data.type
switch (type) {
case 'weather':
console.log('weather data:', data)
bot.sendGeneric({
id: sender,
elements: [{
image_url: data.image,
title: data.disc+' | '+data.temp+'℃',
subtitle: data.location,
}]
}, (e,d) => {
if (e) console.log('sendText error:', e)
else console.log('sendText callback:', d)
})
break;
case 'text':
default:
bot.sendText({
id: sender,
text: data.text
}, (e,d) => {
if (e) console.log('sendText error:', e)
else console.log('sendText callback:', d)
})
}
})
}
}
bot.on('message', (sender, message, data) => {
if (profiles[sender]) {
reply(sender, message, data)
} else {
// first-time user
bot.getUserProfile(sender, (err, info) => { //可以知道是誰送的
if (err) {
console.log('getUserProfile error:', err)
} else {
profiles[sender] = info
bot.sendText({
id: sender,
text: 'Hello~'+profiles[sender].first_name
}, (e, d) => {
if (e) {
console.log('sendText error:', e)
} else {
console.log('sendText callback:', d)
reply(sender, message, data)
}
})
}
})
}
})
app.use(WEBHOOK, bot.router())
app.listen(process.env.PORT || 8080)
<file_sep>/linebot-server/configs_template.js
module.exports = {
linebot: {
WEBHOOK: '',
CHANNEL_ID: 0,
CHANNEL_SECRET: '',
CHANNEL_ACCESS_TOKEN: ''
},
mqtt: {
organizationId: '',
type: 'd',
deviceType: '',
deviceId: '',
username: 'use-token-auth',
password: ''
}
}<file_sep>/README.md
# angelhack2017
build your line bot
https://github.com/davidhu34/linebot-server
build your Fb bot
https://github.com/davidhu34/messenger-server
build your TJbot
https://github.com/victordibia/tjwave
then code in node-red, to control messenger mix.
| 3e9ba0633ce3fd0772622ee8bb52692599c0439e | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | d8815460/angelhack2017 | 4bd2f1499b1719f59a4311c98acd23484d9935b3 | 0fe0ca4dd84dfccaa86fc298b24e56a210f193c9 |
refs/heads/main | <repo_name>99066957/werken-met-gegevens<file_sep>/feestlunch.py
# feestlunch.py
print("17 * 0.39")
print("= 6.63")
print("2 * 2.78")
print("= 5.56")
print("6.63 + 5.56")
print("= 12.19")
print("12.19 - 1.50")
print("= 10.69")
print("De feestlunch kost je bij de bakker 10.69 euro voor de 17 croissantjes en de 2 stokbroden als de 3 kortingsbonnen nog geldig zijn!")<file_sep>/speelhaldag.py
# speelhaldag.py
print("7 * 7.45")
print("= 22.35")
print("5 * 9")
print("= 45")
print("(0.37 * 9) * 4")
print("= 13.32")
print("22.35 + 13.32")
print("= 35.67")
print("Dit geweldige dagje-uit met 4 mensen in de Speelhal met 45 minuten VR kost je maar 35.67 euro!") | 3725d262a8ba94c8fcfbbe9534128910a6bbf629 | [
"Python"
] | 2 | Python | 99066957/werken-met-gegevens | 49765ebe56eb6bf120d8776bd5d58e1e2c137266 | 873fab976f43028e31984181616ccfdf88743f9d |
refs/heads/master | <file_sep><?php
class Dashboard extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->helper('url_helper');
$this->load->model('General_model');
}
public function view(){
//load total hts
//$this->load->model('Hts_model');
$data['allHts'] = $this->General_model->getAllRows('hts');
//clients
//$this->load->model('Clients_model');
$data['allclients'] = $this->General_model->getAllRows('clients');
//patients
//$this->load->model('Patient_model');
$data['allpatients'] = $this->General_model->getAllRows('hivpatients');
$data['negativeclients'] = $data['allclients'] - $data['allpatients'];
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/dashboard_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/home',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/dashboard_js');
$this->load->view('templates/global/end_global_footer');
}
}
?>
<file_sep><?php
class Clients extends CI_Controller{
//clients constructor
public function __construct(){
parent::__construct();
$this->load->model('Clients_model');
$this->load->helper('url_helper');
$this->load->helper('url');
$this->load->library('session');
}
/*
* REGISTER CLIENT FOR THE FIRST TIME:
* ===================================
* 1. insert client
* Use UUID as the unique client ID
* 2. insert the hts visit
*/
public function register_client(){
//get form helper and validation library
$this->load->helper('form');
$this->load->library('form_validation');
//fields to validate. set_rules(the name of the input field, the name to be used in error messages, and the rule.)
$this->form_validation->set_rules('date','Provide Date','required');
$this->form_validation->set_rules('name','Provide Name','required');
$this->form_validation->set_rules('surname', 'Provide Surname','required');
$this->form_validation->set_rules('gender', 'Provide Gender','required');
$this->form_validation->set_rules('dob', 'Provide date of birth','required');
if($this->form_validation->run()===FALSE){
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/new_client');
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer.php');
$this->load->view('templates/global/end_global_footer.php');
}else{
//get uuid
$clientid = $this->Clients_model->generate_uuid();
//get array of clients table specific information
$clientdata = array(
'id' => $clientid,
'creation_date' => $this->input->post('date'),
'name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'gender' => $this->input->post('gender'),
'dob' => $this->input->post('dob')
);
//insert client info
$this->Clients_model->add('clients',$clientdata);
//get array of hts table specific information
$htsdata = array(
'clientid' => $clientid,
'hivstatus' => $this->input->post('hiv_status'),
'date' => $this->input->post('date'),
'nextdate' => $this->input->post('next_date'),
);
//insert hts visit info
$this->Clients_model->add('hts',$htsdata);
//hex the client id
$this->load->model('Hts_model');
$client = $this->Hts_model->hexid($clientid);
//load successful view
//$this->session->set_flashdata('clientid',$clientid);
//$this->session->set_flashdata('clientid',$clientid);
$this->session->set_flashdata('clientid',$client);
redirect(base_url('view_client_profile'));
}
}
/* VIEW REGISTERED CLIENTS
* ========================
* 1. view all registered clients
* 2. Search for a specific client using any keyword in their info
* 3. Click the action buton to either view single client or update bio
*/
public function returning_clients(){
//get returning clients from clients table
$data['returning'] = $this->Clients_model->returning_clients();
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/datatables_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/returning_client',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/datatables_js');
$this->load->view('templates/global/end_global_footer');
}
/* VIEW CLIENT PROFILE
* ====================
* 1. Client bio
* 2. Client HTS visits
*/
public function view_client_profile(){
//get client id
if(!empty($this->session->clientid)){ //use this if there was a redirect
$clientid = $this->session->clientid;
}else{
$clientid = $this->input->post('id'); //use this if there was a direct view on the client from table list
}
//client bio
$data['client_profile'] = $this->Clients_model->client_profile($clientid);
$data['theid'] = $clientid;
if (empty($data['client_profile']))
{
show_404();
}
//get clinics for if client is hiv+
$this->load->model('Clinics_model');
$data['clinic'] = $this->Clinics_model->get_clinics();
//get districts
$this->load->model('Districts_model');
$data['districts'] = $this->Districts_model->get_district();
//get chiefs
$this->load->model('Chiefs_model');
$data['chiefs'] = $this->Chiefs_model->get_chiefs();
//client HTS visits
//load HTS model
$this->load->model('Hts_model');
//get visits
$data['hts_visits'] = $this->Hts_model->get_client_hts($clientid);
$data['total_visits'] = count($data['hts_visits']);
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/user_profile_css.php');
$this->load->view('templates/global/sweetalerts_css.php');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/view_client',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/view_client_level_plugin.php');
$this->load->view('templates/global/sweetalert_js.php');
$this->load->view('templates/global/end_global_footer');
}
}
?>
<file_sep><?php
class Chiefs_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_chiefs($chief_id = FALSE){
if($chief_id === FALSE){
$query = $this->db->get('chiefs');
return $query->result_array();
}
$query = $this->db->get_where('chiefs', array('id'=>$chief_id));
return $query->result_array();
}
}
?>
<file_sep><!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="<?php echo base_url(); ?>assets/global/scripts/datatable.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN FIXED HEADING SCRIPTS -->
<script src="<?php echo base_url(); ?>assets/pages/scripts/table-datatables-fixedheader.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<file_sep><?php
class Clinics extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('Clinics_model');
$this->load->helper('url_helper');
}
public function get_clinics(){
$data['clinic'] = $this->Clinics_model->get_clinics();
$this->load->view('pages/preart_register',$data);
}
}
?>
<file_sep><!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="<?php echo base_url(); ?>assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<file_sep><?php
class Login extends CI_Controller{
public __construct(){
parent::__construct();
$this->load->helper('url_helper');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function isLoggedin(){
if(auto_login()){
//logged in, remembered
return TRUE;
}else{
return FALSE;
}
}
public function process_login(){
if(isLoggedin()){
redirect(base_url('Dashboard/view'));
}else{
$this->login();
}
}
public function login(){
$this->form_validation->set_rules('username','Provide username','required');
$this->form_validation->set_rules('password','Provide password','<PASSWORD>');
if($this->form_validation->run()===FALSE){
$this->error = validation_errors();
$this->view_login_form();
}
if($this->process_login()){
redirect(base_url('Dashboard'));
}
$this->view_login_form();
}
public function view_login_form(){
$data['form_error'] = $this->error;
$this->load->view('paes/login');
}
public function process_login(){
$this->load->model('User_model');
}
public function auto_login(){
}
}
?>
<file_sep><?php
class Encounters_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function add($table,$data=array()){
return $this->db->insert($table,$data);
}
public function get_encounters($artid){
$query = $this->db->get_where('encounters',array('artid'=> $artid));
return $query->result_array();
}
}
?>
<file_sep><?php
class Encounters extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('Encounters_model');
$this->load->helper('url');
}
public function add_encounter(){
$clientid = $this->input->post('clientid');
$data['encounters'] = array(
'id' => '',
'artid' => $this->input->post('artid'),
'scheduled' => $this->input->post('scheduled'),
'date_scheduled' => $this->input->post('scheduled_date'),
'followup_date' => $this->input->post('followup_date'),
'durationsincefirststart' => $this->input->post('duration'),
'smi_whz_score' => $this->input->post('smi'),
'weight' => $this->input->post('weight'),
'pregnant' => $this->input->post('edd'),
'function' => $this->input->post('function'),
'who_clinicalstage' => $this->input->post('stage'),
'tb_status' => $this->input->post('tb'),
'sti' => $this->input->post('sti'),
'potential_sideeffects' => $this->input->post('side_effects'),
'new_oi' => $this->input->post('new_oi'),
'ctx' => $this->input->post('ctx'),
'ipt' => $this->input->post('ipt'),
'other_meds' => $this->input->post('other_meds'),
'arvdrugs' => $this->input->post('arvdrugs'),
'viraload' => $this->input->post('viraload'),
'cd4' => $this->input->post('cd4'),
'labs' => $this->input->post('labs'),
'refer' => $this->input->post('refer')
);
//insert into encounters
$this->Encounters_model->add('encounters',$data['encounters']);
$this->load->view('pages/success');
}
}
?>
<file_sep><?php
class Districts_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_district($district_id = FALSE){
if($district_id === FALSE){
$query = $this->db->get('districts');
return $query->result_array();
}
$query = $this->db->get_where('districts', array('id'=>$district_id));
return $query->result_array();
}
}
?>
<file_sep><!-- BEGIN SIDEBAR -->
<div class="page-sidebar-wrapper">
<!-- BEGIN SIDEBAR -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<div class="page-sidebar navbar-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) -->
<!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode -->
<!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Set data-keep-expand="true" to keep the submenues expanded -->
<!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<ul class="page-sidebar-menu page-header-fixed " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200" style="padding-top: 20px">
<!-- DOC: To remove the sidebar toggler from the sidebar you just need to completely remove the below "sidebar-toggler-wrapper" LI element -->
<!-- BEGIN SIDEBAR TOGGLER BUTTON -->
<li class="sidebar-toggler-wrapper hide">
<div class="sidebar-toggler">
<span></span>
</div>
</li>
<!-- END SIDEBAR TOGGLER BUTTON -->
<!-- DOC: To remove the search box from the sidebar you just need to completely remove the below "sidebar-search-wrapper" LI element -->
<li class="sidebar-search-wrapper">
<!-- BEGIN RESPONSIVE QUICK SEARCH FORM -->
<!-- DOC: Apply "sidebar-search-bordered" class the below search form to have bordered search box -->
<!-- DOC: Apply "sidebar-search-bordered sidebar-search-solid" class the below search form to have bordered & solid search box -->
<form class="sidebar-search " action="page_general_search_3.html" method="POST">
<a href="javascript:;" class="remove">
<i class="icon-close"></i>
</a>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit">
<i class="icon-magnifier"></i>
</a>
</span>
</div>
</form>
<!-- END RESPONSIVE QUICK SEARCH FORM -->
</li>
<li class="nav-item start active open">
<a href="<?php echo base_url(); ?>home" class="nav-link nav-toggle">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
</li>
<li class="heading">
<h3 class="uppercase">Testing Level</h3>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-layers"></i>
<span class="title">HTS</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="<?php echo base_url(); ?>new_client" class="nav-link ">
<span class="title">New Client</span>
</a>
</li>
<li class="nav-item ">
<a href="<?php echo base_url(); ?>returning_client" class="nav-link ">
<span class="title">Returning Client</span>
</a>
</li>
</ul>
</li>
<li class="heading">
<h3 class="uppercase">ART Level</h3>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-user"></i>
<span class="title">Pre-ART</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="<?php echo base_url(); ?>preart" class="nav-link ">
<i class="icon-users"></i>
<span class="title">View Patients</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-user"></i>
<span class="title">ART</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="<?php echo base_url(); ?>artpatients" class="nav-link ">
<i class="icon-user"></i>
<span class="title">View ART Patients</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-diamond"></i>
<span class="title">Analysis</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="ui_colors.html" class="nav-link ">
<span class="title">HTS</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_buttons.html" class="nav-link ">
<span class="title">ART</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_metronic_grid.html" class="nav-link ">
<span class="title">CoHort</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-puzzle"></i>
<span class="title">Transfers</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="components_color_pickers.html" class="nav-link ">
<span class="title">Request Transfer</span>
</a>
</li>
<li class="nav-item ">
<a href="components_date_time_pickers.html" class="nav-link ">
<span class="title">Inbound Transfers</span>
<span class="badge badge-success">2</span>
</a>
</li>
<li class="nav-item ">
<a href="components_date_time_pickers.html" class="nav-link ">
<span class="title">Outbound Transfers</span>
<span class="badge badge-danger">2</span>
</a>
</li>
<li class="nav-item ">
<a href="components_date_time_pickers.html" class="nav-link ">
<span class="title">View All Transfers</span>
</a>
</li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
<!-- END SIDEBAR MENU -->
</div>
<!-- END SIDEBAR -->
</div>
<!-- END SIDEBAR -->
<file_sep># hivehr
web application which will enable effective and efficient monitoring and recording of patients that test positive for HIV
<file_sep><?php
class General_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function getAllRows($table){
$query = $this->db->get($table);
return $query->num_rows();
}
}
?>
<file_sep><?php
class Chiefs extends CI_Controller{
public function __cosntruct(){
parent::__construct();
$this->load->model('Chiefs_model');
}
}
?>
<file_sep><?php
class Clinics_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_clinics($clinic_id = FALSE){
if($clinic_id === FALSE){
$query = $this->db->get('clinics');
return $query->result_array();
}
$query = $this->db->get_where('clinics', array('id'=>$clinic_id));
return $query->result_array();
}
}
?>
<file_sep><!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE BAR -->
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<a href="home">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Form Stuff</span>
</li>
</ul>
</div>
<!-- END PAGE BAR -->
<!-- END PAGE HEADER-->
<div class="row">
<div class="col-md-12">
<div class="m-heading-1 border-green m-bordered">
<h3>FACILITY HIV Care (pre- ART) REGISTER</h3>
<p> lorem ispam. </p>
<p> lorem ispan
<a class="btn red btn-outline" href="http://example.com" target="_blank">the official documentation</a>
</p>
</div>
<div class="portlet light bordered" id="form_wizard_1">
<div class="portlet-title">
<div class="caption">
<i class=" icon-layers font-red"></i>
<span class="caption-subject font-red bold uppercase">
<span class="step-title"> Step 1 of 4 </span>
</span>
</div>
<div class="actions">
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-cloud-upload"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-wrench"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-trash"></i>
</a>
</div>
</div>
<div class="portlet-body form">
<!--<form class="form-horizontal" action="#" id="submit_form" method="POST">-->
<?php
$attributes = array('class'=>'form-horizontal','id'=>'submit_form');
echo form_open('patients/register_preart',$attributes);
?>
<div class="form-wizard">
<div class="form-body">
<ul class="nav nav-pills nav-justified steps">
<li>
<a href="#tab1" data-toggle="tab" class="step">
<span class="number"> 1 </span>
<span class="desc">
<i class="fa fa-check"></i> Personal Details </span>
</a>
</li>
<li>
<a href="#tab2" data-toggle="tab" class="step">
<span class="number"> 2 </span>
<span class="desc">
<i class="fa fa-check"></i> Additional Information </span>
</a>
</li>
<li>
<a href="#tab3" data-toggle="tab" class="step active">
<span class="number"> 3 </span>
<span class="desc">
<i class="fa fa-check"></i> Clinic Stage </span>
</a>
</li>
<li>
<a href="#tab4" data-toggle="tab" class="step">
<span class="number"> 4 </span>
<span class="desc">
<i class="fa fa-check"></i> Confirm Details </span>
</a>
</li>
</ul>
<div id="bar" class="progress progress-striped" role="progressbar">
<div class="progress-bar progress-bar-success"> </div>
</div>
<div class="tab-content">
<div class="alert alert-danger display-none">
<button class="close" data-dismiss="alert"></button> You have some form errors. Please check below. </div>
<div class="alert alert-success display-none">
<button class="close" data-dismiss="alert"></button> Your form validation is successful! </div>
<div class="tab-pane active" id="tab1">
<h3 class="block">Provide Patient Filing Details</h3>
<div class="form-group">
<label class="control-label col-md-3">Enrolment Date
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="p_hivcare_enrolment" />
<span class="help-block"> Provide Date enrolled in chronic HIV Care</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Clinic
<span class="required"> * </span>
</label>
<div class="col-md-4">
<select class="form-control" name="clinic_id">
<?php
foreach($clinic as $clinic_item):
echo"<option value='".$clinic_item['id']."'>".$clinic_item['name']."</option>";
endforeach;
?>
</select>
<span class="help-block"> Provide Patient's clinic </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Name
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="text" class="form-control" name="p_name" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Surname
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="text" class="form-control" name="p_surname" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="p_dob" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Age
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="text" class="form-control" name="p_age" />
</div>
</div>
<div class="form-group form-md-radios">
<label class="col-md-3 control-label" for="form_control_1">Gender</label>
<div class="col-md-9">
<div class="md-radio-list">
<div class="md-radio">
<input type="radio" id="checkbox1_gen1" name="p_gender" value="Male" class="md-radiobtn">
<label for="checkbox1_gen1">
<span></span>
<span class="check"></span>
<span class="box"></span> Male </label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_gen2" name="p_gender" value="Female" class="md-radiobtn">
<label for="checkbox1_gen2">
<span></span>
<span class="check"></span>
<span class="box"></span> Female </label>
</div>
</div>
</div>
</div>
<div class="form-group form-md-radios">
<label class="col-md-3 control-label" for="form_control_1">Marital Status
<span class="required">*</span>
</label>
<div class="col-md-9">
<div class="md-radio-list">
<div class="md-radio">
<input type="radio" id="checkbox1_s1" name="p_marital_status" value="Single" class="md-radiobtn">
<label for="checkbox1_s1">
<span></span>
<span class="check"></span>
<span class="box"></span> Single</label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_s2" name="p_marital_status" value="Married" class="md-radiobtn">
<label for="checkbox1_s2">
<span></span>
<span class="check"></span>
<span class="box"></span> Married </label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_s3" name="p_marital_status" value="Divorced" class="md-radiobtn">
<label for="checkbox1_s3">
<span></span>
<span class="check"></span>
<span class="box"></span> Divorced </label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_s4" name="p_marital_status" value="Separated" class="md-radiobtn">
<label for="checkbox1_s4">
<span></span>
<span class="check"></span>
<span class="box"></span> Separated </label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_s5" name="p_marital_status" value="Widowed" class="md-radiobtn">
<label for="checkbox1_s5">
<span></span>
<span class="check"></span>
<span class="box"></span> Widowed </label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Physical Address
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="text" class="form-control" name="p_address" />
<span class="help-block"> Where Patient Lives </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Phone Number
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="text" class="form-control" name="p_phone" />
<span class="help-block">e.g. 5700000 . Do not enter +266 or leave any spaces </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Confirmed HIV+ Date
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="p_hivdate" />
<span class="help-block"> Provide date test was positive for HIV</span>
</div>
</div>
</div>
<div class="tab-pane" id="tab2">
<h3 class="block">Isonicotinylhydrazide(INH) - If Applicable</h3>
<div class="form-group">
<label class="control-label col-md-3">Start Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="inh_start" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Stop Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="inh_stop" />
</div>
</div>
<h3 class="block">cotrimoxazole (CTX) - If Applicable</h3>
<div class="form-group">
<label class="control-label col-md-3">Start Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="ctx_start">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Stop Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="ctx_stop" />
</div>
</div>
<h3 class="block"> Fluconazole (FCA) - If Applicable</h3>
<div class="form-group">
<label class="control-label col-md-3">Start Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="fca_start">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Stop Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="fca_stop" />
</div>
</div>
<h3 class="block"> TB Rx - If Applicable</h3>
<div class="form-group">
<label class="control-label col-md-3">Start Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="tb_start">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Stop Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="tb_stop" />
</div>
</div>
<h3 class="block"> Pregnancy - If Applicable</h3>
<div class="form-group">
<label class="control-label col-md-3">Pregnancy Due Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="pregnancy" />
<span class="help-block"> or PMTCT Link </span>
</div>
</div>
<h3 class="block">If patient is DEAD before starting ART - If Applicable</h3>
<div class="form-group">
<label class="control-label col-md-3">Dead Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="dead_date" />
</div>
</div>
<h3 class="block">LOST or TO (Transfer Out) - If Applicable</h3>
<div class="form-group form-md-radios">
<label class="col-md-3 control-label" for="form_control_1">LOST or TO</label>
<div class="col-md-9">
<div class="md-radio-list">
<div class="md-radio">
<input type="radio" id="checkbox1_lost1" name="lost_to" value="LOST" class="md-radiobtn">
<label for="checkbox1_lost1">
<span></span>
<span class="check"></span>
<span class="box"></span> LOST </label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_lost2" name="lost_to" value="TO" class="md-radiobtn">
<label for="checkbox1_lost2">
<span></span>
<span class="check"></span>
<span class="box"></span> TO </label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">LOST or TO Date
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="lost_to_date" />
</div>
</div>
</div>
<div class="tab-pane" id="tab3">
<h3 class="block">Clinical Stage at Registration</h3>
<div class="form-group">
<label class="control-label col-md-3">Clinical Stage
<span class="required"> * </span>
</label>
<div class="col-md-4">
<select class="form-control"name="registration_clinical_stage">
<option></option>
<option value="1">Stage 1</option>
<option value="2">Stage 2</option>
<option value="3">Stage 3</option>
<option value="4">Stage 4</option>
</select>
<span class="help-block"> </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date
<span class="required"> * </span>
</label>
<div class="col-md-4">
<input type="date" class="form-control" name="registration_clinical_stage_date" />
<span class="help-block"> </span>
</div>
</div>
</div>
<div class="tab-pane" id="tab4">
<h3 class="block">Confirm data collected</h3>
<h4 class="form-section">Personal Information</h4>
<div class="form-group">
<label class="control-label col-md-3">Name:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_name"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Surname:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_surname"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_gender"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Age:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_age"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date Of Birth:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_dob"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Marital Status:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_marital_status"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_address"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Phone Number:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_phone"> </p>
</div>
</div>
<h4 class="form-section">HIV Status Information</h4>
<div class="form-group">
<label class="control-label col-md-3">Confirmed HIV+ date:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_hivdate"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Chronic HIV Enrollment date:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="p_hivcare_enrolment"> </p>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Clinical Stage:</label>
<div class="col-md-4">
<p class="form-control-static" data-display="registration_clinical_stage"> </p>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<a href="javascript:;" class="btn default button-previous">
<i class="fa fa-angle-left"></i> Back </a>
<a href="javascript:;" class="btn btn-outline green button-next"> Continue
<i class="fa fa-angle-right"></i>
</a>
<button type="submit" class="btn green"> Submit
<i class="fa fa-check"></i>
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<file_sep><?php
class Patient_model extends CI_Model{
public function __construct(){
$this->load->database();
}
//get hiv patients
public function get_hivpatients($clientid = FALSE){
if($clientid === FALSE){
$query = $this->db->get('hivpatients');
return $query->result_array();
}
$query = $this->db->get_where('hivpatients',array('hex(clientid)'=> $clientid));
return $query->result_array();
}
//global insert
public function add($table,$data=array()){
return $this->db->insert($table,$data);
}
//global insert of related table
function add_multiple($table,$data=array()){
$query = $this->db->insert($table, $data);
return $this->db->insert_id();// return last insert id
}
//joining two tables
public function patient_join_client($condition){
/* SELECTING ALL
* $this->db->select(*);
*/
//select required info
$this->db->select('hex(id), creation_date, name, surname, gender, dob,`clientid`, `clinicid`, `phone`, `address`, `districtid`, `chiefid`, `maritalstatus`, `dateconfirmedhiv_positive`, `firstentry_healthstatusid`, `artid`');
$this->db->from('clients');
$this->db->join("hivpatients",$condition);
$query = $this->db->get()->result_array();
return $query;
}
//get first health status recorded
public function firststatus($clientid){
$query = $this->db->get_where('firstentry_healthstatus',array('hex(clientid)'=>$clientid));
return $query->result_array();
}
//update
public function edit($table,$data,$condition){
$this->db->update($table, $data, $condition);
return true;
}
}
?>
<file_sep><!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE BAR -->
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Form Stuff</span>
</li>
</ul>
</div>
<!-- END PAGE BAR -->
<div class="m-heading-1 border-green m-bordered">
<h3>jQuery Validation Plugin</h3>
<p> This jQuery plugin makes simple clientside form validation easy, whilst still offering plenty of customization options. For more info please check out
<a class="btn red btn-outline" href="http://jqueryvalidation.org" target="_blank">the official documentation</a>
</p>
</div>
<div class="row">
<div class="col-md-12">
<!-- BEGIN VALIDATION STATES-->
<div class="portlet light portlet-fit portlet-form bordered">
<div class="portlet-title">
<div class="caption">
<i class="icon-settings font-red"></i>
<span class="caption-subject font-red sbold uppercase"><?php echo $fname; ?> - Encounter registration</span>
</div>
</div>
<div class="portlet-body">
<!-- BEGIN FORM-->
<?php
$attributes = array('class'=>'form-horizontal','id'=>'form_sample_1');
echo form_open('Encounters/add_encounter',$attributes);
?>
<input type="hidden" name="clientid" value="<?php echo $cid; ?>">
<input type="hidden" name="artid" value="<?php echo $artid; ?>">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button> You have some form errors. Please check below. </div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button> Your form validation is successful! </div>
<div class="form-group">
<label class="control-label col-md-3">Date
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input type="date" name="scheduled_date" data-required="1" class="form-control" /> </div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Scheduled?
<span class="required"> * </span>
</label>
<div class="col-md-6">
<select class="form-control" name="scheduled">
<option value="">Select...</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Follow up date
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input type="date" name="followup_date" data-required="1" class="form-control" /> </div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Duration
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="duration" type="text" class="form-control" />
<span class="help-block"> Duration Since First Starting ART/ Since Starting Current Regimen </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">SMI/WHZ Score
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="smi" type="text" class="form-control" />
<span class="help-block"> SMI if child WHZ SCORE</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Weight
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="weight" type="text" class="form-control" />
<span class="help-block"> Ht at 1st visit for adult,(if chilf record +/_ oedema)</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Pregnant EDD
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="edd" type="text" class="form-control" />
<span class="help-block"> Pregnant EDD? PMTCT? FP/NoFP. If FP, write Method(s), if Child record MUAC</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Function
<span class="required"> * </span>
</label>
<div class="col-md-6">
<select class="form-control" name="function">
<option value="">Select...</option>
<option value="work">Work</option>
<option value="amb">Amb</option>
<option value="bed">Bed</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">WHO Clinical Stage</label>
<div class="col-md-6">
<select class="form-control" name="stage">
<option value="">Select...</option>
<option value="Stage_1">Stage 1</option>
<option value="Stage_2">Stage 2</option>
<option value="Stage_3">Stage 3</option>
<option value="Stage_4">Stage 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">TB Status
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="tb" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">STI</label>
<div class="col-md-6">
<select class="form-control" name="sti">
<option value="">Select...</option>
<option value="signs">Sign</option>
<option value="no-signs">No Sign</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Potential side effects
<span class="required"> * </span>
</label>
<div class="col-md-6">
<textarea name="side_effects" class="form-control" rows="5"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">New OI, other problems
<span class="required"> * </span>
</label>
<div class="col-md-6">
<textarea name="new_oi" rows="5" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Cotrimoxazole
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="ctx" type="text" class="form-control" />
<span class="help-block"> Adhere / No. of days dispensed</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">IPT
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="ipt" type="text" class="form-control" />
<span class="help-block"> Adhere / No. of days dispensed</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Other meds dispensed
<span class="required"> * </span>
</label>
<div class="col-md-6">
<textarea name="other_meds" rows="5" class="form-control" ></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">ARV Drugs
<span class="required"> * </span>
</label>
<div class="col-md-6">
<textarea rows="5" name="arvdrugs" class="form-control"></textarea>
<span class="help-block"> Adhere / Why OR Regimen / No. of days dispensed</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Viral Load
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="viraload" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Cd4
<span class="required"> * </span>
</label>
<div class="col-md-6">
<input name="cd4" type="text" class="form-control" />
<span class="help-block"> if < 5 years write CD4%</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Labs
<span class="required"> * </span>
</label>
<div class="col-md-6">
<textarea name="labs" rows="5" class="form-control" ></textarea>
<span class="help-block"> Hgb, RPR, TLC, TB sputum, Other lab, AFB's</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Refer/ Consults/ Link
<span class="required"> * </span>
</label>
<div class="col-md-6">
<textarea name="refer" rows="5" class="form-control" ></textarea>
<span class="help-block"> Refer or consults or link / provide (including nutritional support & infanct feeding), if hospitalised write # of days)</span>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn grey-salsa btn-outline">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END VALIDATION STATES-->
</div>
</div>
</div>
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
</div>
<!-- END CONTAINER -->
<file_sep><!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE BAR -->
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<a href="home">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">HTS</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Returning Clients</span>
</li>
</ul>
</div>
<!-- END PAGE BAR -->
<!-- END PAGE HEADER-->
<div class="m-heading-1 border-green m-bordered">
<h3>Search for a returning client</h3>
<p> Search for a returning client by any keyword</p>
<p> For more info please check out
<a class="btn red btn-outline" href="https://www.datatables.net/extensions/responsive/" target="_blank">the official documentation</a>
</p>
</div>
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-dark">
<i class="icon-settings font-dark"></i>
<span class="caption-subject bold uppercase">List of Registered Clients</span>
</div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover table-header-fixed" id="sample_1">
<thead>
<tr class="">
<th> Client ID </th>
<th> Registered Date </th>
<th> Name </th>
<th> Surname </th>
<th> Date of Birth </th>
<th> Gender </th>
<th> Action </th>
</tr>
</thead>
<tbody>
<?php
foreach($returning as $client):
?>
<tr>
<td><?php echo $client['hex(id)']; ?></td>
<td><?php echo $client['creation_date']; ?></td>
<td><?php echo $client['name']; ?></td>
<td><?php echo $client['surname']; ?></td>
<td><?php echo $client['dob']; ?></td>
<td><?php echo $client['gender']; ?></td>
<td>
<!-- <div class="btn-group pull-right">
<a href="view_client/<?php //echo $client['hex(id)']; ?>">
<i class="fa fa-print"></i> View
</a>
</div>-->
<div class="btn-group pull-right">
<?php
echo form_open(base_url('view_client_profile'));
?>
<input type="hidden" name="id" id="id" value="<?php echo $client['hex(id)']; ?>" />
<input type="submit" value="View" />
</form>
</div>
</td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div>
</div>
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<file_sep><!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE BAR -->
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<a href="home">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>HTS</span>
</li>
</ul>
</div>
<!-- END PAGE BAR -->
<!-- END PAGE HEADER-->
<div class="m-heading-1 border-green m-bordered">
<h3>HTS Registration</h3>
<p>The test result and any information shared by the client is confidential
<a class="btn red btn-outline" href="http://apps.who.int/iris/bitstream/10665/179870/1/9789241508926_eng.pdf?ua=1&ua=1" target="_blank">the official documentation</a>
</p>
</div>
<div class="row">
<div class="col-md-12">
<!-- BEGIN VALIDATION STATES-->
<div class="portlet light portlet-fit portlet-form bordered">
<div class="portlet-title">
<div class="caption">
<i class=" icon-layers font-green"></i>
<span class="caption-subject font-green sbold uppercase">Register Visit</span>
<?php echo validation_errors(); ?>
</div>
</div>
<div class="portlet-body">
<!-- BEGIN FORM-->
<?php
$attributes = array('class'=>'form-horizontal', 'id'=>'form_sample_1');
echo form_open('clients/register_client',$attributes);
?>
<!-- <form action="#" class="form-horizontal" id="form_sample_1">-->
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button> You have some form errors. Please check below. </div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button> Your form validation is successful! </div>
<div class="form-group form-md-line-input">
<label class="col-md-3 control-label" for="form_control_1">Date
<span class="required">*</span>
</label>
<div class="col-md-9">
<input type="date" class="form-control" placeholder="" name="date">
<div class="form-control-focus"> </div>
</div>
</div>
<div class="form-group form-md-line-input">
<label class="col-md-3 control-label" for="form_control_1">Name
<span class="required">*</span>
</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="" name="name">
<div class="form-control-focus"> </div>
</div>
</div>
<div class="form-group form-md-line-input">
<label class="col-md-3 control-label" for="form_control_1">Surname
<span class="required">*</span>
</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="" name="surname">
<div class="form-control-focus"> </div>
</div>
</div>
<div class="form-group form-md-line-input">
<label class="col-md-3 control-label" for="form_control_1">Date of Birth
<span class="required">*</span>
</label>
<div class="col-md-9">
<input type="date" class="form-control" placeholder="" name="dob">
<div class="form-control-focus"> </div>
</div>
</div>
<div class="form-group form-md-radios">
<label class="col-md-3 control-label" for="form_control_1">Gender
<span class="required">*</span>
</label>
<div class="col-md-9">
<div class="md-radio-list">
<div class="md-radio">
<input type="radio" id="checkbox1_1" name="gender" value="Male" class="md-radiobtn">
<label for="checkbox1_1">
<span></span>
<span class="check"></span>
<span class="box"></span> Male</label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_2" name="gender" value="Female" class="md-radiobtn">
<label for="checkbox1_2">
<span></span>
<span class="check"></span>
<span class="box"></span> Female </label>
</div>
</div>
</div>
</div>
<div class="form-group form-md-radios">
<label class="col-md-3 control-label" for="form_control_1">HIV Status
<span class="required">*</span>
</label>
<div class="col-md-9">
<div class="md-radio-list">
<div class="md-radio">
<input type="radio" id="checkbox1_3" name="hiv_status" value="negative" class="md-radiobtn">
<label for="checkbox1_3">
<span></span>
<span class="check"></span>
<span class="box"></span> Negative</label>
</div>
<div class="md-radio">
<input type="radio" id="checkbox1_4" name="hiv_status" value="positive" class="md-radiobtn">
<label for="checkbox1_4">
<span></span>
<span class="check"></span>
<span class="box"></span> Positive </label>
</div>
</div>
</div>
</div>
<div class="form-group form-md-line-input">
<label class="col-md-3 control-label" for="form_control_1">Next Date of Visit
</label>
<div class="col-md-9">
<input type="date" class="form-control" placeholder="" name="next_date">
<div class="form-control-focus"> </div>
</div>
</div>
<!-- <div class="form-group form-md-checkboxes">
<label class="col-md-3 control-label" for="form_control_1">Reason For Visit</label>
<div class="col-md-9">
<div class="md-checkbox-list">
<div class="md-checkbox">
<input type="checkbox" name="comments[]" value="1" id="checkbox1_1" class="md-check">
<label for="checkbox1_1">
<span></span>
<span class="check"></span>
<span class="box"></span> HTC </label>
</div>
<div class="md-checkbox">
<input type="checkbox" name="comments[]" value="2" id="checkbox1_2" class="md-check">
<label for="checkbox1_2">
<span></span>
<span class="check"></span>
<span class="box"></span> BP </label>
</div>
<div class="md-checkbox">
<input type="checkbox" name="comments[]" value="3" id="checkbox1_211" class="md-check">
<label for="checkbox1_211">
<span></span>
<span class="check"></span>
<span class="box"></span> RBS </label>
</div>
</div>
</div>
</div> -->
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Register</button>
<button type="reset" class="btn default">Reset</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END VALIDATION STATES-->
</div>
</div>
</div>
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<file_sep><?php
class Clients_model extends CI_Model{
public function __construct(){
$this->load->database();
}
/*
* GENERATE UUID
* clients ID = uuid
*
* EXPLAINED:
* ==========
* UUIDs are a good alternative to AUTO_INCREMENT PRIMARY KEY and are used mainly because:
* – the keys are unique across tables, databases and servers
* – are hard(er) to guess (example from an URL)
* – can be generated offline (without any exchange of information with the database or collaboration with other components of the system)
* – simplifies replication
* But they also come with some disadvantages:
* – increased storage: 36 characters
* – more difficult to debug
* – performance issues: mainly because of the size and not being ordered
*
* The solution to this is using 2 functions:
* The UUID_TO_BIN/BIN_TO_UUID functions have a second boolean argument, which is optional,
* and can be used to avoid this problem. Setting the argument to true while inserting the
* values: “INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true));” will rearrange
* the time-related bits so that consecutive generated values will be ordered.
*/
public function generate_uuid(){
$query = $this->db->select("unhex(replace(uuid(),'-','')) AS uid");
$row = $query->get()->row();
$uuid = $row->uid;
return $uuid;
}
//global insert
public function add($table,$data=array()){
return $this->db->insert($table,$data);
}
//get all returning clients
public function returning_clients(){
$this->db->select('hex(id), creation_date, name, surname, gender, dob');
$this->db->from('clients');
$query = $this->db->get()->result_array();
return $query;
}
//get single returning client
public function client_profile($unique_number){
$this->db->select('hex(id), creation_date, name, surname, gender, dob');
$this->db->from('clients');
$this->db->where('hex(id)',$unique_number);
$query = $this->db->get()->result_array();
return $query;
}
//joining two tables
public function join_tables($unique_number){
/* SELECTING ALL
* $this->db->select(*);
*/
//select required info
$this->db->select('clients.id, creation_date, name, surname, gender, dob, hivstatus, date, nextdate');
$this->db->from('clients');
$this->db->join("hts","hts.clientid = clients.id AND clients.id=unhex('.$unique_number.')");
$query = $this->db->get()->result_array();
return $query;
}
//get number of clients
public function clients_number(){
$query = $this->db->get('clients');
return $query->num_rows();
}
}
?>
<file_sep><?php
class Art_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function getart_byclient($clientid){
$query = $this->db->get_where('art',array('hex(clientid)'=> $clientid));
return $query->result_array();
}
public function artstart_byid($artid){
$query = $this->db->get_where('artstart',array('id'=>$artid));
return $query->result_array();
}
}
?>
<file_sep><!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE BAR -->
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">Tables</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Datatables</span>
</li>
</ul>
</div>
<!-- END PAGE BAR -->
<!-- END PAGE HEADER-->
<div class="m-heading-1 border-green m-bordered">
<h3>All HTS visits for the clinic</h3>
<p> Responsive is an extension for DataTables that resolves that problem by optimising the table's layout for different screen sizes through the dynamic insertion and removal of columns from the table. </p>
<p> For more info please check out
<a class="btn red btn-outline" href="https://www.datatables.net/extensions/responsive/" target="_blank">the official documentation</a>
</p>
</div>
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-dark">
<i class="icon-settings font-dark"></i>
<span class="caption-subject bold uppercase">Basic</span>
</div>
<div class="tools"> </div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover dt-responsive" width="100%" id="sample_1">
<thead>
<tr>
<th class="all">First name</th>
<th class="all">Last name</th>
<th class="min-tablet">Registered Date</th>
<th class="desktop">Last Visit</th>
<th class="none">Number of Visits</th>
<th class="none">Age</th>
<th class="none">Gender</th>
<th class="none">Status</th>
<th class="all">Comments</th>
</tr>
</thead>
<tbody>
<?php
foreach($visits as $hts_person):
?>
<tr>
<td><?php echo $hts_person['Name']; ?></td>
<td><?php echo $hts_person['Surname']; ?></td>
<td><?php echo $hts_person['Registration_date']; ?></td>
<td><?php echo $hts_person['Last_visit']; ?></td>
<td><?php echo $hts_person['Visits']; ?></td>
<td><?php echo $hts_person['Age']; ?></td>
<td><?php echo $hts_person['Gender']; ?></td>
<td><?php echo $hts_person['Hiv_status']; ?></td>
<td>
<div class="btn-group pull-right">
<button class="btn green btn-xs btn-outline dropdown-toggle" data-toggle="dropdown">Action
<i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu pull-right">
<li>
<a href="javascript:;">
<i class="fa fa-print"></i> View </a>
</li>
<li>
<a href="#">
<i class="fa fa-file-pdf-o"></i> Update </a>
</li>
<li>
<a href="javascript:;">
<i class="fa fa-file-excel-o"></i> Move to PreART </a>
</li>
</ul>
</div>
</td>
<?php
endforeach;
?>
</tbody>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div>
</div>
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<file_sep><?php
class Patients extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('Patient_model');
$this->load->helper('url_helper');
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
}
//register new HIV + Patient
public function add_patient(){
//get form helper and validation library
$clientid = $this->input->post('clientid');
//load HTS model to get access to unhedid function
$this->load->model('Hts_model');
$unhexed_clientid = $this->Hts_model->unhexid($clientid);
//get first entry health status
$data['firstealth'] = array(
'id' => '',
'clientid' => $unhexed_clientid,
'inh_start' => $this->input->post('inhstart'),
'inh_stop' => $this->input->post('inhstop'),
'ctx_start' => $this->input->post('ctxstart'),
'ctx_stop' => $this->input->post('ctxstop'),
'fca_start' => $this->input->post('fcastart'),
'fca_stop' => $this->input->post('fcastop'),
'tbrx_start' => $this->input->post('tbrx_start'),
'tbrx_stop' => $this->input->post('tbrx_start'),
'lost_to' => $this->input->post('lost_to'),
'lost_to_date' => $this->input->post('losttodate'),
'clinical_stage' => $this->input->post('clinical_stage'),
);
//insert into first entry health status, so that we get its ID for patient insert
$firstentryhealthstatus_id = $this->Patient_model->add_multiple('firstentry_healthstatus',$data['firstealth']);
//get patient personal information
$data['patient'] = array(
'clientid' => $unhexed_clientid,
'clinicid' => $this->input->post('clinic'),
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address'),
'districtid' => $this->input->post('district'),
'chiefid' => $this->input->post('chief'),
'maritalstatus' => $this->input->post('marital_status'),
'dateconfirmedhiv_positive' => $this->input->post('hiv_date'),
'firstentry_healthstatusid' => $firstentryhealthstatus_id
);
//insert into patient
$this->Patient_model->add('hivpatients',$data['patient']);
$this->session->set_flashdata('clientid',$clientid);
redirect(base_url('view_patient_profile'));
}
//view patients in pre-art status
public function view_preart(){
//get information from hivpattients and clients to display
$condition = "hivpatients.clientid = clients.id AND ISNULL(hivpatients.artid)";
$data['hivpatient'] = $this->Patient_model->patient_join_client($condition);
//load view
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/datatables_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/preart',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/datatables_js');
$this->load->view('templates/global/end_global_footer');
}
//view patient PROFILE
public function view_patient_profile(){
if(!empty($this->session->clientid)){
$clientid = $this->session->clientid;
}else{
$clientid = $this->input->post('id');
}
//get patient information
$condition = "hivpatients.clientid = clients.id AND hex(id) = '".$clientid."'";
$data['patientinfo'] = $this->Patient_model->patient_join_client($condition);
//get patient HTS record
$this->load->model('Hts_model');
$data['htsrecords'] = $this->Hts_model->get_client_hts($clientid);
//get total hts visits
$data['total_visits'] = count($data['htsrecords']);
//get first recorded health status
$data['firsthealth'] = $this->Patient_model->firststatus($clientid);
//load view
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/datatables_css');
$this->load->view('templates/global/user_profile_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/view_patient',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/datatables_js');
$this->load->view('templates/global/end_global_footer');
}
//move preart patient to art
public function move_to_art(){
//get client id and names
$data['cid'] = $this->input->post('id');
$data['fname'] = $this->input->post('fullname');
//load view
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/form_wizard_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/art_register',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/form_wizard_js');
$this->load->view('templates/global/end_global_footer');
}
//register into ART
public function art_register(){
//get client id
$clientid = $this->input->post('cid');
/* IMPLODE MULTIPLE CHECKBOXES
* ============================
* use function implode to form care of entry into a string,
* so that we store it in the database.
* e.g: $ids = implode(",",$_POST["ids"]);
* Where you read from the database you can transform the value
* from db to an array like this
* $ids_array = explode(",",$row->ids);
*/
$careofentry = implode(",",$this->input->post('careofentry'));
$statusofenrol = implode(",",$this->input->post('statusofenrol'));
//load HTS model to get access to unhedid function
$this->load->model('Hts_model');
$unhexed_clientid = $this->Hts_model->unhexid($clientid);
//get art start data
$data['artstart'] = array(
'id'=>'',
'weight'=>$this->input->post('weight'),
'function'=>$this->input->post('functional'),
'height' =>$this->input->post('height'),
'whoclinicalstage'=>$this->input->post('clinicalstage'),
'cd4'=>$this->input->post('cd4'),
'statusofenrollment'=>$statusofenrol,
'inh_start'=>$this->input->post('inhstart'),
'inh_stop'=>$this->input->post('inhstop'),
'ctx_start'=>$this->input->post('ctxstart'),
'ctx_stop'=>$this->input->post('ctxstop'),
'tb_treatment_start'=>$this->input->post('tbrx_start'),
'tb_treatment_stop'=>$this->input->post('tbrx_stop')
);
//get 1st line regimen data
$data['regimen'] = array(
'id' => '',
'clientid' => $unhexed_clientid,
'regimen_line' => $this->input->post('regimen_line'),
'regimen' => $this->input->post('regimen'),
'substitution_reason'=>$this->input->post('regimen_reason'),
'substitution_date'=>$this->input->post('firstregimen_date')
);
//insert art start information
$artstartid = $this->Patient_model->add_multiple('artstart',$data['artstart']);
//get art registration data
$data['art'] = array(
'id' => '',
'clientid' => $unhexed_clientid,
'artstartid' => $artstartid,
'dateenrolled'=>$this->input->post('artstartdate'),
'whyeligible'=>$this->input->post('why'),
'careofentry'=> $careofentry,
'cohort' => $this->input->post('artstartdate')
);
//insert into art table
$artid = $this->Patient_model->add_multiple('art',$data['art']);
//insert into regimen
$this->Patient_model->add('regimen',$data['regimen']);
//update hivpatient table with the art ID
$updatecondition = "hex(clientid) = '".$clientid."'";
$data['mypatient'] = array(
'artid' => $artid
);
if($this->Patient_model->edit('hivpatients',$data['mypatient'],$updatecondition)){
$this->load->view('pages/success');
}else{
echo "Not successful";
}
}
//view ART patients
public function artpatients(){
//get information from hivpattients and clients to display
$condition = "hivpatients.clientid = clients.id AND hivpatients.artid IS NOT NULL";
$data['artpatient'] = $this->Patient_model->patient_join_client($condition);
//load view
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/datatables_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/art',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/datatables_js');
$this->load->view('templates/global/end_global_footer');
}
//view art card
public function view_art_card(){
$clientid = $this->input->post('id');
//get patient information
$condition = "hivpatients.clientid = clients.id AND hex(id) = '".$clientid."'";
$data['patientinfo'] = $this->Patient_model->patient_join_client($condition);
//get patient HTS record
$this->load->model('Hts_model');
$data['htsrecords'] = $this->Hts_model->get_client_hts($clientid);
//get total hts visits
$data['total_visits'] = count($data['htsrecords']);
//load ART model
$this->load->model('Art_model');
//get art information
$data['artinfo'] = $this->Art_model->getart_byclient($clientid);
//get art start info
foreach($data['artinfo'] as $art){
$artstartid = $art['artstartid']; //art start id
$artid = $art['id'];
}
$data['artstrartinfo'] = $this->Art_model->artstart_byid($artstartid);
//get first recorded health status
$data['firsthealth'] = $this->Patient_model->firststatus($clientid);
//get clinic, chief and district information
foreach($data['patientinfo'] as $patient){
$clinicid = $patient['clinicid'];
$chiefid = $patient['chiefid'];
$districtid = $patient['districtid'];
}
$this->load->model('Clinics_model');
$data['clinicinfo'] = $this->Clinics_model->get_clinics($clinicid);
$this->load->model('Chiefs_model');
$data['chiefinfo'] = $this->Chiefs_model->get_chiefs($chiefid);
$this->load->model('Districts_model');
$data['districtinfo'] = $this->Districts_model->get_district($districtid);
$this->load->model('Regimen_model');
$data['regimen'] = $this->Regimen_model->get_regimen($clientid);
//load the encounters and view
$this->load->model('Encounters_model');
$data['encounters'] = $this->Encounters_model->get_encounters($artid);
//load view
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/datatables_css');
$this->load->view('templates/global/user_profile_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/view_art_profile',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/datatables_js');
$this->load->view('templates/global/datatables-responsive_js');
$this->load->view('templates/global/end_global_footer');
}
//record encounters
public function record_encounter(){
$data['cid'] = $this->input->post('id');
$data['fname'] = $this->input->post('fullname');
$data['artid'] = $this->input->post('artid');
//load view
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/form_wizard_css');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/add_encounter',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/global/form_wizard_js');
$this->load->view('templates/global/end_global_footer');
}
}
?>
<file_sep><!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE BAR -->
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Dashboard</span>
</li>
</ul>
<div class="page-toolbar">
<div id="dashboard-report-range" class="pull-right tooltips btn btn-sm" data-container="body" data-placement="bottom" data-original-title="Change dashboard date range">
<i class="icon-calendar"></i>
<span class="thin uppercase hidden-xs"></span>
<i class="fa fa-angle-down"></i>
</div>
</div>
</div>
<!-- END PAGE BAR -->
<!-- BEGIN PAGE TITLE-->
<h1 class="page-title"> Population
<small>statistics of people tested</small>
</h1>
<!-- END PAGE TITLE-->
<!-- END PAGE HEADER-->
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="dashboard-stat2 ">
<div class="display">
<div class="number">
<h3 class="font-green-sharp">
<span data-counter="counterup" data-value="<?php echo $allHts; ?>">0</span>
</h3>
<small>TOTAL HTS Visits</small>
</div>
<div class="icon">
<i class="icon-pie-chart"></i>
</div>
</div>
<div class="progress-info">
<div class="progress">
<span style="width: 76%;" class="progress-bar progress-bar-success green-sharp">
<span class="sr-only">76% progress</span>
</span>
</div>
<div class="status">
<div class="status-title"> progress </div>
<div class="status-number"> 76% </div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="dashboard-stat2 ">
<div class="display">
<div class="number">
<h3 class="font-red-haze">
<span data-counter="counterup" data-value="<?php echo $allclients; ?>">0</span>
</h3>
<small>Total Clients</small>
</div>
<div class="icon">
<i class="icon-like"></i>
</div>
</div>
<div class="progress-info">
<div class="progress">
<span style="width: 85%;" class="progress-bar progress-bar-success red-haze">
<span class="sr-only">85% change</span>
</span>
</div>
<div class="status">
<div class="status-title"> change </div>
<div class="status-number"> 85% </div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="dashboard-stat2 ">
<div class="display">
<div class="number">
<h3 class="font-blue-sharp">
<span data-counter="counterup" data-value="<?php echo $allpatients; ?>"></span>
</h3>
<small>Positive Clients</small>
</div>
<div class="icon">
<i class="icon-basket"></i>
</div>
</div>
<div class="progress-info">
<div class="progress">
<span style="width: 45%;" class="progress-bar progress-bar-success blue-sharp">
<span class="sr-only">45% grow</span>
</span>
</div>
<div class="status">
<div class="status-title"> grow </div>
<div class="status-number"> 45% </div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="dashboard-stat2 ">
<div class="display">
<div class="number">
<h3 class="font-purple-soft">
<span data-counter="counterup" data-value="<?php echo $negativeclients; ?>"></span>
</h3>
<small>Negative Clients</small>
</div>
<div class="icon">
<i class="icon-user"></i>
</div>
</div>
<div class="progress-info">
<div class="progress">
<span style="width: 57%;" class="progress-bar progress-bar-success purple-soft">
<span class="sr-only">56% change</span>
</span>
</div>
<div class="status">
<div class="status-title"> change </div>
<div class="status-number"> 57% </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-xs-12 col-sm-12">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<i class="icon-cursor font-dark hide"></i>
<span class="caption-subject font-dark bold uppercase">General Stats</span>
</div>
<div class="actions">
<a href="javascript:;" class="btn btn-sm btn-circle red easy-pie-chart-reload">
<i class="fa fa-repeat"></i> Reload </a>
</div>
</div>
<div class="portlet-body">
<div class="row">
<div class="col-md-4">
<div class="easy-pie-chart">
<div class="number transactions" data-percent="55">
<span>+55</span>% </div>
<a class="title" href="javascript:;"> Transactions
<i class="icon-arrow-right"></i>
</a>
</div>
</div>
<div class="margin-bottom-10 visible-sm"> </div>
<div class="col-md-4">
<div class="easy-pie-chart">
<div class="number visits" data-percent="85">
<span>+85</span>% </div>
<a class="title" href="javascript:;"> New Visits
<i class="icon-arrow-right"></i>
</a>
</div>
</div>
<div class="margin-bottom-10 visible-sm"> </div>
<div class="col-md-4">
<div class="easy-pie-chart">
<div class="number bounce" data-percent="46">
<span>-46</span>% </div>
<a class="title" href="javascript:;"> Bounce
<i class="icon-arrow-right"></i>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-6 col-xs-12 col-sm-12">
<div class="portlet light ">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-dark hide"></i>
<span class="caption-subject font-dark bold uppercase">Server Stats</span>
<span class="caption-helper">monthly stats...</span>
</div>
<div class="tools">
<a href="" class="collapse"> </a>
<a href="#portlet-config" data-toggle="modal" class="config"> </a>
<a href="" class="reload"> </a>
<a href="" class="remove"> </a>
</div>
</div>
<div class="portlet-body">
<div class="row">
<div class="col-md-4">
<div class="sparkline-chart">
<div class="number" id="sparkline_bar5"></div>
<a class="title" href="javascript:;"> Network
<i class="icon-arrow-right"></i>
</a>
</div>
</div>
<div class="margin-bottom-10 visible-sm"> </div>
<div class="col-md-4">
<div class="sparkline-chart">
<div class="number" id="sparkline_bar6"></div>
<a class="title" href="javascript:;"> CPU Load
<i class="icon-arrow-right"></i>
</a>
</div>
</div>
<div class="margin-bottom-10 visible-sm"> </div>
<div class="col-md-4">
<div class="sparkline-chart">
<div class="number" id="sparkline_line"></div>
<a class="title" href="javascript:;"> Load Rate
<i class="icon-arrow-right"></i>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<file_sep><?php
class Patients_not extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('Patient_model');
$this->load->helper('url_helper');
}
public function view($page = 'home'){
if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
// $data['title'] = ucfirst($page); // Capitalize the first letter
$this->load->view('templates/global/start_global_head');
if( file_exists(APPPATH.'views/templates/'.$page.'_level_header.php')){
$this->load->view('templates/'.$page.'_level_header');
}
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/'.$page);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer.php');
if( file_exists(APPPATH.'views/templates/'.$page.'_level_plugin.php')){
$this->load->view('templates/'.$page.'_level_plugin');
}
$this->load->view('templates/global/end_global_footer');
}
public function all_hts(){
$data['visits'] = $this->Patient_model->get_hts();
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/view_hts_visits_level_header');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/view_hts_visits',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer');
$this->load->view('templates/view_hts_visits_level_plugin');
$this->load->view('templates/global/end_global_footer');
}
public function view_hts(){
$data['single_patient'] = $this->Patient_model->get_patients($unique_number);
}
//register HTS visit
public function register_hts(){
$this->load->helper('form');
$this->load->library('form_validation');
//fields to validate. set_rules(the name of the input field, the name to be used in error messages, and the rule.)
$this->form_validation->set_rules('date','Date','required');
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('surname', 'Surname','required');
$this->form_validation->set_rules('number', 'Number','required');
$this->form_validation->set_rules('hiv_status', 'HIV Status','required');
if($this->form_validation->run()===FALSE){
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/hts_regiter');
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer.php');
$this->load->view('templates/global/end_global_footer.php');
}else{
$data = array(
'Name' => $this->input->post('name'),
'Surname' => $this->input->post('surname'),
'Number' => $this->input->post('number'),
'Hiv_status' => $this->input->post('hiv_status'),
'Registration_date' => $this->input->post('date'),
'Gender' => $this->input->post('gender'),
'Age' => $this->input->post('age'),
'Visits' => $this->input->post('visits'),
'Last_visit' => $this->input->post('date'),
'Comments' => $this->input->post('comments')
);
$this->Patient_model->add('htsvisits',$data);
$this->load->view('pages/success');
}
}
public function register_preart(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Clinics_model');
//get the clinic model to select clinics
$data['clinic'] = $this->Clinics_model->get_clinics();
//validation rules
$this->form_validation->set_rules('p_hivcare_enrolment','HIV Care Enrollment','required');
if($this->form_validation->run()===FALSE){
$this->load->view('templates/global/start_global_head');
$this->load->view('templates/preart_register_level_header');
$this->load->view('templates/global/end_global_head');
$this->load->view('templates/global/horizontal_nav');
$this->load->view('templates/global/sidebar_nav');
$this->load->view('pages/preart_register',$data);
$this->load->view('templates/global/quickside_bar');
$this->load->view('templates/global/start_global_footer.php');
$this->load->view('templates/preart_register_level_plugin');
$this->load->view('templates/global/end_global_footer.php');
}else{
//set unique number to Not Applicable NA, for pre-art Registration
$unique_num = "NA";
//get patient info from view
$patient_data = array(
'unique_number' => $unique_num,
'name' => $this->input->post('p_name'),
'surname' => $this->input->post('p_surname'),
'gender' => $this->input->post('p_gender'),
'age' => $this->input->post('p_age'),
'dob' => $this->input->post('p_dob'),
'marital_status' => $this->input->post('p_marital_status'),
'address' => $this->input->post('p_address'),
'phone' => $this->input->post('p_phone'),
'confirmed_hiv_date' => $this->input->post('p_hivdate'),
'hivcare_enrolment' => $this->input->post('p_hivcare_enrolment'),
'clinic_id' => $this->input->post('clinic_id'),
'clinic_number_id' => $this->input->post('clinic_id')
);
//insert into patient and get last insert id to use in aditional info table
$patient_id = $this->Patient_model->add_multiple('patients',$patient_data);
//get patient additional info from view if not empty
if(!empty($this->input->post('inh_start') ||
$this->input->post('inh_start') ||
$this->input->post('ctx_start') ||
$this->input->post('ctx_stop') ||
$this->input->post('fca_start') ||
$this->input->post('fca_stop') ||
$this->input->post('tb_start') ||
$this->input->post('tb_stop') ||
$this->input->post('pregnancy') ||
$this->input->post('dead_date') ||
$this->input->post('lost_to') ||
$this->input->post('lost_to_date') ||
$this->input->post('registration_clinical_stage') ||
$this->input->post('registration_clinical_stage_date'))){
$additional_data = array(
'inh_start' => $this->input->post('inh_start'),
'inh_stop' => $this->input->post('inh_stop'),
'ctx_start' => $this->input->post('ctx_start'),
'ctx_stop' => $this->input->post('ctx_stop'),
'fca_start' => $this->input->post('fca_start'),
'fca_stop' => $this->input->post('fca_stop'),
'tb_start' => $this->input->post('tb_start'),
'tb_stop' => $this->input->post('tb_stop'),
'pregnancy' => $this->input->post('pregnancy'),
'dead_date' => $this->input->post('dead_date'),
'lost_to' => $this->input->post('lost_to'),
'lost_to_date' => $this->input->post('lost_to_date'),
'registration_clinical_stage' => $this->input->post('registration_clinical_stage'),
'registration_clinical_stage_date' => $this->input->post('registration_clinical_stage_date'),
'id' => $patient_id//last insert id from model patient file
);
$this->Patient_model->add('art_additional_info',$additional_data);
$this->load->view('pages/success');
}
//get clinical info
}
}
}
?>
<file_sep><!-- RESPONSIVE SCRIPTS -->
<script src="<?php echo base_url(); ?>assets/pages/scripts/table-datatables-responsive.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<file_sep><?php
class Users extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url_helper');
$this->load->helper('form');
$this->load->model('User_model');
}
public function login_view(){
$this->load->view('templates/global/loginhead');
$this->load->view('pages/login');
$this->load->view('templates/global/loginfooter');
}
public function login(){
}
public function register_user(){
}
/*
* User account information
*/
public function access_map(){
return array(
'index'=>'view',
'update'=>'edit'
);
}
public function account(){
$data = array();
if($this->session->userdata('isUserLoggedIn')){ //user is logged in
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
//load the view
$this->load->view('users/account', $data);
}else{
redirect('users/login');
}
}
/*
* User login
*/
public function __login(){
$data = array();
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
if($this->input->post('loginSubmit')){
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>');
if ($this->form_validation->run() == true) {
$con['returnType'] = 'single';
$con['conditions'] = array(
'email'=>$this->input->post('email'),
'password' => md5($this->input->post('password')),
'status' => '1'
);
$checkLogin = $this->user->getRows($con);
if($checkLogin){
$this->session->set_userdata('isUserLoggedIn',TRUE);
$this->session->set_userdata('userId',$checkLogin['id']);
redirect('users/account/');
}else{
$data['error_msg'] = 'Wrong email or password, please try again.';
}
}
}
//load the view
$this->load->view('users/login', $data);
}
}
?>
<file_sep><?php
class Hts extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('Hts_model');
$this->load->helper('url_helper');
$this->load->helper('url');
}
//record hts
public function record_hts(){
//load helper and validation
$this->load->helper('form');
$this->load->library('form_validation');
//fields to validate. set_rules(the name of the input field, the name to be used in error messages, and the rule.)
$this->form_validation->set_rules('date','Provide Date','required');
$this->form_validation->set_rules('hiv_status', 'Provide HIV Status','required');
if($this->form_validation->run()===FALSE){
}else{
//get client id and unhex it
$client = $this->input->post('id');
$clientid = $this->Hts_model->unhexid($client);
//get posted data
$data = array(
'id' =>'',
'clientid' => $clientid,
'date' => $this->input->post('date'),
'nextdate' => $this->input->post('next_date'),
'hivstatus' => $this->input->post('hiv_status')
);
//insert into hts
$this->Hts_model->recordhts($data);
$this->session->set_flashdata('clientid',$client);
redirect('Clients/view_client_profile');
//$this->load->view('pages/success');
}
}
/*
public function record(){
//load helper and validation
$this->load->helper('form');
$this->load->library('form_validation');
//fields to validate. set_rules(the name of the input field, the name to be used in error messages, and the rule.)
$this->form_validation->set_rules('date','Provide Date','required');
$this->form_validation->set_rules('hiv_status', 'Provide Surname','required');
if($this->form_validation->run()==FALSE){
$this->load->view('pages/view_client');
}else{
if(!empty($this->input->post('id'))){
$clientid = $this->Clients_model->unhexid($this->input->post('id'))
$table = 'hts';
$data = array(
'id' =>'',
'clientid' => $this->input->post('id'),
'date' => $this->input->post('date'),
'nextdate' => $this->input->post('next_date'),
'hivstatus' => $this->input->post('hiv_status')
);
$this->Hts_model->recordhts($table,$data);
$this->load->view('pages/success');
}
}
}*/
}
?>
<file_sep><!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="<?php echo base_url(); ?>assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/bootstrap-wizard/jquery.bootstrap.wizard.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="<?php echo base_url(); ?>assets/pages/scripts/form-wizard.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<file_sep><!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="<?php echo base_url(); ?>assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<file_sep><!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="<?php echo base_url(); ?>assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link href="<?php echo base_url(); ?>assets/pages/css/profile-2.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL STYLES -->
<file_sep><?php
class Regimen_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_regimen($clientid = FALSE){
if($clientid === FALSE){
$query = $this->db->get('regimen');
return $query->result_array();
}
$query = $this->db->get_where('regimen',array('hex(clientid)'=>$clientid));
return $query->result_array();
}
}
?>
<file_sep><!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="<?php echo base_url(); ?>assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/gmaps/gmaps.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<file_sep><?php
class Hts_model extends CI_Model{
public function __construct(){
$this->load->database();
}
//get hts for a specific client
public function get_client_hts($clientid){
$this->db->select('hivstatus, date, nextdate');
$this->db->from('hts');
$this->db->where('hex(clientid)',$clientid);
$query = $this->db->get()->result_array();
return $query;
}
//global get with id
public function get_hts_byid($clientid){
$query = $this->db->get_where('hts', array('hex(clientid)'=>$clientid));
return $query->result_array();
}
//convert string to binary in mysql
public function getbinary($clientid){
$query = $this->db->select("CAST('".$clientid."' AS BINARY) AS uid");
$row = $query->get()->row();
$uuid = $row->uid;
return $uuid;
}
//get all hts
public function get_hts(){
$query = $this->db->get('hts');
return $query->result_array();
}
//get all hts
public function get_hts_num(){
$query = $this->db->get('hts');
return $query->num_rows();
}
//global insert
public function recordhts($data=array()){
$this->db->insert('hts',$data);
}
//unhex the client ID so that we store it as binary
public function unhexid($clientid){
$query = $this->db->select("unhex('".$clientid."') AS uid"); //be careful to place the var into quotes else mysql returns NULL
$row = $query->get()->row();
$uuid = $row->uid;
return $uuid;
}
public function hexid($clientid){
$query = $this->db->select("hex('".$clientid."') AS uid");
$row = $query->get()->row();
$uid = $row->uid;
return $uid;
}
}
?>
| bcf2454c588ed5cde0ce8b5f410b0f08603749c5 | [
"Markdown",
"PHP"
] | 35 | PHP | ramataboee/hivehr | bcdf29b6649dba7e5d45c95f19832bea50234348 | dcb15f9e986997df84fe95d4ef244a3a6670206e |
refs/heads/master | <file_sep>======================
django-adlh-utils
======================
A collection of scripts and template helpers
Quick start
-----------
1) Add ap to settings.py:
```python
# setting.py
INSTALLED_APPS = (
...
'adlh_utils',
)
```
2) Use the utils on your models.
```python
from adlh_utils.model_utils import resize_image_on_upload
#....
post_save.connect(resize_image_on_upload, sender=Image)
```
3) That's it!
<file_sep>from setuptools import setup, find_packages
setup(
name='django-adlh-utils',
version='1.0',
description='A collection of scripts and template helpers',
url='https://github.com/adlh/django-adlh-utils',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 2.2',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
package_dir={'': 'src'},
packages=find_packages(where='src'),
python_requires='>=3.5, <4',
install_requires=['Django', 'Pillow'],
project_urls={
'Bug Reports': 'https://github.com/adlh/django-adlh-utils',
'Source': 'https://github.com/adlh/django-adlh-utils',
},
)
<file_sep>from django import template
from django.conf import settings
import logging
register = template.Library()
logger = logging.getLogger(__name__)
@register.simple_tag
def i18n_url_switch(request, language):
#print(request)
if not hasattr(request, 'path'):
return '#'
request_parts = (request.path).strip('/').split('/')
langs = settings.LANGUAGES
if isinstance(langs, tuple):
if language in [tup[0] for tup in langs]:
request_parts[0] = language
return '/' + '/'.join(request_parts) + '/'
return request.path
<file_sep># coding=UTF-8
from PIL import Image
from django.conf import settings
import os
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
def resize_image_on_upload(*args, **kwargs):
logger.debug('... starting resizing on post_save signal ... ')
obj = kwargs.get("instance", None)
if not obj:
logger.error(' error, no instance! exiting without resizing. ')
return
im_file = getattr(obj, 'image', None)
if not im_file:
logger.error(' error, could not get image from instance! exiting without resizing. ')
return
max_width = 800
max_height = 800
try:
im = Image.open(im_file.path)
except:
logger.error(' error, could not open image! exiting without resizing. ')
return
logger.debug("Image '%s' has size (%d, %d) and limits are (%d, %d)" % (im_file.name, im.size[0], im.size[1], max_width, max_height))
if im.size[0] > max_width or im.size[1] > max_height:
logger.debug('... resizing')
try:
rtc = os.popen("gm convert %(file)s -resize %(width)dx%(height)d %(file)s" % {'file': im_file.path, 'width': max_width, 'height': max_height})
logger.debug('resized image')
except:
logger.error("couldn't resize image!")
| 3147c047fa3ed54a8fe70aa4922df72c919d981d | [
"Markdown",
"Python"
] | 4 | Markdown | adlh/django-adlh-utils | 52e6e929f837502a947294d628a9dc2b7411c6aa | 4a92a7cbdf20e034a2c624fcea4d09dd042fa1a5 |
refs/heads/main | <file_sep>const menu = document.querySelector('#mobile-menu');
const menuLinks = document.querySelector('.navbar__menu');
const navLogo = document.querySelector('#navbar__logo');
const mobileMenu = () => {
menu.classList.toggle('is-active');
menuLinks.classList.toggle('active');
};
menu.addEventListener('click', mobileMenu);
const highlightMenu = () => {
const elem = document.querySelector('.highlight');
const homeMenu = document.querySelector('#home-page');
const aboutMenu = document.querySelector('#about-page');
const servicesMenu = document.querySelector('#services-page');
let scrollPos = window.scrollY;
console.log(scrollPos);
if (window.innerWidth > 960 && scrollPos < 600) {
homeMenu.classList.add('highlight');
aboutMenu.classList.remove('highlight');
return;
} else if (window.innerWidth > 960 && scrollPos < 1400) {
aboutMenu.classList.add('highlight');
homeMenu.classList.remove('highlight');
servicesMenu.classList.remove('highlight');
return;
} else if (window.innerWidth > 960 && scrollPos < 2345) {
servicesMenu.classList.add('highlight');
aboutMenu.classList.remove('highlight');
return;
}
if ((elem && window.innerWIdth < 960 && scrollPos < 600) || elem) {
elem.classList.remove('highlight');
}
};
window.addEventListener('scroll', highlightMenu);
window.addEventListener('click', highlightMenu);
const hideMobileMenu = () => {
const menuBars = document.querySelector('.is-active');
if (window.innerWidth <= 768 && menuBars) {
menu.classList.toggle('is-active');
menuLinks.classList.remove('active');
}
};
menuLinks.addEventListener('click', hideMobileMenu);
navLogo.addEventListener('click', hideMobileMenu);
//popup
document.getElementById("button").addEventListener("click", function(){
document.querySelector(".popup").style.display = "flex";
})
document.querySelector(".close").addEventListener("click", function(){
document.querySelector(".popup").style.display = "none";
})
//forma
const form =document.getElementById('form');
const username =document.getElementById('username');
const password =document.getElementById('password');
const email =document.getElementById('email');
const password2 =document.getElementById('password2');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs(){
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if(usernameValue === ''){
prikaziGreskuZa(username, 'Username ne moze biti prazan!');
}
else{
prikaziTacnoZa(username);
}
if(emailValue === ''){
prikaziGreskuZa(email, 'Email ne moze biti prazan!');
}
else if(!jeEmial(emailValue)){
prikaziGreskuZa(email, 'Email nije ispravan!');
}
else{
prikaziTacnoZa(email);
}
if(passwordValue === ''){
prikaziGreskuZa(password, 'Password ne moze biti prazan!');
}
else{
prikaziTacnoZa(password);
}
if(password2Value === ''){
prikaziGreskuZa(password2, 'PasswordTwo ne moze biti pr<PASSWORD>!');
}
else if(password2Value !== passwordValue){
prikaziGreskuZa(password2, 'Password nije isti!');
}
else{
prikaziTacnoZa(password2);
}
}
function prikaziGreskuZa(input, message){
const formControl = input.parentElement;
const small = formControl.querySelector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function prikaziTacnoZa(input){
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
//jQuery toggle
$(document).ready(function(){
$('#iskljuci').click(function(){
$('#sakrititext').slideToggle('slow');
if($('#sakrititext').is(':visible')){
$(this).val('Hide - Show');
}
else{
$(this).val('Show - Hide');
}
});
}); | 4e7d8b39d4653d0376025d1bfe2f8ca5e3862a49 | [
"JavaScript"
] | 1 | JavaScript | Mikicaa97/Code-No1 | a3583fff6317c4827439f52a7cbf423e23afc504 | 04159af552af6ac941c45ab012ce4f38901cbf07 |
refs/heads/master | <repo_name>MicroCreativity/youngtao-table<file_sep>/js/youngtao.js
(function ($) {
'use strict';
var calculateObjectValue = function(self, name, args){
var func = name;
if (typeof func === 'function') {
return func.apply(self, args);
}
}
var callBack = function(method,value,row,i){
if(method){
var func=eval(method);
if(!func){
throw new Error(method + ' function is no defined');
}
return func(value,row,i);
}else{
return value;
}
}
var YoungTao = function(el,options){
this.$el = $(el);
this.options = options;
this.init();
};
YoungTao.DEFAULTS = {
currentPage: 1,
pageSize: 10,
pageList: [10, 25, 50, 100],
queryParams : undefined,
type : "GET",
dataField : "datas",
totalPageField : "totalPage",
totalRecordField : "totalRecord",
checkboxName : 'checkbox',
loadCompleteExe : undefined
};
YoungTao.LOCALES = {};
YoungTao.LOCALES['zh_CN'] = {
formatLoadingMessage: function () {
return '正在拼命加载数据中,请稍后......';
},
formatRecordsPerPage: function (pageNumber) {
return '每页显示 ' + pageNumber + ' 条记录';
},
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录,总共 ' + totalRows + ' 条记录';
},
formatNoMatches: function () {
return '没有找到匹配的记录';
}
};
$.extend(YoungTao.DEFAULTS, YoungTao.LOCALES['zh_CN']);
var allowedMethods = [
'getOptions',
'refreshOptions',
'getSelectedList'
];
YoungTao.prototype = {
getOptions : function (page) {
return page;
},
refreshOptions : function(options){
var queryParams = options.queryParams;
var params = queryParams(this.options);
this.options = $.extend(this.options,params);
this.initData();
},
getSelectedList : function(){
var getSelectedList = [],that = this;
this.$el.find('>tbody tr input[type="checkbox"]').each(function(i,item){
if($(this).is(':checked')){
getSelectedList.push(that.data_["data_" + i]);
}
});
return getSelectedList;
},
onpageSizeChange : function(even){
this.options = $.extend(this.options, {
pageSize : $(even.currentTarget).val(),
currentPage : 1
});
this.initData();
},
onPageFirst : function(even){
if (even && $(even.currentTarget).parent().hasClass('disabled')) return false;
this.options = $.extend(this.options, {currentPage : 1});
this.initData();
},
onPagePre : function(even){
if (even && $(even.currentTarget).parent().hasClass('disabled')) return false;
this.options = $.extend(this.options, {currentPage : (parseInt(this.options.currentPage) - 1)});
this.initData();
},
onPageNumber : function(even){
if (even && $(even.currentTarget).parent().hasClass('disabled')) return false;
this.options = $.extend(this.options, {currentPage : $(even.currentTarget).text()});
this.initData();
},
onPageNext : function(even){
if (even && $(even.currentTarget).parent().hasClass('disabled')) return false;
console.log(this.options.currentPage);
console.log((parseInt(this.options.currentPage) + 1));
this.options = $.extend(this.options, {currentPage : (parseInt(this.options.currentPage) + 1)});
this.initData();
},
onPageLast : function(even){
if (even && $(even.currentTarget).parent().hasClass('disabled')) return false;
this.options = $.extend(this.options, {currentPage : this.totalPages});
this.initData();
},
init : function(){
this.initLocale();
this.initField();
this.initTitle();
this.initData();
},
initLocale : function () {
if (this.options.locale) {
var parts = this.options.locale.split(/-|_/);
parts[0].toLowerCase();
if (parts[1]) parts[1].toUpperCase();
if ($.fn.youngTao.locales[this.options.locale]) {
// locale as requested
$.extend(this.options, $.fn.youngTao.locales[this.options.locale]);
} else if ($.fn.youngTao.locales[parts.join('-')]) {
// locale with sep set to - (in case original was specified with _)
$.extend(this.options, $.fn.youngTao.locales[parts.join('-')]);
} else if ($.fn.youngTao.locales[parts[0]]) {
// short locale language code (i.e. 'en')
$.extend(this.options, $.fn.youngTao.locales[parts[0]]);
}
}
},
initData : function(){
var that = this;
var params = {
currentPage : this.options.currentPage,
pageSize : this.options.pageSize
};
that.$el.find('>tbody').remove();
$('<tbody id="tableloading" style="text-align: center;"><tr><td colspan='+ this.columns_.length +'>'+ this.options.formatLoadingMessage() +'</td></tr></tbody>').appendTo(that.$el);
params = $.extend(params, this.options.queryParams);
$.utils.ajax({
url : this.options.url,
type : this.options.type,
data : params,
success : function(res){
res = calculateObjectValue(that.options, that.options.responseHandler, [res]);
that.initBody(res);
},
error : function(res){
res = calculateObjectValue(that.options, that.options.responseHandler, [res]);
that.initBody(res);
}
});
},
initField : function(){
var columns = [];
var columnsTitle = [];
var columnsFormatter = [];
this.$el.find('th').each(function (i) {
columns.push($(this).attr("data-field"));
columnsTitle.push($(this).attr("data-title"));
columnsFormatter.push($(this).attr("data-formatter"));
});
this.columnsFormatter_ = columnsFormatter;
this.columnsTitle_ = columnsTitle;
this.columns_ = columns;
},
initTitle : function(){
var that = this;
$.each(that.columnsTitle_,function(i,item){
var title = that.$el.find('th')[i];
$(title).html(item ? item : '');
});
},
initBody : function(data){
var that = this;
that.$body = that.$el.find('>tbody');
if (!that.$body.length) {
that.$body = $('<tbody style="text-align: center;"></tbody>').appendTo(that.$el);
}
var tbodyHtml = [];
var item_ = {};
$.each(data[this.options.dataField],function(i,item){
item_["data_" + i] = item;
if(i % 2 != 0){
tbodyHtml.push('<tr class="warning">');
}else{
tbodyHtml.push('<tr>');
}
$.each(that.columns_,function(j,colimnItems){
var method = that.columnsFormatter_[j];
var value = colimnItems ? item[colimnItems] : '';
if(that.options.checkboxName == colimnItems){
tbodyHtml.push(' <td style="text-align: center;">');
tbodyHtml.push(' <input type="checkbox" class="flat-red">');
tbodyHtml.push(' </td>');
}else{
var result = callBack(method,value,item,j);
tbodyHtml.push(' <td>');
tbodyHtml.push(result);
tbodyHtml.push(' </td>');
}
});
tbodyHtml.push('</tr>');
});
this.data_ = item_;
that.$body.html(tbodyHtml.join(''));
this.initFoots(data);
if (typeof that.options.loadCompleteExe === 'function') {
that.options.loadCompleteExe();
}
var checkAll = that.$el.find('>thead th input[type="checkbox"]');
var tbodyTr = that.$el.find('>tbody tr');
checkAll.on('ifChecked ifUnchecked',function(event){
if (event.type == 'ifChecked') {
tbodyTr.find('input[type="checkbox"]').iCheck('check');
} else {
tbodyTr.find('input[type="checkbox"]').iCheck('uncheck');
}
});
tbodyTr.on('click',function(event){
if(!$(this).find('input[type="checkbox"]').is(':checked')){
$(this).find('input[type="checkbox"]').iCheck('check');
}else{
$(this).find('input[type="checkbox"]').iCheck('uncheck');
}
var checkboxes = that.$el.find('>tbody tr input[type="checkbox"]');
if(checkboxes.filter(':checked').length == checkboxes.length) {
checkAll.prop('checked', 'checked');
} else {
checkAll.removeProp('destroy');
}
checkAll.iCheck('update');
});
},
initFoots : function(data){
var that = this;
that.$el.parent().find(".tableFoots").remove();
that.$el.parent().find(".pagination").remove();
var currentPage = this.options.currentPage;
var pageSize = this.options.pageSize;
var pageFrom = currentPage == 1 ? 1 : ((currentPage - 1) * pageSize) + 1;
var pageTo = ((currentPage - 1) * pageSize) + data[this.options.dataField].length;
var selectHtml = [];
selectHtml.push('<select class="pageSizeChange" data-am-selected="{searchBox: 1}">');
$.each(this.options.pageList,function(i,item){
selectHtml.push('<option '+ (item == pageSize ? 'selected="selected"' : '') +' value="'+ item +'">'+ item +'</option>');
});
selectHtml.push('</select>');
var recordHtml = [];
recordHtml.push('<div class="tableFoots" style="font-size: 14px;padding-bottom: 10px;" class="am-cf">');
recordHtml.push(this.options.formatShowingRows(pageFrom,pageTo,data[this.options.totalRecordField]));
recordHtml.push(" " + this.options.formatRecordsPerPage(selectHtml.join('')));
recordHtml.push('</div>');
that.$el.after(recordHtml.join(''));
that.$el.parent().find('.pageSizeChange').off('change').on('change',$.proxy(this.onpageSizeChange,this));
this.totalPages = data[this.options.totalPageField];
if(this.totalPages > 1){
var pageRecord = [];
var from = 1;
var to = this.totalPages;
if(this.totalPages >= 5){
from = currentPage - 2;
to = from + 4;
if(from < 1){
from = 1;
to = 5;
}
if(to > this.totalPages){
to = this.totalPages;
from = to -4;
}
}
for(var i = from;i <= to; i++ ){
pageRecord.push('<li class="page-number '+ (currentPage == i ? 'active' : '') +'"><a href="javascript:void(0);">'+ i +'</a></li>');
}
var pageHtml = [];
pageHtml.push('<ul class="pagination">');
pageHtml.push(' <li class="page-first '+ (currentPage == 1 ? 'disabled' : '') +'"><a href="javascript:void(0);">首页</a></li>');
pageHtml.push(' <li class="page-pre '+ (currentPage == 1 ? 'disabled' : '') +'"><a href="javascript:void(0);">上一页</a></li>');
pageHtml.push( pageRecord.join(''));
pageHtml.push(' <li class="page-next '+ (currentPage == this.totalPages ? 'disabled' : '') +'"><a href="javascript:void(0);">下一页</a></li>');
pageHtml.push(' <li class="page-last '+ (currentPage == this.totalPages ? 'disabled' : '') +'"><a href="javascript:void(0);">尾页</a></li>');
pageHtml.push(' </ul>');
that.$el.after(pageHtml.join(''));
that.$el.parent().find('.page-first a').off('click').on('click',$.proxy(this.onPageFirst,this));
that.$el.parent().find('.page-pre a').off('click').on('click',$.proxy(this.onPagePre,this));
that.$el.parent().find('.page-number a').off('click').on('click',$.proxy(this.onPageNumber,this));
that.$el.parent().find('.page-next a').off('click').on('click',$.proxy(this.onPageNext,this));
that.$el.parent().find('.page-last a').off('click').on('click',$.proxy(this.onPageLast,this));
}
}
};
$.fn.youngTao = function(option){
var value,
$this = $(this),
data = $this.data('bootstrap.table'),
args = Array.prototype.slice.call(arguments, 1),
options = $.extend({}, YoungTao.DEFAULTS, $this.data(),typeof option === 'object' && option);
if (typeof option === 'string') {
if($.inArray(option,allowedMethods) < 0){
throw new Error('Unknown method: ' + option);
}
if (!data) {
throw new Error('Please init object');
}
value = data[option].apply(data, args);
if (option === 'destroy') {
$this.removeData('bootstrap.table');
}
}
if (!data) {
$this.data('bootstrap.table', (data = new YoungTao(this, options)));
}
return typeof value === 'undefined' ? this : value;
};
$.fn.youngTao.Constructor = YoungTao;
$.fn.youngTao.locales = YoungTao.LOCALES;
})(jQuery); | d3d05f0374d6db9a5e18dc9dcf3f9f784246ec4f | [
"JavaScript"
] | 1 | JavaScript | MicroCreativity/youngtao-table | 34338074c697826bcbe160b78776cd2d1926b483 | 79a48cff6ee35d0a1d8860c021eed20871f8bffd |
refs/heads/master | <repo_name>omirror/wsgnatsd<file_sep>/server/conf.go
package server
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/nats-io/nats-server/v2/conf"
"github.com/nats-io/nats-server/v2/logger"
)
type Opts struct {
CaFile string
CertFile string
Debug bool
Dir string
KeyFile string
Logger *logger.Logger
PidDir string
Port int
RemoteNatsHostPort string
NatsHostPort string
TextFrames bool
Trace bool
WSHostPort string
}
func DefaultOpts() Opts {
var c Opts
c.Port = -1
c.WSHostPort = "127.0.0.1:0"
c.PidDir = os.Getenv("TMPDIR")
return c
}
func LoadOpts(fp string) (*Opts, error) {
b, err := ioutil.ReadFile(fp)
if err != nil {
return nil, fmt.Errorf("error reading configuration file: %v", err)
}
return ParseOpts(string(b))
}
func ParseOpts(c string) (*Opts, error) {
m, err := conf.Parse(c)
if err != nil {
return nil, err
}
var o Opts
for k, v := range m {
k = strings.ToLower(k)
switch k {
case "cafile":
v, err := parseStringValue(k, v)
if err != nil {
panic(err)
}
o.CaFile = v
case "certfile":
v, err := parseStringValue(k, v)
if err != nil {
panic(err)
}
o.CertFile = v
case "debug":
v, err := parseBooleanValue(k, v)
if err != nil {
panic(err)
}
o.Debug = v
case "dir":
v, err := parseStringValue(k, v)
if err != nil {
panic(err)
}
o.Dir = v
case "keyfile":
v, err := parseStringValue(k, v)
if err != nil {
panic(err)
}
o.KeyFile = v
case "piddir":
v, err := parseStringValue(k, v)
if err != nil {
panic(err)
}
o.PidDir = v
case "port":
v, err := parseIntValue(k, v)
if err != nil {
panic(err)
}
o.Port = v
case "remotenatshostport":
v, err := parseStringValue(k, v)
if err != nil {
panic(err)
}
o.RemoteNatsHostPort = v
case "textframes":
v, err := parseBooleanValue(k, v)
if err != nil {
panic(err)
}
o.TextFrames = v
case "trace":
v, err := parseBooleanValue(k, v)
if err != nil {
panic(err)
}
o.Trace = v
case "wshostport":
v, err := parseStringValue(k, v)
if err != nil {
panic(err)
}
o.Dir = v
default:
return nil, fmt.Errorf("error parsing store configuration. Unknown field %q", k)
}
}
return &o, nil
}
func parseIntValue(keyName string, v interface{}) (int, error) {
i := 0
var err error
switch t := v.(type) {
case int, int8, int16, int32, int64:
i = t.(int)
case string:
i, err = strconv.Atoi(v.(string))
if err != nil {
err = fmt.Errorf("error parsing %s option %v as a int", keyName, v)
}
default:
err = fmt.Errorf("unable to parse integer: %v", v)
}
return i, err
}
func parseStringValue(keyName string, v interface{}) (string, error) {
sv, ok := v.(string)
if !ok {
return "", fmt.Errorf("error parsing %s option %q", keyName, v)
}
return sv, nil
}
func parseBooleanValue(keyname string, v interface{}) (bool, error) {
switch t := v.(type) {
case bool:
return bool(t), nil
case string:
sv := v.(string)
return strings.ToLower(sv) == "true", nil
default:
return false, fmt.Errorf("error parsing %s option %q as a boolean", keyname, v)
}
}
<file_sep>/server/assertserver.go
package server
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/mitchellh/go-homedir"
)
type AssetsServer struct {
*Opts
s *http.Server
l net.Listener
}
func NewAssetsServer(conf *Opts) (*AssetsServer, error) {
if conf.Port == 0 {
return nil, nil
}
d, err := homedir.Expand(conf.Dir)
if err != nil {
return nil, err
}
d, err = filepath.Abs(d)
if err != nil {
return nil, err
}
conf.Dir = d
fi, err := os.Stat(conf.Dir)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf("%q is not a directory", conf.Dir)
}
conf.Logger.Noticef("serving assets from %q", conf.Dir)
var server AssetsServer
server.Opts = conf
return &server, nil
}
func (s *AssetsServer) filter() http.Handler {
protocol := "ws"
if s.Opts.CertFile != "" {
protocol = "wss"
}
WSURL := fmt.Sprintf("%s://%s", protocol, s.WSHostPort)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// FIXME: this is a simple SSI include function, likely has security issues
// FIXME: this is non portable since the file access code assumes slashes
fp := filepath.Join(s.Opts.Dir, r.URL.Path)
// make the request path absolute
fp, err := filepath.Abs(fp)
if err != nil {
s.Logger.Errorf("failed to calculate abs for %q: %v", fp, err)
http.Error(w, "", http.StatusBadRequest)
return
}
// if the calculated path doesn't begin with the servers data dir,
// we are outside the servers data directory
if strings.Index(fp, s.Opts.Dir) != 0 {
s.Logger.Errorf("request outside data dir %q", fp)
http.Error(w, "", http.StatusBadRequest)
return
}
f, err := os.Open(fp)
if err != nil {
if os.IsNotExist(err) {
s.Logger.Noticef("GET %q 404", fp)
http.Error(w, "", http.StatusNotFound)
return
}
s.Logger.Errorf("%v", fp, err)
http.Error(w, "", http.StatusInternalServerError)
return
}
defer f.Close()
d, err := ioutil.ReadAll(f)
if err != nil {
s.Logger.Errorf("error reading %q: %v", fp, err)
}
d = bytes.ReplaceAll(d, []byte("{{WSURL}}"), []byte(WSURL))
s.Logger.Noticef("GET %q", fp)
w.Write(d)
})
}
func (s *AssetsServer) Start() error {
hp := fmt.Sprintf("0.0.0.0:%d", s.Port)
l, err := CreateListen(hp, s.Opts)
if err != nil {
return err
}
s.l = l
s.s = &http.Server{
ErrorLog: log.New(os.Stderr, "ws", log.LstdFlags),
Handler: s.filter(),
}
s.Logger.Noticef("Listening for asset requests on %v\n", hostPort(s.l))
go func() {
if err := s.s.Serve(s.l); err != nil {
// we orderly shutdown the s?
if !strings.Contains(err.Error(), "Server closed") {
s.Logger.Fatalf("assetserver error: %v\n", err)
panic(err)
}
}
s.s.Handler = nil
s.s = nil
s.Logger.Noticef("asset server has stopped\n")
}()
return nil
}
func (s *AssetsServer) Shutdown() {
if s.s != nil {
s.s.Shutdown(context.TODO())
}
}
<file_sep>/main.go
package main
import (
"errors"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
"github.com/aricart/wsgnatsd/server"
"github.com/nats-io/nats-server/v2/logger"
)
var bridge *Bridge
var assetServer *server.AssetsServer
type Bridge struct {
*server.Opts
WsServer *server.WsServer
NatsServer *server.NatsServer
PidFile *os.File
}
func NewBridge(o *server.Opts) (*Bridge, error) {
var err error
var bridge Bridge
bridge.Opts = o
fi, err := os.Stat(bridge.PidDir)
if os.IsNotExist(err) {
bridge.Logger.Fatalf("piddir [%s] doesn't exist", bridge.PidDir)
}
if !fi.IsDir() {
bridge.Logger.Fatalf("piddir [%s] is not a directory", bridge.PidDir)
}
bridge.NatsServer, err = server.NewNatsServer(o)
if err != nil {
return nil, err
}
if bridge.NatsServer == nil {
return nil, nil
}
bridge.WsServer, err = server.NewWsServer(o)
if err != nil {
return nil, err
}
return &bridge, nil
}
func (b *Bridge) Start() error {
if err := b.NatsServer.Start(); err != nil {
return err
}
kind := "embedded"
if b.NatsServer == nil {
kind = "remote"
}
bridge.Logger.Noticef("Bridge using %s NATS server %s", kind, b.NatsServer.HostPort())
if err := b.WsServer.Start(); err != nil {
return err
}
if err := b.writePidFile(); err != nil {
return err
}
return nil
}
func (b *Bridge) Shutdown() {
b.WsServer.Shutdown()
b.NatsServer.Shutdown()
b.Cleanup()
}
func (b *Bridge) Cleanup() {
err := b.PidFile.Close()
if err != nil {
b.Logger.Errorf("Failed closing pid file: %v", err)
}
if err := os.Remove(b.pidPath()); err != nil {
b.Logger.Errorf("Failed removing pid file: %v", err)
}
}
func (b *Bridge) pidPath() string {
return filepath.Join(b.PidDir, fmt.Sprintf("wsgnatsd_%d.pid", os.Getpid()))
}
func (b *Bridge) writePidFile() error {
var err error
b.PidFile, err = os.Create(b.pidPath())
if err != nil {
return err
}
_, err = b.PidFile.Write([]byte(strings.Join([]string{b.WsServer.GetURL(), b.NatsServer.GetURL()}, "\n")))
if err != nil {
return err
}
return nil
}
func BridgeArgs() []string {
inlineArgs := -1
for i, a := range os.Args {
if a == "--" {
inlineArgs = i
break
}
}
var args []string
if inlineArgs == -1 {
args = os.Args[1:]
} else {
args = os.Args[1 : inlineArgs+1]
}
return args
}
func parseFlags() (*server.Opts, error) {
opts := flag.NewFlagSet("bridge-c", flag.ExitOnError)
var confFile string
c := server.DefaultOpts()
opts.StringVar(&confFile, "c", "", "configuration file")
opts.IntVar(&c.Port, "p", c.Port, "port - http port for asset server default is no asset server")
opts.StringVar(&c.Dir, "d", c.Dir, "dir - asset directory, requires depends port")
opts.StringVar(&c.WSHostPort, "whp", c.WSHostPort, "wshostport - (default is auto port)")
opts.StringVar(&c.RemoteNatsHostPort, "rhp", c.RemoteNatsHostPort, "remotenatshostport - disables embedded NATS and proxies requests to the specified hostport")
opts.StringVar(&c.CaFile, "ca", c.CaFile, "cafile - ca certificate file for asset and ws servers")
opts.StringVar(&c.CertFile, "cert", c.CertFile, "certfile - certificate file for asset and ws servers")
opts.StringVar(&c.KeyFile, "key", c.KeyFile, "keyfile - certificate key for asset and ws servers")
opts.StringVar(&c.PidDir, "pid", c.PidDir, "piddir - piddir path for auto assigned port information")
opts.BoolVar(&c.TextFrames, "text", c.TextFrames, "textframes - use text websocket frames")
opts.BoolVar(&c.Debug, "D", c.Debug, "debug - enable debugging output")
opts.BoolVar(&c.Trace, "V", c.Trace, "trace - enable tracing output")
a := BridgeArgs()
if err := opts.Parse(a); err != nil {
opts.Usage()
os.Exit(0)
}
if confFile != "" && len(a) > 0 {
return nil, errors.New("no additional flags for the bridge can be specified in the command")
}
if confFile != "" {
fc, err := server.LoadOpts(confFile)
if err != nil {
return nil, err
}
c = *fc
}
if c.KeyFile != "" || c.CertFile != "" {
if c.KeyFile == "" || c.CertFile == "" {
panic("if -cert or -key is specified, both must be supplied")
}
}
return &c, nil
}
func main() {
o, err := parseFlags()
if err != nil {
panic(err)
}
o.Logger = logger.NewStdLogger(true, o.Debug, o.Trace, true, true)
bridge, err = NewBridge(o)
if err != nil {
o.Logger.Errorf("Failed to create sub-systems: %v\n")
panic(err)
}
if bridge == nil {
// prob help option
return
}
if err := bridge.Start(); err != nil {
o.Logger.Errorf("Failed to start sub-systems: %v\n")
bridge.Shutdown()
panic(err)
}
if o.Port > 0 {
as, err := server.NewAssetsServer(o)
if err != nil {
panic(err)
}
if err := as.Start(); err != nil {
panic(err)
}
assetServer = as
}
handleSignals()
if bridge != nil {
runtime.Goexit()
}
}
// handle signals so we can orderly shutdown
func handleSignals() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
go func() {
for sig := range c {
switch sig {
case syscall.SIGINT:
if assetServer != nil {
assetServer.Shutdown()
}
bridge.Shutdown()
os.Exit(0)
}
}
}()
}
<file_sep>/go.mod
module github.com/aricart/wsgnatsd
require (
github.com/gorilla/websocket v1.4.1
github.com/mitchellh/go-homedir v1.1.0
github.com/nats-io/nats-server/v2 v2.0.1-0.20190625001713-2db76bde3329
)
replace github.com/nats-io/nats-server/v2 v2.0.1-0.20190625001713-2db76bde3329 => /Users/aricart/Dropbox/code/go-mod-projects/nats-server
go 1.13
<file_sep>/README.md
# WebSocket NATS Server
A WebSocket Server embedding a [NATS](https://nats.io/) server used for development
while NATS server gets own native WS/S support.
This server has 3 different servers:
- Asset Server
- WebSocket Server
- NATS Server
## Asset Server
Is an HTTP server that can serve content from a document root. The server processes all files
and replaces `{{WSURL}}` with the WebSocket URL for the WS server.
To enable asset serving specify the `-p` with a port and the `-d` with the document root.
## WebSocket Server
This server is just a proxy server to a NATS server. The NATS server can be the embedded
server or a remote server (from `-rhp`). WebSocket connections are proxied over to the
embedded NATS Server or the hostport specified by `-rhp`. Note that the connection between
WS and NATS server is *always* in the clear.
## NATS Server
A full NATS Server. Additional options can be passed to it by passing `--` followed by any
allowed NATS server options. By default ports for the embedded NATS server are auto selected,
if a `-c` or `-config` option is specified, the server will reject port/host port options.
## Flags
```
-D debug - enable debugging output
-V trace - enable tracing output
-c string
configuration file
-ca string
cafile - ca certificate file for asset and ws servers
-cert string
certfile - certificate file for asset and ws servers
-d string
dir - asset directory, requires depends port
-key string
keyfile - certificate key for asset and ws servers
-p int
port - http port for asset server default is no asset server (default -1)
-pid string
piddir - piddir path for auto assigned port information (default "/<KEY>/")
-rhp string
remotenatshostport - disables embedded NATS and proxies requests to the specified hostport
-text
textframes - use text websocket frames
-whp string
wshostport - (default is auto port) (default "127.0.0.1:0")
```
## Examples
```bash
wsgnatsd -p 80 -d /tmp/docroot
wsgnatsd -c /path/to/conf -- -c /path/to/natsserver.conf -DV
wsgnatsd -p 80 -whp 127.0.0.1:8080
wsgnatsd -rhp localhost:4222
```
<file_sep>/Formula/wsgnatsd.rb
# This file was generated by GoReleaser. DO NOT EDIT.
class Wsgnatsd < Formula
desc "A websocket server proxy for nats-server"
homepage "https://github.com/aricart/wsgnatsd"
version "0.8.10"
bottle :unneeded
if OS.mac?
url "https://github.com/aricart/wsgnatsd/releases/download/v0.8.10/wsgnatsd-v0.8.10-darwin-amd64.zip"
sha256 "38a1e1242a6a429a92849333956244edd53123e05e8461171a3900b3b1a2bb23"
elsif OS.linux?
if Hardware::CPU.intel?
url "https://github.com/aricart/wsgnatsd/releases/download/v0.8.10/wsgnatsd-v0.8.10-darwin-amd64.zip"
sha256 "d758aa5ff8903b0c25cf267c16697810ccb7ec769a8b658f62e0019e7f035943"
end
end
def install
bin.install "wsgnatsd"
end
test do
system "#{bin}/wsgnatsd --help"
end
end
| 32e122343250f026f54e45e2b95929332f2f99d5 | [
"Markdown",
"Go Module",
"Go",
"Ruby"
] | 6 | Go | omirror/wsgnatsd | 137974ec7c2ea078a0d811dacd319840a503765a | d4a86d5111d9135d4d3e8aa48d212e33f9b2af9a |
refs/heads/master | <repo_name>AnttiVirtanen/moboproj<file_sep>/app/pages/list/list.ts
import {Component, NgZone, ViewChild, ElementRef} from '@angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {ItemDetailsPage} from '../item-details/item-details';
import {PlacesService} from '../../providers/places-service/places-service';
import {GoogleMap, GoogleMapsEvent, GoogleMapsLatLng, GoogleMapsMarkerOptions, CameraPosition, GoogleMapsMarker} from 'ionic-native/dist/plugins/googlemaps';
@Component({
templateUrl: 'build/pages/list/list.html',
providers: [PlacesService]
})
export class ListPage {
@ViewChild('map') mapElement: ElementRef;
selectedType: any;
selectedItem: any;
icons: string[];
items: Array<{title: string, note: string, icon: string}>;
placesURL: string;
public places: any;
map: GoogleMap;
constructor(public navCtrl: NavController, navParams: NavParams, public placesService: PlacesService, private platform: Platform) {
this.selectedType = navParams.get('type');
this.selectedItem = navParams.get('item');
this.icons = ['flask', 'wifi', 'beer', 'football', 'basketball', 'paper-plane',
'american-football', 'boat', 'bluetooth', 'build'];
this.items = [];
for(let i = 1; i < 11; i++) {
this.items.push({
title: 'Item ' + i,
note: 'This is item #' + i,
icon: this.icons[Math.floor(Math.random() * this.icons.length)]
});
}
this.loadPlaces(this.selectedType.type);
this.map = new GoogleMap('map');
platform.ready().then(() => {
this.loadMap();
});
}
loadMap(){
let location = new GoogleMapsLatLng(-34.9290,138.6010);
this.map = new GoogleMap('map', {
'backgroundColor': 'red',
'gestures': {
'scroll': true,
'tilt': true,
'rotate': true,
'zoom': true
},
'camera': {
'latLng': location,
'tilt': 30,
'zoom': 15,
'bearing': 50
}
});
this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => {
console.log('Map is ready!!!!!!!!!!!!!!!!!!!!!!!!!!!111 !!!!!!!!!');
});
}
itemTapped(event, item) {
this.navCtrl.push(ItemDetailsPage, {
item: item
});
}
ngOnInit(){
let pageArray = document.getElementsByClassName("show-page");
for(var i = pageArray.length-1; i>= 0; i--){
pageArray[i].classList.remove('show-page');
}
}
loadPlaces(placeType){
this.placesService.load(placeType)
.then(data => {
this.places = data;
console.log(this.places);
});
}
}
<file_sep>/app/services/mock.service.ts
import { Injectable } from '@angular/core';
const PLACES = [
{
type: 'night_club',
name: 'Night life'
},
{
type: 'cafe',
name: 'Café'
},
{
type: 'bar',
name: 'Bars'
},
{
type: 'movie_theater',
name: 'Movie theaters'
},
{
type: 'gym',
name: 'Gyms'
}
];
@Injectable()
export class MenuService {
getPlaces(): Promise<any> {
return Promise.resolve(PLACES);
}
}<file_sep>/README.md
1. npm install -g ionic
2. git clone https://github.com/AnttiVirtanen/moboproj.git
3. ionic serve
noi kuvat ei skaalaa toho selaimee, mut vissii mobiilissa iha ok.<file_sep>/app/pages/hello-ionic/hello-ionic.ts
import {Component} from '@angular/core';
import {MenuService} from '../../services/mock.service';
import {NavController, NavParams} from 'ionic-angular';
import {OnInit} from '@angular/core';
import {ListPage} from '../list/list';
@Component({
templateUrl: 'build/pages/hello-ionic/hello-ionic.html',
providers: [MenuService]
})
export class HelloIonicPage implements OnInit{
places = [];
constructor(private menuService: MenuService, public navCtrl: NavController, navParams: NavParams) { }
getPlaces(): void {
this.menuService.getPlaces().then((PLACES) => {
console.log("jee");
this.places = PLACES;
}
);
}
typeTapped(event, type) {
this.navCtrl.push(ListPage, {
type: type
});
}
ngOnInit(): void {
this.getPlaces();
}
}
<file_sep>/app/providers/places-service/places-service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the PlacesService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class PlacesService {
placesURL: string;
data: any;
constructor(private http: Http) {
}
load(placeType) {/*
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}*/
this.placesURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=61.497452,23.766331&radius=3500&type=" + placeType + "&key=<KEY>";
// don't have the data yet
return new Promise(resolve => {
this.http.get(this.placesURL)
.map(res => res.json())
.subscribe(data => {
this.data = data.results;
resolve(this.data);
}, error => {
console.log(JSON.stringify(error.json()));
});
});
}
}
<file_sep>/app/pages/item-details/item-details.ts
import {Component, NgZone, ViewChild, ElementRef} from '@angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {GoogleMap, GoogleMapsEvent, GoogleMapsLatLng, GoogleMapsMarkerOptions, CameraPosition, GoogleMapsMarker} from 'ionic-native/dist/plugins/googlemaps';
@Component({
templateUrl: 'build/pages/item-details/item-details.html'
})
export class ItemDetailsPage {
selectedItem: any;
@ViewChild('map') mapElement: ElementRef;
map: GoogleMap;
constructor(public navCtrl: NavController, navParams: NavParams, private platform:Platform) {
this.selectedItem = navParams.get('item');
platform.ready().then(() => {
this.loadMap();
});
}
loadMap(){
let location = new GoogleMapsLatLng(-34.9290,138.6010);
this.map = new GoogleMap('map', {
'backgroundColor': 'red',
'gestures': {
'scroll': true,
'tilt': true,
'rotate': true,
'zoom': true
},
'camera': {
'latLng': location,
'tilt': 30,
'zoom': 15,
'bearing': 50
}
});
this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => {
console.log('Map is ready!!!!!!!!!!!!!!!!!!!!!!!!!!!111 !!!!!!!!!');
});
}
}
| bd9dda1ec3d244df5a2259c3e388ef49a49ad358 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | AnttiVirtanen/moboproj | f50a6f9b2b3f2f51360af6b41d8d5cb2e1bd1c7e | c4ce88b5da77ecdcebf4eb8fb63e38b44ecabfdd |
refs/heads/master | <file_sep><hr width=50%> | 36a781bb593957872acdd9acea17853145ee224d | [
"JavaScript"
] | 1 | JavaScript | 531809110/resume | ca4159a7c18d92f037efe81c09358c7c6ed55188 | 8a0efb043a259fd692d372b9d20392332e4dc197 |
refs/heads/master | <file_sep>package com.kratos;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException
{
System.out.println("BASIC CONNECTION");
try
{
ConnectSQLServer connectSQL=new ConnectSQLServer();
String sql="select * from NguoiChoi";
ResultSet result=connectSQL.executeQuery(sql);
while (result.next())
{
String taikhoan=result.getString("TaiKhoan");
String matkhau=result.getString("MatKhau");
System.out.println("Tai khoan: " +taikhoan);
System.out.println("Mat khau: "+matkhau);
}
}
catch (SQLException e)
{
e.printStackTrace();
throw new SQLException("Loi ket noi"+e.getMessage());
}
}
}
<file_sep>driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost;databaseName=JavaFinalProject;integratedSecurity=true
user=
password= | 55d551608e3f85bef8c8182208261d2b49d224b2 | [
"Java",
"INI"
] | 2 | Java | nguyentheanst/javafinalproject | 875745f441ed293712a807cac68fc6c0ff30ef67 | b4137638a31200d7c575f955d359541677354615 |
refs/heads/master | <repo_name>A00895704/A00895704.github.io<file_sep>/controllers/loginController.js
exports.get = (req, res)=>{
console.log("rendering login");
res.render("login");
}
exports.login = (req, res)=>{
const username = req.body.username;
const password = req.body.password;
console.log("got here");
if(username.toLowerCase() === 'a00895704' && password === "<PASSWORD>"){
console.log("password accepted");
res.redirect(301, '/artistList');
} else{
console.log("password incorrect");
return res.render('login', {msg: 'Username or password incorrect'});
}
}<file_sep>/database/db.js
const {Pool} = require ('pg');
const pool = new Pool({
host:'ec2-34-200-116-132.compute-1.amazonaws.com',
user:'bnazibarppglxd',
database:'dm7qd4s58e41t',
password:'<PASSWORD>',
port:5432,
ssl:true
});
module.exports=pool;<file_sep>/README.md
# A00895704.github.io<file_sep>/index.js
let express = require('express');
let bodyParser = require('body-parser');
let app = express();
let loginRoute = require('./routes/loginRoute');
let artistRoute = require('./routes/artistRoutes');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.use(loginRoute);
app.use(artistRoute);
app.get('/', (req, res, next)=>{
console.log("redurecting to login");
res.redirect(301, '/login');
});
app.listen(process.env.PORT|| 3000, () => console.log('Server ready'))<file_sep>/routes/artistRoutes.js
const express = require('express');
const router = express.Router();
const artistController = require('../controllers/artistController');
router.get('/artistList', artistController.getAllArtists);
router.get('/artistList/:name', artistController.getArtist);
router.post('/artistList/add', artistController.addArtist);
router.get('/artistList/delete/:id', artistController.deleteArtist);
module.exports = router;<file_sep>/controllers/artistController.js
let artistModel = require('../models/artistData');
exports.getAllArtists = async(req, res, next) =>{
if(req.query.searchInput){
const filter = req.query.searchInput;
data = await artistModel.getartistsfiltered(filter);
console.log("something");
return res.render('artist', {artists:data.rows, filter:filter});
}else{
console.log("no filter");
let data = await artistModel.getall();
res.render('artist', {artists:data.rows});
}
}
exports.addArtist = async(req, res, next)=>{
let artist = {
artistName: req.body.name,
artistAbout: req.body.about,
artistURL: req.body.url
};
console.log(artist);
await artistModel.addartist(artist);
return res.redirect(301, '/artistList');
}
exports.getArtist = async(req, res, next)=>{
let data = await Artist.getartist(req.params.name);
return res.render('artist', {artists:data.rows});
}
exports.deleteArtist = async(req, res, next)=>{
await artistModel.deleteartist(req.params.id);
return res.redirect(301, '/artistList');
}
<file_sep>/public/js/lab5.js
//submits form button
const addBtn = document.getElementById('addArtist');
//display form button
const addFormButton = document.getElementById('displayAddForm');
//add form
const addForm = document.getElementById('addForm');
addFormButton.addEventListener('click', ()=>{
if(addForm.style.display ==="none"){
addForm.style.display = "block";
} else{
addForm.style.display = "none";
}
});
// var artistStorage={};
// getArtistsFromText().then(data=>{
// console.log(data);
// artistStorage = data;
// start();
// });
// function start(){
// var form = document.getElementById("directoryForm");
// form.addEventListener('submit', event => { event.preventDefault(); search(); });
// if(artistStorage.length >0){
// var artistList = document.getElementById("artistList");
// for(var i=0; i<artistStorage.length; i++){
// var artistItem = document.createElement("li");
// artistItem.setAttribute("class", "artists");
// var artistPicture = document.createElement("img");
// var divDesc = document.createElement("div");
// let pName = document.createElement("p");
// let pAbout = document.createElement("p");
// var deleteButton = createDeleteButton(artistStorage[i].artistName);
// pName.setAttribute("class", "name");
// divDesc.style.flexGrow="2";
// divDesc.style.marginLeft="10%";
// pAbout.setAttribute("class", "desc");
// pName.textContent = artistStorage[i].artistName;
// pAbout.textContent = artistStorage[i].artistAbout;
// artistPicture.setAttribute("src", artistStorage[i].artistURL);
// divDesc.appendChild(pName);
// divDesc.appendChild(pAbout);
// artistItem.appendChild(artistPicture);
// artistItem.appendChild(divDesc);
// artistItem.appendChild(deleteButton);
// artistList.appendChild(artistItem);
// }
// }
// }
// function add(){
// var addForm = document.getElementById("addForm");
// if(addForm.style.display){
// addForm.style.display=((addForm.style.display!='none')?'none':'block');
// } else{
// addForm.style.display='block';
// }
// }
// function addArtistToCollection(elem){
// var addForm = document.getElementById("addForm");
// addForm.style.display="none";
// var artistList = document.getElementById("artistList");
// var artistItem = document.createElement("li");
// artistItem.setAttribute("class", "artists");
// var artistPicture = document.createElement("img");
// var artistName = document.getElementById("addName");
// var artistAbout = document.getElementById("addAbout");
// var artistURL = document.getElementById("addURL");
// var divDesc = document.createElement("div");
// var pName = document.createElement("p");
// var pAbout = document.createElement("p");
// var deleteButton = createDeleteButton(artistName.value);
// var newArtist={'artistName':artistName.value, 'artistAbout':artistAbout.value, 'artistURL':artistURL.value};
// artistStorage.push(newArtist);
// saveArtistsToText();
// pName.setAttribute("class", "name");
// divDesc.style.flexGrow="2";
// divDesc.style.marginLeft="10%";
// pAbout.setAttribute("class", "desc");
// pName.textContent = artistName.value;
// pAbout.textContent = artistAbout.value;
// artistPicture.setAttribute("src", artistURL.value);
// divDesc.appendChild(pName);
// divDesc.appendChild(pAbout);
// artistItem.appendChild(artistPicture);
// artistItem.appendChild(divDesc);
// artistItem.appendChild(deleteButton);
// artistList.appendChild(artistItem);
// artistName.value="";
// artistAbout.value="";
// artistURL.value="";
// }
// async function deleteArtist(elem){
// var artistIndex=elem.getAttribute("data-index");
// var found = false;
// try{
// await deleteArtistsFromText(artistIndex);
// for(var i=0; i<artistStorage.length && !found; i++){
// console.log("searching for " + artistIndex);
// if(artistStorage[i].artistName == artistIndex){
// artistStorage.splice(i, 1);
// console.log("spliced");
// }
// }
// elem.parentNode.remove();
// } catch (err){
// console.log(err);
// }
// }
// async function saveArtistsToText(){
// try{
// let res = await fetch('/artistList', {
// method: 'POST',
// headers:{
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(artistStorage)
// });
// console.log(res);
// }catch(err){
// console.log(err);
// }
// }
// async function deleteArtistsFromText(artistIndex){
// return new Promise(async(resolve, reject)=>{
// try{
// let res = await fetch(`/artistList/${artistIndex}`, {
// method: 'DELETE',
// headers:{
// 'Content-Type': 'application/json'
// },
// });
// console.log(res);
// if(!res.ok) throw res;
// resolve(res);
// }catch(err){
// console.log(err);
// reject(err);
// }
// });
// }
// async function getArtistsFromInput(name){
// return new Promise(async(resolve, reject) =>{
// try{
// let res = await fetch(`/artistList/${name}`, {
// method:'GET',
// headers:{
// 'Content-Type': 'application/json'
// }
// });
// if(!res.ok) throw res;
// var data = await res.json();
// resolve(data);
// } catch(err){
// console.log(err);
// reject(err);
// }
// });
// }
// async function getArtistsFromText(){
// try{
// var res = await fetch('/artistList', {
// method: 'GET',
// headers:{
// 'Content-Type': 'application/json'
// }
// });
// var data = await res.json();
// return data;
// }catch(err){
// console.log(err);
// }
// }
// function createDeleteButton(name){
// var deleteButton = document.createElement("button");
// deleteButton.setAttribute("type", "button");
// deleteButton.setAttribute("onclick", "deleteArtist(this)");
// deleteButton.textContent="Delete";
// deleteButton.style.backgroundColor="red";
// deleteButton.style.border="none";
// deleteButton.style.textAlign="center";
// deleteButton.style.borderRadius="5px";
// deleteButton.style.color="white";
// deleteButton.style.display="block";
// deleteButton.style.padding="10px";
// deleteButton.setAttribute("data-index", name);
// return deleteButton;
// }
// function search(){
// var searchInput = document.getElementById("directInput");
// var artistList = document.getElementById("artistList");
// var allArtists = artistList.querySelectorAll("p.name");
// if(searchInput.value !== ""){
// getArtistsFromInput(searchInput.value).then(data=>{
// console.log(data);
// for(var i=0; i< allArtists.length; i++){
// for(var j=0; j< data.length; j++){
// if(!allArtists[i].textContent.includes(data[j].artistName)){
// allArtists[i].parentElement.parentElement.style.display="none";
// } else{
// allArtists[i].parentElement.parentElement.style.display="flex";
// }
// }
// }
// });
// } else{
// alert("No search parameters found.");
// for(var i=0; i<allArtists.length; i++){
// allArtists[i].parentElement.parentElement.style.display="flex";
// }
// }
// }
<file_sep>/models/artistData.js
let db = require('../database/db');
const sqlFilter = "Select * from artists where lower(name) like '%' || $1 || '%'";
function addArtist(e){
db.query("Insert into artists(name, about, url) values ('"+ e.artistName + "','"+ e.artistAbout+"','"+e.artistURL +"')");
}
function getAllArtists(){
return db.query('Select * from artists');
}
function getArtists(name){
return db.query('Select * from artists where name =' + name);
}
function deleteArtist(id){
db.query('delete from artists where artist_id=' + id);
}
function getArtistsFiltered(filter){
return db.query(sqlFilter, [filter.toLowerCase()]);
}
module.exports = {
addartist: addArtist,
getall: getAllArtists,
getartist: getArtists,
deleteartist: deleteArtist,
getartistsfiltered: getArtistsFiltered
} | 373acda62a39d93d50f421b74f2a43ecc4a47511 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | A00895704/A00895704.github.io | f9d720acaff159d71fbde5258cf73f2cf169069e | 93c8a24fb5a48a833d01ca6305118deae342ae6d |
refs/heads/master | <repo_name>Jackliu007888/djcli<file_sep>/templates/files/controller.js
const Utils = require('../../utils')
module.exports = {
version: '1.0.0',
description: 'controller 模板文件',
prompts: [{
name: 'controllerName',
message: '请输入 controller 名称'
}],
stringFn({controllerName}) {
return `
const Controller = require('egg').Controller
class ${Utils.firstUpperCase(controllerName)}Controller extends Controller {
constructor(ctx) {
super(ctx)
this.getListRule = {
id: { type: 'string', required: true, allowEmpty: false },
}
this.createRule = {
}
this.removeRule = {
ids: { type: 'array', itemType: 'string' }
}
this.updateRule = {
id: { type: 'string', required: true, allowEmpty: false },
}
}
async getList() {
const {
ctx,
ctx: {
request: {
body = {}
}
}
} = this
ctx.validate(this.getListRule)
const { res, pager } = await ctx.service.${controllerName}.getList(body)
ctx.helper.success({
ctx,
res,
pager
})
}
async create() {
const {
ctx,
ctx: {
request: {
body = {}
}
}
} = this
ctx.validate(this.createRule)
const res = await ctx.service.${controllerName}.create(body)
ctx.helper.success({
ctx,
res,
})
}
async remove() {
const {
ctx,
ctx: {
request: {
body = {}
}
}
} = this
ctx.validate(this.removeRule)
const res = await ctx.service.${controllerName}.remove(body)
ctx.helper.success({
ctx,
res,
})
}
async update() {
const {
ctx,
ctx: {
request: {
body = {}
}
}
} = this
ctx.validate(this.updateRule)
const res = await ctx.service.${controllerName}.update(body)
ctx.helper.success({
ctx,
res,
})
}
}
module.exports = ${Utils.firstUpperCase(controllerName)}Controller
`
},
}<file_sep>/lib/cmd/config.js
const Table = require('cli-table')
const tip = require('../tip')
const table = new Table({
head: ['KEY', 'VALUE' ],
style: {
head: ['cyan']
}
})
module.exports = () => {
const config = require('../../config')
const keys = Object.keys(config)
if (keys.length) {
keys.forEach((key) => {
const value = config[key]
table.push(
[key, value]
)
})
const list = table.toString()
if (list) {
console.log(`${list}\n`)
} else {
tip.fail('配置不存在!')
}
} else {
tip.fail('配置不存在!')
}
// process.exit()
}<file_sep>/lib/cmd/list.js
const Table = require('cli-table')
const Path = require('path')
const fse = require('fs-extra')
const tip = require('../tip')
const table = new Table({
head: ['NAME', 'TYPE','VERSION', 'URL', 'DESCRIPTION' ],
style: {
head: ['cyan']
}
})
module.exports = () => {
{
const {
templates,
version
} = require('../../templates/project')
Object.keys(templates).forEach((key) => {
const {
description,
url
} = templates[key]
table.push(
[key, 'project', version, url, description]
)
})
}
{
const {
templates,
version
} = require('../../templates/block')
Object.keys(templates).forEach((key) => {
const {
description,
url
} = templates[key]
table.push(
[key, 'block', version, url, description]
)
})
}
{
const filePath = Path.join(__dirname, '../../templates/files')
const fileList = fse.readdirSync(filePath)
fileList.forEach(fileaName => {
const file = require(Path.join(filePath, '/', fileaName))
table.push(
[fileaName.replace('.js', ''), 'file', file.version, '-', file.description,]
)
})
}
const list = table.toString()
if (list) {
tip.info('模板列表是: ')
console.log(`${list}\n`)
} else {
tip.fail('模板不存在!')
}
process.exit()
}<file_sep>/lib/cmd/setConfig.js
const fse = require('fs-extra')
const inquirer = require('inquirer')
const path = require('path')
const tip = require('../tip')
module.exports = async () => {
const configPath = path.join(__dirname, '../../config.json')
const config = await fse.readJson(configPath)
if (config && config.gitAccount && config.gitPassword) {
tip.info('当前配置信息是: \n')
require('./config')()
const { isContinue } = await inquirer.prompt([{
name: 'isContinue',
message: '是否继续? 继续请输入 y or yes'
}])
if (isContinue.toLowerCase() !== 'yes' && isContinue.toLowerCase() !== 'y') {
process.exit()
}
}
const {
gitAccount,
gitPassword
} = await inquirer.prompt([{
name: 'gitAccount',
message: '请输入 git 账号',
}, {
name: 'gitPassword',
message: '请输入 git 密码',
}])
await fse.writeJSONSync(configPath, {
gitAccount,
gitPassword
})
tip.info('已修改配置信息')
}<file_sep>/utils/index.js
const firstUpperCase = ([first, ...rest]) => first.toUpperCase() + rest.join('')
module.exports = {
firstUpperCase
}<file_sep>/lib/cli/index.js
const program = require('commander')
const PKG = require('../../package.json')
program.version(PKG.version)
program
.command('init')
.description('生成一个项目')
.alias('i') // 简写
.action(() => {
require('../cmd/init')()
})
program
.command('list')
.description('查看模板列表')
.alias('l')
.action(() => {
require('../cmd/list')()
})
program
.command('config')
.description('查看配置信息')
.alias('c')
.action(() => {
require('../cmd/config')()
})
program
.command('setConfig')
.description('设置配置')
.alias('sc')
.action(() => {
require('../cmd/setConfig')()
})
program
.command('new')
.description('新建模板文件')
.alias('n')
.action(() => {
require('../cmd/new')()
})
program
.command('block')
.description('初始化区块')
.alias('b')
.action(() => {
require('../cmd/block')()
})
program.parse(process.argv)
if(!program.args.length){
program.help()
}<file_sep>/templates/files/router.js
module.exports = {
version: '1.0.0',
description: 'Router 模板文件',
prompts: [{
name: 'controllerName',
message: '请输入 controller 名称'
}],
stringFn({controllerName}) {
return `
/**
* @param {Egg.Application} app - egg application
*/
const { API_VERSION_PREFIX } = require('../utils/enums/router')
module.exports = app => {
const { router, controller } = app
const subRouter = router.namespace(API_VERSION_PREFIX + '/${controllerName}')
subRouter.post('/getList', controller.${controllerName}.getList)
subRouter.post('/create', controller.${controllerName}.create)
subRouter.post('/remove', controller.${controllerName}.remove)
subRouter.post('/update', controller.${controllerName}.update)
}
`
},
}<file_sep>/lib/cmd/block.js
const exec = require('child_process').exec
const ora = require('ora')
const inquirer = require('inquirer')
const fse = require('fs-extra')
const Path = require('path')
const rimraf = require('rimraf')
const tip = require('../tip')
const TMPS = require('../../templates/block')
const spinner = ora('正在生成...')
module.exports = async () => {
const { templateName } = await inquirer.prompt([{
name: 'templateName',
message: '请输入区块名称'
}])
if (!templateName || !TMPS.templates[templateName]) {
tip.fail('区块不存在!')
process.exit()
}
const {
url,
branch,
replace: {
variables = {},
paths = [],
} = {}
} = TMPS.templates[templateName]
const baseVariables = {
}
const variablesResult = {
...variables,
...baseVariables,
}
const answer = await inquirer.prompt(Object.keys(variablesResult).map(key => ({
name: key,
message: '请输入' + variablesResult[key]
})))
const config = await fse.readJson(Path.join(__dirname, '../../config.json'))
// git命令,远程拉取项目并自定义项目名
let cmdStr = ''
if (config && config.gitAccount && config.gitPassword) {
const [protocol, urlPath] = url.split('//')
cmdStr = `git clone -b ${branch} ${protocol}//${config.gitAccount}:${config.gitPassword}@${urlPath} ${templateName}`
} else {
cmdStr = `git clone -b ${branch} ${url} ${templateName}`
}
console.log('执行命令:' + cmdStr)
spinner.start()
exec(cmdStr, async (err) => {
if (err) {
console.log(err)
tip.fail('请重新运行!')
process.exit()
}
// 替换变量
console.log('正在替换变量')
await Promise.all(paths.map(async path => {
const filePath = Path.join(process.cwd(), templateName, path)
if (fse.pathExistsSync(filePath)) {
const fileString = await fse.readFileSync(filePath, 'utf-8')
const replacedFileString = Object.keys(variablesResult).reduce((prev, key) => {
// eslint-disable-next-line
return prev = prev.replace(new RegExp(`__${key}__`, 'g'), answer[key])
}, fileString)
await fse.writeFileSync(filePath, replacedFileString, 'utf-8')
}
}))
// 删除 git 文件
console.log('正在删除 git 文件')
await rimraf(Path.join(process.cwd(), templateName, '.git'), function () {
tip.suc('初始化完成!')
process.exit()
})
})
}<file_sep>/README.md
# fecli 前端应用 脚手架
## 安装
```shell
npm i -g @jackliulovelt/dj-cli
```
## 命令
- 查看现有模板 `fecli l`
- 查看git配置 `fecli c`
- 设置git配置 `fecli sc`
- 初始化一个项目模板 `fecli init`
- 新建一个文件模板 `fecli new`
- 需进入待生成文件模板的目录,再执行命令
- 目前支持的文件模板有 router 、controller 、service
- 文件模板的新增方式:在 templates 目录下新增 xxx.js,定义 prompts 和 stringFn 即可。
## 项目模板配置
形如以下形式
- replace 是需要替换变量的信息
- 在初始化项目的时候会提示输入,在git clone 之后对`replace.paths`下的文件进行替换
- replace.paths 默认为项目根路径
- 项目模板需要用 `$${变量名}$$` 写好在需要替换的文件中
```JSON
"eggjs": {
"url": "https://gitlab.51zcm.cc/front/service",
"branch": "test",
"description": "eggjs S端模板",
"replace": {
"variables": {
"spaceName": "k8s 部署空间",
"k8sServerName": "服务名",
"dockerRegistryNamespace": "docker 仓库空间"
},
"paths": [
"Jenkinsfile",
"package.json",
"build.sh"
]
}
}
```
<file_sep>/templates/files/service.js
const Utils = require('../../utils')
module.exports = {
version: '1.0.0',
description: 'Service 模板文件',
prompts: [{
name: 'repoName',
message: '请输入 repoName 名称'
}],
stringFn({repoName}) {
return `
const Service = require('egg').Service
const API = require('../api')
class ${Utils.firstUpperCase(repoName)}Service extends Service {
async getList(payload) {
const { ctx, app } = this
/* eslint-disable-next-line */
const { op, getRepo } = ctx.helper
const {
pageSize = 10,
curPageNum = 1,
// TODO: 补充
} = payload
const condition = {}
const { records, total, } = await app.$http.post(API.mpInformation + '/${repoName}/page', {
condition,
fieldNames: [
'id',
'createInfo.timestamp',
// TODO: 补充
],
pager: {
curPageNum,
pageSize,
}
})
return {
res: records,
pager: {
curPageNum,
pageSize,
totalCount: total,
}
}
}
async create(payload) {
const { ctx, app } = this
const { op, getRepo } = ctx.helper
const id = await app.getAsyncBatchId(4)
const ops = []
ops.push(op.add(getRepo('${repoName}'), {
id,
...payload
// TODO: 补充
}))
return await app.$httpBatch(ops)
}
async remove(payload) {
const { ctx, app } = this
const { ids = [] } = payload
const { op, getRepo } = ctx.helper
return await app.$httpBatch([
op.batchDelete(getRepo('${repoName}'), ids)
])
}
async update(payload) {
const { ctx, app } = this
const {
id = '',
} = payload
const { op, getRepo } = ctx.helper
return await app.$httpBatch([
op.update(getRepo('${repoName}'), {
id,
// TODO: 补充
})
])
}
}
module.exports = ${Utils.firstUpperCase(repoName)}Service
`
},
}<file_sep>/lib/cmd/new.js
const inquirer = require('inquirer')
const fse = require('fs-extra')
const Path = require('path')
const tip = require('../tip')
module.exports = async () => {
const { templateName } = await inquirer.prompt([{
name: 'templateName',
message: '请输入模板名称'
}])
const filePath = Path.join(__dirname, `../../templates/files/${templateName}.js`)
if (!templateName || !fse.pathExistsSync(filePath)) {
tip.fail('模板不存在!')
process.exit()
}
const { fileName } = await inquirer.prompt([{
name: 'fileName',
message: '请输入待生成的文件名称'
}])
const { stringFn, prompts } = require(filePath)
const answer = await inquirer.prompt(prompts)
fse.writeFileSync(Path.join(process.cwd(), `${fileName}.js`), stringFn(answer), 'utf-8')
process.exit()
} | 558bf86a61be8255829c8437b8b2ddd09fd9d83f | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | Jackliu007888/djcli | 243b3d7bf45adc4bf43be535da462bd4d4c593a0 | a4a4b0e3a83cd901b537c1af149f868d623f7a95 |
refs/heads/master | <repo_name>Dilandau/MhoEssentials<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/WoEManager.java
package com.sheeris.mho.MhoEssentials.modules;
import java.util.HashMap;
import java.util.Map;
import mho.dilandau.MhoDilandau;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Cuboid;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
import com.sheeris.mho.MhoEssentials.util.Vault;
public class WoEManager implements Listener {
public static boolean isStarted() {
return start;
}
private Map<String, ItemStack[]> armors = new HashMap<String, ItemStack[]>();
private Map<String, ItemStack[]> inventorys = new HashMap<String, ItemStack[]>();
private boolean enabled;
private static boolean start = false;
private static int blockWoe;
private static boolean reset = false;
public static void changeFlag() {
if (Cuboid.getWorldEdit() != null) {
/*
* EditSession editSession = WorldEdit .getInstance()
* .getEditSessionFactory() .getEditSession(
* BukkitUtil.getLocalWorld(Bukkit.getWorld("world")), -1);
* editSession.replaceBlocks(region, fromBlockTypes, pattern);
*/
}
}
public static boolean needReset() {
return reset;
}
public static void resetCastle() {
for (String blockString : Config.getWoeBlock()) {
String[] info = blockString.split(",");
Bukkit.getWorld(info[0])
.getBlockAt(Integer.valueOf(info[1]),
Integer.valueOf(info[2]), Integer.valueOf(info[3]))
.setTypeId(MhoDilandau.BlockWoe.id, true);
}
blockWoe = 0;
}
public static void resetDown() {
reset = false;
}
public static void resetPlayer() {
for (Player player : Cuboid.listPlayer(Bukkit.getWorld("world"),
"woesafe")) {
PvpListener.removeTag(player);
if (Manager.getGroup(player).equalsIgnoreCase(
(Config.getWoeOwner()))) {
player.teleport(Util.getSpawnLocationByName(player.getWorld()
.getName(), "woe_owner"), TeleportCause.PLUGIN);
} else {
player.teleport(Util.getSpawnLocationByName(player.getWorld()
.getName(), "woe"), TeleportCause.PLUGIN);
}
}
for (Player player : Cuboid.listPlayer(Bukkit.getWorld("world"), "woe")) {
PvpListener.removeTag(player);
if (Manager.getGroup(player).equalsIgnoreCase(
(Config.getWoeOwner()))) {
player.teleport(Util.getSpawnLocationByName(player.getWorld()
.getName(), "woe_owner"), TeleportCause.PLUGIN);
} else {
player.teleport(Util.getSpawnLocationByName(player.getWorld()
.getName(), "woe"), TeleportCause.PLUGIN);
}
}
}
public static void start() {
resetPlayer();
resetCastle();
blockWoe = 0;
start = true;
Bukkit.broadcastMessage(ChatColor.GOLD
+ "[WoE] La War of Emperium est ouverte !" + ChatColor.RESET);
Bukkit.broadcastMessage(ChatColor.GOLD
+ "[WoE] Qui prendra le contrôle du château à la place de la faction "
+ ChatColor.translateAlternateColorCodes(
'&',
Vault.getChat()
.getGroupPrefix(Bukkit.getWorlds().get(0),
Config.getWoeOwner()))
+ Config.getWoeOwner() + ChatColor.GOLD
+ " ? A vous de jouer !" + ChatColor.RESET);
}
public static void stop() {
start = false;
Bukkit.broadcastMessage(ChatColor.GOLD
+ "[WoE] La War of Emperium est terminée !" + ChatColor.RESET);
Bukkit.broadcastMessage(ChatColor.GOLD
+ "[WoE] La faction "
+ ChatColor.translateAlternateColorCodes(
'&',
Vault.getChat()
.getGroupPrefix(Bukkit.getWorlds().get(0),
Config.getWoeOwner()))
+ Config.getWoeOwner() + ChatColor.GOLD
+ " possède le château jusqu'au prochain événement."
+ ChatColor.RESET);
for (String blockString : Config.getWoeBlock()) {
String[] info = blockString.split(",");
Bukkit.getWorld(info[0])
.getBlockAt(Integer.valueOf(info[1]),
Integer.valueOf(info[2]), Integer.valueOf(info[3]))
.setType(Material.AIR);
}
resetPlayer();
}
public WoEManager() {
enabled = Config.isEnabled("woe");
start = false;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (!enabled || !start || !Config.isWoeBlock(event.getBlock())) {
return;
}
Player player = event.getPlayer();
String group = Manager.getGroup(player);
if (Config.getWoeOwner().equals(group)) {
event.setCancelled(true);
return;
}
blockWoe++;
int life = Config.getWoeBlockNum() - blockWoe;
ChatColor.translateAlternateColorCodes('&', Vault.getChat()
.getPlayerPrefix(player));
String message;
if (blockWoe == Config.getWoeBlockNum()) {
message = String
.format(ChatColor.GOLD
+ "[WoE] %s vient de détruire l'Emperium. La faction %s%s"
+ ChatColor.GOLD
+ " prend le contrôle du château !!", player
.getName(), ChatColor.translateAlternateColorCodes(
'&', Vault.getChat().getPlayerPrefix(player)),
group);
Config.setWoeOwner(group);
reset = true;
resetPlayer();
} else {
message = String
.format(ChatColor.GOLD
+ "[WoE] %s (%s%s"
+ ChatColor.GOLD
+ ") vient d'affaiblir l'Emperium. %s point(s) de vie restant(s) !",
player.getName(),
ChatColor.translateAlternateColorCodes('&', Vault
.getChat().getPlayerPrefix(player)), group,
life);
}
Bukkit.broadcastMessage(message);
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if (!enabled
|| !start
|| (!Cuboid.isInRegion(player, player.getWorld().getName(),
"woe") && !Cuboid.isInRegion(player, player.getWorld()
.getName(), "woesafe"))) {
return;
}
armors.put(player.getName(), player.getInventory().getArmorContents()
.clone());
inventorys.put(player.getName(), player.getInventory().getContents()
.clone());
event.getDrops().clear();
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
if (!enabled
|| !start
|| (!Cuboid.isInRegion(player, player.getWorld().getName(),
"woe") && !Cuboid.isInRegion(player, player.getWorld()
.getName(), "woesafe"))) {
return;
}
PvpListener.removeTag(player);
String group = Manager.getGroup(player);
Location loc;
if (!group.equalsIgnoreCase(Config.getWoeOwner())) {
loc = Util.getSpawnLocationByName(player.getWorld().getName(),
"woe");
} else {
loc = Util.getSpawnLocationByName(player.getWorld().getName(),
"woe_owner");
PvpListener.setTimerTag(player, Config.getWoETagDuration());
}
if (loc != null) {
event.setRespawnLocation(loc);
}
ItemStack[] arms = armors.get(player.getName());
boolean updateInventory = false;
if (arms != null) {
player.getInventory().setArmorContents(arms);
armors.remove(player.getName());
updateInventory = true;
}
ItemStack[] invs = inventorys.get(player.getName());
if (invs != null) {
player.getInventory().setContents(invs);
inventorys.remove(player.getName());
updateInventory = true;
}
if (updateInventory) {
player.updateInventory();
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/MineWatchListener.java
package com.sheeris.mho.MhoEssentials.modules;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.ItemStack;
import com.Acrobot.Breeze.Utils.MaterialUtil;
import com.Acrobot.Breeze.Utils.StringUtil;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Util;
public class MineWatchListener implements Listener {
public List<Location> foundblocks = new ArrayList<Location>();
private boolean enabled;
public MineWatchListener() {
enabled = Config.isEnabled("mineWatch");
}
private int getAllRelative(Block block) {
Integer total = 0;
for (BlockFace face : BlockFace.values()) {
if (block.getRelative(face).getType() == block.getType()) {
Block rel = block.getRelative(face);
if (!foundblocks.contains(rel.getLocation())) {
foundblocks.add(rel.getLocation());
total++;
total = total + getAllRelative(rel);
}
}
}
return total;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
if (!enabled || player.getGameMode() == GameMode.CREATIVE) {
return;
}
Block block = event.getBlock();
Location loc = block.getLocation();
if (foundblocks.contains(loc)) {
foundblocks.remove(loc);
return;
}
ChatColor color = null;
switch (block.getType()) {
case DIAMOND_ORE:
color = ChatColor.AQUA;
break;
case GOLD_ORE:
color = ChatColor.GOLD;
break;
case LAPIS_ORE:
color = ChatColor.BLUE;
break;
default:
color = null;
break;
}
if (color != null) {
foundblocks.add(block.getLocation());
int total = getAllRelative(block) + 1;
String itemName = StringUtil.capitalizeFirstLetter(
MaterialUtil.getName(new ItemStack(block.getType())), '_');
Util.sendMessageByPermission(String.format("[MineWatch] %s trouve "
+ color + "%d * %s" + ChatColor.RESET + ".",
player.getDisplayName(), total, itemName),
"mho.minewatch.admin");
foundblocks.remove(loc);
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/ChoppeMoutonTask.java
package com.sheeris.mho.MhoEssentials.modules;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Cuboid;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
public class ChoppeMoutonTask extends TimerTask {
public ChoppeMoutonTask() {
}
@Override
public void run() {
if (Manager.getChoppeMoutonTimer() > 0) {
Util.broadcastMessage(ChatColor.GREEN
+ "Le Choppe-Mouton se termine dans " + ChatColor.RESET
+ ChatColor.RED + Manager.getChoppeMoutonTimer()
+ ChatColor.RESET + ChatColor.GREEN + " minute(s)."
+ ChatColor.RESET);
Manager.setChoppeMoutonTimer(Manager.getChoppeMoutonTimer() - 1);
} else {
Util.broadcastMessage(ChatColor.RED
+ "Le Choppe-Mouton est terminé." + ChatColor.RESET);
Config.setToggle("statutCM", false);
Cuboid.tpPlayer(Bukkit.getWorld(Config.getCMWorldName()),
Config.getCMRegionName(), Util.getPlayerCMLocation());
Map<DyeColor, Integer> total = Cuboid.countSheep(
Bukkit.getWorld(Config.getCMWorldName()),
Config.getCMRegionName());
Set<DyeColor> colors = total.keySet();
String result = ChatColor.RED + " | " + ChatColor.RESET;
for (DyeColor color : colors) {
result = result
+ color.toString().substring(0, 1).toUpperCase()
+ color.toString().substring(1).toLowerCase() + " = "
+ total.get(color) + ChatColor.RED + " | "
+ ChatColor.RESET;
}
Util.broadcastMessage(ChatColor.GREEN
+ "Résultat du Choppe-Mouton: " + ChatColor.RESET + result);
Bukkit.getScheduler().cancelTasks(Util.getMhoEssentials());
}
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/DonjonCommand.java
package com.sheeris.mho.MhoEssentials.command;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.Acrobot.Breeze.Utils.MaterialUtil;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.modules.DonjonManager;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.NestedCommand;
public class DonjonCommand {
public DonjonCommand(MhoEssentials instance) {
}
@Command(aliases = { "chestitem" }, usage = "<nom_chest> <item,nbr,%> [item,nbr,%]", desc = "Définition des items d'un coffre.", min = 2)
@CommandPermissions({ "mho.donjon.admin" })
public void cItem(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
String chest = args.getString(0).toLowerCase();
if (Manager.getDonjon().existDonjon(donjon)) {
if (Manager.getDonjon().existChest(donjon, chest)) {
String[] items = args.getSlice(2);
player.sendMessage("Donjon: " + ChatColor.GREEN + donjon
+ ChatColor.RESET + ", Coffre:" + ChatColor.BLUE
+ chest + ChatColor.RESET);
for (String item : items) {
String[] info = item.split(",");
if (info.length == 3) {
ItemStack is = MaterialUtil.getItem(info[0]);
if (is != null) {
int number = 0;
int pourcentage = 0;
try {
number = Integer.valueOf(info[1]);
pourcentage = Integer.valueOf(info[2]);
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.RED
+ "Item invalide: " + item
+ ChatColor.RESET);
return;
}
if ((pourcentage < 1 && pourcentage > 100)
|| (number < 1 && number > 100)) {
player.sendMessage(ChatColor.RED
+ "Item invalide: " + item
+ ChatColor.RESET);
return;
}
Manager.getDonjon().addItemChest(player.getName(),
chest, item);
player.sendMessage("Ajout de l'item: "
+ DonjonManager.infoItem(is, number,
pourcentage));
} else {
player.sendMessage(ChatColor.RED
+ "Item invalide: " + item
+ ChatColor.RESET);
return;
}
}
}
} else {
player.sendMessage(ChatColor.RED + "Le coffre n'existe pas."
+ ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
}
}
@Command(aliases = { "clear" }, desc = "Vide Chest/Group")
@NestedCommand({ DonjonClearCommand.class })
@CommandPermissions({ "mho.donjon.admin" })
public void clear(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "close" }, desc = "Déselection Donjon/Group")
@NestedCommand({ DonjonCloseCommand.class })
@CommandPermissions({ "mho.donjon.admin" })
public void close(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "create" }, desc = "Création d'un Donjon/Chest/Group")
@NestedCommand({ DonjonCreateCommand.class })
@CommandPermissions({ "mho.donjon.admin" })
public void create(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "delete" }, desc = "Suppréssion Donjon/Chest/Group")
@NestedCommand({ DonjonDeleteCommand.class })
@CommandPermissions({ "mho.donjon.admin" })
public void delete(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "dispenseritem" }, usage = "<nom_dispenser> <item,nbr,%> [item,nbr,%]", desc = "Définition des items d'un distributeur.", min = 2)
@CommandPermissions({ "mho.donjon.admin" })
public void dItem(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
String dispenser = args.getString(0).toLowerCase();
if (Manager.getDonjon().existDonjon(donjon)) {
if (Manager.getDonjon().existDispenser(donjon, dispenser)) {
String[] items = args.getSlice(2);
player.sendMessage("Donjon: " + ChatColor.GREEN + donjon
+ ChatColor.RESET + ", Distributeur:" + ChatColor.BLUE
+ dispenser + ChatColor.RESET);
for (String item : items) {
String[] info = item.split(",");
if (info.length == 3) {
ItemStack is = MaterialUtil.getItem(info[0]);
if (is != null) {
int number = 0;
int pourcentage = 0;
try {
number = Integer.valueOf(info[1]);
pourcentage = Integer.valueOf(info[2]);
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.RED
+ "Item invalide: " + item
+ ChatColor.RESET);
return;
}
if ((pourcentage < 1 && pourcentage > 100)
|| (number < 1 && number > 100)) {
player.sendMessage(ChatColor.RED
+ "Item invalide: " + item
+ ChatColor.RESET);
return;
}
Manager.getDonjon().addItemDispenser(
player.getName(), dispenser, item);
player.sendMessage("Ajout de l'item: "
+ DonjonManager.infoItem(is, number,
pourcentage));
} else {
player.sendMessage(ChatColor.RED
+ "Item invalide: " + item
+ ChatColor.RESET);
return;
}
}
}
} else {
player.sendMessage(ChatColor.RED
+ "Le distributeur n'existe pas." + ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
}
}
@Command(aliases = { "info" }, desc = "Information Donjon/Chest/Group")
@NestedCommand({ DonjonInfoCommand.class })
@CommandPermissions({ "mho.donjon.admin" })
public void info(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "list" }, usage = "", desc = "Liste des donjons.", max = 0)
@CommandPermissions({ "mho.donjon.admin" })
public void list(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
for (String donjon : Manager.getDonjon().getDonjons()) {
player.sendMessage("Donjon: " + ChatColor.GREEN + donjon
+ ChatColor.RESET);
}
}
@Command(aliases = { "reset" }, usage = "<hh:mm> [hh:mm]", desc = "Heure(s) du reset du donjon.", min = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void reset(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
if (Manager.getDonjon().existDonjon(donjon)) {
if (args.getString(0).equalsIgnoreCase("now")) {
player.sendMessage(ChatColor.GREEN + "Reset du donjon."
+ ChatColor.RESET);
Manager.getDonjon().resetDonjon(donjon);
Util.info(player.getName() + " reset le donjon " + donjon);
return;
}
boolean error = false;
String[] reset = args.getSlice(1);
for (String time : reset) {
if (!Pattern.matches("^([01][0-9]|2[0-3]):[0-5][0-9]$", time)) {
error = true;
break;
}
}
if (!error) {
Manager.getDonjon().setDonjonReset(donjon, reset);
player.sendMessage("Reset du donjon: " + ChatColor.GREEN
+ args.getJoinedStrings(0) + ChatColor.RESET);
} else {
player.sendMessage(ChatColor.RED + "Reset invalide."
+ ChatColor.RESET);
return;
}
} else {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
return;
}
}
@Command(aliases = { "select" }, desc = "Selection Donjon/Group")
@NestedCommand({ DonjonSelectCommand.class })
@CommandPermissions({ "mho.donjon.admin" })
public void select(CommandContext args, CommandSender sender) {
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/StatsCommand.java
package com.sheeris.mho.MhoEssentials.command;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.database.DataManager;
import com.sheeris.mho.MhoEssentials.entry.PlayerEntry;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Vault;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class StatsCommand {
public StatsCommand(MhoEssentials instance) {
}
@Command(aliases = { "info" }, usage = "[player_name]", desc = "Information sur les Stats", min = 0, max = 1)
@CommandPermissions({ "mho.stats.use", "mho.stats.use.others" })
public void list(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
if (!Config.isEnabled("stats")) {
player.sendMessage(ChatColor.RED + "Command disabled."
+ ChatColor.RESET);
return;
}
String name = player.getName();
PlayerEntry playerEntry;
if (args.argsLength() == 0) {
playerEntry = DataManager.getPlayerEntry(DataManager
.getPlayer(name));
} else if ((Vault.hasPermission(player, "mho.stats.use.others") && DataManager
.havePlayer(args.getString(0)))
|| args.getString(0).equalsIgnoreCase(name.toLowerCase())) {
playerEntry = DataManager.getPlayerEntry(DataManager.getPlayer(args
.getString(0)));
} else if (!Vault.hasPermission(player, "mho.stats.use.others")) {
player.sendMessage(ChatColor.RED
+ "Vous ne pouvez pas regarder les statistiques des autres joueurs."
+ ChatColor.RESET);
return;
} else {
player.sendMessage(ChatColor.RED
+ "Aucune statistique pour le joueur." + ChatColor.RESET);
return;
}
player.sendMessage("Joueur: " + ChatColor.YELLOW
+ playerEntry.getPlayerName() + ChatColor.RESET);
player.sendMessage("Pvp Kill: " + ChatColor.GREEN
+ playerEntry.getPvpKill() + ChatColor.RESET + ", Pvp Death: "
+ ChatColor.RED + playerEntry.getPvpDeath() + ChatColor.RESET
+ ", Pvp Elo: " + ChatColor.BLUE + playerEntry.getPlayerElo()
+ ChatColor.RESET);
player.sendMessage("Pve Kill: " + ChatColor.GREEN
+ playerEntry.getPveKill() + ChatColor.RESET + ", Pve Death: "
+ ChatColor.RED + playerEntry.getPveDeath() + ChatColor.RESET);
if (Vault.getMoneyAmount(playerEntry.getPlayerName()) > 0.00) {
player.sendMessage("HardCoins: " + ChatColor.GREEN
+ Vault.getMoneyAmount(playerEntry.getPlayerName())
+ ChatColor.RESET);
}
}
@Command(aliases = { "top" }, usage = "[type]", desc = "Information sur le Top PVP/PVE", min = 1, max = 1)
@CommandPermissions({ "mho.stats.top", "mho.stats.top.pve",
"mho.stats.top.pvp" })
public void top(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
if (!Config.isEnabled("stats")) {
player.sendMessage(ChatColor.RED + "Command disabled."
+ ChatColor.RESET);
return;
}
Map<Integer, PlayerEntry> playerTop;
if (args.getString(0).equalsIgnoreCase("pvp")
&& (Vault.hasPermission(player, "mho.stats.top.pvp") || Vault
.hasPermission(player, "mho.stats.top"))) {
playerTop = DataManager.getTop("pvp");
} else if (args.getString(0).equalsIgnoreCase("pve")
&& (Vault.hasPermission(player, "mho.stats.top.pve") || Vault
.hasPermission(player, "mho.stats.top"))) {
playerTop = DataManager.getTop("pve");
} else if (args.getString(0).equalsIgnoreCase("pvp")
&& !Vault.hasPermission(player, "mho.stats.top.pvp")) {
player.sendMessage("Vous n'avez pas la permission d'afficher le top pvp.");
return;
} else if (args.getString(0).equalsIgnoreCase("pve")
&& !Vault.hasPermission(player, "mho.stats.top.pve")) {
player.sendMessage("Vous n'avez pas la permission d'afficher le top pve.");
return;
} else {
player.sendMessage("Merci d'essayer avec 'pvp' ou 'pve'.");
return;
}
int i = 0;
while (i < playerTop.size()) {
i++;
PlayerEntry playerEntry = playerTop.get(i);
player.sendMessage(i + ") " + ChatColor.YELLOW
+ playerEntry.getPlayerName() + ChatColor.RESET);
if (args.getString(0).equalsIgnoreCase("pvp")) {
player.sendMessage("Elo:" + ChatColor.BLUE
+ playerEntry.getPlayerElo() + ChatColor.RESET
+ ", Kill:" + ChatColor.GREEN
+ playerEntry.getPvpKill() + ChatColor.RESET
+ ", Death:" + ChatColor.RED
+ playerEntry.getPvpDeath() + ChatColor.RESET);
} else if (args.getString(0).equalsIgnoreCase("pve")) {
player.sendMessage("Kill:" + ChatColor.GREEN
+ playerEntry.getPveKill() + ChatColor.RESET
+ ", Death:" + ChatColor.RED
+ playerEntry.getPveDeath() + ChatColor.RESET);
}
}
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/LimitCreaListener.java
package com.sheeris.mho.MhoEssentials.modules;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.entity.StorageMinecart;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.inventory.InventoryHolder;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Vault;
public class LimitCreaListener implements Listener {
private boolean enabled;
public LimitCreaListener() {
enabled = Config.isEnabled("limitCrea");
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
if (!enabled || player.getGameMode() != GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass")) {
return;
}
Block block = event.getBlock();
if (block.getType() == Material.BEDROCK) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
Player player = event.getPlayer();
if (!enabled || player == null
|| player.getGameMode() == GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass")) {
return;
}
Block block = event.getBlock();
if (event.getCause() == IgniteCause.FLINT_AND_STEEL
&& block.getWorld().getBlockTypeIdAt(block.getX(),
block.getY() - 1, block.getZ()) != net.minecraft.server.Block.NETHERRACK.id) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
if (!enabled || player.getGameMode() != GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass")) {
return;
}
Block block = event.getBlock();
if (block.getType() == Material.BEDROCK) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
if (!enabled || player.getGameMode() != GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass")) {
return;
}
event.getItemDrop().remove();
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPickupItem(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
if (!enabled || player.getGameMode() != GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass")) {
return;
}
event.getItem().remove();
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerAccess(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (!enabled
|| player.getGameMode() != GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass.interact")
|| (event.useInteractedBlock() == Result.DENY && event
.useItemInHand() == Result.DENY)) {
return;
}
if (event.getItem() != null
&& (event.getItem().getTypeId() == 373
|| event.getItem().getTypeId() == 383 || event
.getItem().getTypeId() == 384)) {
event.setUseItemInHand(Result.DENY);
event.setCancelled(true);
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
Block block = event.getClickedBlock();
if (block.getState() instanceof InventoryHolder
|| block.getType() == Material.WORKBENCH
|| block.getTypeId() == 179 || block.getTypeId() == 180
|| block.getTypeId() == 181) {
event.setUseInteractedBlock(Result.DENY);
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerDie(PlayerDeathEvent event) {
Player player = event.getEntity();
if (!enabled || player.getGameMode() != GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass")) {
return;
}
event.getDrops().clear();
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
if (!enabled || player.getGameMode() != GameMode.CREATIVE
|| Vault.hasPermission(player, "mho.limitcrea.bypass.interact")) {
return;
}
if (event.getRightClicked() instanceof StorageMinecart) {
event.setCancelled(true);
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/StopChatListener.java
package com.sheeris.mho.MhoEssentials.modules;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Util;
import com.sheeris.mho.MhoEssentials.util.Vault;
public class StopChatListener implements Listener {
private boolean enabled;
public StopChatListener() {
enabled = Config.isEnabled("stopChat");
}
private void chatEvil(Player player) {
player.damage(1);
if (player.isDead()) {
Util.broadcastMessage(ChatColor.RED + player.getName()
+ " est mort(e). Il faut savoir se taire."
+ ChatColor.RESET);
} else {
player.sendMessage("Ca fait mal, hein !");
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChat(PlayerChatEvent event) {
if (!enabled || !Config.getToggle("chatOff")) {
return;
}
Player player = event.getPlayer();
boolean canChat = Vault.hasPermission(player, "mho.stopchat.bypass");
if (!canChat) {
player.sendMessage("Tu ne peux pas parler !");
if (Config.getToggle("chatEvil")) {
chatEvil(player);
}
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (!enabled || !Config.getToggle("chatOff")) {
return;
}
Player player = event.getPlayer();
boolean canChat = Vault.hasPermission(player, "mho.stopchat.bypass");
if (!canChat) {
String message = event.getMessage().toLowerCase();
if (message.contains("/me")) {
player.sendMessage("Tu ne peux pas parler !");
if (Config.getToggle("chatEvil")) {
chatEvil(player);
}
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
if (!enabled || !Config.getToggle("chatOff")) {
return;
}
Player player = event.getPlayer();
player.sendMessage(ChatColor.RED + "Le chat est actuellement fermé !"
+ ChatColor.RESET);
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/DonjonDeleteCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class DonjonDeleteCommand {
public DonjonDeleteCommand(MhoEssentials instance) {
}
@Command(aliases = { "chest" }, usage = "<nom_coffre>", desc = "Suppression d'un coffre.", min = 1, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void chest(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
if (!Manager.getDonjon().existDonjon(donjon)) {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
return;
}
String chest = args.getString(0).toLowerCase();
if (donjon != null) {
if (Manager.getDonjon().existChest(donjon, chest)) {
Manager.getDonjon().deleteChest(donjon, chest);
player.sendMessage("Suppréssion du Coffre: " + ChatColor.GREEN
+ chest + ChatColor.RESET);
} else {
player.sendMessage(ChatColor.RED + "Le coffre n'existe pas."
+ ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
}
}
@Command(aliases = { "dispenser" }, usage = "<nom_distributeur>", desc = "Suppression d'un distributeur.", min = 1, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void dispenser(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
if (!Manager.getDonjon().existDonjon(donjon)) {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
return;
}
String dispenser = args.getString(0).toLowerCase();
if (donjon != null) {
if (Manager.getDonjon().existDispenser(donjon, dispenser)) {
Manager.getDonjon().deleteDispenser(donjon, dispenser);
player.sendMessage("Suppréssion du Distributeur: "
+ ChatColor.GREEN + dispenser + ChatColor.RESET);
} else {
player.sendMessage(ChatColor.RED
+ "Le distributeur n'existe pas." + ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
}
}
@Command(aliases = { "donjon" }, usage = "<nom_donjon>", desc = "Suppression d'un Donjon.", min = 1, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void donjon(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = args.getString(0).toLowerCase();
if (Manager.getDonjon().existDonjon(donjon)) {
if (donjon.equalsIgnoreCase(Manager.getDonjon().getDonjon(
player.getName()))) {
Manager.getDonjon().closeDonjon(player.getName());
}
Manager.getDonjon().deleteDonjon(donjon);
player.sendMessage("Suppréssion du Donjon: " + ChatColor.GREEN
+ donjon + ChatColor.RESET);
} else {
player.sendMessage(ChatColor.RED + "Le donjon n'existe pas."
+ ChatColor.RESET);
}
}
@Command(aliases = { "group" }, usage = "<nom_groupe>", desc = "Suppression d'un groupe.", min = 1, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void group(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
if (!Manager.getDonjon().existDonjon(donjon)) {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
return;
}
String group = args.getString(0).toLowerCase();
if (donjon != null) {
if (Manager.getDonjon().existGroup(donjon, group)) {
if (group.equalsIgnoreCase(Manager.getDonjon().getGroup(
player.getName()))) {
Manager.getDonjon().closeGroup(player.getName());
}
Manager.getDonjon().deleteGroup(donjon, group);
player.sendMessage("Suppression du Groupe: " + ChatColor.GREEN
+ group + ChatColor.RESET);
} else {
player.sendMessage(ChatColor.RED + "Le groupe n'existe pas."
+ ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED
+ "Vous n'avez pas de donjon selectionné."
+ ChatColor.RESET);
}
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/WorldParamCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class WorldParamCommand {
public WorldParamCommand(MhoEssentials instance) {
}
@Command(aliases = { "difficulty" }, usage = "", desc = "Définition de la difficulté du Monde.", min = 1, max = 2)
@CommandPermissions({ "mho.world.admin" })
public void difficulty(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
World world = player.getWorld();
String worldDiff = args.getString(0);
Difficulty newDiff = null;
try {
newDiff = Difficulty.valueOf(worldDiff.toUpperCase());
} catch (IllegalArgumentException e) {
player.sendMessage(ChatColor.RED + "Difficulté invalide."
+ ChatColor.RESET);
return;
}
if (args.argsLength() == 2) {
world = Bukkit.getWorld(args.getString(1));
if (world == null) {
player.sendMessage(ChatColor.RED + "Ce monde n'existe pas."
+ ChatColor.RESET);
return;
}
}
player.sendMessage("Modification de la difficulté:");
player.sendMessage("Monde: " + ChatColor.BLUE + world.getName()
+ ChatColor.RESET + ", Difficulté: " + ChatColor.GREEN
+ world.getDifficulty().name() + ChatColor.RESET + ".");
world.setDifficulty(newDiff);
Config.setWorldDifficulty(world.getName(), newDiff.name());
player.sendMessage("vers:");
player.sendMessage("Monde: " + ChatColor.BLUE + world.getName()
+ ChatColor.RESET + ", Difficulté: " + ChatColor.GREEN
+ world.getDifficulty().name() + ChatColor.RESET + ".");
}
@Command(aliases = { "pvp" }, usage = "", desc = "Définition de la difficulté du Monde.", min = 1, max = 2)
@CommandPermissions({ "mho.world.admin" })
public void pvp(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
World world = player.getWorld();
String worldState = args.getString(0);
boolean newState;
if (worldState.equalsIgnoreCase("on")) {
newState = true;
} else if (worldState.equalsIgnoreCase("off")) {
newState = false;
} else {
player.sendMessage(ChatColor.RED + "Valeur invalide."
+ ChatColor.RESET);
return;
}
if (args.argsLength() == 2) {
world = Bukkit.getWorld(args.getString(1));
if (world == null) {
player.sendMessage(ChatColor.RED + "Ce monde n'existe pas."
+ ChatColor.RESET);
return;
}
}
player.sendMessage("Modification du PvP:");
player.sendMessage("Monde: " + ChatColor.BLUE + world.getName()
+ ChatColor.RESET + ", PvP: " + ChatColor.GREEN
+ world.getPVP() + ChatColor.RESET + ".");
world.setPVP(newState);
Config.setWorldPvp(world.getName(), newState);
player.sendMessage("vers:");
player.sendMessage("Monde: " + ChatColor.BLUE + world.getName()
+ ChatColor.RESET + ", PvP: " + ChatColor.GREEN
+ world.getPVP() + ChatColor.RESET + ".");
}
@Command(aliases = { "weather" }, usage = "", desc = "Définition de la difficulté du Monde.", min = 1, max = 2)
@CommandPermissions({ "mho.world.admin" })
public void weather(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
World world = player.getWorld();
String worldState = args.getString(0);
boolean newState;
if (worldState.equalsIgnoreCase("on")) {
newState = true;
} else if (worldState.equalsIgnoreCase("off")) {
newState = false;
} else {
player.sendMessage(ChatColor.RED + "Valeur invalide."
+ ChatColor.RESET);
return;
}
if (args.argsLength() == 2) {
world = Bukkit.getWorld(args.getString(1));
if (world == null) {
player.sendMessage(ChatColor.RED + "Ce monde n'existe pas."
+ ChatColor.RESET);
return;
}
}
player.sendMessage("Modification de la météorologie:");
player.sendMessage("Monde: " + ChatColor.BLUE + world.getName()
+ ChatColor.RESET + ", Météorologie: " + ChatColor.GREEN
+ worldState + ".");
Config.setWorldWeather(world.getName(), newState);
if (!newState && (world.hasStorm() || world.isThundering())) {
world.setStorm(false);
world.setThundering(false);
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/MhoCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.modules.PvpListener;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
import com.sheeris.mho.MhoEssentials.util.Vault;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.NestedCommand;
public class MhoCommand {
public MhoCommand(MhoEssentials instance) {
}
@Command(aliases = { "avatar" }, desc = "Avatar Management")
@NestedCommand({ AvatarCommand.class })
@CommandPermissions({ "mho.avatar.use" })
public void avatar(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "cm" }, desc = "Choppe Mouton Management")
@NestedCommand({ ChoppeMoutonCommand.class })
@CommandPermissions({ "mho.choppemouton.use" })
public void cm(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "dj" }, desc = "Donjon Module Management")
@NestedCommand({ DonjonCommand.class })
@CommandPermissions({ "mho.donjon.admin" })
public void donjon(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "dragoncube" }, desc = "Dragon Cube Management")
@NestedCommand({ DragonCubeCommand.class })
@CommandPermissions({ "mho.dragoncube.admin" })
public void dragoncube(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "g" }, usage = "<message>", desc = "Envoyer un message à sont groupe.", min = 1)
@CommandPermissions({ "mho.chat.use" })
public void groupchat(CommandContext args, CommandSender sender) {
if (!Config.isEnabled("groupChat")) {
return;
}
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
int joinedString = 0;
String group = Manager.getGroup(player);
for (String chatGroup : Config.groups) {
if (args.argsLength() > 1
&& chatGroup.equalsIgnoreCase(args.getString(0))
&& Vault.hasPermission(player, "mho.chat.use.others")) {
group = args.getString(0);
joinedString = 1;
}
}
for (Player p : Bukkit.getOnlinePlayers()) {
if (Manager.playerInGroup(p, group)
|| Vault.hasPermission(p, "mho.chat.spy")) {
p.sendMessage("[" + player.getDisplayName() + ChatColor.GRAY
+ " -> " + group + "] " + ChatColor.RESET
+ args.getJoinedStrings(joinedString));
}
}
}
@Command(aliases = { "market" }, desc = "Market Watch Module Management")
@NestedCommand({ MarketCommand.class })
@CommandPermissions({ "mho.market.admin" })
public void market(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "mho" }, desc = "Mho Management")
@NestedCommand({ ModuleCommand.class })
public void mho(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "npc" }, desc = "NPC Module Management")
@NestedCommand({ NPCCommand.class })
@CommandPermissions({ "mho.npc.admin" })
public void npc(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "ct" }, usage = "", desc = "Permet de savoir si on est tag en PVP.", min = 0, max = 0)
@CommandPermissions({ "mho.pvp.tag.use" })
public void pvptag(CommandContext args, CommandSender sender) {
if (!Config.isEnabled("pvp")) {
return;
}
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (PvpListener.isPvpTag(player)) {
player.sendMessage(ChatColor.RED + "Vous êtes en PVP."
+ ChatColor.RESET);
} else {
player.sendMessage(ChatColor.GREEN + "Vous n'êtes pas en PVP."
+ ChatColor.RESET);
}
}
@Command(aliases = { "rand", "random" }, desc = "Random", min = 0, max = 1)
public void random(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
int rand = 100;
try {
rand = args.getInteger(0, 100);
} catch (NumberFormatException ignored) {
}
int result = Util.random.nextInt(rand + 1);
for (Player see : Bukkit.getOnlinePlayers()) {
if (player.getWorld().equals(see.getWorld())
&& player.getLocation().distanceSquared(see.getLocation()) < 256D) {
see.sendMessage("Random " + ChatColor.RED + rand
+ ChatColor.RESET + " de " + player.getDisplayName()
+ ChatColor.RESET + " : " + result);
}
}
}
@Command(aliases = { "spawn" }, desc = "Spawn Module Management")
@NestedCommand({ SpawnCommand.class })
@CommandPermissions({ "mho.spawn.use", "mho.spawn.admin" })
public void spawn(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "stats" }, desc = "Stats Information")
@NestedCommand({ StatsCommand.class })
@CommandPermissions({ "mho.stats.use", "mho.stats.use.others",
"mho.stats.top", "mho.stats.top.pve", "mho.stats.top.pvp" })
public void stats(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "sh" }, desc = "Stonehenge Module Management")
@NestedCommand({ StonehengeCommand.class })
@CommandPermissions({ "mho.stonehenge.admin" })
public void stonehenge(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "stopchat" }, desc = "StopChat Module Management")
@NestedCommand({ StopChatCommand.class })
@CommandPermissions({ "mho.stopchat.admin" })
public void stopchat(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "woe" }, desc = "WoE Management")
@NestedCommand({ WoECommand.class })
public void woe(CommandContext args, CommandSender sender) {
}
@Command(aliases = { "worldparam" }, desc = "World Param Module Management")
@NestedCommand({ WorldParamCommand.class })
@CommandPermissions({ "mho.world.admin" })
public void worldparam(CommandContext args, CommandSender sender) {
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/ChoppeMoutonCommand.java
package com.sheeris.mho.MhoEssentials.command;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Cuboid;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class ChoppeMoutonCommand {
public ChoppeMoutonCommand(MhoEssentials instance) {
}
@Command(aliases = { "lever" }, usage = "", desc = "Défini le levier d'activation.", min = 0, max = 0)
@CommandPermissions({ "mho.choppemouton.admin" })
public void lever(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
Location loc = player.getLocation();
Map<String, Object> newSpawn = new HashMap<String, Object>();
newSpawn.put("world", loc.getWorld().getName());
newSpawn.put("x", ((double) Math.round(loc.getX() * 10) / 10));
newSpawn.put("y", ((double) Math.round(loc.getY() * 10) / 10));
newSpawn.put("z", ((double) Math.round(loc.getZ() * 10) / 10));
newSpawn.put("yam", ((double) Math.round(loc.getYaw() * 10) / 10));
newSpawn.put("pitch", 0.0);
Config.setCMLever(newSpawn);
player.sendMessage("Emplacement du levier défini.");
}
@Command(aliases = { "sheep" }, usage = "<num>", desc = "Nombre de mouton dans l'arene.", min = 1, max = 1)
@CommandPermissions({ "mho.choppemouton.use" })
public void sheep(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
Location loc = Util.getSheepCMLocation();
try {
int num = args.getInteger(0);
int i = 0;
if (num >= 0) {
Cuboid.resetSheep(Bukkit.getWorld(Config.getCMWorldName()),
Config.getCMRegionName());
if (num == 0) {
player.sendMessage(ChatColor.GREEN
+ "Reset du Choppe-Mouton." + ChatColor.RESET);
} else {
while (i < num && i < 50) {
loc.getWorld().spawnEntity(loc, EntityType.SHEEP);
i++;
}
player.sendMessage(ChatColor.GREEN + "Mise en place de "
+ i + " mouton(s)." + ChatColor.RESET);
}
}
} catch (Exception e) {
player.sendMessage(ChatColor.RED + "Nombre invalide."
+ ChatColor.RESET);
}
}
@Command(aliases = { "spawn" }, usage = "", desc = "Défini le spawn des Moutons.", min = 0, max = 0)
@CommandPermissions({ "mho.choppemouton.admin" })
public void spawn(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
Location loc = player.getLocation();
Map<String, Object> newSpawn = new HashMap<String, Object>();
newSpawn.put("world", loc.getWorld().getName());
newSpawn.put("x", ((double) Math.round(loc.getX() * 10) / 10));
newSpawn.put("y", ((double) Math.round(loc.getY() * 10) / 10));
newSpawn.put("z", ((double) Math.round(loc.getZ() * 10) / 10));
newSpawn.put("yam", ((double) Math.round(loc.getYaw() * 10) / 10));
newSpawn.put("pitch", 0.0);
Config.setSheepCMSpawn(newSpawn);
player.sendMessage("Spawn des moutons défini.");
}
@Command(aliases = { "time" }, usage = "<timer>", desc = "Durée du Choppe Mouton", min = 1, max = 1)
@CommandPermissions({ "mho.choppemouton.use" })
public void time(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
try {
Manager.setChoppeMoutonTimer(args.getInteger(0));
player.sendMessage(ChatColor.GREEN + "Durée du ChoppeMouton: "
+ Manager.getChoppeMoutonTimer() + " minute(s)"
+ ChatColor.RESET);
} catch (Exception e) {
player.sendMessage(ChatColor.RED + "Durée invalide."
+ ChatColor.RESET);
}
}
@Command(aliases = { "tp" }, usage = "", desc = "Crée le TP de fin d'évenement.", min = 0, max = 0)
@CommandPermissions({ "mho.choppemouton.admin" })
public void tp(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
Location loc = player.getLocation();
Map<String, Object> newSpawn = new HashMap<String, Object>();
newSpawn.put("world", loc.getWorld().getName());
newSpawn.put("x", ((double) Math.round(loc.getX() * 10) / 10));
newSpawn.put("y", ((double) Math.round(loc.getY() * 10) / 10));
newSpawn.put("z", ((double) Math.round(loc.getZ() * 10) / 10));
newSpawn.put("yam", ((double) Math.round(loc.getYaw() * 10) / 10));
newSpawn.put("pitch", 0.0);
Config.setCMSpawn(newSpawn);
player.sendMessage(Util.getCMSpawnString());
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/DonjonInfoCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class DonjonInfoCommand {
public DonjonInfoCommand(MhoEssentials instance) {
}
@Command(aliases = { "chest" }, usage = "<nom_coffre>", desc = "Information sur un coffre.", min = 1, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void chest(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
String chest = args.getString(0).toLowerCase();
if (Manager.getDonjon().existDonjon(donjon)) {
if (Manager.getDonjon().existChest(donjon, chest)) {
player.sendMessage("Information du Coffre: " + ChatColor.GREEN
+ chest + ChatColor.RESET);
player.sendMessage(Manager.getDonjon().infoLocationChest(
donjon, chest));
String[] items = Manager.getDonjon().infoItemsChest(donjon,
chest);
for (String item : items) {
player.sendMessage("Item: " + item);
}
} else {
player.sendMessage(ChatColor.RED + "Le coffre n'existe pas."
+ ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED + "Le donjon n'existe pas."
+ ChatColor.RESET);
}
}
@Command(aliases = { "dispenser" }, usage = "<nom_distributeur>", desc = "Information sur un distributeur.", min = 1, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void dispenser(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
String dispenser = args.getString(0).toLowerCase();
if (Manager.getDonjon().existDonjon(donjon)) {
if (Manager.getDonjon().existDispenser(donjon, dispenser)) {
player.sendMessage("Information du Distributeur: "
+ ChatColor.GREEN + dispenser + ChatColor.RESET);
player.sendMessage(Manager.getDonjon().infoLocationDispenser(
donjon, dispenser));
String[] items = Manager.getDonjon().infoItemsDispenser(donjon,
dispenser);
for (String item : items) {
player.sendMessage("Item: " + item);
}
} else {
player.sendMessage(ChatColor.RED
+ "Le distributeur n'existe pas." + ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED + "Le donjon n'existe pas."
+ ChatColor.RESET);
}
}
@Command(aliases = { "donjon" }, usage = "[nom_donjon]", desc = "Information sur un Donjon.", min = 0, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void donjon(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = args.getString(0,
Manager.getDonjon().getDonjon(player.getName()));
if (Manager.getDonjon().existDonjon(donjon)) {
player.sendMessage("Information du Donjon: " + ChatColor.GREEN
+ donjon + ChatColor.RESET);
player.sendMessage("Reset: " + ChatColor.RED
+ Manager.getDonjon().infoResetDonjon(donjon)
+ ChatColor.RESET);
player.sendMessage("Groupe(s): " + ChatColor.YELLOW
+ Manager.getDonjon().infoGroupsDonjon(donjon)
+ ChatColor.RESET);
player.sendMessage("Coffre(s): " + ChatColor.BLUE
+ Manager.getDonjon().infoChestsDonjon(donjon)
+ ChatColor.RESET);
player.sendMessage("Distributeur(s): " + ChatColor.DARK_PURPLE
+ Manager.getDonjon().infoDispensersDonjon(donjon)
+ ChatColor.RESET);
} else {
player.sendMessage(ChatColor.RED + "Le donjon n'existe pas."
+ ChatColor.RESET);
}
}
@Command(aliases = { "group" }, usage = "[nom_groupe]", desc = "Information sur un groupe.", min = 0, max = 1)
@CommandPermissions({ "mho.donjon.admin" })
public void group(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
String donjon = Manager.getDonjon().getDonjon(player.getName());
if (Manager.getDonjon().existDonjon(donjon)) {
String group = args.getString(0,
Manager.getDonjon().getGroup(player.getName()))
.toLowerCase();
if (Manager.getDonjon().existGroup(donjon, group)) {
player.sendMessage("Information du Groupe: " + ChatColor.GREEN
+ group + ChatColor.RESET);
player.sendMessage("Pourcentage d'apparition: "
+ ChatColor.RED
+ Manager.getDonjon().infoPourcentageGroup(donjon,
group) + ChatColor.RESET);
player.sendMessage("Nombre de Bloc(s): " + ChatColor.YELLOW
+ Manager.getDonjon().infoBlocksGroup(donjon, group)
+ ChatColor.RESET);
} else {
player.sendMessage(ChatColor.RED + "Le groupe n'existe pas."
+ ChatColor.RESET);
}
} else {
player.sendMessage(ChatColor.RED + "Le donjon n'existe pas."
+ ChatColor.RESET);
}
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/MarketCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.util.Util;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class MarketCommand {
public MarketCommand(MhoEssentials instance) {
}
@Command(aliases = { "update" }, usage = "", desc = "Force la MAJ du MarketWatch.", min = 0, max = 0)
@CommandPermissions({ "mho.market.admin" })
public void update(CommandContext args, CommandSender sender)
throws CommandException {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
player.sendMessage("MAJ du MarketWatch en cours.");
Util.marketCheck();
player.sendMessage("Fin de la MAJ du MarketWatch.");
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/StonehengeTask.java
package com.sheeris.mho.MhoEssentials.modules;
import java.util.TimerTask;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
public class StonehengeTask extends TimerTask {
private int timer;
private int taskid;
public StonehengeTask(int time) {
timer = time;
}
@Override
public void run() {
switch (timer) {
case 0:
Bukkit.getScheduler().cancelTask(taskid);
Util.broadcastMessage(ChatColor.RED + "Fin du Stonehenge."
+ ChatColor.RESET);
Util.broadcastMessage("Résultat du Stonehenge: ");
Manager.getStonehenge().stop();
Manager.getStonehenge().info();
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 10:
case 15:
case 30:
case 45:
case 60:
case 75:
case 90:
case 105:
case 120:
case 135:
case 150:
case 165:
case 180:
Util.broadcastMessage(ChatColor.GREEN + "Il reste "
+ ChatColor.RESET + ChatColor.RED + timer + ChatColor.RESET
+ ChatColor.GREEN + " minute(s) pour le Stonehenge."
+ ChatColor.RESET);
Manager.getStonehenge().save();
Manager.getStonehenge().info();
timer--;
break;
default:
timer--;
}
}
public void setId(int id) {
taskid = id;
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/DonjonCloseCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class DonjonCloseCommand {
public DonjonCloseCommand(MhoEssentials instance) {
}
@Command(aliases = { "donjon" }, usage = "", desc = "Déselection d'un Donjon.", min = 0)
@CommandPermissions({ "mho.donjon.admin" })
public void donjon(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
Manager.getDonjon().closeDonjon(player.getName());
player.sendMessage(ChatColor.GREEN + "Déselection du donjon."
+ ChatColor.RESET);
}
@Command(aliases = { "group" }, usage = "", desc = "Déselection d'un groupe.", min = 0)
@CommandPermissions({ "mho.donjon.admin" })
public void group(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
Manager.getDonjon().closeGroup(player.getName());
player.sendMessage(ChatColor.GREEN + "Déselection du groupe."
+ ChatColor.RESET);
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/DragonCubeCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.modules.DragonCubeListener;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class DragonCubeCommand {
public DragonCubeCommand(MhoEssentials instance) {
}
@Command(aliases = { "info" }, usage = "", desc = "Info sur le Dragon Cube", min = 0, max = 0)
@CommandPermissions({ "mho.dragoncube.admin" })
public void info(CommandContext args, CommandSender sender) {
DragonCubeListener.getInfo(sender);
}
@Command(aliases = { "spawn" }, usage = "", desc = "Spawn un Dragon Cube", min = 0, max = 0)
@CommandPermissions({ "mho.dragoncube.admin" })
public void spawn(CommandContext args, CommandSender sender) {
DragonCubeListener.deleteOldDragonCube();
DragonCubeListener.createDragonCube();
}
@Command(aliases = { "tp" }, usage = "", desc = "Téléportation sur le Dragon Cube", min = 0, max = 0)
@CommandPermissions({ "mho.dragoncube.admin" })
public void tp(CommandContext args, CommandSender sender) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
DragonCubeListener.tpTo(player);
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/command/StonehengeCommand.java
package com.sheeris.mho.MhoEssentials.command;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.modules.StonehengeTask;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
public class StonehengeCommand {
private MhoEssentials plugin;
private int taskid = -1;
public StonehengeCommand(MhoEssentials instance) {
plugin = instance;
}
@Command(aliases = { "info" }, usage = "", desc = "Info du Stonehenge.", min = 0, max = 0)
@CommandPermissions({ "mho.stonehenge.admin" })
public void info(CommandContext args, CommandSender sender) {
if (Config.isEnabled("stonehenge")) {
Manager.getStonehenge().save();
Manager.getStonehenge().info();
}
}
@Command(aliases = { "reset" }, usage = "", desc = "Reset du Stonehenge.", min = 0, max = 0)
@CommandPermissions({ "mho.stonehenge.admin" })
public void reset(CommandContext args, CommandSender sender) {
if (Config.isEnabled("stonehenge")) {
Bukkit.getScheduler().cancelTask(taskid);
Manager.getStonehenge().reset();
}
}
@Command(aliases = { "score" }, usage = "", desc = "Info du Stonehenge.", min = 0, max = 0)
@CommandPermissions({ "mho.stonehenge.use" })
public void score(CommandContext args, CommandSender sender) {
if (Config.isEnabled("stonehenge")) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
Manager.getStonehenge().save();
Manager.getStonehenge().info(player);
}
}
@Command(aliases = { "start" }, usage = "<time_minute>", desc = "Lance un Stonehenge pour X minutes.", min = 1, max = 1)
@CommandPermissions({ "mho.stonehenge.admin" })
public void start(CommandContext args, CommandSender sender) {
if (Config.isEnabled("stonehenge")) {
Manager.getStonehenge().start();
int time = args.getInteger(0, 60);
Bukkit.broadcastMessage(ChatColor.GREEN + "Début du Stonehenge."
+ ChatColor.RESET);
StonehengeTask task = new StonehengeTask(time);
taskid = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin,
task, 0, 1200);
task.setId(taskid);
}
}
@Command(aliases = { "stop" }, usage = "", desc = "Stop un Stonehenge.", min = 0, max = 0)
@CommandPermissions({ "mho.stonehenge.admin" })
public void stop(CommandContext args, CommandSender sender) {
if (Config.isEnabled("stonehenge") && taskid >= 0) {
Bukkit.getScheduler().cancelTask(taskid);
Manager.getStonehenge().stop();
Bukkit.broadcastMessage(ChatColor.RED + "Fin du Stonehenge."
+ ChatColor.RESET);
Manager.getStonehenge().info();
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/util/Util.java
package com.sheeris.mho.MhoEssentials.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Logger;
import net.minecraft.server.EntityTypes;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.entity.CraftEntity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import com.Acrobot.ChestShop.Signs.ChestShopSign;
import com.sheeris.mho.MhoEssentials.MhoEssentials;
import com.sheeris.mho.MhoEssentials.database.DataManager;
import com.sheeris.mho.MhoEssentials.entry.PlayerEntry;
import com.sheeris.mho.MhoEssentials.event.ShopCheckEvent;
public class Util {
public static final Random random = new Random();
private static final Logger logger = Logger.getLogger("Minecraft");
private static MhoEssentials plugin = null;
public static void broadcastMessage(String message) {
Bukkit.broadcastMessage(message);
}
public static void calcElo(PlayerEntry winner, PlayerEntry loser) {
double scoreWinner = 1 / (1 + (Math.pow(10,
(loser.getPlayerElo() - winner.getPlayerElo()) / 400)));
double scoreLoser = 1 / (1 + (Math.pow(10,
(winner.getPlayerElo() - loser.getPlayerElo()) / 400)));
int kWinner = 15;
int kLoser = 15;
if (winner.getPvpKill() + winner.getPvpDeath() <= 30) {
kWinner = 25;
} else if (winner.getPlayerElo() > 2400) {
kWinner = 10;
}
if (loser.getPvpKill() + loser.getPvpDeath() <= 30) {
kLoser = 25;
} else if (loser.getPlayerElo() > 2400) {
kLoser = 10;
}
double newWinner = winner.getPlayerElo()
+ (kWinner * (1 - scoreWinner));
double newLoser = loser.getPlayerElo() + (kLoser * (0 - scoreLoser));
winner.setPlayerElo((int) Math.round(newWinner));
loser.setPlayerElo((int) Math.round(newLoser));
}
public static String capitalizeFirstLetter(String string) {
return capitalizeFirstLetter(string, ' ');
}
public static String capitalizeFirstLetter(String string, char separator) {
String[] split = string.toLowerCase().split(
Character.toString(separator));
StringBuilder total = new StringBuilder(string.length());
for (String s : split) {
total.append(Character.toUpperCase(s.charAt(0)))
.append(s.substring(1)).append(' ');
}
return total.toString().trim();
}
public static boolean deleteFile(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
if (!deleteFile(new File(file, children[i]))) {
return false;
}
}
}
return file.delete();
}
public static void disablePlugin() {
Bukkit.getPluginManager().disablePlugin(Util.getMhoEssentials());
}
public static void download(URL url, File file) throws IOException {
if (!file.getParentFile().exists())
file.getParentFile().mkdir();
if (file.exists())
file.delete();
file.createNewFile();
int size = url.openConnection().getContentLength();
Util.info("Downloading " + file.getName() + " (" + size / 1024
+ "kb) ...");
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[1024];
int len, downloaded = 0, msgs = 0;
final long start = System.currentTimeMillis();
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
downloaded += len;
if ((int) ((System.currentTimeMillis() - start) / 500) > msgs) {
Util.info((int) ((double) downloaded / (double) size * 100d)
+ "%");
msgs++;
}
}
in.close();
out.close();
Util.info("Download finished");
}
public static String getCMSpawnString() {
Map<String, Object> spawnInfo = Config.getCMSpawn();
return "Monde: " + ChatColor.BLUE + spawnInfo.get("world").toString()
+ ChatColor.RESET + ", Position: " + ChatColor.GREEN
+ spawnInfo.get("x").toString() + " "
+ spawnInfo.get("y").toString() + " "
+ spawnInfo.get("z").toString() + ChatColor.RESET + ".";
}
public static String getDisplayName(Player player) {
return ChatColor.translateAlternateColorCodes('&', Vault.getChat()
.getPlayerPrefix(player)
+ player.getName()
+ Vault.getChat().getPlayerSuffix(player));
}
public static Location getLocation(String group, String spawn) {
String worldDest;
double x, y, z;
float yam, pitch;
Map<String, Object> spawnInfo = Config.getSpawn(group, spawn);
worldDest = (String) spawnInfo.get("world");
x = (Double) spawnInfo.get("x");
y = (Double) spawnInfo.get("y");
z = (Double) spawnInfo.get("z");
yam = new Float(spawnInfo.get("yam").toString());
pitch = new Float(spawnInfo.get("pitch").toString());
World world = Bukkit.getWorld(worldDest);
return new Location(world, x, y, z, yam, pitch);
}
public static MhoEssentials getMhoEssentials() {
if (plugin == null) {
plugin = (MhoEssentials) Bukkit.getPluginManager().getPlugin(
"MhoEssentials");
}
return plugin;
}
public static String getMobName(LivingEntity entity) {
return EntityTypes.b(((CraftEntity) entity).getHandle());
}
public static Player getPlayer(List<HumanEntity> humans) {
Player player = null;
for (HumanEntity human : humans) {
player = (Player) human;
}
return player;
}
public static Location getPlayerCMLocation() {
String worldDest;
double x, y, z;
Map<String, Object> spawnInfo = Config.getCMSpawn();
worldDest = (String) spawnInfo.get("world");
x = (Double) spawnInfo.get("x");
y = (Double) spawnInfo.get("y");
z = (Double) spawnInfo.get("z");
World world = Bukkit.getWorld(worldDest);
return new Location(world, x, y, z);
}
public static Location getSheepCMLocation() {
String worldDest;
double x, y, z;
Map<String, Object> spawnInfo = Config.getSheepCMSpawn();
worldDest = (String) spawnInfo.get("world");
x = (Double) spawnInfo.get("x");
y = (Double) spawnInfo.get("y");
z = (Double) spawnInfo.get("z");
World world = Bukkit.getWorld(worldDest);
return new Location(world, x, y, z);
}
public static Location getSpawnLocationByName(String world, String spawn) {
String group = Config.getSpawnGroup(world);
if (!Config.isSpawn(group, spawn)) {
return null;
}
return Util.getLocation(group, spawn);
}
public static Location getSpawnLocationByPermission(Player player) {
Location loc;
String group = Config.getSpawnGroup(player.getWorld().getName());
loc = Util.getLocation(group, Config.getSpawnDefault(group));
Set<String> spawnNames = Config.getSpawnList(group);
for (String spawnName : spawnNames) {
if (Vault.hasPermission(player, "mho.spawn.use." + group + "."
+ spawnName)) {
loc = Util.getLocation(group, spawnName);
break;
}
}
return loc;
}
public static Location getSpawnLocationByRegion(Player player) {
Location loc;
String group = Config.getSpawnGroup(player.getWorld().getName());
loc = Util.getSpawnLocationByPermission(player);
List<String> regions = Cuboid.getRegionList(player);
for (String region : regions) {
String spawnName = Config.getSpawnRegion(group, region);
if (spawnName != null && Config.isSpawn(group, spawnName)) {
loc = Util.getLocation(group, spawnName);
break;
}
}
return loc;
}
public static String getSpawnString(String group, String spawn) {
Map<String, Object> spawnInfo = Config.getSpawn(group, spawn);
return "Nom: " + ChatColor.RED + spawn + ChatColor.RESET + ", Monde: "
+ ChatColor.BLUE + spawnInfo.get("world").toString()
+ ChatColor.RESET + ", Position: " + ChatColor.GREEN
+ spawnInfo.get("x").toString() + " "
+ spawnInfo.get("y").toString() + " "
+ spawnInfo.get("z").toString() + ChatColor.RESET + ".";
}
public static void info(String msg) {
logger.info("[MhoEssentials] " + msg);
}
public static void marketCheck() {
try {
Util.info("Launch MarketWatch check.");
Map<Integer, Map<String, Integer>> map = DataManager.getShops();
for (Integer shopId : map.keySet()) {
Block block = Bukkit.getWorld(
DataManager.getWorld(map.get(shopId).get("world_id")))
.getBlockAt(map.get(shopId).get("shop_x"),
map.get(shopId).get("shop_y"),
map.get(shopId).get("shop_z"));
if (block.getState() instanceof Sign
&& ChestShopSign.isValid((Sign) block.getState())) {
Bukkit.getPluginManager().callEvent(
new ShopCheckEvent((Sign) block.getState()));
} else {
DataManager.deleteShop(shopId);
}
}
Util.info("MarketWatch check done.");
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public static void registerEvents(Listener listener) {
Bukkit.getPluginManager().registerEvents(listener,
Util.getMhoEssentials());
}
public static void scheduleAsyncRepeatingTask(Runnable task, long delay,
long period) {
Bukkit.getScheduler().scheduleAsyncRepeatingTask(
Util.getMhoEssentials(), task, delay, period);
}
public static void scheduleSyncRepeatingTask(Runnable task, long delay,
long period) {
Bukkit.getScheduler().scheduleSyncRepeatingTask(
Util.getMhoEssentials(), task, delay, period);
}
public static void sendMessageByPermission(String txt, String perm) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (Vault.hasPermission(player, perm)) {
player.sendMessage(txt);
}
}
}
public static void severe(String msg) {
logger.severe("[MhoEssentials] " + msg);
}
public static void warning(String msg) {
logger.warning("[MhoEssentials] " + msg);
}
}<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/entry/PlayerEntry.java
package com.sheeris.mho.MhoEssentials.entry;
import org.bukkit.Location;
import com.sheeris.mho.MhoEssentials.database.DataManager;
public class PlayerEntry extends DataEntry {
public static PlayerEntry monsterDeath(PlayerEntry player, String monster) {
PlayerEntry clone = new PlayerEntry();
clone.setPlayerId(Integer.valueOf(player.getPlayerId()));
clone.setPlayerName(String.valueOf(player.getPlayerName()));
clone.setPlayerElo(Integer.valueOf(player.getPlayerElo()));
clone.setPveKill(Integer.valueOf(player.getPveKill()));
clone.setPveDeath(Integer.valueOf(player.getPveDeath()));
clone.setPvpKill(Integer.valueOf(player.getPvpKill()));
clone.setPvpDeath(Integer.valueOf(player.getPvpDeath()));
clone.setPvp(false);
clone.setDeath(true);
clone.setNameMonster(monster);
clone.setTime(getDate());
return clone;
}
public static PlayerEntry monsterKill(PlayerEntry player, String monster,
int idObject, String strEnchant) {
PlayerEntry clone = new PlayerEntry();
clone.setPlayerId(Integer.valueOf(player.getPlayerId()));
clone.setPlayerName(String.valueOf(player.getPlayerName()));
clone.setPlayerElo(Integer.valueOf(player.getPlayerElo()));
clone.setPveKill(Integer.valueOf(player.getPveKill()));
clone.setPveDeath(Integer.valueOf(player.getPveDeath()));
clone.setPvpKill(Integer.valueOf(player.getPvpKill()));
clone.setPvpDeath(Integer.valueOf(player.getPvpDeath()));
clone.setPvp(false);
clone.setDeath(false);
clone.setNameMonster(monster);
clone.setObject(idObject);
clone.setEnchant(strEnchant);
clone.setTime(getDate());
return clone;
}
public static PlayerEntry playerDeath(PlayerEntry player) {
PlayerEntry clone = new PlayerEntry();
clone.setPlayerId(Integer.valueOf(player.getPlayerId()));
clone.setPlayerName(String.valueOf(player.getPlayerName()));
clone.setPlayerElo(Integer.valueOf(player.getPlayerElo()));
clone.setPveKill(Integer.valueOf(player.getPveKill()));
clone.setPveDeath(Integer.valueOf(player.getPveDeath()));
clone.setPvpKill(Integer.valueOf(player.getPvpKill()));
clone.setPvpDeath(Integer.valueOf(player.getPvpDeath()));
clone.setPvp(true);
clone.setDeath(true);
clone.setTime(getDate());
return clone;
}
public static PlayerEntry playerKill(PlayerEntry player,
PlayerEntry idKilled, int idObject, String strEnchant) {
PlayerEntry clone = new PlayerEntry();
clone.setPlayerId(Integer.valueOf(player.getPlayerId()));
clone.setPlayerName(String.valueOf(player.getPlayerName()));
clone.setPlayerElo(Integer.valueOf(player.getPlayerElo()));
clone.setPveKill(Integer.valueOf(player.getPveKill()));
clone.setPveDeath(Integer.valueOf(player.getPveDeath()));
clone.setPvpKill(Integer.valueOf(player.getPvpKill()));
clone.setPvpDeath(Integer.valueOf(player.getPvpDeath()));
clone.setPvp(true);
clone.setDeath(false);
clone.setObject(idObject);
clone.setEnchant(strEnchant);
clone.setPlayerOpponent(idKilled);
clone.setTime(getDate());
return clone;
}
private int playerId;
private String playerName;
private int playerElo;
private int pveKill;
private int pveDeath;
private int pvpKill;
private int pvpDeath;
private String time = null;
private boolean pvp = false;
private boolean death = false;
private int object = 0;
private String enchant = "{}";
private String nameMonster = "";
private PlayerEntry playerOpponent = null;
private Location loc = null;
public String getEnchant() {
return enchant;
}
public String getNameMonster() {
return nameMonster;
}
public int getObject() {
return object;
}
public int getPlayerElo() {
return playerElo;
}
public int getPlayerId() {
return playerId;
}
public String getPlayerName() {
return playerName;
}
public PlayerEntry getPlayerOpponent() {
return playerOpponent;
}
public int getPveDeath() {
return pveDeath;
}
public int getPveKill() {
return pveKill;
}
public int getPvpDeath() {
return pvpDeath;
}
public int getPvpKill() {
return pvpKill;
}
@Override
public String getSQL() {
return null;
}
public String getTime() {
return time;
}
public int getWorld() {
if (loc == null) {
return 0;
}
return DataManager.getWorld(loc.getWorld().getName());
}
public int getX() {
if (loc == null) {
return 0;
}
return loc.getBlockX();
}
public int getY() {
if (loc == null) {
return 0;
}
return loc.getBlockY();
}
public int getZ() {
if (loc == null) {
return 0;
}
return loc.getBlockZ();
}
public boolean isDeath() {
return death;
}
public boolean isPvp() {
return pvp;
}
public void setDeath(boolean death) {
this.death = death;
}
public void setEnchant(String enchant) {
this.enchant = enchant;
}
public void setLocation(Location location) {
loc = location;
}
public void setNameMonster(String nameMonster) {
this.nameMonster = nameMonster;
}
public void setObject(int object) {
this.object = object;
}
public void setPlayerElo(int playerElo) {
this.playerElo = playerElo;
}
public void setPlayerId(int playerId) {
this.playerId = playerId;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public void setPlayerOpponent(PlayerEntry playerOpponent) {
this.playerOpponent = playerOpponent;
}
public void setPveDeath(int pveDeath) {
this.pveDeath = pveDeath;
}
public void setPveKill(int pveKill) {
this.pveKill = pveKill;
}
public void setPvp(boolean pvp) {
this.pvp = pvp;
}
public void setPvpDeath(int pvpDeath) {
this.pvpDeath = pvpDeath;
}
public void setPvpKill(int pvpKill) {
this.pvpKill = pvpKill;
}
public void setTime(String time) {
this.time = time;
}
}
<file_sep>/src/main/resources/create_mysql.sql
CREATE TABLE IF NOT EXISTS `mho_players` (
`player_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`player_name` varchar(32) NOT NULL,
`player_name_lower` varchar(32) NOT NULL,
PRIMARY KEY (`player_id`),
UNIQUE KEY `player_name` (`player_name`),
UNIQUE KEY `player_name_lower` (`player_name_lower`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `mho_players_stats` (
`player_id` int(10) unsigned NOT NULL,
`player_elo` int(10) unsigned NOT NULL DEFAULT '1200',
`pve_kill` int(10) unsigned NOT NULL DEFAULT '0',
`pve_death` int(10) unsigned NOT NULL DEFAULT '0',
`pvp_kill` int(10) unsigned NOT NULL DEFAULT '0',
`pvp_death` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`player_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `mho_pve` (
`pve_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pve_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`player_id` int(10) unsigned NOT NULL,
`pve_kill` tinyint(1) unsigned NOT NULL DEFAULT '1',
`pve_opponent` varchar(255) NOT NULL,
`pve_object` int(10) unsigned NOT NULL,
`pve_object_enchant` varchar(255) NOT NULL DEFAULT '{}',
PRIMARY KEY (`pve_id`),
KEY `player_kill` (`player_id`,`pve_kill`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `mho_pvp` (
`pvp_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pvp_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`player_id_winner` int(10) unsigned NOT NULL,
`player_elo_winner` int(10) unsigned NOT NULL,
`player_id_loser` int(10) unsigned NOT NULL,
`player_elo_loser` int(10) unsigned NOT NULL,
`pvp_object` int(10) unsigned NOT NULL,
`pvp_object_enchant` varchar(255) NOT NULL DEFAULT '{}',
PRIMARY KEY (`pvp_id`),
KEY `player_id_winner` (`player_id_winner`),
KEY `player_id_loser` (`player_id_loser`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `mho_worlds` (
`world_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`world_name` varchar(32) NOT NULL,
PRIMARY KEY (`world_id`),
UNIQUE KEY `world_name` (`world_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `mho_shops` (
`shop_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`world_id` int(10) unsigned NOT NULL,
`shop_x` int(11) NOT NULL,
`shop_y` int(11) NOT NULL,
`shop_z` int(11) NOT NULL,
`shop_create_date` datetime NOT NULL,
`shop_update_date` datetime NOT NULL,
`player_id` int(11) NOT NULL,
`shop_buy_price` float DEFAULT NULL,
`shop_sell_price` float DEFAULT NULL,
`shop_item_id` int(10) unsigned NOT NULL,
`shop_item_durability` int(10) unsigned NOT NULL,
`shop_item_enchant` varchar(255) DEFAULT NULL,
`shop_quantity` int(10) unsigned NOT NULL,
PRIMARY KEY (`shop_id`),
UNIQUE KEY `shop_world_x_y_z` (`world_id`,`shop_x`,`shop_y`,`shop_z`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `mho_weathers` (
`weather_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`world_id` int(10) unsigned NOT NULL,
`weather_date` datetime NOT NULL,
`weather_state` varchar(16) NOT NULL,
`weather_duration` int(10) unsigned NOT NULL,
PRIMARY KEY (`weather_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/StonehengeListener.java
package com.sheeris.mho.MhoEssentials.modules;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import com.Acrobot.Breeze.Utils.StringUtil;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
public class StonehengeListener implements Listener {
private boolean enabled;
public boolean start;
private static ConcurrentHashMap<String, Integer> score = new ConcurrentHashMap<String, Integer>();
private static ConcurrentHashMap<String, Long> time = new ConcurrentHashMap<String, Long>();
private static ConcurrentHashMap<String, String> team = new ConcurrentHashMap<String, String>();
public StonehengeListener() {
enabled = Config.isEnabled("stonehenge");
start = false;
}
public void info() {
if (score.isEmpty()) {
return;
}
for (String group : score.keySet()) {
if (group.length() > 0) {
String name = StringUtil.capitalizeFirstLetter(group);
String display = String.format(ChatColor.GRAY + "%s"
+ ChatColor.RESET + ": %d points.", name,
score.get(group));
Util.broadcastMessage(display);
}
}
}
public void info(Player player) {
if (score.isEmpty()) {
player.sendMessage(ChatColor.RED + "Aucun score disponible."
+ ChatColor.RESET);
return;
}
for (String group : score.keySet()) {
if (group.length() > 0) {
String name = StringUtil.capitalizeFirstLetter(group);
String display = String.format(ChatColor.GRAY + "%s"
+ ChatColor.RESET + ": %d points.", name,
score.get(group));
player.sendMessage(display);
}
}
}
public boolean isInProgress() {
return start;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (!enabled || !start) {
return;
}
Block block = event.getBlock();
if (!Config.isValidStonehengeBlock(block.getWorld().getName(),
block.getX(), block.getY(), block.getZ())
|| block.getType().getId() != Material.WOOL.getId()) {
return;
}
String blockName = Config.getStonehengeBlockName(block.getWorld()
.getName(), block.getX(), block.getY(), block.getZ());
String blockSH = block.getWorld().getName().toLowerCase() + ","
+ block.getX() + "," + block.getY() + "," + block.getZ();
String player = event.getPlayer().getDisplayName();
if (team.containsKey(blockSH) && time.get(blockSH) != 0) {
long placetime = time.get(blockSH);
long breaktime = System.currentTimeMillis();
int addscore = Math.round((int) (breaktime - placetime) / 1000);
String groupKey = team.get(blockSH);
String group = StringUtil.capitalizeFirstLetter(team.get(blockSH));
if (!score.containsKey(groupKey)) {
score.put(groupKey, addscore);
} else {
int newScore = score.get(groupKey) + addscore;
score.put(groupKey, newScore);
}
Util.broadcastMessage(player + ChatColor.RESET
+ " détruit le point '" + ChatColor.RED + blockName
+ ChatColor.RESET + "' des " + ChatColor.GRAY + group
+ ChatColor.RESET + ".");
}
time.put(blockSH, 0L);
team.put(blockSH, "");
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
if (!enabled || !start) {
return;
}
Block block = event.getBlock();
if (!Config.isValidStonehengeBlock(block.getWorld().getName(),
block.getX(), block.getY(), block.getZ())
|| block.getType().getId() != Material.WOOL.getId()) {
return;
}
String blockSH = block.getWorld().getName().toLowerCase() + ","
+ block.getX() + "," + block.getY() + "," + block.getZ();
String player = event.getPlayer().getDisplayName();
String group = Manager.getGroup(event.getPlayer());
long placetime = System.currentTimeMillis();
team.put(blockSH, group);
time.put(blockSH, placetime);
String blockName = Config.getStonehengeBlockName(block.getWorld()
.getName(), block.getX(), block.getY(), block.getZ());
Util.broadcastMessage(player + ChatColor.RESET + " prend le point '"
+ ChatColor.RED + blockName + ChatColor.RESET + "'.");
}
public void reset() {
this.start = false;
score.clear();
team.clear();
time.clear();
}
public void save() {
long breaktime = System.currentTimeMillis();
for (String block : time.keySet()) {
long placetime = time.get(block);
int addscore = Math.round((int) (breaktime - placetime) / 1000);
time.put(block, breaktime);
String group = team.get(block);
if (!score.containsKey(group)) {
score.put(group, addscore);
} else {
score.put(group, score.get(group) + addscore);
}
}
}
public void start() {
reset();
this.start = true;
}
public void stop() {
this.start = false;
long breaktime = System.currentTimeMillis();
for (String block : time.keySet()) {
long placetime = time.get(block);
int addscore = Math.round((int) (breaktime - placetime) / 1000);
String group = team.get(block);
if (!score.containsKey(group)) {
score.put(group, addscore);
} else {
score.put(group, score.get(group) + addscore);
}
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/entry/WeatherEntry.java
package com.sheeris.mho.MhoEssentials.entry;
public class WeatherEntry extends DataEntry {
public enum State {
SUN, RAIN, THUNDER,
}
private int worldId;
private int weatherDuration;
private String weatherDate;
private String weatherState;
public WeatherEntry(int world, WeatherEntry.State state, int duration) {
worldId = world;
weatherState = state.name();
weatherDate = getDate();
weatherDuration = Math.round(duration / 20);
}
@Override
public String getSQL() {
String sql = String
.format("INSERT INTO mho_weathers (`world_id`, `weather_date`, `weather_state`, `weather_duration`) VALUES (%s, '%s', '%s', %s);",
worldId, weatherDate, weatherState, weatherDuration);
return sql;
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/BlockCodeListener.java
package com.sheeris.mho.MhoEssentials.modules;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Vault;
public class BlockCodeListener implements Listener {
private boolean enabled;
public BlockCodeListener() {
enabled = Config.isEnabled("blockCode");
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (!enabled || Vault.hasPermission(player, "mho.blockcode.bypass")) {
return;
}
for (String code : Config.getBlockCode()) {
player.sendMessage(code.replaceAll("(&([a-fk0-9]))", "\u00a7$2"));
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/NPCSpawnTask.java
package com.sheeris.mho.MhoEssentials.modules;
import java.util.TimerTask;
import org.bukkit.Location;
import com.sheeris.mho.MhoEssentials.util.Manager;
import com.sheeris.mho.MhoEssentials.util.Util;
public class NPCSpawnTask extends TimerTask {
private Location spawn = null;
private int id = 0;
public NPCSpawnTask(Location spawnLoc, int spawnId) {
spawn = spawnLoc;
id = spawnId;
}
@Override
public void run() {
if (spawn.getChunk().load()) {
Manager.getNPC().spawnNPC(spawn, id);
spawn.getChunk().unload(true, true);
} else {
Util.warning("Fail Spawn NPC: " + id + ", Location: "
+ spawn.toString());
}
}
}
<file_sep>/src/main/java/com/sheeris/mho/MhoEssentials/modules/BanPotionListener.java
package com.sheeris.mho.MhoEssentials.modules;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.BrewEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import com.sheeris.mho.MhoEssentials.util.Config;
import com.sheeris.mho.MhoEssentials.util.Vault;
public class BanPotionListener implements Listener {
private static Map<String, Long> cooldown = new HashMap<String, Long>();
public static boolean isCoolDown(Player player) {
return cooldown.containsKey(player.getName())
&& cooldown.get(player.getName()) >= Calendar.getInstance()
.getTime().getTime();
}
private boolean enabled;
public BanPotionListener() {
enabled = Config.isEnabled("banPotion");
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBrewEvent(BrewEvent event) {
if (!enabled) {
return;
}
String ingredient = event.getContents().getIngredient().getType()
.name();
for (int i = 0; i < 3; i++) {
if (event.getContents().getItem(i) != null) {
if (!Config.isValidPotion(ingredient, (int) event.getContents()
.getItem(i).getDurability())) {
ItemStack item = new ItemStack(373);
item.setDurability((short) 16);
event.getContents().setItem(i, item);
}
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
if (!enabled) {
return;
}
Player player = event.getPlayer();
if ((event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)
&& player.getItemInHand().getTypeId() == 373) {
if (!Config.isValidPotion((int) player.getItemInHand()
.getDurability())
&& !Vault.hasPermission(player, "mho.banpotion.bypass")) {
player.sendMessage(ChatColor.RED
+ "Cette potion est interdite." + ChatColor.RESET);
event.setCancelled(true);
} else if (Config.isCoolDownPotion((int) player.getItemInHand()
.getDurability())
&& !Vault.hasPermission(player, "mho.banpotion.bypass")) {
if (!isCoolDown(player)) {
Long coolEnd = Calendar.getInstance().getTime().getTime()
+ Config.getPotionCoolDownDuration();
cooldown.put(player.getName(), coolEnd);
} else {
player.sendMessage(ChatColor.RED
+ "Cooldown pour cette potion en cours."
+ ChatColor.RESET);
event.setCancelled(true);
}
}
}
}
} | bbf8d21491c1c6941bff7b637e86ca8c7c0ede01 | [
"Java",
"SQL"
] | 25 | Java | Dilandau/MhoEssentials | f1086d2e685e968345eb332c62c8301928a3c5ee | da23a3b153c0406e37516b45cce851e05ca3b1a9 |
refs/heads/master | <repo_name>zrob/yay-buildpack<file_sep>/bin/supply
#!/usr/bin/env bash
build_path=${1}
cache_path=${2}
deps_path=${3}
index=${4}
echo "-----> Adding some YAY to your app."
bin_path=${deps_path}/${index}/bin
mkdir -p ${bin_path}
cat > ${bin_path}/yay <<EOF
#!/usr/bin/env bash
echo "YAY!!!"
EOF
chmod +x ${bin_path}/yay
mkdir -p ${build_path}/.profile.d
echo "export PATH=${bin_path}:\$PATH" > ${build_path}/.profile.d/0000_yay-path.sh
<file_sep>/README.md
# yay-buildpack
Add some YAY to your app.
```
cf push MYAPP -b https://github.com/zrob/yay-buildpack -b USEFUL_BUILDPACK
cf logs MYAPP
cf run-task MYAPP yay
```
| 4c885ef53aa9a0c1a58b7e95ec83d45400bb2bf8 | [
"Markdown",
"Shell"
] | 2 | Shell | zrob/yay-buildpack | d3cbce69db896c31a590101ceadd5d07f70fa3c4 | bc820c8c1ce555bdb004c73cfe7eaf2dd81dc920 |
refs/heads/master | <repo_name>tulustobing/SelfManagement<file_sep>/src/main/java/com/self/management/service/ReminderService.java
package com.self.management.service;
import java.util.List;
import org.springframework.stereotype.Component;
import com.self.management.model.Reminder;
import com.self.management.model.ToDo;
@Component
public interface ReminderService {
public List<Reminder> getAll();
public Reminder getReminder(int id);
public int save(Reminder reminder);
public void update(Reminder reminder);
public void delete(int id);
}
<file_sep>/src/main/java/com/self/management/dao/ToDoDao.java
package com.self.management.dao;
import org.hibernate.SessionFactory;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.self.management.model.ToDo;
@Component
@Repository
public class ToDoDao {
@Autowired
private SessionFactory sessionFactory;
public ToDo getToDo(int id) {
return (ToDo) sessionFactory.getCurrentSession().get(ToDo.class, id);
}
public int save(ToDo todo) {
return (int) sessionFactory.getCurrentSession().save(todo);
}
public void update(ToDo todo) {
sessionFactory.getCurrentSession().update(todo);
}
public void delete(int id) {
sessionFactory.getCurrentSession().delete(getToDo(id));
}
public List<ToDo> getAll() {
return sessionFactory.getCurrentSession().createQuery("from ToDo").list();
}
}
<file_sep>/src/main/java/com/self/management/model/Reminder.java
package com.self.management.model;
import java.sql.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Component
@Entity
@Table(name = "reminder")
public class Reminder {
private int id;
private String title;
private String description;
private Date startDate;
private Date dueDate;
private ColourLevel colourLevel;
@Id
@Column(name = "ID")
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "LEVEL_ID")
public ColourLevel getColourLevel() {
return colourLevel;
}
public void setColourLevel(ColourLevel colourLevel) {
this.colourLevel = colourLevel;
}
}
<file_sep>/src/main/java/com/self/management/model/Item.java
package com.self.management.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Component
@Entity
@Table(name = "item")
public class Item {
private int id;
private String imagePath;
private String Description;
@Id
@Column(name = "ID")
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
};
}
<file_sep>/src/main/resources/self_management.sql
/*
SQLyog Community v12.2.1 (64 bit)
MySQL - 10.1.9-MariaDB : Database - self_management
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`self_management` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `self_management`;
/*Table structure for table `colour_level` */
DROP TABLE IF EXISTS `colour_level`;
CREATE TABLE `colour_level` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`COLOUR` varchar(10) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
/*Data for the table `colour_level` */
insert into `colour_level`(`ID`,`COLOUR`) values
(1,'green'),
(2,'yellow'),
(3,'red'),
(4,'string'),
(6,'string');
/*Table structure for table `item` */
DROP TABLE IF EXISTS `item`;
CREATE TABLE `item` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`IMANGE_PATH` varchar(500) DEFAULT NULL,
`DESCRIPTION` varchar(1000) DEFAULT NULL,
`image_path` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
/*Data for the table `item` */
insert into `item`(`ID`,`IMANGE_PATH`,`DESCRIPTION`,`image_path`) values
(1,'IMANGE_PATH','DESCRIPTION',NULL),
(5,'IMANGE_PATH','DESCRIPTION',NULL);
/*Table structure for table `reminder` */
DROP TABLE IF EXISTS `reminder`;
CREATE TABLE `reminder` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`TITLE` varchar(500) DEFAULT NULL,
`DESCRIPTION` varchar(1000) DEFAULT NULL,
`START_DATE` date DEFAULT NULL,
`DUE_DATE` date DEFAULT NULL,
`LEVEL_ID` int(11) DEFAULT NULL,
`image_path` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
/*Data for the table `reminder` */
insert into `reminder`(`ID`,`TITLE`,`DESCRIPTION`,`START_DATE`,`DUE_DATE`,`LEVEL_ID`,`image_path`) values
(1,'Project','Please review your project','2016-05-10','2016-05-10',1,NULL),
(2,'Projects','Please review your project','2016-05-10','2016-05-10',2,NULL),
(4,'string','string','2016-05-10','2016-05-10',6,NULL);
/*Table structure for table `to_do` */
DROP TABLE IF EXISTS `to_do`;
CREATE TABLE `to_do` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`TITLE` varchar(100) DEFAULT NULL,
`DESCRIPTION` varchar(1000) DEFAULT NULL,
`IS_DONE` tinyint(1) DEFAULT NULL,
`DUE_DATE` date DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;
/*Data for the table `to_do` */
insert into `to_do`(`ID`,`TITLE`,`DESCRIPTION`,`IS_DONE`,`DUE_DATE`) values
(2,'string','Gstring',1,'2016-05-10'),
(3,'test','test',0,NULL),
(4,'string','string',1,'2016-04-20'),
(5,'string','string',1,'2016-04-20'),
(6,'string','string',1,'2016-04-20'),
(7,'string','string',1,'2016-04-20'),
(8,'string','string',1,'2016-04-20'),
(9,'string','string',1,'2016-04-20'),
(10,'string','string',1,'2016-04-20'),
(11,'string','string',1,'2016-04-20'),
(12,'string','string',1,'2016-04-20'),
(13,'string','string',1,'2016-04-20'),
(14,'string','string',1,'2016-04-20');
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) DEFAULT NULL,
`PASSWORD` varchar(256) DEFAULT NULL,
`DISABLE` tinyint(1) DEFAULT NULL,
`LOGIN_FAILURES` int(11) DEFAULT NULL,
`LAST_LOGGED_IN` date DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*Data for the table `user` */
insert into `user`(`ID`,`NAME`,`PASSWORD`,`DISABLE`,`LOGIN_FAILURES`,`LAST_LOGGED_IN`) values
(1,'Jaka','tarub',0,0,'2016-04-11');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep>/target/classes/application.properties
spring.datasource.url=jdbc:mysql://localhost/self_management
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
<file_sep>/src/main/java/com/self/management/model/ColourLevel.java
package com.self.management.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Component
@Entity
@Table(name = "colour_level")
public class ColourLevel {
@Id
@Column(name = "ID")
@GeneratedValue
private int id;
private String colour;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
<file_sep>/src/main/java/com/self/management/model/ToDo.java
package com.self.management.model;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Component
@Entity
@Table(name = "to_do")
public class ToDo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String title;
private String description;
private boolean is_done;
private Date due_date;
public ToDo() {
super();
this.id = 1;
this.title = "Doto";
this.description = "Winning Doto";
this.is_done = true;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isIs_done() {
return is_done;
}
public void setIs_done(boolean is_done) {
this.is_done = is_done;
}
public Date getDue_date() {
return due_date;
}
public void setDue_date(Date due_date) {
this.due_date = due_date;
}
@Override
public String toString() {
return "ToDo [id=" + id + ", title=" + title + ", description=" + description + ", is_done=" + is_done
+ ", due_date=" + due_date + "]";
}
}
<file_sep>/README.md
# SelfManagement Backend With Spring Boot + MySQL + Swagger
Repositories for Self Management project
Project merupakan projek backend untuk project Self Management yang menyediakan API untuk proses CRUD(Create Update Delete) terhadap tabel yang ada didalam database.
Untuk mempermudah dalam mengakses API yang disediakan, saya menggunakan swagger sebagai interface yang memudahkan dalam mengakses API yang telah disediakan.
# Cara penggunaan
## Build DB
Silahkan clone project ini, lalu jalankan self_management.sql yanga ada di folder sources.
## Run Project
Silahkan masuk kedalam folder SelfManagement, lalu jalankan CMD didalam folder tersebut,
*caranya klik pada addressbar, lalu hapus pathnya, lalu ketikkan cmd.
lalu ketikkan mvn spring-boot:run
Project akan berjalan di port 8080, silahkan akses localhost:8080/swagger/index.html
Salam
<NAME>
<file_sep>/src/main/java/com/self/management/dao/ReminderDao.java
package com.self.management.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.self.management.model.Reminder;
@Component
@Repository
public class ReminderDao {
@Autowired
private SessionFactory sessionFactory;
public List<Reminder> getAll() {
return sessionFactory.getCurrentSession().createQuery("from Reminder").list();
}
public Reminder getReminder(int id) {
return (Reminder) sessionFactory.getCurrentSession().get(Reminder.class, id);
}
public int save(Reminder reminder) {
return (int) sessionFactory.getCurrentSession().save(reminder);
}
public void update(Reminder reminder) {
sessionFactory.getCurrentSession().update(reminder);
}
public void delete(int id) {
sessionFactory.getCurrentSession().delete(getReminder(id));
}
}
<file_sep>/src/main/java/com/self/management/impl/ItemServiceImpl.java
package com.self.management.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.self.management.dao.ItemDao;
import com.self.management.model.Item;
import com.self.management.service.ItemService;
@Component
@Service
@Transactional
public class ItemServiceImpl implements ItemService {
@Autowired
ItemDao itemDao;
@Override
public List<Item> getAll() {
return itemDao.getAll();
}
@Override
public Item getItem(int id) {
return itemDao.getItem(id);
}
@Override
public int save(Item item) {
return itemDao.save(item);
}
@Override
public void update(Item item) {
itemDao.update(item);
}
@Override
public void delete(int id) {
itemDao.delete(id);
}
}
| a880ce8a47b0da67dc54f20aa4471895d746a875 | [
"Markdown",
"Java",
"SQL",
"INI"
] | 11 | Java | tulustobing/SelfManagement | 2ec29b992f9145e6ca47198b2ffa79c748687fc1 | 65fd9f353c36b448c0f627395035d8fcd6a4c636 |
refs/heads/master | <file_sep>var clases = document.getElementsByClassName("mensaje");//Se guarda en la variable clases el arreglo obtenido mediante .getElementsByClassName
var tam = clases.length;//Se obtiene el tamaño del arreglo(contiene el total de elementos que coinciden con la clase "mensaje")
console.log(tam);//Se verifica el tamaño del arreglo
// Condicionales para verificar en que caso cae la variable tam
if(tam == 1){//1ra condicion
alert("Es muy poco"); // Si se cumple se muestra el mensaje "Es muy poco"
}
else if (tam >= 4) {//2da condicion
alert("Son muchos!");//Si se cumple muestra el mensaje "Son muchos"
}
else{ //En cualquier otro caso
alert("No está mal");//Muestra el mensaje "No está mal"
}
<file_sep>
function myFunction() {
var nombre = document.getElementById("name").value;//Se obtiene el valor del elemento con el id = name
var email = document.getElementById("email").value;//Se obtiene el valor del elemento con el id = email
document.getElementById("name").value = "";// Se limpia el contenido del elemento con el id = name
document.getElementById("email").value = "";// Se limpia el contenido del elemento con el id = email
document.getElementById("datos").innerHTML = "Datos ingresados:"//Se asigna un texto a la etiqueta <h3> que coincide con el id
document.getElementById("mostrarNombre").innerHTML = nombre; // Se escribe en el elemento con el id = mostrarNombre el valor de la variable nombre
document.getElementById("mostrarMail").innerHTML = email; // Se escribe en el elemento con el id = mostrarMail el valor de la variable email
}
| 366a3010c0f0e4b17d4f557d5330aaf02159f375 | [
"JavaScript"
] | 2 | JavaScript | IntiDev/ejerciciosDOM | 09d90af30211e5c39b8f6675c75a74cc924da481 | cb4ae22485bc0877cca9807d9f3d5f1839bb0dfd |
refs/heads/master | <repo_name>kalinni/JSSP-Tabu<file_sep>/planner.py
import operation
import pickle
import random
from os import path
#constructs a random plan by repeatedly picking the next step to be performed at random
def random_plan(plan):
next_step = [0 for i in range(plan['jobs'])]
new_plan = dict()
new_plan['machines'], new_plan['jobs'], new_plan['steps'] = plan['machines'], plan['jobs'], plan['steps']
for i in range(new_plan['machines']):
new_plan[i] = []
finished = True
for n in next_step: # the loop is performed while there are still steps not
finished = finished and not (n < new_plan['steps']) # sorted into the new plan (i.e. not finished)
while not finished:
options = [ i for i in range(new_plan['jobs']) # choose one job among the ones where
if next_step[i] < new_plan['steps'] ] # not all steps have been sorted in yet
job = random.choice(options)
insert = False
for m in range(plan['machines']): # find job and insert the next step into the new plan
i = 0
while i < len(plan[m]) and not insert:
# find the next step of the chosen job in the old plan and copy it into the new plan
# insert makes sure that only one job is added in every interation
if plan[m][i].job == job and plan[m][i].step == next_step[job] and not insert:
new_plan[m].append(plan[m][i])
next_step[job] += 1
insert = True
i += 1
finished = True
for n in next_step:
finished = finished and not (n < new_plan['steps'])
return new_plan
# fixed plan loads one of the precomputed plans for a given instance from a binary file
# this function also precomputes plans in case
def fixed_plan(plan, index, instance):
file_path = "plans/" + instance + ".txt"
plans = []
if not path.exists(file_path): # if the plans have not been precomputed yet
file = open(file_path, "wb") # construct a new file and add 15 random plans
for i in range(15):
new_plan = random_plan(plan)
plans.append(new_plan)
pickle.dump(plans, file) # store the computed plans persistently as a binary file
file.close()
file = open(file_path, "rb")
plans = pickle.load(file)
file.close()
return plans[index]<file_sep>/evaluator.py
import pickle
import math
import numpy as np
import matplotlib.pyplot as plt
from searcher import tabu_search
# all instances with the optimal times given
# here: https://pdfs.semanticscholar.org/1d26/47ac792c6f199bfd4893692648c437c0bab2.pdf
# and here: https://books.google.de/books?id=xj00CwAAQBAJ&pg=PA565&lpg=PA565&dq=job+shop+scheduling+abz5-abz9+benchmarks&source=bl&ots=8j7oSEcsqq&sig=ACfU3U2DWype-Kv7ixGnl8TFpDp2zYZe4g&hl=de&sa=X&ved=2ahUKEwj8hvL61ILnAhUSy6QKHXSDD9wQ6AEwAHoECAkQAQ#v=onepage&q=job%20shop%20scheduling%20abz5-abz9%20benchmarks&f=false
INSTANCES_ALL = {'abz5': 1234, 'abz6': 943, 'abz7': 656, 'abz8': 665, 'abz9': 679,
'ft06': 55, 'ft10': 930, 'ft20': 1165,
'la01': 666, 'la02': 655, 'la03': 597, 'la04': 590, 'la05': 593,
'la06': 926, 'la07': 890, 'la08': 863, 'la09': 951, 'la10': 958,
'la11': 1222, 'la12': 1039, 'la13': 1150, 'la14': 1292, 'la15': 1207,
'la16': 945, 'la17': 784, 'la18': 848, 'la19': 842, 'la20': 902,
'la21': 1046, 'la22': 927, 'la23': 1032, 'la24': 935, 'la25': 977,
'la26': 1218, 'la27': 1235, 'la28': 1216, 'la29': 1153, 'la30': 1355,
'la31':1784, 'la32':1850, 'la33':1719, 'la34':1721, 'la35':1888,
'la36':1268, 'la37':1397, 'la38':1196, 'la39':1233, 'la40':1222,
'orb01': 1059, 'orb02': 888, 'orb03': 1005, 'orb04': 1005, 'orb05': 887,
'orb06': 1010, 'orb07': 397, 'orb08': 899, 'orb09': 934, 'orb10': 944,
'swv01': 1407, 'swv02': 1475, 'swv03': 1398, 'swv04': 1470, 'swv05': 1424,
'swv06': 1675, 'swv07': 1594, 'swv08': 1755, 'swv09': 1661, 'swv10': 1743,
'swv11': 2983, 'swv12': 2979, 'swv13': 3104, 'swv14': 2968, 'swv15': 2886,
'swv16': 2924, 'swv17': 2794, 'swv18': 2852, 'swv19': 2843, 'swv20': 2823,
'yn1': 884, 'yn2': 904, 'yn3': 892, 'yn4': 968
}
INSTANCES = [
'ft06', # 6x6
'la01', 'la05', # 10x5
'la07', 'la10', # 15x5
'abz5', 'la18', 'orb01', 'orb04', 'orb10', # 10x10
'ft20', 'la13', # 20x5
'la23', 'la25', # 15x10
'la27', 'la28', 'swv01', 'swv05', # 20x10
'la38', 'la39', # 15x15
'la31', 'la34', # 30x10
'abz9', 'swv07', 'swv08', # 20x15
'yn4', #20x20
'swv12', 'swv13', 'swv18' #50x10
]
SOME_INSTANCES = [
'ft06', # 6x6
'la01', 'la05', # 10x5
'la07', # 15x5
'abz5', 'orb10', # 10x10
'ft20', 'la13', # 20x5
'la23', # 15x10
'swv01', # 20x10
'la39', # 15x15
'la31', # 30x10
'abz9', 'swv07', # 20x15
'yn4', #20x20
'swv13', 'swv18' #50x10
]
# This function is used to perform tabu search on all benchmarked instances from the lecture
# It iterates over these instances and stores for all instances
# the best time,
# the best schedule
# the resulting times from all other iterations of tabu search on this instance
def serial_experiments (instances = list(INSTANCES_ALL), path = 'results/results.txt'):
mode = 'Experimental' # For better comparison we work with fixed starting points
result = dict()
for instance in instances:
print("#########################")
print('Now running instance: '+ instance)
print("#########################")
result[instance] = tabu_search(instance, mode)
storage = open(path, 'wb') # for persistency, the results are stored
pickle.dump(result, storage) # to a txt file
storage.close()
#The result from serial experiments is stored in a binary file
#This function outputs all the results in a readable format
def output_serial_results (path = 'results/results.txt'):
file = open(path, 'rb')
result = pickle.load(file)
for instance in result:
print("For instance %s our best schedule takes %s time units" % (instance, result[instance][0]))
file.close()
def performance(resfile='results/results.txt',weights='[no weights known]'):
'''
Given a result file produced for example by the serial_experiments() method
(a dict() containing results per instances pickelt as a txt file)
this method prints an overview of the results to the command line,
calculates how much longer our schedules take on average,
checks how many optimal schedules we found
and generates a chart containing
- the best times known
- the best times from our run
- the mean of our times
- the standard deviation to that mean for our times
The chart is saved as a png with the same name as the given results file
'''
file = open(resfile, 'rb')
result = pickle.load(file)
# For calculating some stats
differences = []
differences_mean = []
optimal = 0
better = []
# Lists for the stacked bar chart
optimals = []
our_best = [] # needed to stack means on top of our best
our_best_diff = [] # difference our best to optimals
means_diff = [] # difference our mean to our best
deviations = [] # standard deviations to the mean
for instance in result:
optimals.append(INSTANCES_ALL[instance])
our_best_diff.append(result[instance][0] - INSTANCES_ALL[instance])
our_best.append(result[instance][0])
# calculate mean
all_times = result[instance][2]
mean = sum(all_times)/len(all_times)
means_diff.append(mean-result[instance][0])
# calculate standard deviation
st_dev = 0
for time in all_times:
st_dev += (time - mean)**2
st_dev /= len(all_times)
st_dev = math.sqrt(st_dev)
deviations.append(st_dev)
# calculate how much longer our schedules take and how many optimal times we found
percent = round((result[instance][0]/INSTANCES_ALL[instance] -1)*100,1)
percent_mean = round((mean/INSTANCES_ALL[instance]-1)*100,1)
differences.append(percent)
differences_mean.append(percent_mean)
if (result[instance][0] - INSTANCES_ALL[instance]) == 0 :
optimal += 1
# Check, whether some results seem to be better then the optimal known so far
elif (result[instance][0] - INSTANCES_ALL[instance]) < 0:
better.append(instance)
print("Instance %s ---- our best: %s ---- optimum: %s ---- difference in percent: %s " % (instance, result[instance][0], INSTANCES_ALL[instance], percent))
print("On average our best schedules take %s" % (round(sum(differences)/len(differences),2)) + "% more time.")
print("On average our schedules take %s" % (round(sum(differences_mean)/len(differences_mean),2)) + "% more time.")
print("%s out of %s schedules where optimal!" % (optimal, len(result)))
if len(better) > 0:
print("Caution! The following instances got schedules performing better than the best solution known so far!")
for instance in better:
print(instance)
# Generate the bar chart
N = len(result)
ind = np.arange(N)
width = 0.5
plt.rcParams.update({'font.size': 9})
plt.figure(figsize=(((0.1*len(result))+8),6.5))
p1 = plt.bar(ind, optimals, width)
p2 = plt.bar(ind, our_best_diff, width, bottom=optimals)
p3 = plt.bar(ind, means_diff, width, bottom=our_best, yerr=deviations)
plt.ylabel('Time')
plt.title('Results for %s' % str(weights)
+ "\n On average our best schedules take %s" % (round(sum(differences)/len(differences),2)) + "% more time."
+ "\n On average our schedules take %s" % (round(sum(differences_mean)/len(differences_mean),2)) + "% more time."
+ "\n %s out of %s schedules where optimal!" % (optimal, len(result)))
plt.xticks(ind, list(result), rotation='vertical')
plt.yticks(np.arange(0, 5000, 500))
plt.legend((p1[0], p2[0], p3[0]), ('Optimal', 'Our Best', 'Our Mean with Standard Deviation'))
plt.savefig(resfile.replace('.txt','.png'), dpi=500)
def parameter_checker(instances=SOME_INSTANCES):
'''
This is a function for playing around with the influence of our parameters.
'''
mode = 'Experimental' # For better comparison we work with fixed starting points
list_of_weights = [(0.5, 2, 0.3),(1, 2, 0.3),(0.5, 4, 0.3),(0.5, 2, 0.6),(0.5, 2, 0.15)]
for weights in list_of_weights:
result = dict()
for instance in instances:
print("#########################")
print('Now running instance: '+ instance + ' for weights ' + str(weights))
print("#########################")
result[instance] = tabu_search(instance, mode, weights)
resfile = 'results/results'+str(weights)+'.txt'
storage = open(resfile, 'wb') # for persistency, the results are stored
pickle.dump(result, storage) # to a txt file
storage.close()
performance(resfile,weights)<file_sep>/neighbourhood.py
import copy
#generates one neighbour (plan) by swapping steps at index a and index b on indicated machine
#returns False if swap fails
def generate_neighbour(plan, machine, index_a, index_b):
if plan[machine][index_a].job == plan[machine][index_b].job: # Swapping generates an impermissible schedule
return False # when two steps of the same job are swapped
for index in range(index_a + 1, index_b): # Swapping also generates an impermissible schedule
if (plan[machine][index].job == plan[machine][index_a].job # when any step in-between belongs to either of
or plan[machine][index].job == plan[machine][index_b].job): # the swapped steps
return False
#copy original plan and swap elements
neighbour = copy.deepcopy(plan) #shallow copy would cause change in the original plan
swapElement = neighbour[machine][index_a]
neighbour[machine][index_a] = neighbour[machine][index_b]
neighbour[machine][index_b] = swapElement
return neighbour<file_sep>/searcher.py
import sys
from os import path
import math
import time
import copy
from jssp_parser import parse_instance
from scheduler import realize_plan
from neighbourhood import generate_neighbour
from planner import random_plan, fixed_plan
NO_IMPROVE_MAX = 12 # How many iterations without improvement before we stop?
NO_IMPROVE_SWITCH = 6 # How many iterations without improvement before we switch to a more complex neighbourhood?
TRIES = 5 # From how many different starting schedules do we run the tabu search?
MODE = 'Active' # MODE variable shows whether the program is supposed to measure performance
# on a preset list of plans ('Experimental') or supposed to run for arbitrary plans ('Active')
# This function prints the schedule to the command line
# It also identifies inconsistency in the schedule (though our tabu search should not cause any)
def print_schedule(schedule):
timetable = [ [ 0 for s in range(schedule['steps']) ] for j in range(schedule['jobs']) ]
if schedule['time'] < 0:
print("Couldn't schedule all jobs with this plan")
else:
print("Schedule takes %s time intervals" % schedule['time'])
for m in range(schedule['machines']):
print("Machine %s:" % m)
for op in schedule[m]:
if op[0].machine != m:
print("Job %s is on the wrong machine." % op[0])
if op[2] - op[1] != op[0].duration:
print("Job %s takes a wrong amount of time, it takes %s" % (op[0], op[2]-op[1]))
print('--- %s.%s start %s duration %s end %s' % (op[0].job, op[0].step, op[1], op[0].duration, op[2]))
timetable[op[0].job][op[0].step] = (op[1], op[2])
for t in timetable:
for i in range(len(t)):
if i <= len(t) - 2:
if t[i][1] > t[i+1][0]:
print("Steps from the same Job overlap: %s" % t)
# This function performs the tabu search on the given problem instance represented as plan
def search_schedule(plan):
# Initialization
schedule = realize_plan(plan) # schedule is a dict with its overall time as value to the key 'time'
# and ordered lists of (operation, start, end)-triples for each machine
machines = plan['machines']
best_schedule = schedule
no_improve = 0
tabus = dict()
frequencies = dict()
iteration=0
# Those two simply serve to see how many valid and invalid neighbours we check
valid = 0
invalid = 0
aspiration = 0
# Start of the Tabu Search
### While last improvement is less than a fixed number of steps away, find best neighbour for current plan
while no_improve < NO_IMPROVE_MAX:
best_time = -1
aspiration_check = []
# Try out all positions on all machines for swapping
for m in range(machines):
for i in range(len(plan[m])-1):
# If we had no improvement recently switch from fast but simple swapping of only neighbours to more complex swapping of any operations on the same machine
if no_improve < NO_IMPROVE_SWITCH:
neighbourrange = [i+1]
else:
neighbourrange = range(i+1,len(plan[m]))
for j in neighbourrange:
neighbour = generate_neighbour(plan, m, i, j)
if neighbour != False: # for all permissible plans:
sched = realize_plan(neighbour) # construct the corresponding schedule
if sched['time'] > 0: # and compare it to the best schedule seen so far
valid += 1
penalty = 0
if m in frequencies:
penalty += len(frequencies[m])
penalty *= FREQUENCY_INFLUENCE + no_improve
if (best_time == -1) or (sched['time'] + penalty < best_time):
if m in tabus:
aspiration_check.append((copy.deepcopy(sched),penalty,m,i,j))
## print("Swapping %s with %s is tabu!" % (plan[m][j],plan[m][i]))
else:
best_neighbour = sched
best_time = sched['time'] + penalty
swap = (m, i, j)
else:
invalid += 1
# Aspiration Search: If there is tabu neighbour with time better than current optimum
# and best found swap, choose tabu swap instead
threshold = min(best_time, best_schedule['time']) if best_time > 0 else best_schedule['time']
for (sched,penalty,m,i,j) in aspiration_check:
if (sched['time'] + penalty < threshold):
best_neighbour = sched
best_time = sched['time'] + penalty
threshold = best_time
swap = (m, i, j)
aspiration += 1
## print("Swapping %s with %s is tabu but great! Gives %s" % (plan[m][j],plan[m][i],best_neighbour['time']))
if best_time == -1:
print("No valid neighbour found.")
break
# Get swapped operations
op1 = plan[swap[0]][swap[1]]
op2 = plan[swap[0]][swap[2]]
print("Swapped: %s with %s -- Current schedule's time: %s" % (op1,op2,best_neighbour['time']))
# Update the best schedule and no-improvement-counter
if best_neighbour['time'] >= best_schedule['time']:
no_improve +=1
else:
best_schedule = best_neighbour
no_improve = 0
# Update tabus and add new tabu
for machine in list(tabus):
if tabus[machine] > 1:
tabus[machine] -= 1
else:
del tabus[machine]
tabus[swap[0]] = RECENCY_MEMORY
# Update frequency memory
for machine in list(frequencies):
if frequencies[machine][0] == (iteration - FREQUENCY_MEMORY):
frequencies[machine].pop(0)
if len(frequencies[machine]) == 0: del frequencies[machine]
if swap[0] in frequencies:
frequencies[swap[0]].append(iteration)
else:
frequencies[swap[0]] = [iteration]
iteration += 1
# Make the plan giving the best neighbour the starting point for the next iteration
plan = generate_neighbour(plan, swap[0], swap[1], swap[2])
print("valid: %s, invalid: %s, aspiration %s, iterations %s" % (valid,invalid,aspiration, iteration))
return best_schedule
def set_dynamic_parameters(plan, weights=(0.5, 2, 0.3)):
global RECENCY_MEMORY, FREQUENCY_MEMORY, FREQUENCY_INFLUENCE
jobs = plan['jobs']
steps = plan['steps']
machines = plan['machines']
(recency_weight, frequency_weight, influence_weight) = weights
RECENCY_MEMORY = machines*recency_weight # How long are specific swaps tabu?
FREQUENCY_MEMORY = machines*frequency_weight # For how many steps do we remember our moves
FREQUENCY_INFLUENCE = round((influence_weight * math.sqrt(jobs * steps)),2) # Weight for the influence of the frequency
print("Swaps are Tabu for %s steps" % RECENCY_MEMORY)
print("Frequency Memory remembers the past %s steps" % FREQUENCY_MEMORY)
print("Weight of frequency of moves is %s" % FREQUENCY_INFLUENCE)
print("")
def tabu_search(instance, mode = MODE, weights=(0.5, 2, 0.3)):
instance_path = 'instances/' + instance + '.txt'
if not path.exists(instance_path):
raise SystemExit("There is no instance at %s" % instance_path)
# Get plan for the chosen instance
### Note: Will always give a valid schedule, due to how we get the plan from the instance
plan = parse_instance(instance_path) # plan is a dict, also contains machine, step and job numbers
set_dynamic_parameters(plan, weights)
# Run the tabu search for fixed number of starting points
best_time = -1
times = []
for i in range(TRIES):
if mode == 'Active':
plan = random_plan(plan)
elif mode == 'Experimental':
plan = fixed_plan(plan, i, instance)
else:
raise SystemExit("The MODE variable is set to an undefined value!")
schedule = search_schedule(plan)
times.append(schedule['time'])
print("Best Schedule in %s. Run: %s" % (i+1,schedule['time']))
print("++++++++++++++++++++")
print("")
if (best_time < 0) or (schedule['time'] < best_time):
best_time = schedule['time']
best_schedule = schedule
best_schedule['steps'] = plan['steps']
best_schedule['jobs'] = plan['jobs']
best_schedule['machines'] = plan['machines']
return (best_time, best_schedule, times)
def main():
start_time = time.time()
# Decide, on which instance to test our code
if len(sys.argv) > 1:
# you may run the script with a name of an instance as the argument
instance = sys.argv[1]
else:
# default if no argument is passed
instance = 'simple'
# Run the search
(optimum, optimum_schedule, times) = tabu_search(instance)
# Output
execution_time = round(time.time() - start_time)
print("Program takes %s minutes and %s seconds to run" \
% (round(execution_time / 60), execution_time % 60) )
print_schedule(optimum_schedule)
if __name__ == "__main__": main()<file_sep>/results/ReadMe.txt
Results for runs with complex neighbour switch after 6 of 12 iterations.<file_sep>/operation.py
class Operation:
"""Operations form the various steps of a job for the JSSP"""
def __init__(self, job, step, duration, machine):
self.job=job
self.step=step
self.duration=duration
self.machine=machine
def __eq__(self, other):
return (isinstance(other, type(self))
and self.job == other.job
and self.step == other.step)
def __hash__(self):
return hash((self.job,self.step))
def __str__(self):
return "Job %s.%s" % (self.job,self.step)
def __repr__(self):
return "<Operation job:%s step:%s, duration:%s, machine:%s>" % (self.job,self.step,self.duration,self.machine)<file_sep>/README.md
# JSSP-Tabu
This is an implementation of the tabu search algorithm for solving the Job Shop Scheduling Problem (JSSP). It was done as a solution to the practical task for the Problem Solving and Search in AI lecture at TU Dresden.
## Our Vocabulary for the JSSP
A JSSP has several jobs consisting of several steps each. We call one such step an _operation_. Each operation can be performed by only one machine.
Given are _instances_ for the JSSP, where operations are sorted by their jobs. We parse those instances into _plans_. A plan has all operations sorted by machine and already gives the order in which they are executed.
However, a plan does not contain start and end times for the operations. To get those, a plan is turned into its corresponding _schedule_.
Notice: Not every plan generated during a run of our tabu search can be turned into a complete schedule - some plans contain deadlocks caused by dependencies between machines. As our code only checks for a reasonable order of operations located on the same machine before trying to schedule a plan, those deadlocks will only be found during scheduling.
## Our Tabu Search Implementation
### Neighbourhood
Our tabu search algorithm constructs the neighbourhood of a plan by considering all plans obtained through swapping two ''adjacent'' operations on one machine. We decided on resticting swaps to neighbouring operations to keep the runtime from blowing up. To avoid getting stuck in a local optimum too easily, the algorithm is allowed to swap any two operations of the same machine when no improvement has been found in a number of iterations. This way we get a good tradeoff between runtime of the algorithm and runtime of the resulting best schedule.
### Evaluation
The evalutation of the neighbouring plans is done by creating the corresponding schedules and getting their respective runtimes. A runtime of -1 is returned for plans that contain deadlocks.
### Recency Memory/Tabu List
We tried several versions of the tabu list for our algorithm:
1. tabu on both operations of the performed swap (i.e. both can not take part in any swaps for a while)
2. tabu only on the swap undoing the performed swap
3. tabu on the machine on which the swap took place
Performance increased when we decided to move to tabus on machine level, probably because the number of operations or potential swaps in total was too big compared to the total number of iterations we would usually see before termination of the algorithm.
The current implementation therefore has a recency memory storing the machines the performed swaps occured on.
### Aspiration criterion
To improve the results further, we have implemented a simple aspiration criterion to allow for good swaps to still happen, even if the respective machine is currently on the tabu list. Moving to machine based tabus caused the aspiration criterion to actually be relevant. With operation based tabus we almost never saw any use of the criterion.
### Frequency Memory
The same happened with the frequency memory. Here, too, we started by remembering how often operations where part of swaps and moved on to remembering only the machine numbers instead. The frequencies are used to compute a penalty which is added to the time returned for the neighbour during evaluation. The penalties influence increases when no improvement occures for several iterations.
### Termination
The tabu search terminates when no better swap has been found for a number of iterations.
## Parameters of the algorithm
The general mechanisms of the algorithm work as outlined above, but concrete runs of the algorithm are influenced by the parameters described below.
The following parameters are dynamically set and depend on the size of the current instance. Coefficients can be passed to the tabu_search() method to further influence their values. If no coefficients are passed, default weights (for which we obtained good results among the different test instances) are used.
* RECENCY_MEMORY : After a swap has been performed, the machine will be tabu for this many following iterations.
* FREQUENCY_MEMORY : A move will be remembered for the frequency-based penalty for this number of iterations.
* FREQUENCY_INFLUENCE : This weight will be used to control the influence of the frequency-based penalty.
The following parameters are static (i.e. not depending on the instance size in our implementation) and we have currently hardcoded their values in the source code.
* NO_IMPROVEMENT_SWITCH = 6 : After this many iterations without improvement the algorithm will allow arbitrary swaps.
* NO_IMPROVEMENT_MAX = 12: After this many iterations without improvement the algorithm will terminate the run.
* TRIES = 5: Number of different starting plans from which the algorithm will run when called once for one instance.
* MODE = 'Active': The starting plans mentioned above should be chosen randomly. However, in order to evaluate the influence of different parameter values without running the algorithm often enough to get meaningful results for random starting plans, it is possible to fall back on pregenerated and fixed starting plans by using mode 'Experimental'. For truely random starting points use 'Active'.
## Running our Code
Type the following into your command line
```
python searcher.py la26
```
This will run a tabu search for the la26 instance. You can also leave the parameter, the code will then take a very simple and tiny test instance as default.
## Checking our results
__evaluator.py__ has a method called ```output_serial_results()``` which will simply print our best results for some of the benchmark instances to the command line. In addition there are several methods we used to test varous parameter configurations and a method ```performance()``` which calculates means and standard deviations of results, compares them to the known optimums for the benchmark instances and generates a chart containing those information. Those charts can also be found in the results folder.
## Some Notes on the Content and Structure of the Repository
Folders:
- instances/
- contains all instances from http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/jobshop1.txt separeted into separate files
- plans/
- Contains binaries of lists of plans for those instances
- These plans are the starting points for tabu search iterations in experimental mode
- results/
- Results of various tests with the benchmark instances
- .txt files are binaries used by the methods in evaluator.py to store results
- .png contain charts generated from those results
- Files in the sub folder contain results from runs with operation-level recency and frequency memories
- other/
- The original jobshop1.txt file and our slides for the status talk.
Python files:
- searcher.py
- This is the __main file__, it contains the methods and structure for the search, for recency and frequency memories, a print\_schedule function and a main method.
- neighbourhood.py
- Contains the function that returns a neighbour for a given plan. The function takes two indices and is capable of doing long distant swaps on a machine and checking them for reasonability if asked to.
- operation.py
- Contains only a class for operations. Each operation contains its job, machine, step (which step of the job it is) and duration.
- jssp\_parser.py
- Function to turn a given instance into a plan (and the script that separeted jobshop1.txt).
- planner.py
- Functions to create either a random starting point for the tabu search (i.e. a random plan) from another plan or give pregenerated plans to enable us to compare runtime and result for a fixed set of starting points.
- scheduler.py
- The method to turn a plan into a schedule. This resamples the evaluation function of our tabu search.
- evalutor.py
- Methods to evaluate how our search algorithm is performing on the given __benchmark instances__.
<file_sep>/scheduler.py
#this function calculates an optimal schedule from the given plan (i.e. order of steps on every machine)
def realize_plan (plan):
#store the number of jobs, steps and machines for easier access
jobs, steps, machines = plan['jobs'], plan['steps'], plan['machines']
#enabled tracks at which point in time a step is 'enabled' (i.e. its predecessor step has finished)
enabled = [[0 if s == 0 else -1 for s in range(steps)] for j in range(jobs)]
schedule = { m:[] for m in range(machines) }
following = {m:0 for m in range(machines)} # following tracks the next step for every machine
# for every machine, check whether the next planned step is already enabled
# if so: insert that step into the schedule
# if no step can be inserted: plan is blocking and thus impermissible (deadlock occurred)
blocked = False
while not blocked:
blocked = True
for m in range(machines):
if following[m] < len(plan[m]):
j, s = plan[m][following[m]].job, plan[m][following[m]].step
if enabled[j][s] != -1:
blocked = False
if schedule[m]:
start = max(schedule[m][-1][2], enabled[j][s])
else:
start = enabled[j][s]
finish = start + plan[m][following[m]].duration
schedule[m].append( ( plan[m][following[m]], start, finish ) )
following[m] += 1
if s < steps -1:
enabled[j][s+1] = finish # after inserting step s, the successor step s+1 is enabled
#finished checks whether schedule is complete (i.e. no deadlock)
finished = True
for m in range(machines):
finished = finished and (following[m] >= len(plan[m]))
#time records the number of machine cycles needed for the schedule (in case the plan is permissible), otherwise: -1
time =-1
if finished:
for m in range(machines):
time = max(time, schedule[m][-1][2])
schedule['time']=time
#output: dictionary with the following keys and values
# machinenumber -> List of 3-tuples (Step, starting time, finish time) for the respective machine
# time -> number of machine cycles needed for the plan
return schedule<file_sep>/jssp_parser.py
from operation import Operation
def separate_instances(file,directory):
'''
This function simply separates the instances found in jobshop1.txt into extra files
on which the parse_instance function can then be called.
'''
with open(file,encoding="utf8") as file:
first_instance_found = False
file_created = False
for line in file:
if first_instance_found:
content = line.split()
if len(content) > 0 and content[0] == 'instance':
try:
if file_created: instance.close()
instance = open(directory + content[1] + ".txt", "x")
print(directory + content[1] + ".txt was created")
file_created = True
except:
print("File %s.txt already exists." % (content[1]))
file_created = False
if file_created: instance.write(line)
else:
if line.find(' +++'): first_instance_found = True
def parse_instance(file):
'''
This function reads in given instances of the JSSP
It takes the location of a file containing a single instance of the JSSP as input.
Example: plan = parse_instance('instances/abz5.txt')
The output is a dictionary containing:
- the number of jobs as the value for the key "jobs"
- the number of machines as the value for the key "machines"
- the number of steps per job as the value for the key "steps"
- all machine numbers as keys with all operations on that specific machine in a list as their values
'''
plan = dict()
with open(file,encoding="utf8") as instance:
for line in instance:
try:
if line.find('instance') > -1: continue
if line.find('+') > -1: continue
content = line.split()
if len(content) == 2:
plan['jobs'] = int(content[0])
plan['machines'] = int(content[1])
job = -1
if len(content) > 2:
if 'steps' not in plan: plan['steps'] = int(len(content)/2)
job += 1
for i in range(0,len(content),2):
if int(content[i]) not in plan: plan[int(content[i])]=[]
plan[int(content[i])].append(Operation(job, int(i/2), int(content[i+1]), int(content[i])))
except:
pass
return plan | 5d99eb38040786618facb784d07d5c9617b9d667 | [
"Markdown",
"Python",
"Text"
] | 9 | Python | kalinni/JSSP-Tabu | 8d63a17aab0ec40d8d2a47a27cb3aebcb12b75a7 | e27268bab81dabd442309d433b80d9ae5a14ff51 |
refs/heads/master | <file_sep>import {Body, Controller, Post, UsePipes} from '@nestjs/common';
import {UserService} from './user.service';
import {CreateUserDto} from './dto';
import {ValidationPipe} from '../shared/pipes/validation.pipe';
import {ApiBearerAuth, ApiTags} from '@nestjs/swagger';
@ApiBearerAuth()
@ApiTags('user')
@Controller()
export class UserController {
constructor(private readonly userService: UserService) {}
@UsePipes(new ValidationPipe())
@Post('users')
async create(@Body('user') userData: CreateUserDto) {
return this.userService.create(userData);
}
}
<file_sep>export const contentApiUrl = process.env.REACT_APP_CONTENT_API_URL
export const usersApiUrl = process.env.REACT_APP_USERS_API_URL
export const keycloakUrl = process.env.REACT_APP_KEYCLOAK_URL
export const keycloakRealm = process.env.REACT_APP_KEYCLOAK_REALM
export const keycloakClientId = process.env.REACT_APP_KEYCLOAK_CLIENT_ID
<file_sep>import {Injectable} from '@nestjs/common';
import KcAdminClient from 'keycloak-admin';
import axios from 'axios';
import {CreateUserDto} from './dto';
import {UserRO} from './user.interface';
import * as config from '../config'
@Injectable()
export class UserService {
async create(dto: CreateUserDto): Promise<UserRO> {
const client = new KcAdminClient({
baseUrl: config.keycloakUrl,
realmName: config.keycloakRealmName
})
await client.auth({
grantType: 'client_credentials',
username: null,
password: <PASSWORD>,
clientId: config.keycloakAdminClientId,
clientSecret: config.keycloakAdminClientSecret
})
await client.users.create({
enabled: true,
username: dto.username,
email: dto.email,
credentials: [
{ type: '<PASSWORD>', value: <PASSWORD> }
],
})
const response = await axios.post(config.contentApiUrl + '/users', {
user: {
username: dto.username,
email: dto.email
}
})
return response.data
}
}
<file_sep>import Keycloak from 'keycloak-js'
import { keycloakUrl, keycloakRealm, keycloakClientId } from './config'
const keycloak = new Keycloak({
url: keycloakUrl,
realm: keycloakRealm,
clientId: keycloakClientId,
})
export default keycloak
<file_sep>FROM node AS builder
RUN mkdir /build
WORKDIR /build
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
RUN yarn build
FROM node
WORKDIR /app
COPY package.json ./
RUN yarn install --production
COPY --from=builder /build/dist ./dist
CMD ["npm", "run", "start:prod"]
<file_sep>import {MiddlewareConsumer, Module, NestModule} from '@nestjs/common';
import {UserController} from './user.controller';
import {UserService} from './user.service';
@Module({
imports: [],
providers: [UserService],
controllers: [
UserController
],
exports: [UserService]
})
export class UserModule implements NestModule {
public configure(consumer: MiddlewareConsumer) {
}
}
<file_sep># Kubernetes Hackathon
## Components
Taken straight from [RealWorld](https://github.com/gothinkster/realworld) project.
### Frontend
Based on [React/Redux](https://github.com/gothinkster/react-redux-realworld-example-app) example app. Authentication uses Keycloak. Frontend connects to Content API and Users API.
### Content API
Based on [NestJS + TypeORM/Prisma](https://github.com/lujakob/nestjs-realworld-example-app) example app. NodeJS API that stores data in PostgreSQL database.
### User API
Simple Nest.js API that contains one endpoint for registration which creates users both in Keycloak and Content API.
## Running locally
Simply run `docker-compose up` to spin up the whole project and visit http://localhost:4100/
<file_sep>#!/usr/bin/env bash
set -e
export REACT_APP_CONTENT_API_URL=https://conduit.productionready.io/api
export KEYCLOAK_URL=http://keycloak:8080
export KEYCLOAK_REALM_NAME=conduit
export KEYCLOAK_ADMIN_CLIENT_ID=users-api
export KEYCLOAK_ADMIN_CLIENT_SECRET=<KEY>
#yarn run build
cd ./build
aws s3 sync --delete ./static s3://www.k8s-hackathon.brainhub.pl/static --cache-control "max-age=2628000,public"
aws s3 sync --delete --exclude "static/*" . s3://www.k8s-hackathon.brainhub.pl --cache-control "public,must-revalidate,proxy-revalidate,max-age=0"
<file_sep>export const contentApiUrl = process.env.CONTENT_API_URL
export const keycloakUrl = process.env.KEYCLOAK_URL
export const keycloakRealmName = process.env.KEYCLOAK_REALM_NAME
export const keycloakAdminClientId = process.env.KEYCLOAK_ADMIN_CLIENT_ID
export const keycloakAdminClientSecret = process.env.KEYCLOAK_ADMIN_CLIENT_SECRET
| 743923ef3f95374fbb9ad5d2202ed5c3acc89868 | [
"JavaScript",
"Markdown",
"TypeScript",
"Dockerfile",
"Shell"
] | 9 | TypeScript | brainhubeu/k8s-hackathon | ad4eae640fa1caf9783e8f2658451ed4443ba2e6 | 69da8c0d1e02a7f8034c49678dbd5eaab393e243 |
refs/heads/master | <repo_name>jaychacko/React-Shopping-cart-Proposel<file_sep>/src/reducers/shoppingCart.js
const INIT_STATE=[];
import {ADD_TO_CART,REMOVE_FROM_CART} from '../actions/index'
export default (state =INIT_STATE,action) => {
switch (action.type) {
case ADD_TO_CART:
return [...state, action.payload]
case REMOVE_FROM_CART:
const keepItem =(item) =>{return item.id !=action.payload};
return state.filter(keepItem);
default:
return state
}
}
<file_sep>/src/components/App.js
import React from 'react';
import Items from '../container/items/index'
import ShoppingCart from '../container/shoppingcart'
import './App.css'
const App = () => (
<div className = 'App-mainbody'>
<div><Items/></div>
<div className='shoppingCart'><ShoppingCart/></div>
</div>
)
export default App;
<file_sep>/src/container/shoppingcart/index.js
import React ,{Component} from 'react';
import {connect} from 'react-redux';
import './shoppingCart.css';
import {removeFromCart} from '../../actions/index'
export class ShoppingCart extends Component {
renderShoppingCart =()=>{
const {shoppingCart,removeFromCartaction } = this.props;
return shoppingCart.map((item) => (
<li
key ={item.id}
className = {'SC-list-item'}
onClick={()=> removeFromCartaction(item.id)}>
<img role ="presentaion" className='SC-items-image' src={item.link}/>
<span>{item.title}</span>
</li>
))
}
render() {
return (
<div className='cartdivwrap'>
<h1>Cart</h1>
<ul className = {'SC-list'}>
{this.renderShoppingCart()}
</ul>
</div>
)
}
}
const mapStateToProps = (reduxState) =>({
shoppingCart:reduxState.shoppingCart
});
const mapDispatchToProps = (dispatch)=>({
removeFromCartaction:(id) =>dispatch(removeFromCart(id))
})
export default connect(mapStateToProps,mapDispatchToProps)(ShoppingCart);
<file_sep>/src/container/items/index.js
import React , {Component} from 'react';
import {connect} from 'react-redux';
import {addToCart} from '../../actions/index'
import './items.css';
export class Items extends Component {
renderList = ()=>{
const { items, addToCartAction } = this.props;
console.log(items);
return items.map((item) => (
<li
key ={item.id}
className = {'item-list-item'}
onClick={()=> addToCartAction(item)}>
<img role ="presentaion" className={"items-image"} src={item.link}/>
<span>{item.title}</span>
</li>
))
}
render() {
return (
<div className='divwrap'>
<h1>Buy now</h1>
<ul className = {'items-list'}>
{this.renderList()}
</ul>
<hr></hr>
</div>
)
}
}
const mapStateToProps = (reduxState) =>({
items:reduxState.item
});
const mapDispatchToProps = (dispatch) =>({
addToCartAction: (item)=>dispatch(addToCart(item))
});
export default connect(mapStateToProps, mapDispatchToProps)(Items)
<file_sep>/README.md
# React-Shopping-cart-Proposel | a863a5358d84fa11c780932af075392a40b42597 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | jaychacko/React-Shopping-cart-Proposel | 83a7d51845e8c877b5248c53aa8cd16382ada6e7 | 227853e205d5f0e44fb6b07079cb16085cb17e32 |
refs/heads/master | <repo_name>pkhmelyov/Codeforces118A<file_sep>/Codeforces118A/Program.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Codeforces118A
{
class Program
{
private static HashSet<char> lettersToExclude = new HashSet<char>(new[] {'A', 'O', 'Y', 'E', 'U', 'I'});
static void Main(string[] args)
{
var input = Console.ReadLine();
var builder = new StringBuilder();
foreach (char letter in input)
if (lettersToExclude.Contains(Char.ToUpper(letter))) continue;
else builder.Append($".{Char.ToLower(letter)}");
Console.WriteLine(builder.ToString());
}
}
}
| eef8ab76645ee9599bb7194d3bf0e86f1e69e43e | [
"C#"
] | 1 | C# | pkhmelyov/Codeforces118A | e275ff944162c7f14e6e28bc6355cd8aa17cd78d | a04730ed24061bc1f07fd12a79df7c9ee8b4c040 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.