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
<file_sep>package com.knunu.android.whesiknow; /** * Created by USER on 2016-07-23. */ import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; public class Pop extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.popupwindow); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); }} <file_sep># 회식나우(WhesikNow) 회식나우 안드로이드 어플리케이션 <file_sep>apply plugin: 'com.android.application' apply plugin: 'android-apt' android { compileSdkVersion 23 buildToolsVersion '23.0.3' defaultConfig { applicationId "com.knunu.android.whesiknow" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { } } repositories { mavenCentral() } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' apt 'com.jakewharton:butterknife-compiler:8.2.1' compile group: 'com.kakao.sdk', name: 'usermgmt', version: '1.1.20' compile 'com.android.support:design:24.0.0' compile 'com.android.support:appcompat-v7:24.0.0' compile 'com.jakewharton:butterknife:8.2.1' compile 'com.google.android.gms:play-services:9.2.1' compile 'com.google.android.gms:play-services-ads:9.2.1' compile 'com.google.android.gms:play-services-identity:8.4.0' compile 'com.google.android.gms:play-services-gcm:8.4.0' compile 'com.facebook.android:facebook-android-sdk:4.+' compile 'com.tsengvn:typekit:1.0.1' compile 'com.android.support:support-v4:23.4.0' }
d9f95a20598c15ac692e64268d69f02a1f06773f
[ "Markdown", "Java", "Gradle" ]
3
Java
sumin22/android_whesiknow
c0ae9afefad6c6ad3b727668d4084e8cae3734b2
5acff397e9cf9b7af62d1595e9b30457ce26a90d
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-server', templateUrl: './server.component.html', styleUrls: ['./server.component.css'] }) export class ServerComponent implements OnInit { serverId: number = 10; serverStatus: string = 'offline'; serverName: string = ''; allowNewServer: boolean = true; serverCreationStatus: string = 'No Server was created!'; onCreateServer(){ this.serverCreationStatus = 'Server was JUST created!'; } onCreateServer2(){ console.log('HOVERED!') } onUpdateServerName(event: Event){ this.serverName = event.target.value; } constructor() { setTimeout(() =>{ this.allowNewServer = false; },2000); } ngOnInit() { } }
2d3578d214349db9c1984d115f1d264ce4908fb1
[ "TypeScript" ]
1
TypeScript
shebbbby/angular-dream
ae764c22e826d3fc64f701a71f87eeba00bc3648
48dc2fa8b502a0deecb03784112d9f8b274a7f1f
refs/heads/master
<file_sep>import java.util.Scanner; public class Apellido_mas_largo { public static void main(String[] args) { Scanner lector = new Scanner(System.in); String apellido1; String apellido2; System.out.println("Escribir apellido 1"); apellido1 = lector.nextLine(); System.out.println("Escribir apellido 2"); apellido2 = lector.nextLine(); if(apellido1.length() > apellido2.length()){ System.out.println( apellido1 + "es más largo"); }else{ if(apellido1.length() < apellido2.length()){ System.out.println( apellido2 + "es más largo"); }else{ System.out.println("Apellidos iguales"); } } } } <file_sep>import java.util.Scanner; public class Ordenar_apellidos_alfab { public static void main(String[] args) { //ordenar apellido alfabeticamente Scanner lector = new Scanner(System.in); String apellido1; String apellido2; System.out.println("Escribir apellido"); apellido1 = lector.nextLine(); System.out.println("Escribir otro apellido"); apellido2 = lector.nextLine(); if(apellido1.compareTo(apellido2) <0) // al final lo que nos dan es un número System.out.println(apellido1 + "va antes alfabéticamente"); else{ if(apellido2.compareTo(apellido1) <0){ System.out.println(apellido2 + "va antes alfabéticamente"); }else{ System.out.println("Son iguales"); } } } }
3b49f878a0d29e37979641344ed3f08a9078916c
[ "Java" ]
2
Java
maitanegarbizu/06_strings
523e0bfb02069bfd7810278950e89bef8b52be14
e84af9250a7b80be690d5d415ff8664935b2ecbd
refs/heads/master
<file_sep># Maid Spin Discord Bot A bot for Discord that lets you spin maids. ![Maid Spinning](https://i.imgur.com/WxIrcsu.gif) **The most *revolutionary* discord game ever created!** You can either add the public instance to your server [here](https://discord.com/oauth2/authorize?client_id=715582108600369253&scope=bot), or see below on how to set-up your own instance. *The bot requires the **embed links** permission to work.* ### Rules: - To spin a maid simply command her to spin by saying *"Spin the maid!"* or something similar into the chat. - The maids can only spin every 5 mins, they get dizzy! - The maids can spin for as many minutes as have passed since they recovered. So if you spin 5 mins after they have recovered, you get 5 spin points. - When you spin, there is a random chance that you will get a special multiplier and different gif. - You will get extra spins if you spin the maids using a message no one has used before, so be creative. - Occasionally you will find a mysterious *meido no hearto*, you can trade these for spins or multipliers. - There are a few other ways to get spins which wou'll find out as you play. ### Commands: - View help with *"**@Maid Spin** help"*. - You can check on the maids' dizziness in more detail using *"**@Maid Spin** timer"*. - To view who has spun the most maids, use *"**@Maid Spin** top"*. - To view who has had the biggest maid spin, use *"**@Maid Spin** toph"*. - To view the scoreboard from v1 (defunct), use *"**@Maid Spin** topold"*. - To view your current meido no hearto, and meido no hearto help, use *"**@Maid Spin** hearto"*. - To trade a meido no hearto for some spins, use *"**@Maid Spin** hearto spins"*. - To trade some meido no hearto to start a maid day, use *"**@Maid Spin** hearto maid day X"*, where X is the number you want to use. - To wave at Mahoro, use *"**@Maid Spin** wave"*. ### Set Up Instance: 1. To set up your own instance of this bot, first create a Discord application and bot on "https://discord.com/developers/applications". 2. Move the files in /default into the root (password.config and spinData.json). 3. In password.config, paste your bot's "secret" (not the application's secret). This will link your bot to the code. 4. Open index.js in a text editor and configurate the variables at the top of the file labelled CONFIG as you wish. 5. Install the discord.js module with npm (npm install discord.js). 6. Invite the bot to your server by going to "https://discordapp.com/oauth2/authorize?client_id=CLIENTID&scope=bot", replacing CLIENT_ID with your application's client ID. 7. The bot requires a few permissions to function. It must be able to: **view/send messages** in at least one channel and **embed links**. 8. Run the application with "node index.js". 9. Spin maids! ### GIF Sources: For more details see the notes for each GIF within the source code (at the top of index.js). The anime used are: - Mahoromatic - GJ-bu - Kiniro Mosaic - Kaichou wa Maid-sama - Seto no Hanayome - Familiar of Zero - Gochiusa - Tsukihime - Hinako Note - Digi Charat - Hayate no Gotoku - Konosuba - Comic Girls - Shadows House - Kobayashi-san's Maid Dragon - Uzamaid! - Soredemo Machi wa Mawatteiru - He is my Master - <NAME> - Hand Maid May - A Certain Magical Index - Prisma Illya - Keion! - Shomin Sample - Blend S - Futari wa Precure <file_sep>const Discord = require('discord.js'); var fs = require('fs'); const client = new Discord.Client(); //CONFIG: change to your discord application's ID const myID = "776090583362043906"; //CONFIG: change to how long you want between spins //default 5 const coolDownMins = 5; //CONFIG: change to how many spins you want 1 hearto to be worth //1 hearto = x spins //default 250 const heartoExchangeRate = 250; //GIF DB const GIFdizzy = ["https://i.imgur.com/spr5vSH.gif", //chiyo dizzy "https://i.imgur.com/spr5vSH.gif", "https://i.imgur.com/spr5vSH.gif", "https://i.imgur.com/6K8xuk1.gif"]; //minawa dizzy const GIFfirst = ["https://i.imgur.com/kBwlzG5.gif"]; //tohru nerd const GIFhearto = ["https://i.imgur.com/ks69ysE.gif", //mio "https://i.imgur.com/ks69ysE.gif", "https://i.imgur.com/ks69ysE.gif", "https://i.imgur.com/ZsAtJ79.gif", //illya "https://i.imgur.com/u0THn5v.gif", //tohru hearto "https://i.imgur.com/Ulnp3Pn.gif"]; //shomin const GIFx1 = ["https://i.imgur.com/7hqhB0M.gif", //mori "https://i.imgur.com/7hqhB0M.gif", "https://i.imgur.com/7hqhB0M.gif", "https://i.imgur.com/7hqhB0M.gif", "https://i.imgur.com/7hqhB0M.gif", "https://i.imgur.com/7hqhB0M.gif", "https://i.imgur.com/2zr3Y66.gif", //shinobu "https://i.imgur.com/rvdiMVi.gif", //misaki "https://i.imgur.com/g6uPz0v.gif", //sun "https://i.imgur.com/ewDf0ZS.gif", //siesta "https://i.imgur.com/fnFiCSt.gif", //chiyo syaro "https://i.imgur.com/zb30FvR.gif", //kohaku "https://i.imgur.com/r7311cq.gif", //mahoro dress "https://i.imgur.com/xmyBake.gif", //mahoro summer "https://i.imgur.com/pdRg9wY.gif", //mayu "https://i.imgur.com/5e2WlD2.gif", //usada ice "https://i.imgur.com/WxIrcsu.gif"]; //maria const GIFx2 = ["https://i.imgur.com/ESBg2pr.gif", //aqua "https://i.imgur.com/H6ejqG9.gif", //comic girls "https://i.imgur.com/gDSmFko.gif", //emilyko "https://i.imgur.com/dkZXDEJ.gif", //mahoro minawa "https://i.imgur.com/wZB84I2.gif", //tohru kanna "https://i.imgur.com/WTcm1zq.gif"]; //uchimaid const GIFx3 = ["https://i.imgur.com/swxzqBI.gif", //hinako note "https://i.imgur.com/yz6XX5b.gif", //hotori sing "https://i.imgur.com/EJcsTXG.gif", //he is my master "https://i.imgur.com/jiwrXYq.gif", //tohru old "https://i.imgur.com/DPSNmnB.gif"]; //chiyo const GIFx5 = ["https://i.imgur.com/0axpToa.gif", //hotori mug "https://i.imgur.com/lLscYGH.gif", //kurumi "https://i.imgur.com/viNIPJK.gif", //usada rice "https://i.imgur.com/JJWccfF.gif"]; //may const GIFbirth = ["https://i.imgur.com/tBRfWSr.gif"]; //mahoro cake const GIFxmas = ["https://i.imgur.com/N8qbwqR.gif"]; //mahoro christmas const GIFmatic = ["https://i.imgur.com/z6sjRXh.gif"]; //maiko rotate const GIFx10 = ["https://i.imgur.com/2Uy7EMA.gif", //dejiko "https://i.imgur.com/yGPPyon.gif"]; //mahoro fast const GIFbikini = ["https://i.imgur.com/RJCx1rX.gif"]; //bikini mori const GIFyukata = ["https://i.imgur.com/TezaN62.gif"]; //yukata mori //spin regex const maidWords = "maid|meid|mori|mahoro|maria|tohru"; const spinWords = "spin|twirl|rotat|turn|twist|gyrat|spun|span|revol|roll|spiral|whir|reel|pirouet|oscil|mawar"; //on startup client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); fs.readFile('spinData.json', function(err, data) { if (err) { return console.error(err); } var fullData = JSON.parse(data.toString()); currentTime = new Date(); for (server in fullData["servers"]) { fullData["servers"][server]["lastSpin"] = currentTime - (60000 * coolDownMins); } newJSON = JSON.stringify(fullData); fs.writeFile('spinData.json', newJSON, function(err) { if (err) { return console.error(err); } }); }); }); //return fullData function getFullData(data) { var fullData = JSON.parse(data.toString()); return fullData; } //write fullData to spinData function writeData(fullData) { newJSON = JSON.stringify(fullData); fs.writeFile('spinData.json', newJSON, function(err) { if (err) { return console.error(err); } }); } //return server data from msg's server function getServerData(fullData, msg, verboseKA) { newServer = true; //test for new server for (server in fullData["servers"]) { if (fullData["servers"][server]["id"] == msg.guild.id) { spinData = fullData["servers"][server]; newServer = false; break; } } //if new server, return 0 if (newServer) { spinData = 0; if (verboseKA) { msg.channel.send('This server has not been initialised for maid spin. Try spinning a maid to initialise. View help with *"**@Maid Spin** help"*.'); } } return spinData; } //return user data from msg's user function getUserData(spinData, msg, verboseKA) { //test for new user in server newUser = true; for (user in spinData["users"]) { if (spinData["users"][user]["id"] == msg.author.id) { olduser = spinData["users"][user]; newUser = false; break; } } //if new user return 0 if (newUser) { if (verboseKA) { msg.channel.send("You haven't spun any maids yet." + ' View help with *"**@Maid Spin** help"*.'); } olduser = 0; } return olduser; } function getGIF(GIFDB) { selectedGIF = Math.floor(Math.random() * GIFDB.length); //0 - DB.len return GIFDB[selectedGIF]; } function atID(id) { atString = "<@" + id + ">"; return atString; } function printSpin(msg, spins, total, spinType, hiSpinKA, newCallKA, firstOfTheDay, heartoKA, maidDayKA, maidDayElapsedHours, maidDayMulti, overtaken) { //correct noun for single/plural if (spins == 1) { nounVar = "maid"; } else { nounVar = "maids"; } //send base message msg.channel.send(`${msg.author}` + " spun " + spins + " " + nounVar + "! *(" + total + " spins total)*"); //select multiplier message flavourRan = Math.floor(Math.random() * 100) + 1; //1-100 switch(spinType) { case 2: multiMessage = "The maids span extra fast today! *(x2 spins)*"; gif = GIFx2; break; case 3: multiMessage = "Many maids spin better than one. *(x3 spins)*"; gif = GIFx3; break; case 5: if (flavourRan < 55) { //basic x5 multiMessage = "With maids, you're one step closer to paradise. *(x5 spins)*"; gif = GIFx5; } else if (flavourRan < 70) { //birthday multiMessage = "With maids, every day is your birthday! *(x5 spins)*"; gif = GIFbirth; } else if (flavourRan < 85) { //christmas multiMessage = "With maids, every day is Christmas day! *(x5 spins)*"; gif = GIFxmas; } else { //spinomatic multiMessage = "We brought the maid-spinomatic out for this one! *(x5 spins)*"; gif = GIFmatic; } break; case 10: multiMessage = "The maids have reached supersonic speeds! *(x10 spins)*"; gif = GIFx10; break; case 25: if (flavourRan < 67) { multiMessage = "Wow! Today is the beach episode! *(x25 spins)*"; gif = GIFbikini; } else { multiMessage = "Wow! Today is the summer festival episode! *(x25 spins)*"; gif = GIFyukata; } break; default: gif = GIFx1; } //maid day handling if (maidDayKA) { //correct noun for single/plural if (maidDayElapsedHours == 23) { dayNounVar = "hour remains"; } else { dayNounVar = "hours remain"; } msg.channel.send("Today is maid day, time to celebrate! Under " + (24 - maidDayElapsedHours) + " " + dayNounVar + ". *(x" + maidDayMulti+ " spins)*"); } //firstOfTheDay handling if (firstOfTheDay) { msg.channel.send("You got the first spin of the day! Well done. *(+100 free spins)*"); gif = GIFfirst; } //send multiplier message if (spinType > 1) { msg.channel.send(multiMessage); } //if newCall then send hispin message if (newCallKA) { msg.channel.send('No one has ever used that call before! *(x1½ spins)*'); } //if hispin then send hispin message if (hiSpinKA) { msg.channel.send('This is a new highest spin score for you! (Check leaderboard with *"**@Maid Spin** toph"*).'); } //if hearto notify if (heartoKA) { msg.channel.send("What's this? Your love for maids has manifested into a legendary **MEIDO NO HEARTO**!"); msg.channel.send('Check what uses you can do with it with *"**@Maid Spin** hearto"*'); gif = GIFhearto; } //notify overtaken users if (overtaken.length > 0) { userNoun = "user "; overtakenList = atID(overtaken[overtaken.length - 1]); overtaken.pop(); if (overtaken.length > 0) { userNoun = "users "; overtakenList = atID(overtaken[overtaken.length - 1]) + " and " + overtakenList; } overtaken.pop(); if (overtaken.length > 0) { for (user in overtaken) { overtakenList = atID(overtaken[user]) + ", " + overtakenList; } } msg.channel.send("You have overtaken " + userNoun + overtakenList + "."); } //send GIF msg.channel.send(getGIF(gif)); } //test if call is new on current server function testNewCall(msg) { data = fs.readFileSync('callData.json'); //get server data var fullData = JSON.parse(data.toString()); //find current server newServer = true; while (newServer) { //test for new server for (server in fullData["servers"]) { if (fullData["servers"][server]["id"] == msg.guild.id) { callData = fullData["servers"][server]; newServer = false; break; } } //if new server, create tag if (newServer) { var newServerObj = new Object(); newServerObj.id = msg.guild.id; newServerObj.calls = []; fullData["servers"].push(newServerObj); } } //loop through calls to find duplicates newCallKA = true; currentCall = msg.content; for (call in callData["calls"]) { if (callData["calls"][call] == currentCall) { newCallKA = false; break; } } //if new then append to file if (newCallKA) { callData["calls"].push(currentCall); newJSON = JSON.stringify(fullData); fs.writeFile('callData.json', newJSON, function(err) { if (err) { return console.error(err); } }); } return newCallKA; } //check for overtaking on rank function checkOvertaken(spinData, oldAmount, newAmount) { overtaken = []; for (user in spinData["users"]) { if (spinData["users"][user]["spins"] >= oldAmount && spinData["users"][user]["spins"] < newAmount) { overtaken.push(spinData["users"][user]["id"]); } } return overtaken; } //calculate spins and update data files function updateCount(msg) { fs.readFile('spinData.json', function(err, data) { if (err) { return console.error(err); } //get server data var fullData = JSON.parse(data.toString()); //find current server newServer = true; while (newServer) { //test for new server for (server in fullData["servers"]) { if (fullData["servers"][server]["id"] == msg.guild.id) { spinData = fullData["servers"][server]; newServer = false; break; } } //if new server, create tag if (newServer) { var newServerObj = new Object(); newServerObj.id = msg.guild.id; currentTime = new Date(); newServerObj.lastSpin = currentTime - (60000 * coolDownMins); newServerObj.hearto = Math.floor(Math.random() * 20) + 20; //ran 20-40 newServerObj.maidDay = 0; newServerObj.maidDayMulti = 1; newServerObj.users = []; fullData["servers"].push(newServerObj); } } //test for new user in server newUser = true; for (user in spinData["users"]) { if (spinData["users"][user]["id"] == msg.author.id) { olduser = spinData["users"][user]; newUser = false; break; } } currentTime = new Date(); //calc spin amount oldTime = new Date(spinData["lastSpin"]); elapsedMins = Math.floor((currentTime - oldTime) / 60000); amount = (elapsedMins - coolDownMins) + 1; //update data spinKA = true; hiSpinKA = false; newCallKA = false; firstOfTheDay = false; heartoKA = false; maidDayKA = false; if (newUser) { //create new user entry var newUserObj = new Object(); newUserObj.id = msg.author.id; newUserObj.name = msg.author.username; amount = 1; //only 1 for first free spin newUserObj.spins = amount; newUserObj.hiSpin = amount; newUserObj.hearto = 0; spinData["users"].push(newUserObj); console.log("New user " + `${newUserObj.name}` + " spun the maid. (" + `${newUserObj.spins}` + " spins)."); msg.channel.send(`${msg.author}` + " spun a maid! (Free spin for new user)"); msg.channel.send("To read how to play use " + '*"**@Maid Spin** help"*.'); msg.channel.send("https://i.imgur.com/7hqhB0M.gif"); total = newUserObj.spins; } else { //old user, check for timeout if (elapsedMins >= coolDownMins) { //cooldown over, SPIN oldAmount = olduser["spins"]; //check for firstOfTheDay if (oldTime.getDate() != currentTime.getDate()) { firstOfTheDay = true; amount = amount + 100; } //calc roll multiplier spinType = 0; ran = Math.floor(Math.random() * 100) + 1; //ran = 1-100 if (ran > 99) { //100 25x spinType = 25; } else if (ran > 96) { //97-99 10x spinType = 10; } else if (ran > 88) { //89-96 5x spinType = 5; } else if (ran > 75) { //78-91 3x spinType = 3; } else if (ran > 55) { //58-77 2x spinType = 2; } else { //1-57 1x spinType = 1; } amount = amount * spinType; //test for new call if (testNewCall(msg)) { amount = Math.ceil(amount * 1.5); newCallKA = true; } //calc elapsed hours since maid day start maidDayStart = new Date(spinData["maidDay"]); elapsedMaidDayHours = Math.floor((currentTime - maidDayStart) / 3600000); //test for maid day maidDayMulti = spinData["maidDayMulti"]; if (elapsedMaidDayHours < 24) { maidDayKA = true; amount = amount * maidDayMulti; } spinData["lastSpin"] = currentTime; olduser.spins = olduser.spins + amount; //check if overtaken anyone overtaken = checkOvertaken(spinData, oldAmount, olduser.spins); //update hispin if higher than current top if (!(olduser.hasOwnProperty("hiSpin") && amount <= olduser.hiSpin)) { hiSpinKA = true; olduser.hiSpin = amount; } console.log(currentTime.getHours() + ":" + currentTime.getMinutes() + " - " + amount + " spins (ran=" + ran + ") for " + `${olduser.name}` + " (" + `${olduser.spins}` + " total)"); total = olduser.spins; //check meido no hearto spinData["hearto"] = spinData["hearto"] - 1; if (spinData["hearto"] == 0) { heartoKA = true; spinData["hearto"] = Math.floor(Math.random() * 20) + 20; //ran 20-40 olduser.hearto = olduser.hearto + 1; console.log(currentTime.getHours() + ":" + currentTime.getMinutes() + " " + `${olduser.name}` + "found a meido no hearto"); } printSpin(msg, amount, total, spinType, hiSpinKA, newCallKA, firstOfTheDay, heartoKA, maidDayKA, elapsedMaidDayHours, maidDayMulti, overtaken); } else { //cooldown not over, no spin, dizzy spinKA = false; msg.channel.send('The maids are too dizzy to spin.\nCheck the cooldown with *"**@Maid Spin** timer"*.'); console.log(currentTime.getHours() + ":" + currentTime.getMinutes() + " " + `${olduser.name}` + " attempted to spin."); msg.channel.send(getGIF(GIFdizzy)); } } //if spinKA is still true, save spin details and post spin if (spinKA) { writeData(fullData); } }); } function spin(msg) { updateCount(msg); } function spinTest(msg) { regexString = ".*(((" + spinWords + ").*(" + maidWords + "))|((" + maidWords + ").*(" + spinWords + "))).*"; spinRegex = new RegExp(regexString, "i"); if (spinRegex.test(msg.content)) { spin(msg); } } //print help function spinHelp(msg) { msg.channel.send("***Maid Spin Help:***\n" + "This bot lets you do what you've always wanted to do: **SPIN MAIDS**.\n" + 'To spin a maid simply command her to spin by saying *"Spin the maid!"* or something similar into the chat.\n' + 'The maids can only spin every **' + coolDownMins + " mins**, they get dizzy!\n" + 'The maids can spin for as many minutes as have passed since they recovered. So if you spin 5 mins after they have recovered, you get 5 spin points.\n' + 'You will get extra spins if you spin the maids using a message no one has used before, so be creative.\n' + 'Occasionally you will find a mysterious *meido no hearto*, use *"**@Maid Spin** hearto"* to see what you can do with them.\n' + 'To view who has spun the most maids, use *"**@Maid Spin** top"*.\n' + 'To view who had the biggest spin, use *"**@Maid Spin** toph"*.\n' + 'To view the leaderboard from v1, use *"**@Maid Spin** topold"*.\n' + '*Bot built and maintained by **iklone**: http://iklone.org*'); } //display hispin leader board function topHiSpins(msg) { fs.readFile('spinData.json', function(err, data) { if (err) { return console.error(err); } //get server data var spinData = getServerData(getFullData(data), msg, true); var parsedData = []; for (user in spinData["users"]) { if (spinData["users"][user].hasOwnProperty("hiSpin")) { //only include those with hispin property parsedData.push(spinData["users"][user]); } } parsedData.sort((a, b) => b.hiSpin - a.hiSpin); topstring = "***Highest One-Time Spin:***"; rank = 0; for (user in parsedData) { rank = rank + 1; topstring = topstring + "\n#" + rank + " : **" + parsedData[user]["name"] + "** (" + parsedData[user]["hiSpin"] + " spin)"; } msg.channel.send(topstring); }); } //display basic leader board function topSpins(msg) { fs.readFile('spinData.json', function(err, data) { if (err) { return console.error(err); } //get server data var spinData = getServerData(getFullData(data), msg, true); spinData["users"].sort((a, b) => b.spins - a.spins); topstring = "***Top Maid Spinners:***"; rank = 0; for (user in spinData["users"]) { rank = rank + 1; topstring = topstring + "\n#" + rank + " : **" + spinData["users"][user]["name"] + "** (" + spinData["users"][user]["spins"] + " spins)"; } msg.channel.send(topstring); }); } //display old leader board function topOldSpins(msg) { fs.readFile('oldSpinData.json', function(err, data) { if (err) { msg.channel.send("This bot is not configured with data from Maid Spin v1."); return console.error(err); } //get server data var spinData = getServerData(getFullData(data), msg, false); if (spinData == 0) { //notify if no old data msg.channel.send("This server has no data from Maid Spin v1."); return; } spinData["users"].sort((a, b) => b.spins - a.spins); topstring = "***Top Maid Spinners:***"; rank = 0; for (user in spinData["users"]) { rank = rank + 1; topstring = topstring + "\n#" + rank + " : **" + spinData["users"][user]["name"] + "** " + spinData["users"][user]["spins"] + " spins (highest " + spinData["users"][user]["hiSpin"] + ")"; } msg.channel.send(topstring); }); } function timerUp(msg) { fs.readFile('spinData.json', function(err, data) { if (err) { return console.error(err); } //get server data var spinData = getServerData(getFullData(data), msg, true); //get timings currentTime = new Date(); lastSpin = new Date(spinData["lastSpin"]); elapsedMins = Math.floor((currentTime - lastSpin) / 60000); if (elapsedMins >= coolDownMins) { verbVar = "CAN"; spins = (elapsedMins - coolDownMins + 1); if (spins == 1) { nounVar = "maid is"; } else { nounVar = "maids are"; } extraInfo = spins + " " + nounVar + " waiting to be spun!\n"; } else { verbVar = "cannot" extraInfo = "The next maid can be spun in " + (coolDownMins - elapsedMins) + ' mins.\nFor more information use *"**@Maid Spin** help"*\n'; } msg.channel.send("The last maid was spun " + elapsedMins + " mins ago. The cooldown is " + coolDownMins + " mins.\n" + extraInfo + "You **" + verbVar + "** spin a maid now."); }); } //check your number of heartos function heartoCheck(msg) { fs.readFile('spinData.json', function(err, data) { if (err) { return console.error(err); } olduser = getUserData(getServerData(getFullData(data), msg, true), msg, true); if (olduser) { msg.channel.send("You currently have **" + olduser["hearto"] + "** meido no hearto."); msg.channel.send("With your meido no hearto you can either:\n" + "Trade x1 for " + heartoExchangeRate + " spins with " + '*"**@Maid Spin** hearto spins"*\n' + "Trade any number to initiate *MAID DAY* with " + '*"**@Maid Spin** hearto maid day X"*\n' + "*Maid Day* is a 24 hour period where all spins will be given a multiplier." + "The number you specify with X will be both the cost and the multiplier for the day."); } }); } //spend heartos, return true is successful false if not function spendHearto(cost, msg) { data = fs.readFileSync('spinData.json'); fullData = getFullData(data); olduser = getUserData(getServerData(fullData, msg, true), msg, true); if (olduser) { //check balance is valid if (olduser["hearto"] < cost) { msg.channel.send("You do not have enough meido no hearto. *(" + olduser["hearto"] + "/" + cost + ")*"); return false; } else { olduser["hearto"] = olduser["hearto"] - cost; writeData(fullData); return true; } } } //trade hearto for spins function heartoTrade(msg) { //spend heartos if (spendHearto(1, msg)) { fs.readFile('spinData.json', function(err, data) { fullData = getFullData(data); olduser = getUserData(getServerData(fullData, msg, true), msg, true); olduser["spins"] = olduser["spins"] + heartoExchangeRate; msg.channel.send("The meido no hearto dissolves into " + heartoExchangeRate + " tiny maids, all spinning. *(+" + heartoExchangeRate + " spins)*"); msg.channel.send("https://i.imgur.com/Hu6nQHB.gif"); writeData(fullData); }); } } //start maid day with hearto function heartoMaidDay(msg) { //get final input, should be valid number value, run if valid integer msgArray = msg.content.split(" "); cost = parseInt(msgArray[msgArray.length - 1]); if (Number.isInteger(cost)) { //run if cost is 2 or more if (cost > 1) { //run if enough heartos if (spendHearto(cost, msg)) { fs.readFile('spinData.json', function(err, data) { fullData = getFullData(data); spinData = getServerData(fullData, msg, true); spinData["maidDay"] = new Date(); spinData["maidDayMulti"] = cost; msg.channel.send("The " + cost + " meido no hearto burst into flames. You have completed the maid day ritual. All spins will be worth " + cost + "x more for 24 hours. "); if (cost > 4) { //maid day flavour text differs with multiplier if (cost < 10) { msg.channel.send("They burn pink with the power of a maid's beauty. This is a legendary maid day that will be recorded in maid history forever."); msg.channel.send("**MAID DAY OF JUSTICE HAS BEGUN**"); msg.channel.send("https://i.imgur.com/e7CMBJM.gif"); } else { msg.channel.send("They burn a rainbow of colours with the power of a maid's tears. This maid day marks a new era of maids."); msg.channel.send("**MAID DAY OF HEAVEN HAS BEGUN**"); msg.channel.send("https://i.imgur.com/bQHwKhE.gif"); } } else { msg.channel.send("**MAID DAY HAS BEGUN**"); msg.channel.send("https://i.imgur.com/fDnQnao.gif"); } writeData(fullData); }); } } else { msg.channel.send("You don't want to do that, a 1x multiplier won't do anything. Use the form " + '*"**@Maid Spin** maid day X"*, where X is the multiplier you want.'); } } else { msg.channel.send("You must use a valid number more than 1. Use the form " + '*"**@Maid Spin** maid day X"*, where X is the multiplier you want.'); } } //on message client.on('message', msg => { //stop if msg by self if (msg.author.id != myID) { //console.log(msg); n = true; //if in DM then cancel and log if (msg.guild === null) { msg.channel.send("Maid Spin cannot be played in DMs. You cheater."); msg.channel.send("https://i.imgur.com/rjm5m8y.jpg"); console.log(`${msg.author.username}` + " attempted to cheat."); n = false; } //if @bot then command if (n && msg.mentions.users.array().length > 0 && msg.mentions.users.array()[0]["id"] == myID) { trueContent = msg.content; console.log(trueContent); //test for leaderboard topRegex = new RegExp(/.*top.*/i); if (n && topRegex.test(trueContent)) { //top hispin tophRegex = new RegExp(/.*(toph|top-h|top h).*/i); if (n && tophRegex.test(trueContent)) { n = false; topHiSpins(msg); } //top old topOldRegex = new RegExp(/.*old.*/i); if (n && topOldRegex.test(trueContent)) { n = false; topOldSpins(msg); } //else go basic leaderboard if (n) { topSpins(msg); n = false; } } //test for timer timerRegex = new RegExp(/.*(tim|tu|clock).*/i); if (n && timerRegex.test(trueContent)) { n = false; timerUp(msg); } //test for hearto heartoRegex = new RegExp(/.*heart.*/i); if (n && heartoRegex.test(trueContent)) { //trade for spins heartoTradeRegex = new RegExp(/.*(trade|spin).*/i); if (n && heartoTradeRegex.test(trueContent)) { n = false; heartoTrade(msg); } //trade for maid day heartoMaidDayRegex = new RegExp(/.*(maid day|maidday|maiday).*/i); if (n && heartoMaidDayRegex.test(trueContent)) { n = false; heartoMaidDay(msg); } //else check hearto count and shop if (n) { heartoCheck(msg); n = false; } } //Else then try to spin if (n) { spinTest(msg); } //Mahoro wave easter egg waveRegex = new RegExp(/.*(wav).*/i); if (waveRegex.test(msg.content)) { msg.channel.send("https://i.imgur.com/jQpZFsp.gif"); n = false; } //Else then help if (n) { spinHelp(msg); } } //spin if (n) { spinTest(msg); } //important jojo PSA. Comment out if you don't want this. jojoRegex = new RegExp(/.*(jojo).*/i); if (jojoRegex.test(msg.content)) { msg.channel.send("Jojo is bad."); } } }); fs.readFile('password.config', function(err, data) { client.login(data.toString()); });
20e7a05edbdb1b88624569f5dc7aca8d92bbd011
[ "Markdown", "JavaScript" ]
2
Markdown
iklone/maidspin
81a9e6a8ad879d8d3be37a630973783e74df8675
cc27c5f4c7966a7e337e71ac54fd1bf118944ebb
refs/heads/master
<repo_name>mariehuynh/dotfiles<file_sep>/.bash_profile alias ll='ls -alF' # Download from https://raw.github.com/git/git/master/contrib/completion/git-completion.bash source ~/git-completion.bash # Download from https://raw.github.com/git/git/master/contrib/completion/git-prompt.sh source ~/git-prompt.sh GIT_PS1_SHOWDIRTYSTATE=true GIT_PS1_SHOWUNTRACKEDFILES=true GIT_PS1_SHOWCOLORHINTS=true GIT_PS1_SHOWUPSTREAM="auto" LIGHTNING_BOLT=$'\xE2\x9A\xA1' # LONG RIGHTWARDS SQUIGGLE ARROW SA=$'\xe2\x9f\xbf' # Pencil going to the right PENCIL=$'\xE2\x9C\x8F' # Bread BREAD=$'\xF0\x9F\x8D\x9E' # Hamster HAMSTER=$'\xF0\x9F\x90\xB9' # Wave WAVE=$'\xF0\x9F\x8C\x8A' # Eggplant EGGPLANT=$'\xF0\x9F\x8D\x86' # Tomato TOMATO=$'\xF0\x9F\x8D\x85' PROMPT_COMMAND='__git_ps1 "\W" "$HAMSTER "\ '
861c24323a8dc9007b9ade4ad60172ee35cc913e
[ "Shell" ]
1
Shell
mariehuynh/dotfiles
4bb90187297da311f341eee3b8aa3f7d9bba6d07
5396a9c39400adde9056b83d42edf4c07f150e57
refs/heads/master
<file_sep>#include <stdio.h> #include <gmp.h> char *prog; typedef struct elliptic_curve_t { mpz_t A,B,p; } elliptic_curve; typedef struct point_t { mpz_t x,y; } point; void elliptic_curve_init(elliptic_curve* e) { mpz_init(e->A); mpz_init(e->B); mpz_init(e->p); } void point_init(point* p) { mpz_init(p->x); mpz_init(p->y); } int is_Singular(elliptic_curve e) { // Check condition mpz_t a3, b2; mpz_init(a3); mpz_init(b2); mpz_powm_ui(a3 , e.A , 3, e.p); mpz_powm_ui(b2 , e.B , 2 , e.p); mpz_mul_ui(a3 , a3 , 4); mpz_addmul_ui(a3 , b2 , 27); mpz_mod(a3 , a3 , e.p); if(mpz_sgn(a3)) return 0; return 1; } void generate_random_seed(mpz_t seed) { __uint8_t input[20]; FILE *fp; if((fp = fopen("/dev/urandom","r")) == NULL) { fprintf(stderr, "%s: can't read /dev/urandom \n", prog); } else { for(int i = 0; i < 19; i++) { input[i] = getc(fp); } mpz_import(seed, sizeof(input), 1, sizeof(input[0]), 0, 0, input); } } void generate_random_number(mpz_t x, int num_bits) { gmp_randstate_t state; gmp_randinit_default(state); mpz_t seed; mpz_init(seed); generate_random_seed(seed); gmp_randseed(state, seed); mpz_urandomb(x, state , num_bits); gmp_randclear(state); } void elliptic_curve_random_generate(elliptic_curve* e, int n) // n = number of bits { // Randomly choose a prime p mpz_t p; mpz_init(p); int val = 0; // while(val != 2){ // generate_random_number(p, n); // val = mpz_probab_prime_p(p, 40); // } generate_random_number(p, n); int cnt = 0; while(1){ val = mpz_probab_prime_p(p, 40); if(val >= 1){ break; } if(mpz_even_p(p)){ mpz_add_ui(p, p, 1); //printf("1\n"); }else{ mpz_add_ui(p, p, 2); //printf("2\n"); } } mpz_out_str(stdout,10,p); mpz_set(e->p, p); printf("\n"); mpz_t A, B; mpz_init(A); mpz_init(B); do{ // Randomly choose A generate_random_number(A, n); // Randomly choose B generate_random_number(B, n); mpz_set(e->A, A); mpz_set(e->B, B); }while(is_Singular(*e)); return ; } void slope(elliptic_curve e, point p1, point p2 , mpz_t lambda) { mpz_t temp; mpz_init(temp); if(mpz_cmp(p1.x , p2.x) == 0 && mpz_cmp(p1.y , p2.y) == 0) { mpz_powm_ui(lambda , p1.x , 2 , e.p); mpz_mul_ui(lambda , lambda , 3); mpz_add(lambda , lambda , e.A); mpz_mod(lambda , lambda , e.p); mpz_mul_ui(temp , p1.y , 2); mpz_mod(temp , temp , e.p); mpz_invert(temp , temp , e.p); mpz_mul(lambda , lambda , temp); mpz_mod(lambda , lambda , e.p); return ; } mpz_sub(temp , p2.x , p1.x); mpz_mod(temp , temp , e.p); mpz_invert(lambda, temp , e.p); mpz_sub(temp , p2.y , p1.y); mpz_mod(temp , temp , e.p); mpz_mul(lambda , lambda , temp); mpz_mod(lambda , lambda , e.p); return ; } point elliptic_curve_operation(elliptic_curve e, point p1, point p2) // operation = addition { point result; point_init(&result); mpz_mod(p1.x , p1.x , e.p); mpz_mod(p1.y , p1.y , e.p); mpz_mod(p2.x , p2.x , e.p); mpz_mod(p2.y , p2.y , e.p); mpz_t temp; mpz_init(temp); mpz_add(temp , p1.y , p2.y); mpz_mod(temp ,temp , e.p); if(mpz_cmp(p1.x , p2.x) == 0 && mpz_sgn(temp) == 0) { mpz_set_str(result.x , "0", 10); mpz_set_str(result.y , "0", 10); return result; } mpz_t lambda, lambda_squared; mpz_init(lambda); mpz_init(lambda_squared); slope(e, p1, p2 , lambda); mpz_powm_ui(lambda_squared , lambda, 2 , e.p); mpz_sub(result.x , lambda_squared , p1.x); mpz_sub(result.x , result.x , p2.x); mpz_mod(result.x , result.x , e.p); mpz_sub(result.y , p1.x, result.x); mpz_mul(result.y , result.y , lambda); mpz_sub(result.y , result.y , p1.y); mpz_mod(result.y , result.y , e.p); return result; } int main(int argc, char *argv[]) { prog = argv[0]; elliptic_curve e1,e2; int num_bits; printf("Enter number of bits: "); scanf("%d", &num_bits); elliptic_curve_init(&e1); elliptic_curve_init(&e2); elliptic_curve_random_generate(&e1, num_bits); point p1, p2, p3; point_init(&p1); point_init(&p2); point_init(&p3); mpz_set_str(e2.A , "1" , 10); mpz_set_str(e2.B , "6" , 10); mpz_set_str(e2.p , "11" , 10); mpz_set_str(p1.x , "2" , 10); mpz_set_str(p1.y , "7" , 10); mpz_set_str(p2.x , "2" , 10); mpz_set_str(p2.y , "7" , 10); printf("\n"); for(int i = 0 ; i < 12 ; i++) { printf("Point %d :\n" , i+1); p3 = elliptic_curve_operation(e2 , p1 , p2); mpz_out_str(stdout,10,p3.x); printf("\n"); mpz_out_str(stdout,10,p3.y); printf("\n\n"); p2 = p3; } return 0; } <file_sep>/************************** Authors: Rajat & Manas Algorithm Details: https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2withchangenotice.pdf : https://www.youtube.com/watch?v=f9EbD6iY9zI *************************/ #include <stdio.h> #include <stdlib.h> #include <memory.h> // SHA256 outputs a 32 unchar digest #define BLOCK_SIZE 32 // 8-bit char typedef unsigned char unchar; typedef unsigned int unint; typedef unsigned long long unll; typedef struct { unchar data[64]; unint datalen, hashValue[8]; unll totalLen; } SHA_256; /************-Operations on unints-********/ #define SHFR(x, n) (x >> n) #define ROTL(x, n) ((x << n) | (x >> (32 - n))) #define ROTR(x, n) ((x >> n) | (x << (32 - n))) /******************************************/ /************-Functions-*******************/ #define CH(x, y, z) ((x & y) ^ (~x & z)) #define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) #define EP0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) #define EP1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) #define SIG0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3)) #define SIG1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10)) /*******************************************/ /************-SHA-256 Constants-************/ /*SHA-256 uses a sequence of sixty-four constant 32-bit unints, K 0 {256} , K 1 {256} ,K, K {256} . These 63 unints represent the first thirty-two bits of the fractional parts of the cube roots of the first sixty- four prime numbers. In hex, these constant unints are (from left to right)*/ static const unint k[64] = { 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 }; /*******************************************/ /************-Function Definations-*******************/ void Transform(SHA_256 *msgDigest, const unchar data[]) { unint a, b, c, d, e, f, g, h; unint idx1, idx2, temp1, temp2; unint message[64]; //Message Schedule for (idx1 = 0, idx2 = 0; idx1 < 16; idx1++, idx2 += 4){ message[idx1] = (data[idx2] << 24) | (data[idx2 + 1] << 16) | (data[idx2 + 2] << 8) | (data[idx2 + 3]); } while(idx1 < 64){ message[idx1] = SIG1(message[idx1 - 2]) + message[idx1 - 7] + SIG0(message[idx1 - 15]) + message[idx1 - 16]; idx1++; } //Compression a = msgDigest->hashValue[0]; b = msgDigest->hashValue[1]; c = msgDigest->hashValue[2]; d = msgDigest->hashValue[3]; e = msgDigest->hashValue[4]; f = msgDigest->hashValue[5]; g = msgDigest->hashValue[6]; h = msgDigest->hashValue[7]; for (idx1 = 0; idx1 < 64; idx1++) { temp1 = h + EP1(e) + CH(e,f,g) + k[idx1] + message[idx1]; temp2 = EP0(a) + MAJ(a,b,c); h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2; } msgDigest->hashValue[0] += a; msgDigest->hashValue[1] += b; msgDigest->hashValue[2] += c; msgDigest->hashValue[3] += d; msgDigest->hashValue[4] += e; msgDigest->hashValue[5] += f; msgDigest->hashValue[6] += g; msgDigest->hashValue[7] += h; } void Initialize(SHA_256 *msgDigest) { //Set the initial hash value, H (0) msgDigest->datalen = 0; msgDigest->totalLen = 0; msgDigest->hashValue[0] = 0x6a09e667; msgDigest->hashValue[1] = 0xbb67ae85; msgDigest->hashValue[2] = 0x3c6ef372; msgDigest->hashValue[3] = 0xa54ff53a; msgDigest->hashValue[4] = 0x510e527f; msgDigest->hashValue[5] = 0x9b05688c; msgDigest->hashValue[6] = 0x1f83d9ab; msgDigest->hashValue[7] = 0x5be0cd19; } void Update(SHA_256 *msgDigest, unchar data[], size_t len) { unint idx; for (idx = 0; idx < len; idx++) { msgDigest->data[msgDigest->datalen] = data[idx]; msgDigest->datalen++; if (msgDigest->datalen == 64) { //For each Message Block Transform(msgDigest, msgDigest->data); msgDigest->totalLen += 512; msgDigest->datalen = 0; } } } void OutputHash(SHA_256 *msgDigest, unchar hash[]) { unint idx; idx = msgDigest->datalen; /*Suppose that the length of the message, M, is l bits. Append the bit “ 1” to the end of the message, followed by k zero bits, where k is the smallest, non-negative solution to the equation l + 1 + k ” 448 mod 512 . Then append the 64-bit block that is equal to the number l expressed using a binary representation. For example, the (8-bit ASCII) message “abc ” has length 8· 3 = 24 , so the message is padded with a one bit, then 448 - (24 +1) = 423 zero bits, and then the message length, to become the 512-bit padded message*/ //Padding if (msgDigest->datalen < 56) { msgDigest->data[idx] = 0x80; idx++; while (idx < 56){ msgDigest->data[idx] = 0x00; idx++; } } else { msgDigest->data[idx] = 0x80; idx++; while (idx < 64){ msgDigest->data[idx] = 0x00; idx++; } //For last Message Block Transform(msgDigest, msgDigest->data); memset(msgDigest->data, 0, 56); } // Append length of message in last padded block and Transform msgDigest->totalLen += msgDigest->datalen * 8; msgDigest->data[63] = msgDigest->totalLen; msgDigest->data[62] = msgDigest->totalLen >> 8; msgDigest->data[61] = msgDigest->totalLen >> 16; msgDigest->data[60] = msgDigest->totalLen >> 24; msgDigest->data[59] = msgDigest->totalLen >> 32; msgDigest->data[58] = msgDigest->totalLen >> 40; msgDigest->data[57] = msgDigest->totalLen >> 48; msgDigest->data[56] = msgDigest->totalLen >> 56; Transform(msgDigest, msgDigest->data); //SHA uses big endian thus reverse the unchars when copying the final hashValue to the output hash. for (idx = 0; idx < 4; idx++) { hash[idx] = (msgDigest->hashValue[0] >> (24 - idx * 8)) & 0x000000ff; hash[idx + 4] = (msgDigest->hashValue[1] >> (24 - idx * 8)) & 0x000000ff; hash[idx + 8] = (msgDigest->hashValue[2] >> (24 - idx * 8)) & 0x000000ff; hash[idx + 12] = (msgDigest->hashValue[3] >> (24 - idx * 8)) & 0x000000ff; hash[idx + 16] = (msgDigest->hashValue[4] >> (24 - idx * 8)) & 0x000000ff; hash[idx + 20] = (msgDigest->hashValue[5] >> (24 - idx * 8)) & 0x000000ff; hash[idx + 24] = (msgDigest->hashValue[6] >> (24 - idx * 8)) & 0x000000ff; hash[idx + 28] = (msgDigest->hashValue[7] >> (24 - idx * 8)) & 0x000000ff; } } /*******************************************/ int main() { int temp; unchar text[] = {"abc"}; unchar hash[BLOCK_SIZE] = {0xba,0x78,0x16,0xbf,0x8f,0x01,0xcf,0xea,0x41,0x41,0x40,0xde,0x5d,0xae,0x22,0x23, 0xb0,0x03,0x61,0xa3,0x96,0x17,0x7a,0x9c,0xb4,0x10,0xff,0x61,0xf2,0x00,0x15,0xad}; unchar buffer[BLOCK_SIZE]; SHA_256 msgDigest; int pass = 1; Initialize(&msgDigest); Update(&msgDigest, text, strlen(text)); OutputHash(&msgDigest, buffer); //Check If both Hash Values are same pass = pass && !memcmp(hash, buffer, BLOCK_SIZE); for(int idx = 0; idx < BLOCK_SIZE; idx++){ temp = buffer[idx]; if(temp < 16) printf("0"); // so that first 0 is not ignored printf("%x", buffer[idx]); } printf("\n"); for(int idx = 0; idx < BLOCK_SIZE; idx++){ temp = hash[idx]; if(temp < 16) printf("0"); // so that first 0 is not ignored printf("%x", hash[idx]); } printf("\n"); printf("SHA-256 test: %s\n", pass ? "SUCCEEDED" : "FAILED"); return 0; } <file_sep># Elliptic-Curve Elliptic Curve module for ECC <file_sep>#include <stdio.h> #include <gmp.h> char *prog; typedef struct elliptic_curve_t { mpz_t A,B,p; } elliptic_curve; typedef struct point_t { mpz_t x,y; } point; void elliptic_curve_init(elliptic_curve* e) { mpz_init(e->A); mpz_init(e->B); mpz_init(e->p); } void point_init(point* p) { mpz_init(p->x); mpz_init(p->y); } int is_Singular(elliptic_curve e) { // Check condition mpz_t a3, b2; mpz_init(a3); mpz_init(b2); mpz_powm_ui(a3 , e.A , 3, e.p); mpz_powm_ui(b2 , e.B , 2 , e.p); mpz_mul_ui(a3 , a3 , 4); mpz_addmul_ui(a3 , b2 , 27); mpz_mod (a3 , a3 , e.p); if(mpz_sgn(a3)) return 0; return 1; } void generate_random_seed(mpz_t seed){ __uint8_t input[20]; FILE *fp; if((fp = fopen("/dev/urandom","r")) == NULL){ fprintf(stderr, "%s: can't read /dev/urandom \n", prog); }else{ for(int i = 0; i < 19; i++){ input[i] = getc(fp); } mpz_import(seed, sizeof(input), 1, sizeof(input[0]), 0, 0, input); } } void generate_random_number(mpz_t x, int num_bits){ gmp_randstate_t state; gmp_randinit_default(state); mpz_t seed; mpz_init(seed); generate_random_seed(seed); gmp_randseed(state, seed); mpz_urandomb(x, state , num_bits); gmp_randclear(state); } int elliptic_curve_random_generate(elliptic_curve* e, int n) { // Randomly choose a prime p mpz_t p; mpz_init(p); int val = 0; // while(val != 2){ // generate_random_number(p, n); // val = mpz_probab_prime_p(p, 40); // } generate_random_number(p, n); int cnt = 0; while(1){ val = mpz_probab_prime_p(p, 40); if(val == 2){ break; } if(mpz_even_p(p)){ mpz_add_ui(p, p, 1); //printf("1\n"); }else{ mpz_add_ui(p, p, 2); //printf("2\n"); } } mpz_out_str(stdout,10,p); printf("\n"); mpz_t A, B; mpz_init(A); mpz_init(B); do{ // Randomly choose A generate_random_number(A, n); // Randomly choose B generate_random_number(B, n); mpz_set(e->A, A); mpz_set(e->B, B); mpz_set(e->p, p); }while(is_Singular(*e)); return 0; } point elliptic_curve_operation(point p1, point p2) { point result; point_init(&result); return result; } //gcc crypto.c -lgmp int main(int argc, char *argv[]) { prog = argv[0]; elliptic_curve e1,e2; int num_bits; printf("Enter number of bits: "); scanf("%d", &num_bits); elliptic_curve_init(&e1); elliptic_curve_init(&e2); elliptic_curve_random_generate(&e1, num_bits); return 0; }
60546553b34a71ed91bbc10d1f4bf39bf806ea82
[ "Markdown", "C" ]
4
C
manas0/Elliptic-Curve
3e262cb8f8154d0711f74231ce7f8275a92d0436
ec9a5e21f9b2ac04d92692414d2091b681cf4dc4
refs/heads/master
<file_sep>#include <bits/stdc++.h> using namespace std; int main(void) { //vector of alphabets vector<char> c; for(int i = 97; i <= 122; i++){ if(i == 105){ c.push_back('!'); continue; } if(i == 106){ continue; } c.push_back(i); } //represent the key cout<<"\n"; cout<<"enter the key : "<<"\n"; cout<<"\n"; string key; cin>>key; cout<<"\n"; vector<char> g; bool b = true; for(int i = 0; i < key.size(); i++){ key[i] = tolower(key[i]); if(key[i] == 'i' || key[i] == 'j'){ key[i] = '!'; } for(int j = 0; j < g.size(); j++){ if(key[i] == g[j]){ b = false; break; } } if(b){ g.push_back(key[i]); if(key[i] > 'j'){ key[i]--; } if(key[i] == '!'){ c[8] = '%'; }else{ c[key[i] - 97] = '%'; } } b = true; } //the characters elements in the 5*5 PlayFair array for(char i : c){ if(i != '%'){ g.push_back(i); } } //prepare the 5*5 PlayFair array char arr[5][5]; int k = 0; for(int i = 0; i < 5; i++){ for(int j = 0; j < 5; j++){ arr[i][j] = g[k]; k++; } } //displaying the 5*5 PlayFair array for(int i = 0; i < 5; i++){ for(int j = 0; j < 5; j++){ cout<<arr[i][j]<<" "; } cout<<"\n"; } //---------------------------- insert the Text ------------------- cout<<"\n"; cout<<"press '1' for PlainText or '2' for CipherText"<<"\n"; cout<<"\n"; int type; cin>>type; //---------------------------- insert the PlainText ------------------- if(type == 1){ cout<<"\n"; cout<<"enter the PlainText : "<<"\n"; cout<<"\n"; string str; getline(cin, str); cout<<"\n"; getline(cin, str); vector<char> ptext; cout<<"----------------------\n"; cout<<"the CipherText is : "<<"\n"; cout<<"\n"; //---------------adding the PlainText characters into an array ---------- for(int i = 0; i < str.size(); i++){ if(str[i] != ' '){ if(str[i] == 'i' || str[i] == 'j'){ ptext.push_back('!'); }else{ ptext.push_back(str[i]); } } } //--------------- adding the extra Xs ----------------- for(int i = 1; i < ptext.size(); i++){ if((ptext[i] == ptext[i - 1]) && (i % 2 != 0)){ ptext.insert(ptext.begin() + i, 'x'); } } if(ptext.size() % 2 != 0){ ptext.push_back('x'); } //------------------- divide the text into 2 characters ------------------ char x, y; for(int i = 0; i < ptext.size(); i+=2){ x = ptext[i]; y = ptext[i+1]; //----- getting the indexes of the 2 characters in the 5 * 5 array ---- int i1, j1, i2, j2; int ctn = 0; for(int j = 0; j < 5; j++){ for(int k = 0; k < 5; k++){ if(arr[j][k] == x){ ctn++; i1 = j; j1 = k; } if(arr[j][k] == y){ ctn++; i2 = j; j2 = k; } if(ctn == 2){ j = 5; break; } } } //------ getting the indexes of the two encrypted characters -------- if(i1 == i2){ j1++; j2++; if(j1 > 4) j1 = 0; if(j2 > 4) j2 = 0; }else if(j1 == j2){ i1++; i2++; if(i1 > 4) i1 = 0; if(i2 > 4) i2 = 0; }else{ swap(j1, j2); } cout<<arr[i1][j1]<<arr[i2][j2]<<" "; } cout<<"\n"; //---------------------------- insert the CipherText ------------------- }else if(type == 2){ cout<<"\n"; cout<<"enter the CipherText"<<"\n"; cout<<"\n"; string ctext; cin>>ctext; int x, y; cout<<"----------------------\n"; cout<<"the PlainText is : "<<"\n"; cout<<"\n"; for(int i = 0; i < ctext.size(); i++){ ctext[i] = tolower(ctext[i]); if(ctext[i] == 'i' || ctext[i] == 'j'){ ctext[i] = '!'; } } //----------------- divide the CipherText into two characters ------------ for(int i = 0; i < ctext.size(); i+=2){ x = ctext[i]; y = ctext[i+1]; int i1, j1, i2, j2; int ctn = 0; //--------- getting the indexes of the two characters in the 5*5 array -------- for(int j = 0; j < 5; j++){ for(int k = 0; k < 5; k++){ if(arr[j][k] == x){ i1 = j; j1 = k; ctn++; } if(arr[j][k] == y){ i2 = j; j2 = k; ctn++; } if(ctn == 2){ j = 5; break; } } } //-------- getting the decrypted two characters from the array ---------- if(i1 == i2){ j1--; j2--; if(j1 < 0) j1 = 4; if(j2 < 0) j2 = 4; }else if(j1 == j2){ i1--; i2--; if(i1 < 0) i1 = 4; if(i2 < 0) i2 = 4; }else{ swap(j1, j2); } cout<<arr[i1][j1]<<arr[i2][j2]<<" "; } cout<<"\n"; } return 0; } <file_sep># PlayFair-Cipher a program to encrypted a plaintext and decrypted using playfair cipher algorithm
92298ac428d968c8afeae812fd80ee387ec426e7
[ "Markdown", "C++" ]
2
C++
ahmedaldiahy/PlayFair-Cipher
9d84d96954c5c7b4c61edfb54ecd155e6e627dd0
ad0209f0dc3e411add3c517725f5b8ab7e7115cf
refs/heads/main
<repo_name>London-p/InstaClone<file_sep>/InstaClone/InstaClone/PeopleContent/PersonLikeBarView.swift // // PersonLikeBar.swift // InstaClone // // Created by <NAME> on 3/29/21. // import SwiftUI struct PersonLikeBarView: View { var colWidth: CGFloat var person: Person // var comment: Comment var content: UserContent? @Binding var liked: Bool var body: some View { LazyVGrid(columns: [ GridItem(.fixed(colWidth)), GridItem(.fixed(colWidth)), GridItem(.fixed(colWidth)), ]) { HStack { if liked == false { Button(action: {heartButton()}, label: { Image(systemName: "heart") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 19) .padding(.trailing, 10) .foregroundColor(Color.black) }) } if liked == true { Button(action: {heartButton()}, label: { Image(systemName: "heart.fill") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 19) .padding(.trailing, 10) .foregroundColor(Color.red) }) } NavigationLink(destination: CommentsView(person: person)) { Image(systemName: "message") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 20) .padding(.trailing, 8) .foregroundColor(.black) } Image(systemName: "location") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 19) .padding(.trailing, 10) } Spacer() Image(systemName: "bookmark") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 13) .padding(.trailing, 10) } } func heartButton() { liked.toggle() } } <file_sep>/InstaClone/InstaClone/Story/StoryView.swift // // StoryView.swift // InstaClone // // Created by <NAME> on 3/29/21. // import SwiftUI struct StoryView: View { var people: [Person] var body: some View { ScrollView(.horizontal) { HStack { NavigationLink(destination: StoryVidView()) { VStack { Image(systemName: "person.crop.circle.badge.checkmark") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 65) .foregroundColor(.gray) Text(" Your Story") .foregroundColor(.black) } } ForEach(people, id: \.id) { person in VStack{ NavigationLink(destination: StoryVidView()) { VStack { Image(person.name) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 100) .clipShape(Circle()) Text(person.name) .foregroundColor(.black) } } } } } } } } <file_sep>/InstaClone/InstaClone/PeopleContent/PeopleContentView.swift // // PeopleContentView.swift // InstaClone // // Created by <NAME> on 3/29/21. // import SwiftUI struct PeopleContentView: View { var person: Person var body: some View { HStack { Image(person.name) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 55) .clipShape(Circle()) VStack(alignment: .leading) { Text(person.name) } } } } <file_sep>/InstaClone/InstaClone/Models/Comment.swift // // Comment.swift // InstaClone // // Created by <NAME> on 3/31/21. // import Foundation struct Comment { var id: UUID = UUID() var owner: Person // var respondingTo: Person var respondingId: UUID var respsonses: [Comment]? var text: String var likeCount: Int = Int.random(in: 1..<75) } <file_sep>/InstaClone/InstaClone/OtherViews/CommentsView.swift // // CommentsView.swift // InstaClone // // Created by <NAME> on 3/31/21. // import SwiftUI struct CommentsView: View { @ObservedObject var sot = SourceOfTruth() @State private var text = String() var person: Person var body: some View { NavigationView { VStack{ Text("Comments") .font(.system(size: 30)) .padding(.top, 41) ScrollView { CommentsBodyView(person: person) ForEach(sot.messages) {message in HStack{ Image("London") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 62) .clipShape(Circle()) .padding(.horizontal, 7) Text(message.description!) Spacer() Image(systemName: "heart") } } HStack { TextField("Enter message", text: $sot.messageTxt) Button("Send", action: {didTapSend()}) .padding() }.padding(.horizontal,10) } }.padding(10).edgesIgnoringSafeArea(.all) Spacer() } .onAppear(perform: {sot.getMessages()}) } func didTapSend() { sot.createMessage() sot.getMessages() sot.messageTxt.removeAll() } } <file_sep>/InstaClone/InstaClone/ContentView.swift // // ContentView.swift // InstaClone // // Created by <NAME> on 3/27/21. // import SwiftUI import Amplify import Combine struct ContentView: View { @EnvironmentObject var store: Store @StateObject var vm: FollowingBodyModel = FollowingBodyModel() @State private var liked = false var body: some View { GeometryReader{ geometry in let colWidth = geometry.size.width / 3 TabView{ NavigationView{ VStack{ NavView(colWidth: colWidth) ScrollView{ StoryView(people: store.following) LazyVStack(alignment: .leading) { ForEach(store.following, id: \.id) { person in PeopleContentView(person: person) Image(vm.getContentOfOwners(ownerId: person.id)?.image ?? "") .resizable() .aspectRatio(contentMode: .fill) PersonLikeBarView(colWidth: colWidth, person: person, liked: $liked) PersonFooterView(content: vm.getContentOfOwners(ownerId: person.id), person: person, liked: $liked) } } .onAppear { vm.setContentOfOwners(owners: store.following) } } } .navigationBarHidden(true) } .tabItem { Image(systemName: "house.fill") } NavigationView{ VStack{ SearchView() } .navigationBarHidden(true) } .tabItem { Image(systemName: "magnifyingglass") } NavigationView{ VStack { Button(action: {print("hello")}, label: { Text("Upload A Photo") .frame(width: 312, height: 150, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .background(Color.blue) .foregroundColor(.white) .cornerRadius(128.0) .padding(.top, 10) }) } } .tabItem { Image(systemName: "camera") } NavigationView{ VStack { NotificationsView() Spacer() } .navigationBarHidden(true) } .navigationBarHidden(true) .tabItem { Image(systemName: "heart") } NavigationView{ ScrollView { VStack { ProfileHeaderView() ProfileMiddleView() Spacer() } } .navigationBarHidden(true) } .tabItem { Image(systemName: "person") } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>/InstaClone/InstaClone/Thumbs/DiscoverView.swift // // DiscoverView.swift // InstaClone // // Created by <NAME> on 4/22/21. // import SwiftUI struct DiscoverView: View { var body: some View { HStack { Image("LongHair") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 140, height: 80) .padding(.leading) Image("mrglasses") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 140, height: 90) Image("That guy") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 140, height: 90) . padding(.trailing) } } } struct DiscoverView_Previews: PreviewProvider { static var previews: some View { DiscoverView() } } <file_sep>/InstaClone/InstaClone/OtherViews/SearchView.swift // // SearchView.swift // InstaClone // // Created by <NAME> on 3/31/21. // import SwiftUI struct SearchView: View { @State var Searches = "" var body: some View { VStack { HStack{ TextField("Search", text: $Searches) .padding(.leading, 170) .font(.system(size: 30)) Button(action: {search()}, label: { Image(systemName: "magnifyingglass") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 19) .padding(.trailing, 50) .foregroundColor(Color.black) }) } Text("_____________________________________________") .foregroundColor(.gray) ScrollView { ForEach(1..<15) { _ in DiscoverView() } } } Spacer() } func search() { Searches.removeAll() } } struct SearchView_Previews: PreviewProvider { static var previews: some View { SearchView() } } <file_sep>/InstaClone/InstaClone/Story/StoryVidView.swift // // StoryVidView.swift // InstaClone // // Created by <NAME> on 4/22/21. // import SwiftUI import AVKit struct StoryVidView: View { let url = URL(string: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4")! var body: some View { VStack { VideoPlayer(player: AVPlayer(url: url)) } } } struct StoryVidView_Previews: PreviewProvider { static var previews: some View { StoryVidView() } } <file_sep>/InstaClone/InstaClone/OtherViews/MessageView.swift // // MessageView.swift // InstaClone // // Created by <NAME> on 3/31/21. // import SwiftUI import Amplify import Combine struct MessageView: View { @State private var text = String() @ObservedObject var sot = SourceOfTruth() var body: some View { NavigationView { VStack { Text("Messages") .font(.system(size: 30)) .padding(.top, 51) ScrollView { LazyVStack { ForEach(sot.messages) {message in Text(message.description!) Text(sot.messages.description) } } } HStack { TextField("Enter message", text: $sot.messageTxt) Button("Send", action: {didTapSend()}) .padding() } }.edgesIgnoringSafeArea(.all) .padding(.horizontal,20) }.onAppear(perform: {sot.getMessages()}) Spacer() } func didTapSend() { sot.createMessage() sot.getMessages() sot.messageTxt.removeAll() } } <file_sep>/InstaClone/InstaClone/OtherViews/ProfileHeaderView.swift // // ProfileHeaderView.swift // InstaClone // // Created by <NAME> on 4/4/21. // import SwiftUI struct ProfileHeaderView: View { var body: some View { VStack{ Text("London") .font(.system(size: 25)) .bold() HStack { Spacer() Image(systemName: "person.crop.circle") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 100) .foregroundColor(.gray) Spacer() VStack{ Text("Followers") .font(.system(size: 25)) Text("37") .font(.system(size: 25)) } Spacer() VStack{ Text("Following") .font(.system(size: 25)) Text("15") .font(.system(size: 25)) } Spacer() } } .navigationBarHidden(true) } } struct ProfileHeaderView_Previews: PreviewProvider { static var previews: some View { ProfileHeaderView() } } <file_sep>/InstaClone/InstaClone/SourceOfTruth.swift // // SourceOfTruth.swift // InstaClone // // Created by <NAME> on 4/15/21. // import Amplify import Foundation import Combine class SourceOfTruth: ObservableObject { @Published var messages = [Message]() @Published var messageTxt = "" func send(_ message: Message) { Amplify.API.mutate(request: .create(message)) { mutationResult in switch mutationResult { case .success(let creationResult): switch creationResult { case .success: print("Created message") case .failure(let error): print(error) } case .failure(let apiError): print(apiError) } } } var tokens = Set<AnyCancellable>() var token: AnyCancellable? func createMessage() { let message = Message( name: "London", description: messageTxt ) token = Amplify.DataStore.save(message) .receive(on: DispatchQueue.main) .sink { completion in print(completion) } receiveValue: { savedMessage in print("saved") } } func getMessages() { Amplify.DataStore.query(Message.self) .receive(on: DispatchQueue.main) .sink { completion in print(completion) } receiveValue: { messages in self.messages = messages } .store(in: &tokens) // Amplify.DataStore.clear() } } <file_sep>/InstaClone/InstaClone/PeopleContent/Footer/MiniAddCommentView.swift // // MiniAddCommentView.swift // InstaClone // // Created by <NAME> on 3/30/21. // import SwiftUI struct MiniAddCommentView: View { var person: Person @State var commentTxt: String = "" @State var showSubTextField = false // @Binding var clickedOut: Bool @ObservedObject var sot = SourceOfTruth() let placeHolder = "Add a comment" var body: some View { HStack(spacing: 10) { PersonThumbView(person: person, width: 15, linewidth: 0) TextField("Add a comment", text: $commentTxt, onEditingChanged: {_ in // if self.clickedOut == true { // self.clickedOut = false // } self.showSubTextField = true }) .foregroundColor(.gray) Button("Send", action: {tapSend()}) .padding() HStack{ } } } func tapSend() { commentTxt.removeAll() sot.createMessage() sot.getMessages() } } <file_sep>/InstaClone/InstaClone/ApiService/ApiService.swift // // ApiService.swift // InstaClone // // Created by <NAME> on 3/31/21. // import Foundation class ApiService { static let personApi = PersonApi() static let commentsApi = CommentsApi() static let contentApi = ContentApi() } class ContentApi { fileprivate static var content: [UserContent] = [ UserContent(image: "mrglasses", desc: "Isn't this cool", owner: PersonApi.people[1], comments: [ CommentsApi.comments[1], CommentsApi.comments[0], CommentsApi.comments[4], ]), UserContent(image: "LongHair", desc: "Isn't this cool", owner: PersonApi.people[0], comments: [ CommentsApi.comments[1], CommentsApi.comments[0], CommentsApi.comments[2], ]), UserContent(image: "That guy", desc: "Isn't this cool", owner: PersonApi.people[2], comments: [ CommentsApi.comments[4], CommentsApi.comments[0], CommentsApi.comments[2], ]), ] func getContentOfOwners(owners: [Person]) -> [UserContent]? { ContentApi.content.filter { con in owners.contains { owner in con.owner.id == owner.id } } } } class PersonApi { fileprivate static var people: [Person] = [ Person(name: "mrglasses"), Person(name: "LongHair"), Person(name: "<NAME>"), ] func getFollowing() -> [Person] { return PersonApi.people } func addPerson(person: Person) { PersonApi.people.append(person) } func updatePerson(person: Person) { var foundPerson = PersonApi.people.first { p in p.id == person.id } foundPerson?.name = person.name } } class CommentsApi { fileprivate static var comments: [Comment] = [ Comment(owner: PersonApi.people[2], respondingId: PersonApi.people[1].id, text: "Nice post"), Comment(owner: PersonApi.people[2], respondingId: PersonApi.people[2].id, text: "Nice post"), Comment(owner: PersonApi.people[0], respondingId: PersonApi.people[0].id, text: "Nice post"), Comment(owner: PersonApi.people[1], respondingId: PersonApi.people[2].id, text: "Nice post"), Comment(owner: PersonApi.people[1], respondingId: PersonApi.people[0].id, text: "Nice post"), ] func getComments() -> [Comment] { return CommentsApi.comments } func addComment(comment: Comment) { CommentsApi.comments.append(comment) } } <file_sep>/InstaClone/InstaClone/OtherViews/CommentsBodyView.swift // // CommentsBodyView.swift // InstaClone // // Created by <NAME> on 4/1/21. // import SwiftUI import Amplify import Combine struct CommentsBodyView: View { //private var comment: Comment var isReply: Bool = false var person: Person @ObservedObject var sot = SourceOfTruth() @EnvironmentObject var store: Store /* init(comment: Comment) { self.comment = comment } */ var body: some View { VStack { ForEach(store.following, id: \.id) { person in HStack{ PersonThumbView(person: person, width: 50, linewidth: 2) Text("Nice Post!") Spacer() Image(systemName: "heart") } } } } } <file_sep>/InstaClone/InstaClone/InstaCloneApp.swift // // InstaCloneApp.swift // InstaClone // // Created by <NAME> on 3/27/21. // import SwiftUI import Amplify import AWSDataStorePlugin //import AWSAPIPlugin // UNCOMMENT this line once backend is deployed @main struct InstaCloneApp: App { init() { configureAmplify() } var body: some Scene { WindowGroup { ContentView() .environmentObject(Store()) } } } private func configureAmplify() { let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels()) //let apiPlugin = AWSAPIPlugin(modelRegistration: AmplifyModels()) // UNCOMMENT this line once backend is deployed do { try Amplify.add(plugin: dataStorePlugin) //try Amplify.add(plugin: AWSAPIPlugin(modelRegistration: models)) //try Amplify.add(plugin: apiPlugin) // UNCOMMENT this line once backend is deployed try Amplify.configure() print("Initialized Amplify"); } catch { print("Could not initialize Amplify: \(error)") } } class Store: ObservableObject { @Published var following: [Person] init() { following = ApiService.personApi.getFollowing() } } <file_sep>/InstaClone/InstaClone/Thumbs/PersonThumbView.swift // // PersonThumb.swift // InstaClone // // Created by <NAME> on 3/30/21. // import SwiftUI struct PersonThumbView: View { var person: Person var width: CGFloat var linewidth: CGFloat var body: some View { ZStack { // Rectangle() // .frame(width: width + 8, height: width + 8) // .clipShape(Circle()) Image(person.name) .resizable() .aspectRatio(contentMode: .fit) .frame(width: width + 26) .clipShape(Circle()) } } } <file_sep>/InstaClone/InstaClone/PeopleContent/NotificationsView.swift // // NotificationsView.swift // InstaClone // // Created by <NAME> on 4/22/21. // import SwiftUI struct NotificationsView: View { var body: some View { VStack{ Text("Notifications") .font(.system(size: 25)) Text("_____________________________________________") .foregroundColor(.gray) ForEach(0..<3) { _ in HStack { Image("mrglasses") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 90) .clipShape(Circle()) Text("mrglasses liked your post") .bold() Spacer() } } Spacer() } } } struct NotificationsView_Previews: PreviewProvider { static var previews: some View { NotificationsView() } } <file_sep>/InstaClone/InstaClone/Nav/NavView.swift // // NavView.swift // InstaClone // // Created by <NAME> on 3/27/21. // import SwiftUI struct NavView: View { @StateObject var vm: FollowingBodyModel = FollowingBodyModel() @ObservedObject var sot = SourceOfTruth() var colWidth: CGFloat // var message: Message var body: some View { LazyVGrid(columns:[ GridItem(.fixed(colWidth)), GridItem(.fixed(colWidth)), GridItem(.fixed(colWidth)) ]) { Spacer() Text("InstaClone") .font(.custom("OleoScript-Reqular", size: 29)) NavigationLink(destination: MessageView()) { Image(systemName: "location") .resizable() .frame(width: 30) .foregroundColor(.black) } } } } <file_sep>/InstaClone/InstaClone/MessageExtension.swift // // MessageExtension.swift // InstaClone // // Created by <NAME> on 4/15/21. // import Foundation extension Message: Identifiable { } <file_sep>/InstaClone/InstaClone/OtherViews/CommentsModel/CommentsViewModel.swift // // CommentsViewModel.swift // InstaClone // // Created by <NAME> on 4/1/21. // import Foundation <file_sep>/README.md # Watch gif for a demo <file_sep>/InstaClone/InstaClone/OtherViews/ProfileMiddleView.swift // // ProfileMiddleView.swift // InstaClone // // Created by <NAME> on 4/4/21. // import SwiftUI struct ProfileMiddleView: View { @State private var selection = 1 var body: some View { VStack { HStack{ Text("Swift Developer") .padding(.leading, 24) .padding(.top, 16) Spacer() } Button(action: {print("hello")}, label: { Text("Edit Profile") .frame(width: 312, height: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .background(Color.gray) .foregroundColor(.white) .cornerRadius(8.0) .padding(.top, 10) }) Picker("", selection: $selection) { Image(systemName: "circle.grid.2x2").tag(0) Image(systemName: "person").tag(1) }.pickerStyle(SegmentedPickerStyle()) } } } struct ProfileMiddleView_Previews: PreviewProvider { static var previews: some View { ProfileMiddleView() } } <file_sep>/InstaClone/InstaClone/Models/FollowingBodyModel.swift // // FollowingBodyModel.swift // InstaClone // // Created by <NAME> on 3/31/21. // import Foundation class FollowingBodyModel: ObservableObject { @Published var content: [UserContent]? func setContentOfOwners(owners: [Person]) { self.content = ApiService.contentApi.getContentOfOwners(owners: owners) } func getContentOfOwners(ownerId: UUID) -> UserContent? { if let content = content { return content.first { con in con.owner.id == ownerId } } return nil } } <file_sep>/InstaClone/InstaClone/PeopleContent/Footer/PersonFooterView.swift // // PersonFooterView.swift // InstaClone // // Created by <NAME> on 3/30/21. // import SwiftUI struct PersonFooterView: View { //@Binding var clickedOut: Bool var content: UserContent? var person: Person @Binding var liked: Bool var body: some View { if let content = content { if liked == false { Text("\(content.likeCount) Likes") .padding(.bottom, 3) .padding(.leading, 15) } if liked == true { Text("\(content.likeCount + 1) Likes") .padding(.bottom, 3) .padding(.leading, 15) } HStack{ HStack{ Text(content.owner.name) .bold() .padding(.leading, 15) Text(content.desc) .padding(.leading, 5) } Spacer() } NavigationLink(destination: CommentsView( person: person)) { Text("View all \(content.comments?.count ?? 0) comments") .padding(.bottom, 3) .padding(.top, 3) .padding(.leading, 15) .foregroundColor(.black) } // MiniAddCommentView(person: person) } } } <file_sep>/InstaClone/InstaClone/Models/Person.swift // // Person.swift // InstaClone // // Created by <NAME> on 3/29/21. // import Foundation struct Person:Identifiable { var id: UUID = UUID() var name: String var content: [UserContent]? }
48039ad7560e9de414780aa6a8fa86e03318d945
[ "Swift", "Markdown" ]
26
Swift
London-p/InstaClone
5ebc6bc30a743e17a40d2fbf6e472b60fb5393ef
97ee4929d70dc979324f1a767942e06b950c0922
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Reports.Attendance; using VIS_Repository.Reports; using VIS_Repository.Reports.Attendance; namespace VIS_App.Controllers.Report.Attendance { public class OfficialWorkReportAPIController : BaseAPIController { OfficialWorkReportRepository objOfficialWorkReportRepository = null; public OfficialWorkReportAPIController() { objOfficialWorkReportRepository = new OfficialWorkReportRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/OfficialWorkReportAPI/GetEmployee")] [HttpGet] public HttpResponseMessage GetEmployee() { return ToJson(objOfficialWorkReportRepository.GetEmployee()); } [Route("api/OfficialWorkReportAPI/GetYear")] [HttpGet] public HttpResponseMessage GetYear() { return ToJson(objOfficialWorkReportRepository.GetYear()); } [Route("api/OfficialWorkReportAPI/GetOfficialWorkReport")] [HttpPost] public HttpResponseMessage GetOfficialWorkReport(OfficialWorkReportParamterModel entityobject) { if (entityobject.MonthWise == true) { entityobject.FromDate = new DateTime(Convert.ToInt32(entityobject.FromYear), Convert.ToInt32(entityobject.FromMonth), 01); entityobject.ToDate = new DateTime(Convert.ToInt32(entityobject.FromYear), Convert.ToInt32(entityobject.FromMonth), DateTime.DaysInMonth(Convert.ToInt32(entityobject.FromYear), Convert.ToInt32(entityobject.FromMonth))); } return ToJson(objOfficialWorkReportRepository.GetOfficialWorkReport(entityobject)); } } } <file_sep>export interface IUserType { UserType: boolean; } export interface IUserRoleById { employeeID: number; roleName: string; } export interface IAllSurveyDetails { SurveyId: number; SurveyName: string; SurveyDesc: string; TotalPoints: number; IsTimeBased: boolean; SurveyType: string; SurveyTime: string; SuggestedBy: number; ExpiryDate: Date; } export interface ISurveyType { Id: number; Name: string; } export interface IUserForOwnerSelection { Id: number; EmployeeName: string; }<file_sep>export interface ISkillGroup { Id: number; CompanyId: number; SkillGroupID: number; SkillGroupName: string; RatingGroup: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string; IsActive: boolean; }<file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class RFQResponseService { constructor(private _http: Http) { } GetActionTaken(url: string, UserId:number, Access : boolean): Observable<any> { return this._http.get(url + 'GetActionTaken?UserId='+ UserId + '&' +'Access='+ Access ) .map((response: Response) => <any>response.json()); } GetOnLoadData(url: string, UserId: number, RFQId: number): Observable<any> { return this._http.get(url + 'GetOnLoadData?UserId=' + UserId + '&' + 'RFQId=' + RFQId) .map((response: Response) => <any>response.json()); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } post(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } GetTechnology(url: string): Observable<any> { return this._http.get(url + 'GetTechnology') .map((response: Response) => <any>response.json()); } GetRFQLink(url: string): Observable<any> { return this._http.get(url + 'GetRFQLink') .map((response: Response) => <any>response.json()); } GetRFQDocument(url: string): Observable<any> { return this._http.get(url + 'GetRFQDocument') .map((response: Response) => <any>response.json()); } GetViewRFQResponseById(url: string, Id:number): Observable<any> { return this._http.get(url + 'GetViewRFQResponseById?Id=' + Id) .map((response: Response) => <any>response.json()); } //GetProspectClient(url: string, model: any): Observable<any> { // debugger; // url = url + 'GetProspectClient'; // let body = JSON.stringify(model); // let headers = new Headers({ 'Content-Type': 'application/json' }); // let options = new RequestOptions({ headers: headers }); // return this._http.post(url, body, options) // .map((response: Response) => <any>response.json()) // .catch(this.handleError); //} }<file_sep>export interface ILevelCriteriaSetup { Id: number; IsAutomatic: boolean; IsRange: boolean; IsRepeated: boolean; IsOnce: boolean; IsPerformanceBased: boolean; IsEnable: boolean; IsPercentage: boolean; IsProgressive:boolean // ArbManualType: string; //rbEnabledYes: boolean; //rbEnabledNo: boolean; //rbProgressiveYes: boolean; //rbProgressiveNo: boolean; //rbCSYes: boolean; //rbCSNo: boolean; ArbSubType: string; ArbCriteriaType: string; ArbEnable: string; ArbIsProgressive: string; ArbCascading: string; //ArbMPerBadge: string CriteriaID: number; Criteria: string; Category: string; AIsRange: string; FromLimit: number; ToLimit: number; AIsRepeated: string; Units: number; AIsOnce: string; dtFromDate: Date; dtToDate: Date; // IsMPerformanceBadge: boolean; Point: number; Active: boolean; ProgressiveDays: number; ProgressivePoints: number; IsActive: boolean; CreatedOn: Date; CreatedBy: number; UpdatedOn: Date; UpdatedBy: number; Name: string; CriteriaType: string; CalculatedOn: string; SelectPoint: number; EntityMessage: string; //ArbAutomatic: string; //ArbManual: string; //rbRange: boolean; //rbRepeated: boolean; //rbOnce: boolean; // rbPerformanceBasedType: boolean; ArbManualType: string; //rbEnabledYes: boolean; //rbEnabledNo: boolean; //rbProgressiveYes: boolean; //rbProgressiveNo: boolean; //rbCSYes: boolean; //rbCSNo: boolean; } export interface ICriteriaDLL { CriteriaID: number; CriteriaName: string; } export interface ICategoryDLL { Id: number; Category: string; } export interface ICalculatedOnDLL { Id: number; CalculatedOn: string; } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IOfficialWorkReportBind } from '../../../Model/Report/Attendance/OfficialWorkReport'; @Pipe ({ name: 'officialworkreportFilter' }) export class OfficialWorkReporFilterPipe implements PipeTransform { transform(value: IOfficialWorkReportBind[], filter: string): IOfficialWorkReportBind[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IOfficialWorkReportBind) => app.Employee_Name != null && app.Employee_Name.toLocaleLowerCase().indexOf(filter) != -1 || app.Date != null && app.Date.toLocaleLowerCase().indexOf(filter) != -1 || app.OutTime != null && app.OutTime.toLocaleLowerCase().indexOf(filter) != -1 || app.InTime != null && app.InTime.toLocaleLowerCase().indexOf(filter) != -1 || app.Total_Time != null && app.Total_Time.toLocaleLowerCase().indexOf(filter) != -1 || app.Out_Remark != null && app.OutTime.toLocaleLowerCase().indexOf(filter) != -1 || app.In_Remark != null && app.In_Remark.toLocaleLowerCase().indexOf(filter) != -1 || app.Line_Manager != null && app.Line_Manager.toLocaleLowerCase().indexOf(filter) != -1 || app.ApprovalSentTo != null && app.ApprovalSentTo.toLocaleLowerCase().indexOf(filter) != -1 || app.Status != null && app.Status.toLocaleLowerCase().indexOf(filter) != -1 || app.ActionBy != null && app.ActionBy.toLocaleLowerCase().indexOf(filter) != -1 || app.Action_DateTime != null && app.Action_DateTime.toString().indexOf(filter) != -1 ) : value; } } <file_sep> import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { CompanyMasterService } from '../../../service/Masters/CompanyRelated/CompanyMaster.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ICompanyMaster } from '../../../Model/Masters/CompanyRelated/CompanyMaster'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { ILookup } from '../../../Model/Masters/CompanyRelated/Lookup' import { IFinancialYear } from '../../../Model/Masters/CompanyRelated/FinancialYear' import { IPosition } from '../../../Model/Masters/VacancyRelated/Position' import { FileDropDirective, FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-upload'; import { IForHeaddl } from '../../../Model/Masters/CompanyRelated/ForHeaddll' import { Http, RequestOptions, Headers, Response } from '@angular/http'; @Component({ providers: [CompanyMasterService], templateUrl: 'app/Components/Masters/CompanyRelated/CompanyMaster.component.html' }) export class CompanyMasterComponent implements OnInit { public uploaderF1: FileUploader; @ViewChild('modal') modal: ModalComponent; CompanyMasters: ICompanyMaster[]; Countries: ILookup[]; FinancialYear: IFinancialYear[]; Designation: IPosition[]; ForPositionName: IPosition; ForHeaddl: IForHeaddl[]; public CompanyMaster: ICompanyMaster; public CompanyMasterForImg: ICompanyMaster; msg: string; indLoading: boolean = false; CompanyMasterFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; CompanyMasterFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strsearchCompanyName: string; strSearchCity: string; strSearchState: string; strSearchEmail: string; strSearchCountry: string; strSearchE_mail: string; strSearchCompanyURL: string; fileList1: FileList; fileList2: FileList; fileList3: FileList; fileListUp1: FileList; fileListUp2: FileList; fileListUp3: FileList; File1: File; ImgShowHide: boolean; imagePathCompanyLogo: string; imagePathSignature: string; imagePathSignatureOther: string; ImgGlobalPath: string; constructor(private fb: FormBuilder, private _CompanyMasterService: CompanyMasterService, private pagerService: PagerService, private http: Http) { // //this.uploaderF1 = new FileUploader({ // url: 'http://localhost:53349/api/CompanyMasterAPI/FileUpload', disableMultipart: false, maxFileSize: 50000000 //}); } //file upload event fileChange1(event) { this.fileList1 = event.target.files; } fileChange2(event) { this.fileList2 = event.target.files; // this.CompanyMaster.Signature = this.fileList2.item(0).name; } fileChange3(event) { this.fileList3 = event.target.files; // this.CompanyMaster.SignatureOther = this.fileList3.item(0).name; } ngOnInit(): void { this.CompanyMasterFrm = this.fb.group({ Id: [''], CompanyName: ['', Validators.required], City: [''], ZipCode: [''], State: [''], Country: [''], CountryName:[''], ContactNo: ['', Validators.required], E_mail: ['', Validators.required], Fax: [''], CompanyURL: [''], Address: ['', Validators.required], CompanyLogo: [''], AccountHead: [''], Designation: [''], Signature: [''], CompanyShortCode: ['', Validators.required], Address2: [''], StartSeries: [''], FinancialYear: ['',Validators.required], AccountHeadOther: [''], DesignationOther: [''], SignatureOther: [''], FinancialYeardll: [''], PositionName: [''], Employee_Name: [''], //SignatureOtherUpload: [''], //SignatureUpload: [''], //CompanyLogoUpload:[''], CompanyId: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); if (!this.CompanyMasterForImg) { this.ImgShowHide == false; } this.ImgShowHide = false; this.LoadCompanyMasters() this.LoadFY() this.LoadCountry() this.LoadDesignation() this.LoadHead() //else { this.ImgShowHide = true; } } LoadFY(): void { this.indLoading = true; this._CompanyMasterService.getFY(Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(DATAFY => { this.FinancialYear = DATAFY; } //,error => this.msg = <any>error ); } LoadCountry(): void { this.indLoading = true; this._CompanyMasterService.getCountry(Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(DATACOUNTRY => { this.Countries = DATACOUNTRY; } //,error => this.msg = <any>error ); } LoadDesignation(): void { this.indLoading = true; this._CompanyMasterService.getDesignation(Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(DATAposition => { this.Designation = DATAposition; } //,error => this.msg = <any>error ); } LoadHead(): void { this.indLoading = true; this._CompanyMasterService.getHead(Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(DATAHead => { this.ForHeaddl = DATAHead; } //,error => this.msg = <any>error ); } CompanyMasterFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.CompanyMasterFilter = value; } CompanyMasterSort(property: any) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; }; LoadCompanyMasters(): void { this.indLoading = true; this._CompanyMasterService.get(Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(CompanyMasters => { this.CompanyMasters = CompanyMasters; //Logic for searching - start if (this.ShowHideSearch) { this.strsearchCompanyName = (<HTMLInputElement>document.getElementById("searchCompanyName")).value; if (this.strsearchCompanyName != '') { this.strsearchCompanyName = this.strsearchCompanyName.toLocaleLowerCase(); this.CompanyMasters = this.CompanyMasters.filter( x => x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(this.strsearchCompanyName) != -1); } } if (this.ShowHideSearch) { this.strSearchCity = (<HTMLInputElement>document.getElementById("searchCity")).value; if (this.strSearchCity != '') { this.strSearchCity = this.strSearchCity.toLocaleLowerCase(); this.CompanyMasters = this.CompanyMasters.filter( x => x.City != null && x.City.toLocaleLowerCase().indexOf(this.strSearchCity) != -1); } } if (this.ShowHideSearch) { this.strSearchState = (<HTMLInputElement>document.getElementById("searchState")).value; if (this.strSearchState != '') { this.strSearchState = this.strSearchState.toLocaleLowerCase(); this.CompanyMasters = this.CompanyMasters.filter( x => x.State != null && x.State.toLocaleLowerCase().indexOf(this.strSearchState) != -1); } } if (this.ShowHideSearch) { this.strSearchCountry = (<HTMLInputElement>document.getElementById("searchCountry")).value; if (this.strSearchCountry != '') { this.strSearchCountry = this.strSearchCountry.toLocaleLowerCase(); this.CompanyMasters = this.CompanyMasters.filter( x => x.Country != null && x.Country.toLocaleLowerCase().indexOf(this.strSearchCountry) != -1); } } if (this.ShowHideSearch) { this.strSearchEmail = (<HTMLInputElement>document.getElementById("searchE-mail")).value; if (this.strSearchEmail != '') { this.strSearchEmail = this.strSearchEmail.toLocaleLowerCase(); this.CompanyMasters = this.CompanyMasters.filter( x => x.E_mail != null && x.E_mail.toLocaleLowerCase().indexOf(this.strSearchEmail) != -1); } } if (this.ShowHideSearch) { this.strSearchCompanyURL = (<HTMLInputElement>document.getElementById("searchCompanyURL")).value; if (this.strSearchCompanyURL != '') { this.strSearchCompanyURL = this.strSearchCompanyURL.toLocaleLowerCase(); this.CompanyMasters = this.CompanyMasters.filter( x => x.CompanyURL != null && x.CompanyURL.toLocaleLowerCase().indexOf(this.strSearchCompanyURL) != -1); } } //if (this.ShowHideSearch) { // this.strSearchE_mail = (<HTMLInputElement>document.getElementById("E_mail")).value; // if (this.strSearchE_mail != '') { // this.strSearchE_mail = this.strSearchE_mail.toLocaleLowerCase(); // this.CompanyMasters = this.CompanyMasters.filter( // x => x.E_mail != null && x.E_mail.toLocaleLowerCase().indexOf(this.strSearchE_mail) != -1); // } //} //if (this.ShowHideSearch) { // this.strSearchCompanyURL = (<HTMLInputElement>document.getElementById("CompanyURL")).value; // if (this.strSearchCompanyURL != '') { // this.strSearchCompanyURL = this.strSearchCompanyURL.toLocaleLowerCase(); // this.CompanyMasters = this.CompanyMasters.filter( // x => x.CompanyURL != null && x.CompanyURL.toLocaleLowerCase().indexOf(this.strSearchCompanyURL) != -1); // } //} //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addCompanyMaster() { this.imagePathCompanyLogo = null; this.imagePathSignature = null; this.imagePathSignatureOther = null; this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Company"; this.modalBtnTitle = "Add"; this.CompanyMasterFrm.reset(); this.modal.open(); } editCompanyMaster(id: number) { this.ImgGlobalPath = Global.WebAccessURL; this.ImgShowHide = true; this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Company"; this.modalBtnTitle = "Update"; this.CompanyMaster = this.CompanyMasters.filter(x => x.Id == id)[0]; this.CompanyMasterForImg = this.CompanyMaster; this.imagePathCompanyLogo = this.CompanyMaster.CompanyLogo; this.imagePathSignature = this.CompanyMaster.Signature; this.imagePathSignatureOther=this.CompanyMaster.SignatureOther this.CompanyMaster.PositionName = null; this.CompanyMaster.FinancialYeardll = null; this.CompanyMaster.Employee_Name = null; this.CompanyMaster.CompanyLogo = null; this.CompanyMaster.Signature = null; this.CompanyMaster.SignatureOther = null; this.CompanyMasterFrm.setValue(this.CompanyMaster); //this.CompanyMaster["CompanyLogo"] = null; //this.CompanyMaster["Signature"] = null; //this.CompanyMaster["SignatureOther"] = null; this.modal.open(); } deleteCompanyMaster(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.CompanyMaster = this.CompanyMasters.filter(x => x.Id == id)[0]; this.CompanyMaster.PositionName = null; this.CompanyMaster.FinancialYeardll = null; this.CompanyMaster.Employee_Name = null; this.CompanyMaster.CompanyLogo = null; this.CompanyMaster.Signature = null; this.CompanyMaster.SignatureOther = null; this.CompanyMasterFrm.setValue(this.CompanyMaster); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.CompanyMasterFrm.enable() : this.CompanyMasterFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.CompanyMasters); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: if (this.fileList1 != null) { formData._value.CompanyLogo = "/Upload/CompanyMaster/" + this.fileList1.item(0).name; } else { formData._value.CompanyLogo = null; } if (this.fileList1 != null) { formData._value.Signature = "/Upload/CompanyMaster/" + this.fileList2.item(0).name; } else { formData._value.Signature = null; } if (this.fileList1 != null) { formData._value.SignatureOther = "/Upload/CompanyMaster/" + this.fileList3.item(0).name; } else { formData._value.SignatureOther = null; } this._CompanyMasterService.post(Global.BASE_COMPANYMASTER_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { if (this.fileList1 != null ) { if (this.fileList1.length > 0) { this.fileList1.item(0).name let file: File = this.fileList1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/CompanyMasterAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) this.fileList1 = null; } } if (this.fileList2 != null) { if (this.fileList2.length > 0) { let file: File = this.fileList2[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/CompanyMasterAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) this.fileList2 = null; } } if (this.fileList3 != null) { if (this.fileList3.length > 0) { let file: File = this.fileList3[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/CompanyMasterAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) this.fileList3 = null; } } this.msg = data; this.LoadCompanyMasters(); } else { alert(data); } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.update: this._CompanyMasterService.put(Global.BASE_COMPANYMASTER_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadCompanyMasters(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._CompanyMasterService.delete(Global.BASE_COMPANYMASTER_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Company status changed successfully."; this.LoadCompanyMasters(); } else { this.msg = "Error has occurred while changing status of existing CompanyMaster!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; using VIS_Repository.Reports.Attendance; using VIS_Repository.Dashboard; using VIS_Repository.Reports; namespace VIS_App.Controllers.Masters.Configuration { public class LateEarlyReportAPIController : BaseAPIController { LateEarlyReportRepository objLateEarlyReportRepository = null; public LateEarlyReportAPIController() { objLateEarlyReportRepository = new LateEarlyReportRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/LateEarlyReportAPI/GetEmployee")] [HttpGet] public HttpResponseMessage GetEmployee() { return ToJson(objLateEarlyReportRepository.GetEmployee()); } [Route("api/LateEarlyReportAPI/GetAllEmployee")] [HttpGet] public HttpResponseMessage GetAllEmployee() { return ToJson(objLateEarlyReportRepository.GetAllEmployee()); } [Route("api/LateEarlyReportAPI/GetDepartment")] [HttpGet] public HttpResponseMessage GetDepartment() { return ToJson(objLateEarlyReportRepository.GetDepartment()); } [Route("api/LateEarlyReportAPI/GetCompany")] [HttpGet] public HttpResponseMessage GetCompany() { return ToJson(objLateEarlyReportRepository.GetCompany()); } [Route("api/LateEarlyReportAPI/GetYear")] [HttpGet] public HttpResponseMessage GetYear() { return ToJson(objLateEarlyReportRepository.GetYear()); } [Route("api/LateEarlyReportAPI/GetIdByDepartment")] [HttpGet] public HttpResponseMessage GetIdByDepartment(Int64 Id, DateTime Fromdate, DateTime Todate, bool MonthWise, string FromMonth, string FromYear) { if (MonthWise == true) { Fromdate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), 01); Todate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), DateTime.DaysInMonth(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth))); } return ToJson(objLateEarlyReportRepository.GetEmployeeIdByDepartment(Id, Fromdate, Todate)); } [Route("api/LateEarlyReportAPI/GetIdByEmployee")] [HttpGet] public HttpResponseMessage GetIdByEmployee(Int64 Id, DateTime Fromdate,DateTime Todate,bool MonthWise,string FromMonth,string FromYear) { if (MonthWise == true) { Fromdate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), 01); Todate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), DateTime.DaysInMonth(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth))); } return ToJson(objLateEarlyReportRepository.GetEmployeeIdByEmployee(Id,Fromdate,Todate)); } [Route("api/LateEarlyReportAPI/GetIdByCompany")] [HttpGet] public HttpResponseMessage GetIdByCompany(Int64 Id, DateTime Fromdate, DateTime Todate, bool MonthWise, string FromMonth, string FromYear) { if (MonthWise == true) { Fromdate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), 01); Todate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), DateTime.DaysInMonth(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth))); } return ToJson(objLateEarlyReportRepository.GetEmployeeIdByCompany(Id,Fromdate,Todate)); } [Route("api/LateEarlyReportAPI/GetIdBySelectAll")] [HttpGet] public HttpResponseMessage GetIdBySelectAll(Int64 Id, DateTime Fromdate, DateTime Todate, bool MonthWise, string FromMonth, string FromYear) { if (MonthWise == true) { Fromdate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), 01); Todate = new DateTime(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth), DateTime.DaysInMonth(Convert.ToInt32(FromYear), Convert.ToInt32(FromMonth))); } return ToJson(objLateEarlyReportRepository.GetEmployeeIdSelectAll(Id, Fromdate, Todate)); } } } <file_sep>import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule, Params } from '@angular/router'; import { CurrencyComponent } from './components/Masters/CurrencyRelated/currency.component'; import { LevelsComponent } from './components/Masters/EmployeeLevels/levels.component'; import { HomeComponent } from './components/home.component'; import { LoginComponent } from './components/UserManagement/login.component'; import { AuthGuard } from './Shared/auth.gaurd'; import { UserAuthGuard } from './Shared/user.auth.gaurd'; import { ContactMasterComponent } from './components/Masters/CompanyRelated/ContactMaster.component'; import { BankMasterComponent } from './components/Masters/CompanyRelated/BankMaster.component'; import { RatingTypeComponent } from './components/Masters/VacancyRelated/RatingType.component'; import { LookupTypeComponent } from './components/Masters/CompanyRelated/LookupType.component'; import { LookupComponent } from './components/Masters/CompanyRelated/Lookup.component'; import { SkillGroupComponent } from './components/Masters/VacancyRelated/SkillGroup.component'; import { SkillComponent } from './components/Masters/VacancyRelated/Skill.component'; import { PositionComponent } from './components/Masters/VacancyRelated/Position.component'; import { TechnologyMasterComponent } from './components/Masters/VacancyRelated/TechnologyMaster.component'; import { CompanyMasterComponent } from './components/Masters/CompanyRelated/CompanyMaster.Component'; import { MacIdConfigurationComponent } from './components/Masters/Configuration/MacIdConfiguration.component'; import { SecurityKeyComponent } from './components/Masters/Configuration/SecurityKey.component'; import { FinancialYearComponent } from './components/Masters/CompanyRelated/FinancialYear.component'; import { EventCountDownComponent } from './components/Masters/Configuration/EventCountDown.component'; import { DashboardComponent } from './components/Dashboard/dashboard.component'; import { CommonConfigurationComponent } from './components/Masters/Configuration/CommonConfiguration.component'; import { LevelConfigurationComponent } from './components/Masters/EmployeeLevels/LevelConfiguration.component'; import { PolicyComponent } from './components/Notification/policy.component'; import { ConfigureWorkSheetComponent } from './components/Masters/Configuration/ConfigureWorkSheet.component'; import { NewsComponent } from './components/Notification/News.component'; import { LevelCriteriaSetupComponent } from './Components/Masters/EmployeeLevels/LevelCriteriaSetup.component'; import { ConfigureTicketComponent } from './Components/Masters/Configuration/ConfigureTicket.component'; import { HomePageImageComponent } from './Components/Masters/CompanyRelated/HomePageImage.component'; import { HelpTicketAddComponent } from './Components/Notification/HelpTicketAdd.component'; import { MyTicketComponent } from './Components/Notification/MyTicket.component'; import { ChangePasswordComponent } from './Components/HumanResource/ProfileAttendance/ChangePassword.component'; import { TicketListOpenComponent } from './Components/Notification/TicketListOpen.component'; import { TicketListClosedComponent } from './Components/Notification/TicketListClosed.component'; import { MyProfilesComponent } from './Components/HumanResource/ProfileAttendance/MyProfiles.component'; import { LeaveTypeComponent } from './components/Masters/CompanyRelated/LeaveType.component'; import { GroupNameComponent } from './components/Masters/CompanyRelated/GroupName.component'; import { DailyEntrysheetComponent } from './components/Report/Attendance/DailyEntrysheet.component'; import { AttendanceReportComponent } from './Components/Report/Attendance/AttendanceReport.component'; import { OutReportComponent } from './components/Report/Attendance/OutReport.component'; import { WorkSheetComponent } from './components/HumanResource/Attendance/WorkSheet.component'; import { MySkillComponent } from './components/HumanResource/Attendance/MySkill.component'; import { MyTeamComponent } from './components/HumanResource/Attendance/MyTeam.component'; import { EmployeeFeedbackComponent } from './components/HumanResource/Attendance/EmployeeFeedback.component'; import { Levels_AchievementComponent } from './Components/Masters/EmployeeLevels/Levels_Achievement.component'; import { AttendanceEntryComponent } from './Components/UserManagement/AttendanceEntry.component'; import { EmployeeScreenCaptureReportComponent } from './components/Report/Attendance/EmployeeScreenCapture.component'; import { EmployeeDashboardHeartBeatReportComponent } from './components/Report/Attendance/EmployeeDashboardHeartBeatReport.component'; import { AttendanceAccessCardComparisionReportComponent } from './components/Report/Attendance/AttendanceAccessCardComparisionReport.component'; import { EmployeeListComponent } from './components/HumanResource/EmployeeManagement/EmployeeList.component'; import { EmpInfoTabularComponent } from './components/HumanResource/EmployeeManagement/EmpInfoTabular.component'; import { ManualPointEntryComponent } from './components/Masters/EmployeeLevels/ManualPointEntry.component'; import { LateEarlyReportComponent } from './components/Report/Attendance/LateEarlyReport.component'; import { UserRoleComponent } from './components/Masters/CompanyRelated/UserRole.component'; import { EducationTypeComponent } from './components/Masters/CompanyRelated/EducationType.component'; import { SalaryBreakupTypeComponent } from './components/Masters/CompanyRelated/SalaryBreakupType.component'; import { AddEmployeeRecordcomponent } from './Components/Report/Attendance/AddEmployeeRecord.component'; import { AttendanceReportNewcomponent } from './Components/Report/Attendance/AttendanceReportNew.component'; import { OfficialWorkReportComponent } from './Components/Report/Attendance/OfficialWorkReport.component'; import { ProductivityTrackerReportcomponent } from './Components/Report/Attendance/ProductivityTrackerReport.component'; import { ConfigureSurveycomponent } from './Components/Opinion/ConfigureSurvey.component'; import { RFQComponent } from './components/RFQ/RFQEstimateListing.component'; import { AddRFQComponent } from './components/RFQ/AddRFQ.component'; import { AllRFQComponent } from './components/RFQ/RFQEstimateAllRFQ.component'; import { ResponceRequestedRFQcomponent } from './components/RFQ/ResponceRequestedRFQ.component'; import { MyWatchListRFQComponent } from './components/RFQ/MyWatchListRFQ.component'; import { MyActionRFQcomponent } from './components/RFQ/MyActionRFQ.component'; import { CurrencyHistoryComponent } from './components/Masters/CurrencyRelated/CurrencyHistory.component'; import { SalaryGrievanceComponent } from './Components/HumanResource/Grievance/SalaryGrievance.component'; import { DocumentTemplateComponent } from './Components/DocCenter/DocumentTemplate.component'; import { AddRFQResponsecomponent } from './Components/RFQ/AddResponse.component'; import { ViewRFQResponsecomponent } from './Components/RFQ/ViewResponse.component'; const appRoutes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'home', component: HomeComponent, canActivate: [AuthGuard] }, { path: 'currency', component: CurrencyComponent, canActivate: [AuthGuard] }, { path: 'levels', component: LevelsComponent, canActivate: [AuthGuard] }, { path: 'ContactMaster', component: ContactMasterComponent, canActivate: [AuthGuard] }, { path: 'BankMaster', component: BankMasterComponent, canActivate: [AuthGuard] }, { path: 'LookupType', component: LookupTypeComponent, canActivate: [AuthGuard] }, { path: 'Lookup', component: LookupComponent, canActivate: [AuthGuard] }, { path: 'skillgroup', component: SkillGroupComponent, canActivate: [AuthGuard] }, { path: 'skill', component: SkillComponent, canActivate: [AuthGuard] }, { path: 'position', component: PositionComponent, canActivate: [AuthGuard] }, { path: 'TechnologyMaster', component: TechnologyMasterComponent, canActivate: [AuthGuard] }, { path: 'CompanyMaster', component: CompanyMasterComponent, canActivate: [AuthGuard] }, { path: 'macid', component: MacIdConfigurationComponent, canActivate: [AuthGuard] }, { path: 'securitykey', component: SecurityKeyComponent, canActivate: [AuthGuard] }, { path: 'FinancialYear', component: FinancialYearComponent, canActivate: [AuthGuard] }, { path: 'eventcountdown', component: EventCountDownComponent, canActivate: [AuthGuard] }, { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, { path: 'commonconfiguration', component: CommonConfigurationComponent, canActivate: [AuthGuard] }, { path: 'LevelConfiguration', component: LevelConfigurationComponent, canActivate: [AuthGuard] }, { path: 'policy', component: PolicyComponent, canActivate: [AuthGuard] }, { path: 'configureworksheet', component: ConfigureWorkSheetComponent, canActivate: [AuthGuard] }, { path: 'News', component: NewsComponent, canActivate: [AuthGuard] }, { path: 'LevelCriteriaSetup', component: LevelCriteriaSetupComponent, canActivate: [AuthGuard] }, { path: 'configureticket', component: ConfigureTicketComponent, canActivate: [AuthGuard] }, { path: 'HelpTicketAdd', component: HelpTicketAddComponent, canActivate: [AuthGuard] }, { path: 'MyTicket', component: MyTicketComponent, canActivate: [AuthGuard] }, { path: 'homepageimage', component: HomePageImageComponent, canActivate: [AuthGuard] }, { path: 'ChangePassword', component: ChangePasswordComponent, canActivate: [AuthGuard] }, { path: 'TicketListOpen', component: TicketListOpenComponent, canActivate: [AuthGuard] }, { path: 'TicketListClosed', component: TicketListClosedComponent, canActivate: [AuthGuard] }, { path: 'MyProFiles', component: MyProfilesComponent, canActivate: [AuthGuard] }, { path: 'LeaveType', component: LeaveTypeComponent, canActivate: [AuthGuard] }, { path: 'GroupName', component: GroupNameComponent, canActivate: [AuthGuard] }, { path: 'DailyEntryReport', component: DailyEntrysheetComponent, canActivate: [AuthGuard] }, { path: 'AttendanceReport', component: AttendanceReportComponent, canActivate: [AuthGuard] }, { path: 'outreport', component: OutReportComponent, canActivate: [AuthGuard] }, { path: 'WorkSheet', component: WorkSheetComponent, canActivate: [AuthGuard] }, { path: 'MySkill', component: MySkillComponent, canActivate: [AuthGuard] }, { path: 'MyTeam', component: MyTeamComponent, canActivate: [AuthGuard] }, { path: 'EmployeeFeedBack', component: EmployeeFeedbackComponent, canActivate: [AuthGuard] }, { path: 'RatingType', component: RatingTypeComponent, canActivate: [AuthGuard] }, { path: 'Levels_Achievement', component: Levels_AchievementComponent, canActivate: [AuthGuard] }, { path: 'AttendanceEntry', component: AttendanceEntryComponent, canActivate: [AuthGuard] }, { path: 'EmployeeScreenCaptureReportComponent', component: EmployeeScreenCaptureReportComponent, canActivate: [AuthGuard] }, { path: 'EmployeeDashboardHeartBeatReportComponent', component: EmployeeDashboardHeartBeatReportComponent, canActivate: [AuthGuard] }, { path: 'AttendanceAccessCardComparisionReportComponent', component: AttendanceAccessCardComparisionReportComponent, canActivate: [AuthGuard] }, { path: 'EmployeeList', component: EmployeeListComponent, canActivate: [AuthGuard] }, { path: 'EmpInfoTabular', component: EmpInfoTabularComponent, canActivate: [AuthGuard] }, { path: 'ManualPointEntry', component: ManualPointEntryComponent, canActivate: [AuthGuard] }, { path: 'LateEarlyReport', component: LateEarlyReportComponent, canActivate: [AuthGuard] }, { path: 'UserRole', component: UserRoleComponent, canActivate: [AuthGuard] }, { path: 'EducationType', component: EducationTypeComponent, canActivate: [AuthGuard] }, { path: 'SalaryBreakupType', component: SalaryBreakupTypeComponent, canActivate: [AuthGuard] }, { path: 'AddEmployeeRecord', component: AddEmployeeRecordcomponent, canActivate: [AuthGuard] }, { path: 'AttendanceReportNew', component: AttendanceReportNewcomponent, canActivate: [AuthGuard] }, { path: 'OfficialWorkReport', component: OfficialWorkReportComponent, canActivate: [AuthGuard] }, { path: 'ProductivityTracker', component: ProductivityTrackerReportcomponent, canActivate: [AuthGuard] }, { path: 'Opinion_List', component: ConfigureSurveycomponent, canActivate: [AuthGuard] }, { path: 'MyRFQ', component: RFQComponent, canActivate: [AuthGuard] }, { path: 'AllRFQ', component: AllRFQComponent, canActivate: [AuthGuard] }, { path: 'RFQResponceRequested', component: ResponceRequestedRFQcomponent, canActivate: [AuthGuard] }, // { path: 'RFQ/:param', component: RFQComponent, canActivate: [AuthGuard] }, { path: 'AddRFQ', component: AddRFQComponent, canActivate: [AuthGuard] }, { path: 'MyWatchList', component: MyWatchListRFQComponent, canActivate: [AuthGuard] }, { path: 'MyAction', component: MyActionRFQcomponent, canActivate: [AuthGuard] }, { path: 'CurrencyHistory', component: CurrencyHistoryComponent, canActivate: [AuthGuard] }, { path: 'SalaryGrievance', component: SalaryGrievanceComponent, canActivate: [AuthGuard] }, { path: 'DocumentTemplateComponent', component: DocumentTemplateComponent, canActivate: [AuthGuard] }, { path: 'AddRFQResponsecomponent', component: AddRFQResponsecomponent, canActivate: [AuthGuard] }, { path: 'ViewRFQResponsecomponent', component: ViewRFQResponsecomponent, canActivate: [AuthGuard] } ]; export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var RFQ_service_1 = require("../../Service/RFQ/RFQ.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var router_1 = require("@angular/router"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); var pager_index_1 = require("../../Shared/pager.index"); var http_1 = require("@angular/http"); var AddRFQComponent = (function () { function AddRFQComponent(fb, _RFQService, router, pagerService, http) { this.fb = fb; this._RFQService = _RFQService; this.router = router; this.pagerService = pagerService; this.http = http; this.MultiTechnology = []; this.Technology = []; this.Employee = []; this.RFQDocList = []; this.RFQDocEntityList = []; this.RFQLinkList = []; this.RFQLinkEntityList = []; this.fileListForAPI = []; this.indLoading = false; this.CurrentRecordsPerPage = 10; this.pager = {}; this.MultiTechnology.id = null; this.MultiTechnology.name = null; this.i = 0; } AddRFQComponent.prototype.fileChangeDoc = function (event) { this.fileList = event.target.files; this.fileListForAPI[this.i] = this.fileList; this.i = this.i + 1; }; AddRFQComponent.prototype.addClient = function () { debugger; this.modal.open(); this.ProspectHelper = false; }; AddRFQComponent.prototype.ngOnInit = function () { this.CPFrm = this.fb.group({ Id: [''], CompanyName: [''], Country: [''], FilterRadioButton: [''] }); this.RFQs = ({ Id: 0, BusinessHeadId: 0, BusinessManagerId: 0, Employee_Name: '', BusinessTypeId: 0, BusinessType: '', ProjectTypeId: 0, ProjectType: '', IndustryId: 0, Industries: '', SolutionId: 0, Solution: '', ServiceOfferingId: 0, ServiceOffering: '', TechnologyIdList: 0, TechnologyId: 0, TechnologyName: '', Remark: '', ResponseRequiredBy: null, SupportedBy: '', ConfidenceLevel: 0, OpportunityStatus: '', StatusId: 0, RFQStatus: '', ExpectedClosureDate: null, Source: '', Title: '', ProspectClient: '', DateOfInitiation: null, UserIdList: 0, UserId: 0, ResponseRequiredFrom: 0, CreatedOn: null, CreatedBy: 0, UpdatedBy: 0, UpdatedDate: null, }); this.RFQDoc = ({ FileTypeID: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQDocEntity = ({ FileTypeId: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQLink = ({ RemarkLink: '', UserId: 0, Password: '', URL: '' }); this.forSessionData = ({ SessionId: 0 }); this.prospectClient = ({ Id: 0, CompanyName: "", Country: "", FilterRadioButton: "" }); this.sessionValues = ({ UserType: "", UserId: 0 }); this.GetEmployee(); this.GetTechnology(); this.LoadFillBusinessHead(); this.GetBusinessManager(); this.GetBusinessType(); this.GetProjectType(); this.GetIndustries(); this.GetSolution(); this.GetServiceOffering(); this.GetFileType(); this.GetAuthor(); this.GetRFQStatus(); this.GetProspectClient(); this.ProspectHelper = true; this.SourceVal = false; }; AddRFQComponent.prototype.LoadFillBusinessHead = function () { var _this = this; this.indLoading = true; this._RFQService.FillBusinessHead(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.BusinessHeadDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetBusinessManager = function () { var _this = this; var UserName = sessionStorage.getItem('VISUsername'); var UserType = sessionStorage.getItem('UserType'); this.indLoading = true; this._RFQService.GetBusinessManager(global_1.Global.BASE_RFQ_ENDPOINT, UserName) .subscribe(function (RFQs) { _this.BusinessManagerDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetBusinessType = function () { var _this = this; this.indLoading = true; this._RFQService.GetBusinessType(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.BusinessTypeDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetProjectType = function () { var _this = this; this.indLoading = true; this._RFQService.GetProjectType(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.ProjectTypeDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetIndustries = function () { var _this = this; this.indLoading = true; this._RFQService.GetIndustries(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.IndustriesDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetSolution = function () { var _this = this; this.indLoading = true; this._RFQService.GetSolution(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.SolutionDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetServiceOffering = function () { var _this = this; this.indLoading = true; this._RFQService.GetServiceOffering(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.ServiceOfferingDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetFileType = function () { var _this = this; this.indLoading = true; this._RFQService.GetFileType(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.FileTypeDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetAuthor = function () { var _this = this; this.indLoading = true; this._RFQService.GetAuthor(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.AuthorDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetRFQStatus = function () { var _this = this; this.indLoading = true; this._RFQService.GetRFQStatus(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.RFQStatusDDL = RFQs; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetTechnology = function () { var _this = this; this.indLoading = true; this._RFQService.GetTechnology(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (Technology) { _this.Technology = Technology; _this.myOptions = []; for (var _i = 0, _a = _this.Technology; _i < _a.length; _i++) { var item = _a[_i]; _this.myOptions.push({ id: item.TechnologyId, name: item.TechnologyName }); } _this.indLoading = false; }); }; AddRFQComponent.prototype.GetEmployee = function () { var _this = this; this.indLoading = true; this._RFQService.GetEmployee(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (Emp) { _this.Employee = Emp; debugger; _this.myOptionsEmp = []; for (var _i = 0, _a = _this.Employee; _i < _a.length; _i++) { var item = _a[_i]; _this.myOptionsEmp.push({ id: item.UserId, name: item.Employee_Name }); } debugger; _this.indLoading = false; }); }; AddRFQComponent.prototype.GetProspectClient = function () { var _this = this; this.sessionvar = sessionStorage.getItem('IsAdmin'); this.sessionValues.UserId = +sessionStorage.getItem('Id'); // + is used for casting string to number if (this.sessionvar == "true") { this.sessionValues.UserType = "admin"; } this.sessionValues.UserType = "admin"; this.prospectClient.FilterRadioButton = "Client"; var SuperProspectClient = { ProspectClient: this.prospectClient, SessionValues: this.sessionValues }; this._RFQService.GetProspectClient(global_1.Global.BASE_RFQ_ENDPOINT, SuperProspectClient).subscribe(function (data) { _this.prospectClientList = data; debugger; // initialize to page 1 _this.JumpOnPage(1); }, function (error) { _this.msg = error; }); }; AddRFQComponent.prototype.onRFQInitialSubmit = function (formData) { var _this = this; if (this.ProspectHelper == true) { this.forSessionData.SessionId = +sessionStorage.getItem('Id'); // + is used for casting string to number var MainRFQInitial = { SessionData: this.forSessionData, RFQInitial: formData, RFQDoc: this.RFQDocEntityList, RFQLink: this.RFQLinkEntityList // RFQDoc: this.RFQDocList, //RFQLink: this.RFQLinkList }; this._RFQService.post(global_1.Global.BASE_RFQ_ENDPOINT, MainRFQInitial).subscribe(function (data) { if (data.startsWith("Success:")) { _this.msg = data; if (_this.fileListForAPI.length > 0) { var k = 0; for (var _i = 0, _a = _this.fileListForAPI; _i < _a.length; _i++) { var fileToBeUpload = _a[_i]; var file = fileToBeUpload[0]; var formData_1 = new FormData(); formData_1.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/RFQAPI/UploadRFQDoc"; _this.http.post(apiUrl1, formData_1, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); file = null; formData_1 = null; headers = null; options = null; k = k + 1; } _this.fileListForAPI = null; } _this.router.navigate(['/MyRFQ']); } else { alert(data); } }, function (error) { _this.msg = error; }); } else { this.ProspectHelper = true; } }; AddRFQComponent.prototype.onDocSubmit = function (formDocData) { if (this.fileList != null) { this.RFQDocEntity = formDocData; this.RFQDocEntity.FileName = this.fileList.item(0).name; this.RFQDocEntityList.push(this.RFQDocEntity); this.clearDoc(); } else { alert('please select Any document file'); } }; AddRFQComponent.prototype.deleteRFQDoc = function (FileName) { var elementPos = this.RFQDocList.map(function (x) { return x.FileName; }).indexOf(FileName); this.RFQDocEntityList.splice(elementPos, 1); }; AddRFQComponent.prototype.onLinkSubmit = function (formLinkData) { this.RFQLinkEntity = formLinkData; this.RFQLinkEntityList.push(this.RFQLinkEntity); this.clearLink(); }; AddRFQComponent.prototype.deleteRFQLink = function (UserId) { var elementPos = this.RFQLinkList.map(function (x) { return x.UserId; }).indexOf(UserId); this.RFQLinkEntityList.splice(elementPos, 1); }; AddRFQComponent.prototype.clearDoc = function () { this.RFQDoc.Author = ""; this.RFQDoc.AuthorId = 0; this.RFQDoc.FileName = ""; this.RFQDoc.FileType = ""; this.RFQDoc.RemarkDoc = ""; }; AddRFQComponent.prototype.clearLink = function () { this.RFQLink.Password = ""; this.RFQLink.RemarkLink = ""; this.RFQLink.URL = ""; this.RFQLink.UserId = 0; }; AddRFQComponent.prototype.ProspectClientFilterCriteriaChange = function (value) { if (value != '[object Event]') this.ProspectClientFilter = value; }; AddRFQComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.prospectClientList); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; AddRFQComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; AddRFQComponent.prototype.addClientInForm = function (Id, CompanyName, Country) { this.RFQs.ProspectClient = CompanyName; this.SourceVal = true; this.modal.dismiss(); }; AddRFQComponent.prototype.ClearClient = function () { this.RFQs.ProspectClient = ""; this.ProspectHelper = false; this.SourceVal = false; }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AddRFQComponent.prototype, "modal", void 0); AddRFQComponent = __decorate([ core_1.Component({ providers: [RFQ_service_1.RFQService], templateUrl: 'app/Components/RFQ/AddRFQ.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, RFQ_service_1.RFQService, router_1.Router, pager_index_1.PagerService, http_1.Http]) ], AddRFQComponent); return AddRFQComponent; }()); exports.AddRFQComponent = AddRFQComponent; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { WorkSheetService } from '../../../Service/HumanResource/Attendance/WorkSheet.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IWorkSheet } from '../../../Model/HumanResource/Attendance/WorkSheet'; import { IProject } from '../../../Model/HumanResource/Attendance/WorkSheet'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; import { Ng2TabModule } from 'ng2-tab'; @Component({ providers: [WorkSheetService], templateUrl: 'app/Components/HumanResource/Attendance/WorkSheet.component.html' }) export class WorkSheetComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; WorkSheets: IWorkSheet[]; WorkSheet: IWorkSheet; Date: IWorkSheet[]; DefaulConfigure: IWorkSheet[]; ProjectList: IProject[]; ChildDropDown: IProject[]; ViewEducation: IWorkSheet[]; msg: string; indLoading: boolean = false; WorkSheetFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; isDesc: boolean = false; direction: number; CurrentRecordsPerPage: number = 10; tempUserId : number = 158; tempDate: string = '20150525'; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //other declartion objValue1: string; objValue2: string; objValue3: string; objValue4: string; toStr = JSON.stringify; constructor(private fb: FormBuilder, private _WorkSheetService: WorkSheetService, public http: Http, private router: Router, private pagerService: PagerService) { } ngOnInit(): void { debugger; this.WorkSheetFrm = this.fb.group({ ActivityId: [''], ActivityName: [''], SubActivityId: [''], SubActivityName: [''], Date: [''], UserId: [''], ProjectID: [''], ProjectName: [''], TaskId: [''], Description: [''], Hours: [''], FillDate: [''], WorkSheetID: [''], }); //this.WorkSheet = // ({ // ActivityId:0, // ActivityName: '', // SubActivityId:0, // SubActivityName: '', // Date: '', // UserId: 0, // ProjectID:0, // ProjectName: '', // TaskId: 0, // Description: '', // Hours: '', // FillDate: '', // WorkSheetID: 0, // TaskName:'' // }); this.LoadDeafultConfigure(); this.LoadDate(); this.LoadProjectList(this.tempUserId, this.tempDate); } OpenSave() { this.SetControlsState(true); this.modalTitle = "Task List For Date ()"; this.modalBtnTitle = "Save"; this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.WorkSheetFrm.enable() : this.WorkSheetFrm.disable(); } GetDate(event) { debugger; this.objValue1 = event.target.Date; } ToogleMyProfile() { $("#myprofiledata").slideToggle(300); } CloseWidgetProfile() { $("#adminProfile").hide(300); } createRange(number) { var items: number[] = []; for (var i = 1; i <= number; i++) { items.push(i); } return items; } LoadDeafultConfigure() { this.indLoading = true; this._WorkSheetService.GetDropDownList(Global.BASE_WorkSheet_ENDPOINT) .subscribe(data => { this.DefaulConfigure = data this.indLoading = false; } ); } LoadProjectList(UserId: number, Date: string): void { debugger; this.indLoading = true; this._WorkSheetService.GetProjectList(Global.BASE_WorkSheet_ENDPOINT, UserId, Date) .subscribe(data => { this.ProjectList = data console.log(data); this.indLoading = false; } ); } LoadChildTaskDroDown(event, UserId: number, Date: string): void { debugger; if (event == 0) { $("#taskid").prop("disabled", true); } else { $("#taskid").prop("disabled", false); } this.indLoading = true; this._WorkSheetService.GetChildTaskDropdown(Global.BASE_WorkSheet_ENDPOINT, event.target.value, this.tempUserId, this.tempDate) .subscribe(data => { this.ChildDropDown = data this.indLoading = false; } ); } LoadDate() { debugger; this.indLoading = true; this._WorkSheetService.GetDate(Global.BASE_WorkSheet_ENDPOINT) .subscribe(data => { this.Date = data this.indLoading = false; this.printValues() } ); } printValues(): void { console.log('objValue1', this.Date[0]); console.log('objValue2', this.Date[1]); console.log('objValue3', this.Date[2]); console.log('objValue4', this.Date[3]); } onSubmit(formData: any) { debugger; console.log(formData); this._WorkSheetService.Savepost(Global.BASE_WorkSheet_ENDPOINT, formData._value).subscribe( data => { if (data == "Success") { this.msg = "Worksheet Save successfully."; } else { this.msg = "Worksheet has occurred while modifying existing Ticket Configuration!" } }, error => { this.msg = error; } ); //this._WorkSheetService.Savepost(Global.BASE_WorkSheet_ENDPOINT, formData._value).subscribe( // data => { // if (data == "Success") { // this.msg = "Worksheet Save successfully."; // } // else { // this.msg = "Worksheet has occurred while modifying existing Ticket Configuration!" // } // }, // error => { // this.msg = error; // } //); // this.No++; ///} } }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { ICalTotalAttendance } from '../../../Model/Report/Attendance/AttendanceReport'; @Pipe ({ name:'AttendanceReportFilter' }) export class AttendanceReportFilterPipe implements PipeTransform { transform(value: ICalTotalAttendance[], filter: string): ICalTotalAttendance[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: ICalTotalAttendance) => app.Employee_Name != null && app.Employee_Name.toLocaleLowerCase().indexOf(filter) != -1 || app.Date != null && app.Date.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Repository { public interface VISIBaseRepository<T> : IDisposable { Int32 intAffectedRecords { get; set; } IEnumerable<T> GetEntityList(); T GetEntityByID(Int64 entityId); string AddEntity(T entityObject); string DeleteEntity(Int64 Id); string UpdateEntity(T entityObject); } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IPosition } from '../../../Model/Masters/VacancyRelated/Position'; @Pipe ({ name: 'positionFilter' }) export class PositionFilterPipe implements PipeTransform { transform(value: IPosition[], filter: string): IPosition[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IPosition) => app.PositionName != null && app.PositionName.toLocaleLowerCase().indexOf(filter) != -1 || app.Remarks != null && app.Remarks.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Repository; using VIS_Domain.Dashboard; using VIS_Repository.Dashboard; using System.Configuration; namespace VIS_App.Controllers.Dashboard { public class DashboardAPIController : BaseAPIController { DashboardRepository objDashboardRepository = null; List<MyProfile> EntityList = new List<MyProfile>(); public DashboardAPIController() { } [HttpGet] //public HttpResponseMessage GetDashboardDataSets(int UserId, bool IsApproved, string FromDate, string ToDate, bool IsLineManager, DateTime date, int PunchInId) public HttpResponseMessage GetDashboardDataSets(int UserId, bool IsApproved, string FromDate, string ToDate, bool IsLineManager, DateTime date, int PunchInId, bool IsAdmin) { objDashboardRepository = new DashboardRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); return ToJson(objDashboardRepository.GetDashboardDataSets(UserId, IsApproved, FromDate, ToDate, IsLineManager, date, PunchInId, IsAdmin)); //return ToJson(objDashboardRepository.procGetDashboardDataSets(UserId, IsApproved, FromDate, ToDate, IsLineManager, date, PunchInId)); } //[HttpGet] //public HttpResponseMessage GetProfileInformationForUser(int UserId) //{ // objDashboardRepository = new DashboardRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); // return ToJson(objDashboardRepository.GetProfileInformationForUser(UserId)); //} [HttpGet] [Route("api/DashboardAPI/GetMyAttendance")] public HttpResponseMessage GetMyAttendance(int Id,string Date) { objDashboardRepository = new DashboardRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); return ToJson(objDashboardRepository.GetAttendanceDetail(Id,Date)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class ConfigureWorksheet : VISBaseEntity { /// <summary> /// ConfigureWorksheet Entity Fields. /// </summary> /// public int Fromm { get; set; } public int Too { get; set; } public string HexadecimalValue { get; set; } public string SrNo { get; set; } } public static class ConfigureWorksheetConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_ConfigureWorksheet_Table = "ConfigureWorksheet"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Fromm = "Fromm"; public const string const_Too = "Too"; public const string const_HexadecimalValue = "HexadecimalValue"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procConfigureWorksheet_Add = "procConfigureWorksheet_Add"; public const string const_procConfigureWorksheet_Update = "procConfigureWorksheet_Update"; public const string const_procConfigureWorksheet_ActiveInActive = "procConfigureWorksheet_ActiveInActive"; public const string const_procConfigureWorksheet_SelectAll = "procConfigureWorksheet_SelectAll"; public const string const_procConfigureWorksheet_SelectById = "procConfigureWorksheet_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Reports.Attendance; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Globalization; using VIS_Domain; namespace VIS_Repository.Reports.Attendance { public class Reports_AttendanceRepository : VISDbCommand /*, VISIBaseRepository<AttendanceReport>*/ { public Int32 intAffectedRecords { get; set; } public Int32 PunchInId { get; set; } public Boolean halfLeave { get; set; } public Boolean checkHrs { get; set; } public string approveType { get; set; } public string leaveType { get; set; } public Boolean TwoHalfLeaveSameDay { get; set; } public string mode { get; set; } public string strusertype { get; set; } public string struserId { get; set; } public int Longleavedays { get; set; } public int YearData { get; set; } public int monthData { get; set; } public int day { get; set; } DataTable dt; public string checkedvalueRDB { get; set; } public string checkedvalueDRP { get; set; } DataTable dtdepartemp = new DataTable(); DataTable dpemp = new DataTable(); DataRow dr; public string strUserType { get; set; } int EmployeeId; string FromDate; string EndDate; string DrpemName; int DropdownvalDECL; string RdbDateval; string Rdbmonthval; int mon; int y; IFormatProvider provider = new System.Globalization.CultureInfo("es-ES", true); private static Reports_AttendanceRepository instance = new Reports_AttendanceRepository(string.Empty); public Reports_AttendanceRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_AttendanceRepository getInstance() { return instance; } public DataTable GetLeaveDetailsByDate(int UserID, string strDate) { DataTable dt = new DataTable(); dt.Columns.Add("leaveDuration", Type.GetType("System.String")); dt.Columns.Add("leaveType", Type.GetType("System.String")); dt.Columns.Add("approveType", Type.GetType("System.String")); dt.Columns.Add("shortLeaveType", Type.GetType("System.String")); VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); //VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, UserID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, strDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetLeaveDetailsByDate"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sdaLeavedetailsbydate = new SqlDataAdapter(); DataSet dsleavedetailsbydate = new DataSet(); sdaLeavedetailsbydate.SelectCommand = objVISDbCommand.objSqlCommand; dt.Clear(); sdaLeavedetailsbydate.Fill(dsleavedetailsbydate); objVISDbCommand.objSqlCommand.Connection.Close(); if (dsleavedetailsbydate != null && dsleavedetailsbydate.Tables[0].Rows.Count > 0) { DataRow dr = dt.NewRow(); int CalendarDays = Convert.ToInt32(dsleavedetailsbydate.Tables[0].Rows[0]["CalendarDays"].ToString()); dr["shortLeaveType"] = dsleavedetailsbydate.Tables[0].Rows[0]["LeaveStatus"].ToString(); if (CalendarDays == 0) { if (Convert.ToBoolean(dsleavedetailsbydate.Tables[0].Rows[0]["IsFullDay"])) { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } else if (Convert.ToBoolean(dsleavedetailsbydate.Tables[0].Rows[0]["IsFirstHalf"])) { dr["leaveDuration"] = "FirstHalf"; dr["leaveType"] = "FH"; } else if (Convert.ToBoolean(dsleavedetailsbydate.Tables[0].Rows[0]["IsSecondHalf"])) { dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SH"; } } else { DateTime dtFrom = Convert.ToDateTime(dsleavedetailsbydate.Tables[0].Rows[0]["FromDate"].ToString()); DateTime dtTo = Convert.ToDateTime(dsleavedetailsbydate.Tables[0].Rows[0]["ToDate"].ToString()); DateTime dtCurr = DateTime.ParseExact(strDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); if (dtCurr == dtFrom) { if (Convert.ToBoolean(dsleavedetailsbydate.Tables[0].Rows[0]["IsFullDay"])) { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } else if (Convert.ToBoolean(dsleavedetailsbydate.Tables[0].Rows[0]["IsSecondHalf"])) { dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SH"; } } else if (dtCurr == dtTo) { if (Convert.ToBoolean(dsleavedetailsbydate.Tables[0].Rows[0]["IsFullDay"])) { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } else if (Convert.ToBoolean(dsleavedetailsbydate.Tables[0].Rows[0]["IsFirstHalf"])) { dr["leaveDuration"] = "FirstHalf"; dr["leaveType"] = "FH"; } } else { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } } dr["approveType"] = dr["shortLeaveType"].ToString() + "/" + dr["leaveType"].ToString(); if (dr["shortLeaveType"].ToString() == "Present") { return null; } else { dt.Rows.Add(dr); return dt; } } else { return null; } } private void generateTable() { dt = new DataTable(); dt.Columns.Add("EmployeeCode", Type.GetType("System.String")); //new field dt.Columns.Add("Employee_Name", Type.GetType("System.String")); dt.Columns.Add("Date", Type.GetType("System.String")); dt.Columns.Add("MMDDYYYY_DateFormat", Type.GetType("System.String")); dt.Columns.Add("Employee_Id", Type.GetType("System.String")); dt.Columns.Add("In_Time", Type.GetType("System.String")); dt.Columns.Add("Out_Time", Type.GetType("System.String")); dt.Columns.Add("LunchOut_Time", Type.GetType("System.String")); dt.Columns.Add("LunchIn_Time", Type.GetType("System.String")); dt.Columns.Add("Other_Time", Type.GetType("System.String")); dt.Columns.Add("Total-Out", Type.GetType("System.String")); // shifted dt.Columns.Add("Total_W_Hr", Type.GetType("System.String")); // altered old is - Total_Hr dt.Columns.Add("Total_Hrs", Type.GetType("System.String")); // new added dt.Columns.Add("TotalWorksheet_Hr", Type.GetType("System.String")); dt.Columns.Add("diff", Type.GetType("System.String")); dt.Columns.Add("status", Type.GetType("System.String")); dt.Columns.Add("Days", Type.GetType("System.String")); dt.Columns.Add("ImportRemarks", Type.GetType("System.String")); dt.Columns.Add("HoverImportRemarks", Type.GetType("System.String")); //new field dt.Columns.Add("WNE", Type.GetType("System.String")); dt.Columns.Add("PC", Type.GetType("System.String")); dt.Columns.Add("AUPL", Type.GetType("System.String")); dt.Columns.Add("UUPL", Type.GetType("System.String")); dt.Columns.Add("cl-h", Type.GetType("System.String")); dt.Columns.Add("cl-f", Type.GetType("System.String")); dt.Columns.Add("sl-h", Type.GetType("System.String")); dt.Columns.Add("sl-f", Type.GetType("System.String")); dt.Columns.Add("InId", Type.GetType("System.String")); dt.Columns.Add("OutId", Type.GetType("System.String")); dt.Columns.Add("LunchOutId", Type.GetType("System.String")); dt.Columns.Add("LunchInId", Type.GetType("System.String")); dt.Columns.Add("OtherId", Type.GetType("System.String")); dt.Columns.Add("TotalId", Type.GetType("System.String")); //Add EXT Field dt.Columns.Add("ActualEntryTime", Type.GetType("System.String")); dt.Columns.Add("Grace", Type.GetType("System.String")); } public DataTable GetBindAttendanceData(int EmployeeID, string strDate, string ToDate, string name, int DRPData, string rdbDate, string Rdbmonth, int month, int year) { EmployeeId = EmployeeID; FromDate = strDate; EndDate = ToDate; DrpemName = name; DropdownvalDECL = DRPData; RdbDateval = rdbDate; Rdbmonthval = Rdbmonth; mon = month; y = year; try { generateTable(); DateTime startDate = new DateTime(2010, 01, 01); DateTime endDate = new DateTime(2010, 01, 31); DataSet ds = new DataSet(); if (Rdbmonth == "Month") { monthData = month; YearData = year; day = 1; startDate = new DateTime(YearData, monthData, day); if (YearData == System.DateTime.Now.Year) { if (monthData == System.DateTime.Now.Month) { endDate = new DateTime(YearData, monthData, System.DateTime.Now.Day); TimeSpan ts = endDate - startDate; day = ts.Days; } else { day = DateTime.DaysInMonth(YearData, monthData); endDate = new DateTime(YearData, monthData, day); } } else { day = DateTime.DaysInMonth(YearData, monthData); endDate = new DateTime(YearData, monthData, day); } } if (rdbDate == "checkedDate") { if (strDate != "") { startDate = DateTime.Parse(strDate.ToString(), provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault); } else { startDate = DateTime.Parse(System.DateTime.Now.ToString("dd/MM/yyyy"), provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault); } if (strDate != "") { endDate = DateTime.Parse(ToDate.ToString(), provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault); } else { endDate = startDate; } } if (name == "LineManager") { if (DRPData > 0) { VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetLMemp"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = objVISDbCommand.objSqlCommand; ds.Clear(); da.Fill(ds); objVISDbCommand.objSqlCommand.Connection.Close(); } } TimeSpan tsDays = endDate - startDate; int totalDays = tsDays.Days + 1; DateTime TempStartDate = startDate; DataTable dtLeaveTemp; DataTable dtNWD = new DataTable(); DataSet dsLeave = new DataSet(); DataSet dsTripLeave = new DataSet(); if (name == "LineManager" && DRPData > 0) { for (int k = 0; k < ds.Tables[0].Rows.Count; k++) { startDate = TempStartDate; for (int i = 0; i < totalDays; i++) { //string stDate = startDate.ToString("dd/MM/yyyy"); //string[] arrDate = strDate.Split('/'); VISDbCommand objVISbCommand_1 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISbCommand_1.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISbCommand_1.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISbCommand_1.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, EmployeeID); objVISbCommand_1.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISbCommand_1.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "NWDHISTORY"); objVISbCommand_1.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISbCommand_1.objSqlCommand.Connection.Open(); SqlDataAdapter sdanwd = new SqlDataAdapter(); sdanwd.SelectCommand = objVISbCommand_1.objSqlCommand; dtNWD.Clear(); sdanwd.Fill(dtNWD); objVISbCommand_1.objSqlCommand.Connection.Close(); if (dtNWD.Rows.Count > 0) { VISDbCommand objVISDbCommand_2 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_2.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_2.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_2.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ds.Tables[0].Rows[k]["Id"].ToString()); objVISDbCommand_2.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, startDate.ToString("yyyyMMdd")); objVISDbCommand_2.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LongLeave, Convert.ToInt32(ConfigurationManager.AppSettings["LongLeave"])); objVISDbCommand_2.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LongLeave"); objVISDbCommand_2.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_2.objSqlCommand.Connection.Open(); SqlDataAdapter sdleave = new SqlDataAdapter(); sdleave.SelectCommand = objVISDbCommand_2.objSqlCommand; dsLeave.Clear(); sdleave.Fill(dsLeave); objVISDbCommand_2.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); dtLeaveTemp = GetLeaveDetailsByDate(Convert.ToInt32(ds.Tables[0].Rows[k]["id"].ToString()), startDate.ToString("dd/MM/yyyy")); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["Id"].ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } } else { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } } else { VISDbCommand objVISDbCommand_3 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_3.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_3.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_3.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ds.Tables[0].Rows[k]["Id"].ToString()); objVISDbCommand_3.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, startDate.ToString("yyyyMMdd")); objVISDbCommand_3.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "TripLeaveDetails"); objVISDbCommand_3.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_3.objSqlCommand.Connection.Open(); SqlDataAdapter sdaTripLeave = new SqlDataAdapter(); sdaTripLeave.SelectCommand = objVISDbCommand_3.objSqlCommand; dsTripLeave.Clear(); sdaTripLeave.Fill(dsTripLeave); objVISDbCommand_3.objSqlCommand.Connection.Close(); if (dsTripLeave != null && dsTripLeave.Tables.Count > 0 && dsTripLeave.Tables[0].Rows.Count > 0) { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), false, "", "On Trip/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", "On Trip/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } } else { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), false, "", "NWD/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", "NWD/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } } } } else { VISDbCommand objVISDbCommand_4 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_4.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_4.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_4.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ds.Tables[0].Rows[0]["Id"].ToString()); objVISDbCommand_4.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LeaveChecking"); objVISDbCommand_4.objSqlCommand.Parameters.AddWithValue("LeaveDate", startDate.ToString("yyyyMMdd")); objVISDbCommand_4.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_4.objSqlCommand.Connection.Open(); SqlDataAdapter sdaleavecheck = new SqlDataAdapter(); sdaleavecheck.SelectCommand = objVISDbCommand_4.objSqlCommand; dsLeave.Clear(); sdaleavecheck.Fill(dsLeave); objVISDbCommand_4.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); dtLeaveTemp = GetLeaveDetailsByDate(Convert.ToInt32(ds.Tables[0].Rows[k]["id"].ToString()), startDate.ToString("yyyyMMdd")); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } } else { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } } else { VISDbCommand objVISDbCommand_5 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_5.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_5.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_5.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_5.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Holidayfromdatetodate"); objVISDbCommand_5.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_5.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_5.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholiday = new SqlDataAdapter(); sdaholiday.SelectCommand = objVISDbCommand_5.objSqlCommand; DataSet dsHoliday = new DataSet(); dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_5.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } } else { VISDbCommand objVISDbCommand_6 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_6.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_6.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_6.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_6.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "HolidayFromDate"); objVISDbCommand_6.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_6.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_6.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholidayfdate = new SqlDataAdapter(); sdaholidayfdate.SelectCommand = objVISDbCommand_6.objSqlCommand; dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_6.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } } else { if (name == "LineManager") { fillRecord(startDate.ToString("dd/MM/yyyy"), ds.Tables[0].Rows[k]["id"].ToString(), false, "", "", true, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", "", true, false); } } } } } startDate = startDate.AddDays(1); } } } else if (DRPData == 0) { if (EmployeeID == 0) { if (name == "DepartMent") { dpemp = GetDepartmentEmployee(EmployeeID); } else if (name == "Employee" | name == "Company") // employee dropdown record. { dpemp = GetEmployee(); } } if (rdbDate == "checkedDate") { for (int i = 0; i < totalDays; i++) { for (int j = 0; j < dpemp.Rows.Count; j++) { string stDate = startDate.ToString("dd/MM/yyyy"); //string[] arrDate = strDate.Split('/'); VISDbCommand objVISDbCommand_7 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_7.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_7.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_7.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, dpemp.Rows[j]["Id"].ToString()); objVISDbCommand_7.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_7.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "NWDHISTORY"); objVISDbCommand_7.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_7.objSqlCommand.Connection.Open(); SqlDataAdapter sdanwd = new SqlDataAdapter(); sdanwd.SelectCommand = objVISDbCommand_7.objSqlCommand; dtNWD.Clear(); sdanwd.Fill(dtNWD); objVISDbCommand_7.objSqlCommand.Connection.Close(); if (dtNWD.Rows.Count > 0) { VISDbCommand objVISDbCommand_8 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_8.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_8.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_8.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, dpemp.Rows[j]["Id"].ToString()); objVISDbCommand_8.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, startDate.ToString("yyyyMMdd")); objVISDbCommand_8.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LongLeave, Convert.ToInt32(ConfigurationManager.AppSettings["LongLeave"])); objVISDbCommand_8.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LongLeave"); objVISDbCommand_8.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_8.objSqlCommand.Connection.Open(); SqlDataAdapter sdleave = new SqlDataAdapter(); sdleave.SelectCommand = objVISDbCommand_8.objSqlCommand; dsLeave.Clear(); sdleave.Fill(dsLeave); objVISDbCommand_8.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); dtLeaveTemp = GetLeaveDetailsByDate(Convert.ToInt32(dpemp.Rows[j]["Id"]), startDate.ToString("yyyyMMdd")); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } else { VISDbCommand objVISDbCommand_9 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_9.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_9.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_9.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, dpemp.Rows[j]["Id"]); objVISDbCommand_9.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, startDate.ToString("yyyyMMdd")); objVISDbCommand_9.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "TripLeaveDetails"); objVISDbCommand_9.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_9.objSqlCommand.Connection.Open(); SqlDataAdapter sdaTripLeave = new SqlDataAdapter(); sdaTripLeave.SelectCommand = objVISDbCommand_9.objSqlCommand; dsTripLeave.Clear(); sdaTripLeave.Fill(dsTripLeave); objVISDbCommand_9.objSqlCommand.Connection.Close(); if (dsTripLeave != null && dsTripLeave.Tables.Count > 0 && dsTripLeave.Tables[0].Rows.Count > 0) { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", "On Trip/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", "NWD/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } } } else { VISDbCommand objVISDbCommand_10 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_10.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_10.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_10.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, dpemp.Rows[j]["Id"]); objVISDbCommand_10.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LeaveChecking"); objVISDbCommand_10.objSqlCommand.Parameters.AddWithValue("LeaveDate", startDate.ToString("yyyyMMdd")); objVISDbCommand_10.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_10.objSqlCommand.Connection.Open(); SqlDataAdapter sdaleavecheck = new SqlDataAdapter(); sdaleavecheck.SelectCommand = objVISDbCommand_10.objSqlCommand; dsLeave.Clear(); sdaleavecheck.Fill(dsLeave); objVISDbCommand_10.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); string strdate = startDate.ToString("yyyyMMdd"); dtLeaveTemp = GetLeaveDetailsByDate(Convert.ToInt32(dpemp.Rows[j]["Id"]), strdate); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } else { //Holidayfromdatetodate. VISDbCommand objVISDbCommand_11 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_11.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_11.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_11.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_11.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Holidayfromdatetodate"); objVISDbCommand_11.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_11.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_11.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholiday = new SqlDataAdapter(); sdaholiday.SelectCommand = objVISDbCommand_11.objSqlCommand; DataSet dsHoliday = new DataSet(); dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_11.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { //HolidayFromDate VISDbCommand objVISDbCommand_12 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_12.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_12.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_12.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_12.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "HolidayFromDate"); objVISDbCommand_12.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_12.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_12.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholidayfdate = new SqlDataAdapter(); sdaholidayfdate.SelectCommand = objVISDbCommand_12.objSqlCommand; dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_12.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", "", true, false); } } } } } startDate = startDate.AddDays(1); } } else { DateTime dtTemp; for (int j = 0; j < dpemp.Rows.Count; j++) // checked back { dtTemp = startDate; for (int i = 0; i < totalDays; i++) { VISDbCommand objVISDbCommand_13 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_13.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_13.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_13.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand_13.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, dtTemp.ToString("yyyyMMdd")); objVISDbCommand_13.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "NWDHISTORY"); objVISDbCommand_13.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_13.objSqlCommand.Connection.Open(); SqlDataAdapter sdanwd = new SqlDataAdapter(); sdanwd.SelectCommand = objVISDbCommand_13.objSqlCommand; dtNWD.Clear(); sdanwd.Fill(dtNWD); objVISDbCommand_13.objSqlCommand.Connection.Close(); if (dtNWD.Rows.Count > 0) { VISDbCommand objVISDbCommand_14 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_14.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_14.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_14.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand_14.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, dtTemp.ToString("yyyyMMdd")); objVISDbCommand_14.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LongLeave, Convert.ToInt32(ConfigurationManager.AppSettings["LongLeave"])); objVISDbCommand_14.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LongLeave"); objVISDbCommand_14.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_14.objSqlCommand.Connection.Open(); SqlDataAdapter sdleave = new SqlDataAdapter(); sdleave.SelectCommand = objVISDbCommand_14.objSqlCommand; dsLeave.Clear(); sdleave.Fill(dsLeave); objVISDbCommand_14.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); dtLeaveTemp = GetLeaveDetailsByDate(Convert.ToInt32(dpemp.Rows[j]["Id"]), dtTemp.ToString("yyyyMMdd")); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } else { VISDbCommand objVISDbCommand_15 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_15.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_15.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_15.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand_15.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, dtTemp.ToString("yyyyMMdd")); objVISDbCommand_15.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "TripLeaveDetails"); objVISDbCommand_15.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_15.objSqlCommand.Connection.Open(); SqlDataAdapter sdaTripLeave = new SqlDataAdapter(); sdaTripLeave.SelectCommand = objVISDbCommand_15.objSqlCommand; dsTripLeave.Clear(); sdaTripLeave.Fill(dsTripLeave); objVISDbCommand_15.objSqlCommand.Connection.Close(); if (dsTripLeave != null && dsTripLeave.Tables.Count > 0 && dsTripLeave.Tables[0].Rows.Count > 0) { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", "On Trip/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } else { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", "NWD/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } } } else { VISDbCommand objVISDbCommand_16 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_16.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_16.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_16.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData);//checked back objVISDbCommand_16.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LeaveChecking"); objVISDbCommand_16.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, dtTemp.ToString("yyyyMMdd")); objVISDbCommand_16.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_16.objSqlCommand.Connection.Open(); SqlDataAdapter sdaleavecheck = new SqlDataAdapter(); sdaleavecheck.SelectCommand = objVISDbCommand_16.objSqlCommand; dsLeave.Clear(); sdaleavecheck.Fill(dsLeave); objVISDbCommand_16.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } } else { if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); dtLeaveTemp = GetLeaveDetailsByDate(Convert.ToInt32(dpemp.Rows[j]["Id"]), dtTemp.ToString("yyyyMMdd")); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } else { VISDbCommand objVISDbCommand_17 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_17.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_17.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_17.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_17.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Holidayfromdatetodate"); objVISDbCommand_17.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, dtTemp.ToString("yyyyMMdd")); objVISDbCommand_17.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_17.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholiday = new SqlDataAdapter(); sdaholiday.SelectCommand = objVISDbCommand_17.objSqlCommand; DataSet dsHoliday = new DataSet(); dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_17.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { VISDbCommand objVISDbCommand_18 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_18.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_18.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_18.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_18.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "HolidayFromDate"); objVISDbCommand_18.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, dtTemp.ToString("yyyyMMdd")); objVISDbCommand_18.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_18.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholidayfdate = new SqlDataAdapter(); sdaholidayfdate.SelectCommand = objVISDbCommand_18.objSqlCommand; dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_18.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { fillRecord(dtTemp.ToString("dd/MM/yyyy"), dpemp.Rows[j]["Id"].ToString(), false, "", "", true, false); } } } } } dtTemp = dtTemp.AddDays(1); } dtTemp = startDate; } } } else { for (int i = 0; i < totalDays; i++) { string stDate = startDate.ToString("dd/MM/yyyy"); //string[] arrDate = strDate.Split('/'); VISDbCommand objVISDbCommand_19 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_19.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_19.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_19.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand_19.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_19.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "NWDHISTORY"); objVISDbCommand_19.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_19.objSqlCommand.Connection.Open(); SqlDataAdapter sdanwd = new SqlDataAdapter(); sdanwd.SelectCommand = objVISDbCommand_19.objSqlCommand; dtNWD.Clear(); sdanwd.Fill(dtNWD); objVISDbCommand_19.objSqlCommand.Connection.Close(); if (dtNWD.Rows.Count > 0) { VISDbCommand objVISDbCommand_20 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_20.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_20.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_20.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand_20.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, startDate.ToString("yyyyMMdd")); objVISDbCommand_20.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LongLeave, Convert.ToInt32(ConfigurationManager.AppSettings["LongLeave"])); objVISDbCommand_20.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LongLeave"); objVISDbCommand_20.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_20.objSqlCommand.Connection.Open(); SqlDataAdapter sdleave = new SqlDataAdapter(); sdleave.SelectCommand = objVISDbCommand_20.objSqlCommand; dsLeave.Clear(); sdleave.Fill(dsLeave); objVISDbCommand_20.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); dtLeaveTemp = GetLeaveDetailsByDate(Convert.ToInt32(DRPData), startDate.ToString("yyyyMMdd")); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } else { VISDbCommand objVISDbCommand_21 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_21.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_21.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_21.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand_21.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LeaveDate, startDate.ToString("yyyyMMdd")); objVISDbCommand_21.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "TripLeaveDetails"); objVISDbCommand_21.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_21.objSqlCommand.Connection.Open(); SqlDataAdapter sdaTripLeave = new SqlDataAdapter(); sdaTripLeave.SelectCommand = objVISDbCommand_21.objSqlCommand; dsTripLeave.Clear(); sdaTripLeave.Fill(dsTripLeave); objVISDbCommand_21.objSqlCommand.Connection.Close(); if (dsTripLeave != null && dsTripLeave.Tables.Count > 0 && dsTripLeave.Tables[0].Rows.Count > 0) { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", "On Trip/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", "NWD/" + dtNWD.Rows[0]["leaveType"].ToString(), false, false); } } } else { VISDbCommand objVISDbCommand_22 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_22.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_22.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_22.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "LeaveChecking"); objVISDbCommand_22.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, DRPData); objVISDbCommand_22.objSqlCommand.Parameters.AddWithValue("LeaveDate", startDate.ToString("yyyyMMdd")); objVISDbCommand_22.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_22.objSqlCommand.Connection.Open(); SqlDataAdapter sdaleavecheck = new SqlDataAdapter(); sdaleavecheck.SelectCommand = objVISDbCommand_22.objSqlCommand; dsLeave.Clear(); sdaleavecheck.Fill(dsLeave); objVISDbCommand_22.objSqlCommand.Connection.Close(); if (dsLeave != null && dsLeave.Tables[0].Rows.Count > 0) { double leaveBalance = Convert.ToDouble(dsLeave.Tables[0].Rows[0]["Balance"].ToString()); string leaveDuration = dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString(); string AppliedLeaveType = dsLeave.Tables[0].Rows[0]["AppliedLeaveType"].ToString(); if (leaveBalance == -0.5 && leaveDuration == "Full") { dsLeave.Tables[0].Rows[0]["Balance"] = 0; dsLeave.Tables[0].Rows[0]["leaveDuration"] = "FirstHalf"; dsLeave.Tables[0].Rows[0]["leaveType"] = "FH"; dsLeave.Tables[0].Rows[0]["approveType"] = AppliedLeaveType + "/FH"; DataRow dr = dsLeave.Tables[0].NewRow(); dr["Balance"] = 0; dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SL"; dr["approveType"] = "AUPL/SH"; dr["AppliedLeaveType"] = AppliedLeaveType; dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { dtLeaveTemp = new DataTable(); string strdate = startDate.ToString("yyyyMMdd"); dtLeaveTemp = GetLeaveDetailsByDate(DRPData, strdate); if (dtLeaveTemp != null && dtLeaveTemp.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dtLeaveTemp.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dtLeaveTemp.Rows[0]["leaveType"].ToString(); dr["approveType"] = dtLeaveTemp.Rows[0]["approveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false); } } } else { VISDbCommand objVISDbCommand_23 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_23.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_23.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_23.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_23.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Holidayfromdatetodate"); objVISDbCommand_23.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_23.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_23.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholiday = new SqlDataAdapter(); sdaholiday.SelectCommand = objVISDbCommand_23.objSqlCommand; DataSet dsHoliday = new DataSet(); dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_23.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { VISDbCommand objVISDbCommand_24 = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand_24.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_24.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_24.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVISDbCommand_24.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "HolidayFromDate"); objVISDbCommand_24.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, startDate.ToString("yyyyMMdd")); objVISDbCommand_24.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand_24.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholidayfdate = new SqlDataAdapter(); sdaholidayfdate.SelectCommand = objVISDbCommand_24.objSqlCommand; dsHoliday.Clear(); sdaholiday.Fill(dsHoliday); objVISDbCommand_24.objSqlCommand.Connection.Close(); if (dsHoliday.Tables[0].Rows.Count > 0) { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", dsHoliday.Tables[0].Rows[0]["holidayName"].ToString(), false, false); } else { fillRecord(startDate.ToString("dd/MM/yyyy"), DRPData.ToString(), false, "", "", true, false); } } } } startDate = startDate.AddDays(1); } } } catch (Exception ex) { return null; } finally { SqlConnection.ClearAllPools(); } //} return dt; } private void fillRecord(string date, string empID, Boolean halfLeave, string leaveType, string approveType, Boolean checkHrs, Boolean TwoHalfLeaveSameDay) { try { DataSet ds = new DataSet(); DateTime dateval = Convert.ToDateTime(date, provider); VISDbCommand objvisCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objvisCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objvisCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objvisCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objvisCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Holidayfromdatetodate"); objvisCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, dateval.ToString("yyyyMMdd")); objvisCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objvisCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sdaholidayleave = new SqlDataAdapter(); sdaholidayleave.SelectCommand = objvisCommand.objSqlCommand; DataSet dsHolidayleave = new DataSet(); dsHolidayleave.Clear(); sdaholidayleave.Fill(dsHolidayleave); if (dsHolidayleave.Tables[0].Rows.Count > 0 && dsHolidayleave != null) { approveType = dsHolidayleave.Tables[0].Rows[0]["holidayName"].ToString(); } DataSet dsNWD1 = new DataSet(); DateTime nwddate = Convert.ToDateTime(date, provider); VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, empID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_startdate, nwddate.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "NWDHISTORY"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sdanwd = new SqlDataAdapter(); sdanwd.SelectCommand = objVISDbCommand.objSqlCommand; dsNWD1.Clear(); sdanwd.Fill(dsNWD1); DateTime getDateRecord = Convert.ToDateTime(date, provider); VISDbCommand objVIDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_BindFinalDetails; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, empID); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, getDateRecord.ToString("yyyyMMdd")); objVIDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); DataSet dsTemp = new DataSet(); sda.SelectCommand = objVIDbCommand.objSqlCommand; dsTemp.Clear(); sda.Fill(dsTemp); if (dsTemp.Tables.Count > 0 && dsTemp.Tables[0].Rows.Count > 0) { dr = dt.NewRow(); dr["Employee_Id"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["EmployeeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["EmployeeID"].ToString() : ""; dr["EmployeeCode"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["EmployeeCode"].ToString()) ? dsTemp.Tables[0].Rows[0]["EmployeeCode"].ToString() : ""; dr["Employee_Name"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["EmployeeName"].ToString()) ? dsTemp.Tables[0].Rows[0]["EmployeeName"].ToString() : ""; dr["Date"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["Date"].ToString()) ? dsTemp.Tables[0].Rows[0]["Date"].ToString() : ""; dr["MMDDYYYY_DateFormat"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["MMDDYYYY_DateFormat"].ToString()) ? dsTemp.Tables[0].Rows[0]["MMDDYYYY_DateFormat"].ToString() : ""; dr["Days"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["Days"].ToString()) ? dsTemp.Tables[0].Rows[0]["Days"].ToString() : ""; dr["ImportRemarks"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["ImportRemarks"].ToString()) ? dsTemp.Tables[0].Rows[0]["ImportRemarks"].ToString().Length > 30 ? dsTemp.Tables[0].Rows[0]["ImportRemarks"].ToString().Substring(0, 27) + "..." : dsTemp.Tables[0].Rows[0]["ImportRemarks"].ToString() : ""; dr["HoverImportRemarks"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["ImportRemarks"].ToString()) ? dsTemp.Tables[0].Rows[0]["ImportRemarks"].ToString() : ""; if (!String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTIme"].ToString())) { dr["InId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["InTimeID"].ToString() : ""; dr["In_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["InTIme"].ToString() : ""; if (dr["InId"].ToString() != "") { int intPunchInID = Convert.ToInt32(dr["InId"]); VISDbCommand objVDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVDbCommand.objSqlCommand.Parameters.AddWithValue("PunchInId", intPunchInID); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetActualEntryTimeAndGracebyPunchInId"); objVDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sd = new SqlDataAdapter(); sd.SelectCommand = objVDbCommand.objSqlCommand; ds.Clear(); sd.Fill(ds); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { string[] arr = ds.Tables[0].Rows[0]["actualEntryTime"].ToString().Split(':'); if (arr.Length > 1) { TimeSpan punchInActual = new TimeSpan(Convert.ToInt32(arr[0]), Convert.ToInt32(arr[1]), 0); TimeSpan tsgrace; TimeSpan actualInWithGrace; DateTime dtPunchIN = Convert.ToDateTime(dr["In_Time"]); TimeSpan punchIn = new TimeSpan(dtPunchIN.Hour, dtPunchIN.Minute, dtPunchIN.Second); string strGrace = ""; if (strUserType != "admin" && strUserType != "Hr" && strUserType != "Payroll") { tsgrace = new TimeSpan(0, 0, 0); } else { DateTime dtGetDate = Convert.ToDateTime(date); strGrace = ds.Tables[0].Rows[0]["grace"].ToString(); tsgrace = new TimeSpan(0, Convert.ToInt32(strGrace), 0); } actualInWithGrace = punchInActual.Add(tsgrace); if (halfLeave) { } else { if (punchIn > actualInWithGrace) { dr["diff"] = dr["diff"].ToString() + "I"; } } } } } Boolean IsInOffice = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInOffice"]); Boolean IsInBreak = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInBreak"]); Boolean IsInLunch = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInLunch"]); if (IsInOffice || IsInBreak || IsInLunch) { dr["Out_Time"] = ""; dr["OutId"] = ""; } else { dr["Out_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OutTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["OutTIme"].ToString() : ""; dr["OutId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OutTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["OutTimeID"].ToString() : ""; } dr["LunchOut_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchOutTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchOutTIme"].ToString() : ""; dr["LunchOutId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchOutTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchOutTimeID"].ToString() : ""; if (IsInLunch) { dr["LunchIn_Time"] = ""; dr["LunchInId"] = ""; } else { dr["LunchIn_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchInTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchInTIme"].ToString() : ""; dr["LunchInId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchInTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchInTimeID"].ToString() : ""; } dr["OtherId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString() : ""; dr["Other_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString() : ""; string strWorksheetHours = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalWorksheetHours"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalWorksheetHours"].ToString() : ""; strWorksheetHours = strWorksheetHours.Replace('.', ':') + ":00"; string[] arrWorksheetHours = strWorksheetHours.Split(':'); TimeSpan tsWorksheetHours = new TimeSpan(); tsWorksheetHours = new TimeSpan(Convert.ToInt32(arrWorksheetHours[0]), Convert.ToInt32(arrWorksheetHours[1]), 0); dr["TotalWorksheet_Hr"] = strWorksheetHours.ToString(); dr["ActualEntryTime"] = ds.Tables[0].Rows[0]["actualEntryTime"].ToString(); dr["Grace"] = ds.Tables[0].Rows[0]["grace"].ToString(); if (checkHrs) { if (halfLeave) { if (String.Compare(approveType, "UUPL", true) == 0) { dr["status"] = approveType + "/" + leaveType; } else { dr["status"] = approveType; } } else { if (dsNWD1.Tables[0].Rows.Count > 0) { dr["status"] = "NWD/Full"; } else { dr["status"] = "Present"; } } } else { if (dsNWD1.Tables[0].Rows.Count > 0) { dr["status"] = "NWD/Full"; } else { if (dr["InId"].ToString() != "") { dr["status"] = "Present"; } else { dr["status"] = approveType; } } } dr["Other_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString() : ""; ; dr["Total_W_Hr"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalWorkingTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalWorkingTime"].ToString() : ""; dr["Total_Hrs"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString() : ""; string strTotalOfficeTime = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString() : ""; TimeSpan tsTotalOfficeTime = new TimeSpan(); if (dr["Total_W_Hr"].ToString() != "") { string[] arrTotalOfficeTime = dr["Total_W_Hr"].ToString().Split(':'); tsTotalOfficeTime = new TimeSpan(Convert.ToInt32(arrTotalOfficeTime[0]), Convert.ToInt32(arrTotalOfficeTime[1]), Convert.ToInt32(arrTotalOfficeTime[2])); } else { tsTotalOfficeTime = new TimeSpan(0, 0, 0); } TimeSpan tsTotalWorkingTime = new TimeSpan(); if (strTotalOfficeTime != "") { string[] arrTotalWorksheet_Hr = strTotalOfficeTime.Split(':'); tsTotalWorkingTime = new TimeSpan(Convert.ToInt32(arrTotalWorksheet_Hr[0]), Convert.ToInt32(arrTotalWorksheet_Hr[1]), Convert.ToInt32(arrTotalWorksheet_Hr[2])); } else { tsTotalWorkingTime = new TimeSpan(0, 0, 0); } if (halfLeave) { TimeSpan temp = new TimeSpan(4, 30, 0); ////TimeSpan temp = new TimeSpan(4, 15, 0); // for working Hrs... if (tsTotalOfficeTime < temp) { if (checkHrs) { dr["diff"] = dr["diff"].ToString() + "T"; } } temp = new TimeSpan(5, 0, 0); // for Total Hrs... if (tsTotalWorkingTime < temp) { if (checkHrs) { dr["diff"] = dr["diff"].ToString() + "O"; } } } else { //TimeSpan temp = new TimeSpan(8, 30, 0); // for working Hrs... TimeSpan temp = new TimeSpan(9, 00, 0); // for working Hrs... if (checkHrs && IsInOffice == false && IsInBreak == false && IsInLunch == false) { if (tsTotalOfficeTime < temp) { dr["diff"] = dr["diff"].ToString() + "T"; } //temp = new TimeSpan(9, 00, 0); // for Total Hrs... temp = new TimeSpan(9, 30, 0); // for Total Hrs... if (tsTotalWorkingTime < temp) { dr["diff"] = dr["diff"].ToString() + "O"; } } if (!IsInOffice && !IsInLunch && !IsInBreak) { temp = new TimeSpan(7, 0, 0); if (tsTotalOfficeTime < temp) { if (dsNWD1.Tables[0].Rows.Count > 0) { dr["status"] = "NWD/Full"; } else { temp = new TimeSpan(2, 0, 0); if (approveType == "AUPL/FL" || approveType == "AUPL/FH" || approveType == "AUPL/SH" || approveType == "CL/SH" || approveType == "CL/FL" || approveType == "CL/FH" || approveType == "CL/FH, AUPL/SH" || approveType == "SL/SH" || approveType == "SL/FH" || approveType == "SL/FL" || approveType == "SL/FH, AUPL/SH") { dr["status"] = approveType; } else { if (tsTotalOfficeTime < temp) { dr["status"] = "UUPL"; } else { dr["status"] = "0.5/UUPL"; } } } } } } dr["TotalId"] = "0"; if (dr["OutId"].ToString() == "") { dr["Total_W_Hr"] = ""; dr["Total_Hrs"] = ""; } if (String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString())) { dr["Other_Time"] = ""; } } else { //VISDbCommand objVDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); //objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; //objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; //objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, empID); ////objVDbCommand.objSqlCommand.Parameters.AddWithValue("PunchInId", intPunchInID); //objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetActualEntryTimeAndGracebyPunchInId"); //objVDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); //objVDbCommand.objSqlCommand.Connection.Open(); //SqlDataAdapter sd = new SqlDataAdapter(); //DataSet ds = new DataSet(); //sd.SelectCommand = objVDbCommand.objSqlCommand; //ds.Clear(); //sd.Fill(ds); if (checkHrs) { if (TwoHalfLeaveSameDay) { if (String.Compare(approveType, "UUPL", true) == 0) { dr["status"] = approveType + "/" + leaveType; } else { dr["status"] = approveType; } } else { if (halfLeave && checkHrs) { dr["status"] = leaveType == "FH" ? approveType + " , UUPL/SH" : "UUPL/FH , " + approveType; } else { dr["status"] = "UUPL/FL"; } } } else { dr["status"] = approveType; } dr["ActualEntryTime"] = ""; dr["In_Time"] = ""; dr["InId"] = ""; dr["Out_Time"] = ""; dr["OutId"] = ""; dr["LunchOut_Time"] = ""; dr["LunchOutId"] = ""; dr["LunchIn_Time"] = ""; dr["Other_Time"] = ""; dr["Total_W_Hr"] = ""; dr["diff"] = ""; dr["TotalId"] = ""; } dt.Rows.Add(dr); } } catch (Exception ex) { Console.WriteLine("Exception Message:" + ex.Message); } finally { SqlConnection.ClearAllPools(); } } public DataTable GetDepartment() { string mode = "Department"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetEmployee() { DataTable dt = new DataTable(); string mode = "Employee"; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetAllEmployee() { DataTable dt = new DataTable(); string mode = "AllEmployee"; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetCompany() { string mode = "Company"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetLineManager() { string mode = "LineManager"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetEntityYear() { mode = "Year"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetDepartmentEmployee(int id) { if (String.Compare(strusertype, "DH", true) == 0) { VISDbCommand objVISDbCommand_25 = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand_25.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_25.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_25.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, id); objVISDbCommand_25.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetDPHeadEmployeeData"); objVISDbCommand_25.objSqlCommand.Parameters.AddWithValue("StrUserId", " "); objVISDbCommand_25.objSqlCommand.Connection.Open(); SqlDataAdapter SdaDPEmp = new SqlDataAdapter(); SdaDPEmp.SelectCommand = objVISDbCommand_25.objSqlCommand; dtdepartemp.Clear(); SdaDPEmp.Fill(dtdepartemp); objVISDbCommand_25.objSqlCommand.Connection.Close(); } else { VISDbCommand objVISDbCommand_26 = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand_26.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand_26.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand_26.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, id); objVISDbCommand_26.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetDepartmentEmployee"); objVISDbCommand_26.objSqlCommand.Parameters.AddWithValue("StrUserId", " "); objVISDbCommand_26.objSqlCommand.Connection.Open(); SqlDataAdapter SdaDPEmp = new SqlDataAdapter(); SdaDPEmp.SelectCommand = objVISDbCommand_26.objSqlCommand; dtdepartemp.Clear(); SdaDPEmp.Fill(dtdepartemp); objVISDbCommand_26.objSqlCommand.Connection.Close(); } return dtdepartemp; } public DataTable SelectDepartment(string Department) { DataTable dt = new DataTable(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_SalaryDeduction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_DepartmentId, Department); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetDepartmentSelectedemp"); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter Sda = new SqlDataAdapter(); Sda.SelectCommand = objVISDbCommand.objSqlCommand; dt.Clear(); Sda.Fill(dt); objVISDbCommand.objSqlCommand.Connection.Close(); return dt; } public DataTable SelectCompany(string Company) { DataTable dt = new DataTable(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_SalaryDeduction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_CompanyId, Company); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetCompanySelectedEmployee"); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter Sda = new SqlDataAdapter(); Sda.SelectCommand = objVISDbCommand.objSqlCommand; dt.Clear(); Sda.Fill(dt); objVISDbCommand.objSqlCommand.Connection.Close(); return dt; } public DataTable SelectLineManager(string LineManager) { DataTable dt = new DataTable(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_SalaryDeduction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LineMId, LineManager); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetLineManagerSelectedEmp"); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter Sda = new SqlDataAdapter(); Sda.SelectCommand = objVISDbCommand.objSqlCommand; dt.Clear(); Sda.Fill(dt); objVISDbCommand.objSqlCommand.Connection.Close(); return dt; } public DataTable GetMissingEntry(string fromdate, string todate, string Employeeids) { VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_SalaryDeduction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetMissingEntry"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Date, fromdate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ToDate, todate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_employeeIds, Employeeids); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, DateTime.Now.ToString("yyyyMMdd")); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(); DataSet dsDeductionEntry = new DataSet(); da.SelectCommand = objVISDbCommand.objSqlCommand; dsDeductionEntry.Clear(); da.Fill(dsDeductionEntry); if (dsDeductionEntry.Tables.Count > 0 ? dsDeductionEntry.Tables[0].Rows.Count > 0 ? true : false : false) { foreach (DataRow item in dsDeductionEntry.Tables[0].Rows) { fillRecord(item["forwhichdate"].ToString(), item["employee_id"].ToString(), false, "", "", true, false); } } return dt; } public DataTable GetDeductionDetails(string strDate, string ToDate, string Employeeids) { //DateTime datevalstart = DateTime.ParseExact(strDate, "yyyyMMdd", CultureInfo.InvariantCulture); //var fromdate = datevalstart.ToString("yyyyMMdd"); //DateTime datevalend = DateTime.ParseExact(ToDate, "yyyyMMdd", CultureInfo.InvariantCulture).AddMonths(1).AddDays(-1); //var enddate = datevalend.ToString("yyyyMMdd"); DataSet ds = new DataSet(); VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_SalaryDeduction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "SalaryDeduction"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Date, FromDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ToDate, ToDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_employeeIds, Employeeids); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(); DataSet dsDeductionEntry = new DataSet(); da.SelectCommand = objVISDbCommand.objSqlCommand; dsDeductionEntry.Clear(); da.Fill(dsDeductionEntry); if (dsDeductionEntry.Tables.Count > 0 ? dsDeductionEntry.Tables[0].Rows.Count > 0 ? true : false : false) { foreach (DataRow item in dsDeductionEntry.Tables[0].Rows) { fillRecord(item["forwhichdate"].ToString(), item["employee_id"].ToString(), false, "", "", true, false); } } return dt; } public string GetcheckedData(string name, string DRPData) { checkedvalueRDB = name; checkedvalueDRP = DRPData; return name; } protected string GetEmployeeDetail() { string employeeList = string.Empty; string employee = string.Empty; DataTable dtemp = new DataTable(); if (checkedvalueRDB == "Employee") { } else { if (checkedvalueRDB == "Department") { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_SalaryDeduction; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "DepartmentCHECK_GetEmployee"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dtemp); } } } return null; } public DataTable GetDailyEntryTime(int Employee_Id, string Date) { DataTable Timedt = new DataTable(); DateTime dtDate = DateTime.Parse(Date); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_SalaryDeduction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_empId, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Date, dtDate.ToString("MM/dd/yyyy")); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "btnsavedailyentry_Click"); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objVISDbCommand.objSqlCommand; Timedt.Clear(); sda.Fill(Timedt); objVISDbCommand.objSqlCommand.Connection.Close(); return Timedt; } // Attendance Approve Punch In public string AddEntity(int Id, int Employee_Id, int EntryType, string HODRemarks, string Temp, string strDate, string Time, int Grace) { try { VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Procattendance_transaction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, HODRemarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Entry_Time, Temp); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, strDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, Grace); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, strDate); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, HODRemarks); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AttendanceRejectPunchIn(int Employee_Id, int EntryType, string Date, string RemarksIn, int InId) { try { string[] datearray = Date.Split('/'); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "reject"); if (InId.ToString().Length != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, Convert.ToInt32(InId.ToString())); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, RemarksIn); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, datearray[2] + datearray[1] + datearray[0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "UnApproved"); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string ApproveAttendanceOkIn(int InId, string Remarks) { try { VISDbCommand objISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "CompanyName"); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_InId, InId); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objISDbCommand.objSqlCommand; DataTable dtCompanyName = new DataTable(); dtCompanyName.Clear(); sda.Fill(dtCompanyName); objISDbCommand.objSqlCommand.Connection.Close(); if (dtCompanyName.Rows.Count > 0) { VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "DeleteCompanyName"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_InId, InId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVIDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, InId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, false); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } else { //-----TransactionChange------// VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionChange; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, InId); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //-----TransactionLog------// VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, InId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, true); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string UpdateEntity(int InId, int EntryType, string Remarks, string Date, string Time, int Grace, string ActualHr) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_AttendanceApproval; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, InId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Time, Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, Grace); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, ActualHr); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); //------------Attendance Approved By HOD ----------------------// VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, ""); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, Remarks); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } // Attendance Approve Punch Out public string ApproveAttendancePunchOut(int OutId, int EntryType, string Remarks, string Date, string Time, int Grace, string ActualHrs) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_AttendanceApproval; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, OutId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Time, Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, Grace); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, ActualHrs); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); //------------Attendance Approved By HOD ----------------------// VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, OutId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, Remarks); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AddEmployeeAttendancePunchOut(int Employee_Id, int EntryType, string HODRemarks, string Temp, string strDate, string Time, int Grace) { try { VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Procattendance_transaction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, HODRemarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Entry_Time, Temp); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, strDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, Grace); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, Convert.ToDateTime(strDate)); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, HODRemarks); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AttendanceRejectPunchOut(int Employee_Id, int EntryType, string Date, string HODRemarks, int OutId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "reject"); if (OutId.ToString().Length != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, Convert.ToInt32(OutId.ToString())); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, HODRemarks); string[] datearr = Date.Split('/'); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, datearr[2] + datearr[1] + datearr[0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "UnApproved"); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //GetBindAttendanceData(); } public string ApproveAttendanceOkPunchOut(int OutId, string Remarks) { try { VISDbCommand objISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetCompanyIdByPunchOut"); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_OutId, OutId); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objISDbCommand.objSqlCommand; DataTable dtCompanyName = new DataTable(); dtCompanyName.Clear(); sda.Fill(dtCompanyName); objISDbCommand.objSqlCommand.Connection.Close(); if (dtCompanyName.Rows.Count > 0) { VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "DeleteCompanyIdByPunchOut"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_OutId, OutId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVIDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, OutId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, false); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } else { //-----TransactionChange------// VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionChange; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, OutId); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //-----TransactionLog------// VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, OutId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, true); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } // Attendance Approve Lunch Out public string ApproveAttendanceLunchOut(int LunchOutId, string Remarks, string Time) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_AttendanceApproval; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, LunchOutId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Time, Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, "0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, ""); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, LunchOutId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AddEmployeeAttendanceLunchOut(int Employee_Id, int EntryType, string Remarks, string Temp, string Date, string Time) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Procattendance_transaction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Entry_Time, Temp); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, "0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, Time); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, Remarks); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, Date); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AttendanceRejectLunchOut(int LunchOutId, int Employee_Id, int EntryType, string Date, string HODRemarks) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "reject"); if (LunchOutId.ToString().Length != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, Convert.ToInt32(LunchOutId)); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); string[] datearr = Date.ToString().Split('/'); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, datearr[2] + datearr[1] + datearr[0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "UnApproved"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, HODRemarks); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string ApproveAttendanceOkLunchOut(int LunchOutId, string Remarks) { try { VISDbCommand objISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetCompanyIdByLunchOut"); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LunchOutId, LunchOutId); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objISDbCommand.objSqlCommand; DataTable dtCompanyName = new DataTable(); dtCompanyName.Clear(); sda.Fill(dtCompanyName); objISDbCommand.objSqlCommand.Connection.Close(); if (dtCompanyName.Rows.Count > 0) { VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "DeleteCompanyIdByLunchOut"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LunchOutId, LunchOutId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVIDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, LunchOutId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, false); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } else { //-----TransactionChange------// VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionChange; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, LunchOutId); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //-----TransactionLog------// VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, LunchOutId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, true); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } // Attendance Approve Lunch In public string ApproveAttendanceLunchIn(int LunchInId, string Remarks, string Time) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_AttendanceApproval; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, LunchInId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Time, Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, "0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, ""); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, LunchInId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, Remarks); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AddEmployeeAttendanceLunchIn(int Employee_Id, int EntryType, string Remarks, string Temp, string Date, string Time) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Procattendance_transaction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Entry_Time, Temp); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, "0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, Time); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, Remarks); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, Date); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AttendanceRejectLunchIn(int Employee_Id, int LunchInId, int EntryType, string Date, string HODRemarks) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "reject"); if (LunchInId.ToString().Length != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, Convert.ToInt32(LunchInId)); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); string[] datearr = Date.ToString().Split('/'); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, datearr[2] + datearr[1] + datearr[0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "UnApproved"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, HODRemarks); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string ApproveAttendanceOkLunchIn(int LunchInId, string Remarks) { try { VISDbCommand objISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetCompanyIdByLunchIn"); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LunchInId, LunchInId); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objISDbCommand.objSqlCommand; DataTable dtCompanyName = new DataTable(); dtCompanyName.Clear(); sda.Fill(dtCompanyName); objISDbCommand.objSqlCommand.Connection.Close(); if (dtCompanyName.Rows.Count > 0) { VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "DeleteCompanyIdByLunchIn"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_LunchInId, LunchInId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVIDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, LunchInId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, false); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } else { //-----TransactionChange------// VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionChange; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, LunchInId); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //-----TransactionLog------// VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, LunchInId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, true); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } // Attendance Approve Work In public string ApproveAttendanceOther(int OtherId, string Remarks, string Time) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_AttendanceApproval; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, OtherId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Time, Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, "0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, ""); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, OtherId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, Remarks); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public DataTable GetEmployeeIsNotHostEmployee(int Employee_Id) { DataTable Timedt = new DataTable(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeId, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetEmployeeIsNotHostEmployee"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objVISDbCommand.objSqlCommand; Timedt.Clear(); sda.Fill(Timedt); objVISDbCommand.objSqlCommand.Connection.Close(); return Timedt; } public string AddEmployeeAttendanceOtherwork(int Employee_Id, int EntryType, string HODRemarks, string Temp, string Date, string Time) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Procattendance_transaction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Id, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, HODRemarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Entry_Time, Temp); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_grace, "0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_actualEntryTime, Time); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "approve"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, HODRemarks); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, Date); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "Approved"); if (!objVIDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVIDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //GetBindAttendanceData(EmployeeId, FromDate, EndDate, DrpemName, DropdownvalDECL, RdbDateval, Rdbmonthval, mon, y); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string AttendanceRejectOtherWork(int Employee_Id, int OtherId, int EntryType, string Date, string HODRemarks) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_DailyentrytimingAddEdit; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "reject"); if (OtherId.ToString().Length != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Transaction_Id, Convert.ToInt32(OtherId)); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Employee_ID, Employee_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EntryType, EntryType); string[] datearr = Date.ToString().Split('/'); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_fromDate, datearr[2] + datearr[1] + datearr[0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Bit_Approved, "UnApproved"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_HOD_Remarks, HODRemarks); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public string ApproveAttendanceOkOtherWorkIn(int OtherId, string Remarks) { try { VISDbCommand objISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objISDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "GetCompanyIdByWorkIn"); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_OtherId, OtherId); objISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objISDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objISDbCommand.objSqlCommand; DataTable dtCompanyName = new DataTable(); dtCompanyName.Clear(); sda.Fill(dtCompanyName); objISDbCommand.objSqlCommand.Connection.Close(); if (dtCompanyName.Rows.Count > 0) { VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_procAttendanceReport_SelectById; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "DeleteCompanyIdByWorkIn"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_OtherId, OtherId); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_EmployeeID, ""); objVIDbCommand.objSqlCommand.Parameters.AddWithValue("StrUserId", ""); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, OtherId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, false); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } else { //-----TransactionChange------// VISDbCommand objVIDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVIDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVIDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionChange; objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVIDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, OtherId); objVIDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVIDbCommand.objSqlCommand.ExecuteNonQuery(); objVIDbCommand.objSqlCommand.Connection.Close(); //-----TransactionLog------// VISDbCommand objVDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVDbCommand.objSqlCommand.CommandText = AttendanceReportConstatnts.const_ProcAttendanceReport_Proc_TransactionLog; objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_mode, "Insert"); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Attendance_TransactionId, OtherId); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeType, true); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_UserId, 21); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_ChangeTime, System.DateTime.Now); objVDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceReportConstatnts.const_Field_Remarks, Remarks); objVDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVDbCommand.objSqlCommand.ExecuteNonQuery(); objVDbCommand.objSqlCommand.Connection.Close(); } } catch (Exception ex) { } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } } } <file_sep>import { NgModule, ErrorHandler } from '@angular/core'; import { APP_BASE_HREF } from '@angular/common'; import { CKEditorModule } from 'ng2-ckeditor' import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal'; import { FileDropDirective, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload'; import { HttpModule } from '@angular/http'; import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload'; import { Ng2TabModule } from 'ng2-tab'; import { ColorPickerModule } from 'angular2-color-picker'; import { routing } from './app.routing'; import AppErrorHandler from './Shared/errorhandler'; import { SearchComponent } from './Shared/search.component'; import { OrderrByPipe } from './Shared/orderby.pipe'; import { SharedContents } from './Shared/sharedcontents'; import { AuthGuard } from './Shared/auth.gaurd'; import { UserAuthGuard } from './Shared/user.auth.gaurd'; import { LoginComponent } from './components/UserManagement/login.component'; import { LoginService } from './Service/UserManagement/login.Service'; import { HomeComponent } from './components/home.component'; import { PagerService } from './Shared/pager.index'; import { CommonHelperService } from './Shared/CommonHelper.service'; import { ExcelService } from './Shared/exportexcel.service'; import { MultiselectDropdownModule } from 'angular-2-dropdown-multiselect'; import { CurrencyComponent } from './components/Masters/CurrencyRelated/currency.component'; import { CurrencyService } from './Service/Masters/CurrencyRelated/currency.service' import { CurrencyFilterPipe } from './filter/Masters/CurrencyRelated/currency.pipe' import { LevelsComponent } from './components/Masters/EmployeeLevels/levels.component'; import { LevelsService } from './Service/Masters/EmployeeLevels/levels.service' import { LevelsFilterPipe } from './filter/Masters/EmployeeLevels/levels.pipe' import { ContactMasterComponent } from './components/Masters/CompanyRelated/ContactMaster.component'; import { ContactMasterService } from './Service/Masters/CompanyRelated/ContactMaster.service'; import { ContactMasterFilterPipe } from './filter/Masters/CompanyRelated/ContactMaster.pipe'; import { BankMasterComponent } from './components/Masters/CompanyRelated/BankMaster.component'; import { BankMasterService } from './Service/Masters/CompanyRelated/BankMaster.service'; import { BankMasterFilterPipe } from './filter/Masters/CompanyRelated/BankMaster.pipe'; import { RatingTypeComponent } from './components/Masters/VacancyRelated/RatingType.component'; import { RatingTypeService } from './Service/Masters/VacancyRelated/RatingType.service'; import { RatingTypeFilterPipe } from './Filter/Masters/VacancyRelated/RatingType.pipe'; import { LookupTypeComponent } from './components/Masters/CompanyRelated/LookupType.component'; import { LookupTypeService } from './Service/Masters/CompanyRelated/LookupType.service'; import { LookupTypeFilterPipe } from './Filter/Masters/CompanyRelated/LookupType.pipe'; import { LookupComponent } from './components/Masters/CompanyRelated/Lookup.component'; import { LookupService } from './Service/Masters/CompanyRelated/Lookup.service'; import { LookupFilterPipe } from './filter/Masters/CompanyRelated/Lookup.pipe'; import { SkillGroupComponent } from './components/Masters/VacancyRelated/SkillGroup.component'; import { SkillGroupService } from './Service/Masters/VacancyRelated/SkillGroup.service'; import { SkillGroupFilterPipe } from './filter/Masters/VacancyRelated/SkillGroup.pipe'; import { SkillComponent } from './components/Masters/VacancyRelated/Skill.component'; import { SkillService } from './Service/Masters/VacancyRelated/Skill.service'; import { SkillFilterPipe } from './filter/Masters/VacancyRelated/Skill.pipe'; import { PositionComponent } from './components/Masters/VacancyRelated/Position.component'; import { PositionService } from './Service/Masters/VacancyRelated/Position.service'; import { PositionFilterPipe } from './filter/Masters/VacancyRelated/Position.pipe'; import { TechnologyMasterComponent } from './components/Masters/VacancyRelated/TechnologyMaster.component'; import { TechnologyMasterService } from './Service/Masters/VacancyRelated/TechnologyMaster.service'; import { TechnologyMasterFilterPipe } from './filter/Masters/VacancyRelated/TechnologyMaster.pipe'; import { CompanyMasterComponent } from './components/Masters/CompanyRelated/CompanyMaster.Component'; import { CompanyMasterService } from './Service/Masters/CompanyRelated/CompanyMaster.service'; import { CompanyMasterFilterPipe } from './filter/Masters/CompanyRelated/CompanyMaster.pipe'; import { MacIdConfigurationComponent } from './components/Masters/Configuration/MacIdConfiguration.component'; import { MacIdConfigurationService } from './Service/Masters/Configuration/MacIdConfiguration.service'; import { MacIdConfigurationFilterPipe } from './filter/Masters/Configuration/MacIdConfiguration.pipe'; import { SecurityKeyComponent } from './components/Masters/Configuration/SecurityKey.component'; import { SecurityKeyService } from './Service/Masters/Configuration/SecurityKey.service'; import { SecurityKeyFilterPipe } from './filter/Masters/Configuration/SecurityKey.pipe'; import { FinancialYearComponent } from './components/Masters/CompanyRelated/FinancialYear.component'; import { FinancialYearService } from './Service/Masters/CompanyRelated/FinancialYear.service'; import { FinancialYearFilterPipe } from './filter/Masters/CompanyRelated/FinancialYear.pipe'; import { EventCountDownComponent } from './components/Masters/Configuration/EventCountDown.component'; import { EventCountDownService } from './Service/Masters/Configuration/EventCountDown.service'; import { EventCountDownFilterPipe } from './filter/Masters/Configuration/EventCountDown.pipe'; import { DashboardComponent } from './components/Dashboard/dashboard.component'; import { DashboardService } from './Service/Dashboard/dashboard.service'; import { CommonConfigurationComponent } from './components/Masters/Configuration/CommonConfiguration.component'; import { CommonConfigurationService } from './Service/Masters/Configuration/CommonConfiguration.service'; import { CommonConfigurationFilterPipe } from './filter/Masters/Configuration/CommonConfiguration.pipe'; import { LevelConfigurationComponent } from './components/Masters/EmployeeLevels/LevelConfiguration.component'; import { LevelConfigurationService } from './Service/Masters/EmployeeLevels/LevelConfiguration.service' import { LevelConfigurationFilterPipe } from './filter/Masters/EmployeeLevels/LevelConfiguration.pipe' import { PolicyComponent } from './components/Notification/policy.component'; import { PolicyService } from './Service/Notification/policy.service'; import { PolicyFilterPipe } from './filter/Notification/policy.pipe'; import { ConfigureWorkSheetComponent } from './components/Masters/Configuration/ConfigureWorkSheet.component'; import { ConfigureWorksheetService } from './Service/Masters/Configuration/ConfigureWorksheet.service'; import { ConfigureWorkSheetFilterPipe} from './filter/Masters/Configuration/ConfigureWorksheet.pipe'; import { NewsComponent } from './components/Notification/News.component'; import { NewsService } from './Service/Notification/News.service'; import { NewsFilterPipe } from './filter/Notification/News.pipe'; import { LevelCriteriaSetupComponent } from './Components/Masters/EmployeeLevels/LevelCriteriaSetup.component'; import { LevelCriteriaSetupService } from './Service/Masters/EmployeeLevels/LevelCriteriaSetup.service'; import { LevelCriteriaSetupFilterPipe } from './Filter/Masters/EmployeeLevels/LevelCriteriaSetup.pipe'; import { ConfigureTicketComponent } from './Components/Masters/Configuration/ConfigureTicket.component'; import { ConfigureTicketService } from './Service/Masters/Configuration/ConfigureTicket.service'; import { ConfigureTicketFilterPipe } from './Filter/Masters/Configuration/ConfigureTicket.pipe'; import { HomePageImageComponent } from './Components/Masters/CompanyRelated/HomePageImage.component'; import { HomePageImageService } from './Service/Masters/CompanyRelated/HomePageImage.service'; import { HomePageImageFilterPipe } from './Filter/Masters/CompanyRelated/HomePageImage.pipe'; import { HelpTicketAddComponent } from './Components/Notification/HelpTicketAdd.component'; import { HelpTicketAddService } from './Service/Notification/HelpTicketAdd.service'; import { HelpTicketAddFilterPipe } from './Filter/Notification/HelpTicketAdd.pipe'; import { MyTicketComponent } from './Components/Notification/MyTicket.component'; import { MyTicketService } from './Service/Notification/MyTicket.service'; import { MyTicketFilterPipe } from './Filter/Notification/MyTicket.pipe'; import { ChangePasswordComponent } from './Components/HumanResource/ProfileAttendance/ChangePassword.component'; import { ChangePSWService } from './Service/HumanResource/ProfileAttendance/ChangePassword.service'; import { TicketListOpenComponent } from './Components/Notification/TicketListOpen.component'; import { TicketListOpenService } from './Service/Notification/TicketListOpen.service'; import { TicketListOpenFilterPipe } from './Filter/Notification/TicketListOpen.pipe'; import { TicketListClosedComponent } from './Components/Notification/TicketListClosed.component'; import { TicketListClosedService } from './Service/Notification/TicketListClosed.service'; import { TicketListClosedFilterPipe } from './Filter/Notification/TicketListClosed.pipe'; import { MyProfilesComponent } from './Components/HumanResource/ProfileAttendance/MyProfiles.component'; import { MyProfilesService } from './Service/HumanResource/ProfileAttendance/MyProfiles.service'; import { MyProfilesFilterPipe } from './Filter/HumanResource/ProfileAttendance/MyProfiles.pipe'; import { LeaveTypeComponent } from './components/Masters/CompanyRelated/LeaveType.component'; import { LeaveTypeService } from './Service/Masters/CompanyRelated/LeaveType.service'; import { LeaveTypeFilterPipe } from './filter/Masters/CompanyRelated/LeaveType.pipe' import { GroupNameComponent } from './components/Masters/CompanyRelated/GroupName.component'; import { GroupNameService } from './Service/Masters/CompanyRelated/GroupName.service'; import { GroupNameFilterPipe } from './filter/Masters/CompanyRelated/GroupName.pipe' import { DailyEntrysheetComponent } from './components/Report/Attendance/DailyEntrysheet.component'; import { DailyEntrysheetService } from './Service/Report/Attendance/DailyEntrysheet.service'; import { AttendanceReportComponent } from './Components/Report/Attendance/AttendanceReport.component'; import { AttendanceReportService } from './Service/Report/Attendance/AttendanceReport.Service'; import { OutReportComponent } from './components/Report/Attendance/OutReport.component'; import { OutReportService } from './Service/Report/Attendance/OutReport.service'; import { WorkSheetComponent } from './components/HumanResource/Attendance/WorkSheet.component'; import { WorkSheetService } from './Service/HumanResource/Attendance/WorkSheet.service'; import { WorkSheetFilterPipe } from './filter/HumanResource/Attendance/WorkSheet.pipe'; import { MySkillComponent } from './components/HumanResource/Attendance/MySkill.component'; import { MySkillService } from './Service/HumanResource/Attendance/MySkill.service'; import { MySkillFilterPipe } from './filter/HumanResource/Attendance/MySkill.pipe'; import { MyTeamComponent } from './components/HumanResource/Attendance/MyTeam.component'; import { MyTeamService} from './Service/HumanResource/Attendance/MyTeam.service'; import { MyTeamFilterPipe} from './filter/HumanResource/Attendance/MyTeam.pipe'; import { EmployeeFeedbackComponent } from './components/HumanResource/Attendance/EmployeeFeedback.component'; import { EmployeeFeedbackService } from './Service/HumanResource/Attendance/EmployeeFeedback.service'; import { EmployeeFeedbackFilterPipe } from './filter/HumanResource/Attendance/EmployeeFeedback.pipe'; import { Levels_AchievementComponent } from './Components/Masters/EmployeeLevels/Levels_Achievement.component'; import { Levels_AchievementService } from './Service/Masters/EmployeeLevels/Levels_Achievement.service' import { Levels_AchievementFilterPipe } from './filter/Masters/EmployeeLevels/Levels_Achievement.pipe' import { AttendanceEntryComponent } from './Components/UserManagement/AttendanceEntry.component'; import { AttendanceEntryService } from './Service/UserManagement/AttendanceEntry.Service'; import { EmployeeScreenCaptureReportComponent } from './components/Report/Attendance/EmployeeScreenCapture.component'; import { EmployeeScreenCaptureReportService } from './Service/Report/Attendance/EmployeeScreenCaptureReport.service'; import { EmployeeDashboardHeartBeatReportComponent } from './components/Report/Attendance/EmployeeDashboardHeartBeatReport.component'; import { EmployeeDashboardHeartBeatReportService } from './Service/Report/Attendance/EmployeeDashboardHeartBeat.service'; import { AttendanceAccessCardComparisionReportComponent } from './components/Report/Attendance/AttendanceAccessCardComparisionReport.component'; import { AttendanceAccessCardComparisionReportService } from './Service/Report/Attendance/AttendanceAccessCardComparisionReport.service'; import { EmployeeListComponent } from './components/HumanResource/EmployeeManagement/EmployeeList.component'; import { EmployeeListService } from './Service/HumanResource/EmployeeManagement/EmployeeList.service'; import { EmployeeListFilterPipe } from './filter/HumanResource/EmployeeManagement/EmployeeList.pipe'; import { EmpInfoTabularComponent } from './components/HumanResource/EmployeeManagement/EmpInfoTabular.component'; import { EmpInfoTabularService } from './Service/HumanResource/EmployeeManagement/EmpInfoTabular.service'; import { ManualPointEntryComponent } from './components/Masters/EmployeeLevels/ManualPointEntry.component'; import { ManualPointEntryService } from './Service/Masters/EmployeeLevels/ManualPointEntry.service'; import { ManualPointEntryFilterPipe } from './Filter/Masters/EmployeeLevels/ManualPointEntry.pipe'; import { LateEarlyReportComponent } from './components/Report/Attendance/LateEarlyReport.component'; import { LateEarlyReportFilterPipe } from './Filter/Report/Attendance/LateEarlyReport.pipe'; import { LateEarlyReportService } from './Service/Report/Attendance/LateEarlyReport.service'; import { UserRoleComponent } from './components/Masters/CompanyRelated/UserRole.component'; import { UserRoleService } from './Service/Masters/CompanyRelated/UserRole.service'; import { UserRoleFilterPipe } from './Filter/Masters/CompanyRelated/UserRole.pipe'; import { EducationTypeComponent } from './components/Masters/CompanyRelated/EducationType.component'; import { EducationTypeService } from './Service/Masters/CompanyRelated/EducationType.service'; import { EducationTypeFilterPipe } from './Filter/Masters/CompanyRelated/EducationType.pipe'; import { SalaryBreakupTypeComponent } from './components/Masters/CompanyRelated/SalaryBreakupType.component'; import { SalaryBreakupTypeService } from './Service/Masters/CompanyRelated/SalaryBreakupType.service'; import { SalaryBreakupTypeFilterPipe } from './Filter/Masters/CompanyRelated/SalaryBreakupType.pipe'; import { AddEmployeeRecordcomponent } from './Components/Report/Attendance/AddEmployeeRecord.component'; import { AddEmployeeRecordService } from './Service/Report/Attendance/AddEmployeeRecord.service'; import { AttendanceReportNewcomponent } from './Components/Report/Attendance/AttendanceReportNew.component'; import { AttendanceReportNewService } from './Service/Report/Attendance/AttendanceReportNew.service'; import { OfficialWorkReportComponent } from './Components/Report/Attendance/OfficialWorkReport.component'; import { OfficialWorkReporFilterPipe } from './Filter/Report/Attendance/OfficialWorkReport.pipe'; import { OfficialWorkReportService } from './Service/Report/Attendance/OfficialWorkReport.service'; import { RFQComponent } from './components/RFQ/RFQEstimateListing.component'; import { RFQFilterPipe } from './Filter/RFQ/RFQ.pipe'; import { RFQService } from './Service/RFQ/RFQ.service'; import { AddRFQComponent } from './components/RFQ/AddRFQ.component'; import { AllRFQComponent } from './components/RFQ/RFQEstimateAllRFQ.component'; import { ResponceRequestedRFQcomponent } from './components/RFQ/ResponceRequestedRFQ.component'; import { MyWatchListRFQComponent } from './components/RFQ/MyWatchListRFQ.component'; import { MyActionRFQcomponent } from './components/RFQ/MyActionRFQ.component'; import { ProspectClientFilterPipe } from './Filter/RFQ/RFQProspectClient.pipe'; import { NgDatepickerModule } from 'ng2-datepicker'; import { ProductivityTrackerReportcomponent } from './Components/Report/Attendance/ProductivityTrackerReport.component'; import { ProductivityTrackerReportService } from './Service/Report/Attendance/ProductivityTrackerReport.service'; import { ConfigureSurveycomponent } from './Components/Opinion/ConfigureSurvey.component'; import { ConfigureSurveyService } from './Service/Opinion/ConfigureSurvey.service'; import { TreeModule } from 'ng2-tree'; import { CurrencyHistoryComponent } from './components/Masters/CurrencyRelated/CurrencyHistory.component'; import { CurrencyHistoryService } from './Service/Masters/CurrencyRelated/CurrencyHistory.service'; import { SalaryGrievanceComponent } from './Components/HumanResource/Grievance/SalaryGrievance.component'; import { SalaryGrievanceService } from './Service/HumanResource/Grievance/SalaryGrievance.service'; import { DocumentTemplateComponent } from './Components/DocCenter/DocumentTemplate.component'; import { DocumentTemplateService } from './Service/DocCenter/DocumentTemplate.service'; import { AddRFQResponsecomponent } from './Components/RFQ/AddResponse.component'; import { RFQResponseService } from './Service/RFQ/RFQResponse.service'; import { ViewRFQResponsecomponent} from './Components/RFQ/ViewResponse.component'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule, FormsModule, ColorPickerModule, CKEditorModule, Ng2TabModule, MultiselectDropdownModule, NgDatepickerModule, TreeModule], declarations: [AppComponent, SearchComponent, OrderrByPipe, LoginComponent, HomeComponent, CurrencyComponent, CurrencyFilterPipe, LevelsComponent, LevelsFilterPipe, ContactMasterComponent, ContactMasterFilterPipe, BankMasterComponent, BankMasterFilterPipe, RatingTypeComponent, RatingTypeFilterPipe, LookupTypeComponent, LookupTypeFilterPipe, LookupComponent, LookupFilterPipe, SkillGroupComponent, SkillGroupFilterPipe, SkillComponent, SkillFilterPipe, PositionComponent, PositionFilterPipe, TechnologyMasterComponent, TechnologyMasterFilterPipe, CompanyMasterComponent, CompanyMasterFilterPipe, MacIdConfigurationComponent, MacIdConfigurationFilterPipe, FileDropDirective, FileSelectDirective, SecurityKeyComponent, SecurityKeyFilterPipe, FinancialYearComponent, FinancialYearFilterPipe, EventCountDownComponent, EventCountDownFilterPipe, DashboardComponent, CommonConfigurationComponent, CommonConfigurationFilterPipe, LevelConfigurationComponent, LevelConfigurationFilterPipe, PolicyComponent, PolicyFilterPipe, ConfigureWorkSheetComponent, ConfigureWorkSheetFilterPipe, NewsComponent, NewsFilterPipe, LevelCriteriaSetupComponent, LevelCriteriaSetupFilterPipe, ConfigureTicketComponent, ConfigureTicketFilterPipe, HelpTicketAddComponent, HelpTicketAddFilterPipe, MyTicketComponent, MyTicketFilterPipe, HomePageImageComponent, HomePageImageFilterPipe, ChangePasswordComponent, TicketListOpenComponent, TicketListOpenFilterPipe, TicketListClosedComponent, TicketListClosedFilterPipe, MyProfilesComponent, MyProfilesFilterPipe, LeaveTypeComponent, LeaveTypeFilterPipe, GroupNameComponent, GroupNameFilterPipe, DailyEntrysheetComponent, AttendanceReportComponent, OutReportComponent, WorkSheetComponent, WorkSheetFilterPipe, MySkillComponent, MySkillFilterPipe, MyTeamComponent, MyTeamFilterPipe, EmployeeFeedbackComponent, EmployeeFeedbackFilterPipe, Levels_AchievementComponent, Levels_AchievementFilterPipe, AttendanceEntryComponent, EmployeeScreenCaptureReportComponent, EmployeeDashboardHeartBeatReportComponent, AttendanceAccessCardComparisionReportComponent , EmployeeListComponent, EmployeeListFilterPipe, EmpInfoTabularComponent, ManualPointEntryComponent, ManualPointEntryFilterPipe, LateEarlyReportComponent, LateEarlyReportFilterPipe, UserRoleComponent, UserRoleFilterPipe, EducationTypeComponent, EducationTypeFilterPipe, SalaryBreakupTypeComponent, SalaryBreakupTypeFilterPipe, AddEmployeeRecordcomponent, AttendanceReportNewcomponent, OfficialWorkReportComponent, OfficialWorkReporFilterPipe, ProductivityTrackerReportcomponent, ConfigureSurveycomponent, RFQComponent, RFQFilterPipe, ProspectClientFilterPipe, AddRFQComponent, AllRFQComponent, ResponceRequestedRFQcomponent, MyWatchListRFQComponent, MyActionRFQcomponent, CurrencyHistoryComponent, SalaryGrievanceComponent, DocumentTemplateComponent, AddRFQResponsecomponent, ViewRFQResponsecomponent ], providers: [{ provide: ErrorHandler, useClass: AppErrorHandler }, { provide: APP_BASE_HREF, useValue: '/' }, SharedContents, AuthGuard, UserAuthGuard, LoginService, CurrencyService, LevelsService, PagerService, ContactMasterService, BankMasterService, RatingTypeService, LookupService, LookupTypeService, SkillGroupService, SkillService, PositionService, TechnologyMasterService, CompanyMasterService, MacIdConfigurationService, SecurityKeyService, FinancialYearService, EventCountDownService, DashboardService, CommonConfigurationService, LevelConfigurationService, PolicyService, ConfigureWorksheetService, NewsService, LevelCriteriaSetupService, ConfigureTicketService, HelpTicketAddService, MyTicketService, HomePageImageService, ChangePSWService, TicketListOpenService, TicketListClosedService, MyProfilesService, LeaveTypeService, GroupNameService, DailyEntrysheetService, AttendanceReportService, OutReportService, WorkSheetService, MySkillService, MyTeamService, EmployeeFeedbackService, Levels_AchievementService, AttendanceEntryService, EmployeeScreenCaptureReportService, EmployeeDashboardHeartBeatReportService, AttendanceAccessCardComparisionReportService, EmployeeListService, EmpInfoTabularService, ManualPointEntryService, LateEarlyReportService, UserRoleService, EducationTypeService, SalaryBreakupTypeService, AddEmployeeRecordService, AttendanceReportNewService, OfficialWorkReportService, ProductivityTrackerReportService, ConfigureSurveyService, RFQService, ExcelService, CommonHelperService, CurrencyHistoryService, SalaryGrievanceService, DocumentTemplateService, RFQResponseService], bootstrap: [AppComponent] }) export class AppModule { }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { CurrencyHistoryService } from '../../../service/Masters/CurrencyRelated/CurrencyHistory.service'; import { ICurrency } from '../../../Model/Masters/CurrencyRelated/currency'; import { CurrencyService } from '../../../service/Masters/CurrencyRelated/currency.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ICurrencyHistory } from '../../../Model/Masters/CurrencyRelated/CurrencyHistory'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component({ providers: [CurrencyHistoryService, CurrencyService], templateUrl: 'app/Components/Masters/CurrencyRelated/CurrencyHistory.component.html' }) export class CurrencyHistoryComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; lstCurrency: ICurrency[]; objCurrencyDetail: ICurrency; objICurrencyHistory: ICurrencyHistory; listICurrencyHistory: ICurrencyHistory[]; Year: number[]; ToDayDate: Date = new Date(); YearNow: number = this.ToDayDate.getFullYear(); msg: string; indLoading: boolean = false; currencyFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; CurrencyFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; DefaultExchangeRate: string; CurrentExchangeRate: string; FromDate: string; ToDate: string; ResetModel() { this.objICurrencyHistory = ({ CompanyId: 0, CreatedBy: '', CreatedOn: null, Currency_Id: 0, Current_Exch_Rate: 0, Date_Entered: null, Default_Exch_Rate: 0, FromDate: null, Id: 0, IsActive: false, Month_Entered: 1, ToDate: null, UpdatedBy: '', UpdatedOn: null, Year_Entered: this.YearNow }); } constructor(private _CurrencyHistoryService: CurrencyHistoryService, private pagerService: PagerService, private _CurrencyService: CurrencyService, private _CommonHelperService: CommonHelperService) { } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.ResetModel(); this.listICurrencyHistory = [({ CompanyId: 0, CreatedBy: '', CreatedOn: null, Currency_Id: 0, Current_Exch_Rate: 0, Date_Entered: null, Default_Exch_Rate: 0, FromDate: null, Id: 0, IsActive: false, Month_Entered: 0, ToDate: null, UpdatedBy: '', UpdatedOn: null, Year_Entered: 0 })]; this.LoadCurrencyHistory(); this.BindCurrencyDropdown() this.GetYear(); } GetYear() { this.YearNow = new Date().getFullYear(); this.Year = []; for (var i = 0; i < 100; i++) { this.Year.push(this.YearNow); this.YearNow++; } } ChangeDefaultExchangeRateByCurrency(id:number) { this._CurrencyHistoryService.getbyid(Global.BASE_CurrencyHistoryAPI_ENDPOINT, id). subscribe(defaultexchangerate => { this.objICurrencyHistory.Default_Exch_Rate = Number(defaultexchangerate); }); } CurrencyFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.CurrencyFilter = value; } CurrencySort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } LoadCurrencyHistory(): void { this.indLoading = true; this._CurrencyHistoryService.get(Global.BASE_CurrencyHistoryAPI_ENDPOINT) .subscribe(currencyhistorylist => { this.listICurrencyHistory = currencyhistorylist; //Logic for searching - start if (this.ShowHideSearch) { this.DefaultExchangeRate = (<HTMLInputElement>document.getElementById("txtDefaultExchangeRate")).value; if (this.DefaultExchangeRate != '') { this.DefaultExchangeRate = this.DefaultExchangeRate.toLocaleLowerCase(); this.listICurrencyHistory = this.listICurrencyHistory.filter ( x => x.Default_Exch_Rate != null && x.Default_Exch_Rate.toLocaleString().indexOf(this.DefaultExchangeRate) != -1); } this.CurrentExchangeRate = (<HTMLInputElement>document.getElementById("txtCurrentExchangeRate")).value; if (this.CurrentExchangeRate != '') { this.CurrentExchangeRate = this.CurrentExchangeRate.toLocaleLowerCase(); this.listICurrencyHistory = this.listICurrencyHistory.filter ( x => x.Current_Exch_Rate != null && x.Current_Exch_Rate.toLocaleString().indexOf(this.CurrentExchangeRate) != -1); } this.FromDate = (<HTMLInputElement>document.getElementById("txtfromdate")).value; if (this.FromDate != '') { this.FromDate = this.FromDate.toLocaleLowerCase(); this.listICurrencyHistory = this.listICurrencyHistory.filter ( x => x.FromDate != null && x.FromDate.toLocaleString().indexOf(this.FromDate) != -1); } this.ToDate = (<HTMLInputElement>document.getElementById("txttodate")).value; if (this.ToDate != '') { this.ToDate = this.ToDate.toLocaleLowerCase(); this.listICurrencyHistory = this.listICurrencyHistory.filter ( x => x.ToDate != null && x.ToDate.toLocaleString().indexOf(this.ToDate) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); }); //,error => this.msg = <any>error } BindCurrencyDropdown() { this._CurrencyService.get(Global.BASE_CURRENCY_ENDPOINT). subscribe(currencylist => { this.lstCurrency = currencylist; }) } addCurrencyhistory() { this.dbops = DBOperation.create; this.modalTitle = "Add New Currency History"; this.modalBtnTitle = "Add"; this.objICurrencyHistory.Currency_Id = 0; this.objICurrencyHistory.Default_Exch_Rate = 0; this.objICurrencyHistory.Current_Exch_Rate = 0; this.objICurrencyHistory.Month_Entered = 1; this.YearNow = this.ToDayDate.getFullYear(); this.objICurrencyHistory.Year_Entered = this.YearNow; this.modal.open(); } editCurrencyhistory(id: number) { this.dbops = DBOperation.update; this.modalTitle = "Edit Currency"; this.modalBtnTitle = "Update"; this.objICurrencyHistory = this.listICurrencyHistory.filter(x => x.Id == id)[0]; this.YearNow = this.ToDayDate.getFullYear(); if (this.objICurrencyHistory.Year_Entered < this.YearNow) { this.objICurrencyHistory.Year_Entered = this.YearNow; } this.modal.open(); } deleteCurrencyhistory(id: number, status: boolean) { this.dbops = DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.objICurrencyHistory = this.listICurrencyHistory.filter(x => x.Id == id)[0]; this.YearNow = this.ToDayDate.getFullYear(); if (this.objICurrencyHistory.Year_Entered < this.YearNow) { this.objICurrencyHistory.Year_Entered = this.YearNow; } this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.currencyFrm.enable() : this.currencyFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.listICurrencyHistory); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: ICurrencyHistory) { this.msg = ""; if (formData.Currency_Id != 0) { switch (this.dbops) { case DBOperation.create: this._CurrencyHistoryService.post(Global.BASE_CurrencyHistoryAPI_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadCurrencyHistory(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._CurrencyHistoryService.put(Global.BASE_CurrencyHistoryAPI_ENDPOINT, formData.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadCurrencyHistory(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._CurrencyHistoryService.delete(Global.BASE_CurrencyHistoryAPI_ENDPOINT, formData.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Currency status changed successfully."; this.LoadCurrencyHistory(); } else { this.msg = "Error has occurred while changing status of existing currency!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } else { alert("Please Select Currency !"); } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { CommonConfigurationService } from '../../../service/Masters/Configuration/CommonConfiguration.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ICommonConfiguration } from '../../../Model/Masters/Configuration/CommonConfiguration'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [CommonConfigurationService], templateUrl: 'app/Components/Masters/Configuration/CommonConfiguration.component.html' }) export class CommonConfigurationComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; commonconfigurations: ICommonConfiguration[]; commonconfiguration: ICommonConfiguration; msg: string; indLoading: boolean = false; CommonConfigurationFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; CommonConfigurationFilter: string; isDesc: boolean = false; column: any = 'EventName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; nums: number[]; constructor(private fb: FormBuilder, private _CommonConfigurationService: CommonConfigurationService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.LoadCommonConfiguration(); this.commonconfiguration = ({ Id: 0, URLLocal: '', URLLive: '', MinimumLunchBreak: 0, MinimumOtherBreak: 0, MouseMinutes: 0, PlusMouseMinutes: 0, MouseTracking: 0, ProductivityTracker: 0, WorksheetPrompt: 0, MinimumPunchoutInterval: 0, InTimeMondayToFridayHH: 0, InTimeMondayToFridayMM: 0, OutTimeMondayToFridayHH: 0, OutTimeMondayToFridayMM: 0, InTimeSaturdayHH: 0, InTimeSaturdayMM: 0, OutTimeSaturdayHH: 0, OutTimeSaturdayMM: 0, ShiftDurationHH: 0, ShiftDurationMM: 0, TDSMenuHideOrShow: '', RoleMenu: '', CreatedOn: null, CreatedBy: '', UpdatedOn: null, UpdatedBy: '', IsActive: false }) } LoadCommonConfiguration(): void { this.indLoading = true; this._CommonConfigurationService.getallconfiguration(Global.BASE_COMMONCONFIGURATION_ENDPOINT) .subscribe(data => { this.commonconfiguration = data; this.indLoading = false; } //,error => this.msg = <any>error ); } SetControlsState(isEnable: boolean) { isEnable ? this.CommonConfigurationFrm.enable() : this.CommonConfigurationFrm.disable(); } onSubmit(formData: ICommonConfiguration) { this.msg = ""; console.log(formData); this._CommonConfigurationService.put(Global.BASE_COMMONCONFIGURATION_ENDPOINT, formData.Id, formData).subscribe( data => { //if (data == "Success") { if (data.startsWith("Success: "))//Success { $("html, body").animate({ scrollTop: 590 }, 250); this.msg = data; this.LoadCommonConfiguration(); } else { alert(data); } }, error => { this.msg = error; } ); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.Attendance { public class MySkill : VISBaseEntity { public string mode { get; set; } public Int64 UserID { get; set; } public int SkillID { get; set; } public string SkillName { get; set; } public string SkillGroup { get; set; } public string Skilltext { get; set; } public Int64 lookupSkilId { get; set; } public string Name { get; set; } public Int64 skillgroupid { get; set; } public string status { get; set; } public bool IsApproved { get; set; } public Int64 id { get; set; } } public static class MySkillConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_MySkill = "MySkill"; /// <summary> /// Database table field Name Constants. /// </summary> /// public const string const_Filed_id = "id"; public const string const_Field_mode = "mode"; public const string const_Field_UserId = "UserId"; public const string const_Field_SkillName = "SkillName"; public const string const_Field_SkillGroup = "SkillGroup"; public const string const_Field_Skilltext = "Skilltext"; public const string const_Field_SkillID = "SkillID"; public const string const_Field_lookupSkilId = "lookupSkilId"; public const string const_Field_Name = "Name"; public const string const_Field_skillgroupid = "skillgroupid"; public const string const_Field_status = "status"; public const string const_Field_IsApproved = "IsApproved"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_procGetMySkill = "procGetMySkill"; public const string const_procDeleteSkill = "procDeleteSkill"; public const string const_procSkillUser_Add = "procSkillUser_Add"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var BankMaster_service_1 = require("../../../service/Masters/CompanyRelated/BankMaster.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); //import * as _ from 'underscore'; var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var BankMasterComponent = (function () { function BankMasterComponent(fb, _BankMasterService, pagerService, _CommonHelperService) { this.fb = fb; this._BankMasterService = _BankMasterService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.indLoading = false; this.isDesc = false; this.column = 'BankName'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; } BankMasterComponent.prototype.Resetmodel = function () { this.bankmaster = { AccountNumber: '', BankAddress: '', BankAlias: '', BankDetail: '', BankName: '', BranchName: '', CompanyId: 0, CreatedBy: '', CreatedOn: null, CurrencyId: 0, Id: 0, IsActive: false, Status: false, UpdatedBy: '', UpdatedOn: null, EntityMessage: '', }; }; BankMasterComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.BankMasterFrm = this.fb.group({ Id: [''], BankAlias: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(1), forms_1.Validators.maxLength(50)])], BankName: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(50)])], BranchName: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(50)])], BankAddress: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(100)])], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], BankDetail: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(50)])], CreatedBy: [''], UpdatedBy: [''], AccountNumber: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(1), forms_1.Validators.maxLength(50)])], Status: [''], CompanyId: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(1), forms_1.Validators.maxLength(50)])], CurrencyId: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(1), forms_1.Validators.maxLength(50)])], EntityMessage: [''] }); this.LoadBankMaster(); this.GetCompany(); this.GetCurrency(); }; BankMasterComponent.prototype.BankFilterCriteriaChange = function (value) { if (value != '[object Event]') this.BankMasterFilter = value; }; BankMasterComponent.prototype.BankMasterSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; BankMasterComponent.prototype.LoadBankMaster = function () { var _this = this; this.indLoading = true; this._BankMasterService.get(global_1.Global.BASE_BANKMASTER_ENDPOINT) .subscribe(function (bankmasters) { _this.bankmasters = bankmasters; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchBankAlias = document.getElementById("searchBankAlias").value; if (_this.strSearchBankAlias != '') { _this.strSearchBankAlias = _this.strSearchBankAlias.toLocaleLowerCase(); _this.bankmasters = _this.bankmasters.filter(function (x) { return x.BankAlias != null && x.BankAlias.toLocaleLowerCase().indexOf(_this.strSearchBankAlias) != -1; }); } _this.strSearchBankName = document.getElementById("searchBankName").value; if (_this.strSearchBankName != '') { _this.strSearchBankName = _this.strSearchBankName.toLocaleLowerCase(); _this.bankmasters = _this.bankmasters.filter(function (x) { return x.BankName != null && x.BankName.toLocaleLowerCase().indexOf(_this.strSearchBankName) != -1; }); } _this.strSearchBranchName = document.getElementById("searchBranchName").value; if (_this.strSearchBranchName != '') { _this.strSearchBranchName = _this.strSearchBranchName.toLocaleLowerCase(); _this.bankmasters = _this.bankmasters.filter(function (x) { return x.BranchName != null && x.BranchName.toLocaleLowerCase().indexOf(_this.strSearchBranchName) != -1; }); } _this.strSearchBankAddress = document.getElementById("searchBankAddress").value; if (_this.strSearchBankAddress != '') { _this.strSearchBankAddress = _this.strSearchBankAddress.toLocaleLowerCase(); _this.bankmasters = _this.bankmasters.filter(function (x) { return x.BankAddress != null && x.BankAddress.toLocaleLowerCase().indexOf(_this.strSearchBankAddress) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; BankMasterComponent.prototype.AddBankMaster = function () { this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Bank"; this.modalBtnTitle = "Add"; this.Resetmodel(); this.BankMasterFrm.setValue(this.bankmaster); this.modal.open(); }; BankMasterComponent.prototype.editBankMaster = function (id) { this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Bank"; this.modalBtnTitle = "Update"; this.bankmaster = this.bankmasters.filter(function (x) { return x.Id == id; })[0]; this.BankMasterFrm.setValue(this.bankmaster); this.modal.open(); }; BankMasterComponent.prototype.deleteBankMaster = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.bankmaster = this.bankmasters.filter(function (x) { return x.Id == id; })[0]; this.BankMasterFrm.setValue(this.bankmaster); this.modal.open(); }; BankMasterComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.BankMasterFrm.enable() : this.BankMasterFrm.disable(); }; BankMasterComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; BankMasterComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.bankmasters); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; BankMasterComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; BankMasterComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._BankMasterService.post(global_1.Global.BASE_BANKMASTER_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadBankMaster(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._BankMasterService.put(global_1.Global.BASE_BANKMASTER_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadBankMaster(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._BankMasterService.delete(global_1.Global.BASE_BANKMASTER_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "Bank status changed successfully."; _this.LoadBankMaster(); } else { _this.msg = "Error has occurred while changing status of existing Bank!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; BankMasterComponent.prototype.GetCompany = function () { var _this = this; this.indLoading = true; this._BankMasterService.getcompany(global_1.Global.BASE_BANKMASTER_ENDPOINT) .subscribe(function (companylist) { _this.company = companylist; }); }; BankMasterComponent.prototype.GetCurrency = function () { var _this = this; this.indLoading = true; this._BankMasterService.getcurrency(global_1.Global.BASE_BANKMASTER_ENDPOINT) .subscribe(function (currencylist) { _this.currency = currencylist; }); }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], BankMasterComponent.prototype, "modal", void 0); BankMasterComponent = __decorate([ core_1.Component({ providers: [BankMaster_service_1.BankMasterService], templateUrl: 'app/Components/Masters/CompanyRelated/BankMaster.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, BankMaster_service_1.BankMasterService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], BankMasterComponent); return BankMasterComponent; }()); exports.BankMasterComponent = BankMasterComponent; <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Dashboard; namespace VIS_Repository.Dashboard { public class DashboardRepository : VISDbCommand { public DataSet DashboardDataSet { get; set; } public DashboardRepository(string _connectionstring) : base(_connectionstring) { } public DataSet ReturnDataSetFromSP(string strSPNameOrQuery, SqlParameter[] SPParameters) { DataSet ds = new DataSet(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = strSPNameOrQuery; base.objSqlCommand.Parameters.AddRange(SPParameters); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(ds); } return ds; } public object ReturnScalarValueFromFunction(string strSPNameOrQuery) { object retValue = null; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = CommandType.Text; base.objSqlCommand.CommandText = strSPNameOrQuery; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } retValue = base.objSqlCommand.ExecuteScalar(); } return retValue; } private DataTable ReturnDataTableForSection(string strSectioName) { DataTable dtReturn = new DataTable(); foreach (DataTable dt in DashboardDataSet.Tables) { if (dt.Columns[dt.Columns.Count - 1].ColumnName == strSectioName) { return dt; } } return dtReturn; } public List<T> MapSection<T>(string strSectionName, bool blnSingleRow = false) { List<T> ObjectOfT = new List<T>(); DataTable dtCurrent = ReturnDataTableForSection(strSectionName); if (dtCurrent.Rows.Count > 0) { if (blnSingleRow) { ObjectOfT.Add(VISAutoMapper.ConvertDataRow<T>(dtCurrent.Rows[0])); } else { ObjectOfT.AddRange(VISAutoMapper.ConvertDataTable<T>(dtCurrent)); } } return ObjectOfT; } public DashboardData GetDashboardDataSets(int UserId, bool IsApproved, string strStartDate, string strEndDate, bool IsLineManager, DateTime date, int PunchInId, bool IsAdmin) { DashboardData objDashboardData = new DashboardData(); try { SqlParameter[] sqlParameters = new SqlParameter[8]; sqlParameters[0] = new SqlParameter("Id", UserId); sqlParameters[1] = new SqlParameter("IsApproved", IsApproved); sqlParameters[2] = new SqlParameter("StartDate", strStartDate); sqlParameters[3] = new SqlParameter("EndDate", strEndDate); sqlParameters[4] = new SqlParameter("IsLineManager", IsLineManager); sqlParameters[5] = new SqlParameter("Date", date); sqlParameters[6] = new SqlParameter("PunchInId", PunchInId); sqlParameters[7] = new SqlParameter("IsAdmin", IsAdmin); DashboardDataSet = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (DashboardDataSet.Tables.Count > 0) { objDashboardData.UserProfileData = MapSection<MyProfile>("MyProfile", true)[0]; objDashboardData.UserSkillData = MapSection<MySkill>("MySkill", false); objDashboardData.UserAllocationData = MapSection<MyAllocation>("MyAllocation", false); objDashboardData.UserTeamData = MapSection<MyTeam>("MyTeam", false); objDashboardData.UserAlertData= MapSection<MyAlerts>("MyAlerts", false); //objDashboardData.UserLeaveDetails = MapSection<MyLeaveDetails>("MyLeaveDetails", false); //objDashboardData.UserNwdHistory= MapSection<MyNwdHistory>("NwdHistory", false); //objDashboardData.UserCalTotalAttendanceData = MapSection<CalTotalAttendance>("CalTotalAttendance",true)[0]; //objDashboardData.UserActualEntryTimeAndGracePeriod = MapSection<ActualEntryTimeAndGracePeriod>("ActualEntryTimeAndGracePeriod", true)[0]; //objDashboardData.UserLeaveLedgerData = MapSection<LeaveLedgerData>("LeaveLedgerData", false); //objDashboardData.UserLeaveDetailsByDate = MapSection<LeaveDetailsByDate>("LeaveDetailsByDate", false); //objDashboardData.UserHolidayListForEmployeeData = MapSection<HolidayListForEmployee>("HolidayListForEmployee", false); //objDashboardData.HolidayForDateData = MapSection<HolidayForDate>("HolidayForDate", false); } return objDashboardData; } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); return null; } } public MyProfile GetProfileInformationForUser(Int32 UserId) { MyProfile objEntityToReturn = new MyProfile(); SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter("Id", UserId); DataSet DashboardDataSet = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetProfileById, sqlParameters); if (DashboardDataSet.Tables.Count > 0) { objEntityToReturn = VISAutoMapper.ConvertDataRow<MyProfile>(DashboardDataSet.Tables[0].Rows[0]); } return objEntityToReturn; } #region UserDo //UserDO public DataSet GetAllUser(Int32 UserId, string userType) { //procGetAllUesrForLoggedInUser => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@usertype", userType); DataSet DashboardDataSet = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetAllUser, sqlParameters); return DashboardDataSet; } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } } public DataSet UserDetailById(Int32 UserId) { //procGetUserDetailById => This is the SP which can be called to remove logic below. DataSet dsUserDetail = new DataSet(); try { SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); dsUserDetail = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetUserDetailById, sqlParameters); if (dsUserDetail != null && dsUserDetail.Tables.Count > 0 && dsUserDetail.Tables[0].Rows.Count > 0) { return dsUserDetail; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } public DataSet GetAllUserWithOutLM(Int32 UserId, string userType) { //procGetAllUserWithOutLM => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@usertype", userType); DataSet dsAllUserWithOutLM = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetAllUserWithOutLM, sqlParameters); return dsAllUserWithOutLM; } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } } #endregion #region Profile //BLProfile public DataSet GetProfileById(Int32 UserId) { //procGetProfileById => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet dsProfile = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetProfileById, sqlParameters); if (dsProfile != null && dsProfile.Tables.Count > 0 && dsProfile.Tables[0].Rows.Count > 0) { return dsProfile; } else { return null; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } } public DataSet getprojectallocationdetails(Int32 userid, string strfromdate, string strtodate) { //procgetprojectallocationdetails => this is the sp which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[3]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, userid); sqlParameters[1] = new SqlParameter("@StartDate", strfromdate); sqlParameters[2] = new SqlParameter("@EndDate", strtodate); DataSet dsprojectallocationdetails = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (dsprojectallocationdetails != null && dsprojectallocationdetails.Tables.Count > 0 && dsprojectallocationdetails.Tables[0].Rows.Count > 0) { return dsprojectallocationdetails; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } public DataSet GetShortProfileDetails(int UserId, string UserType) { //ProcGetShortProfileDetails => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[3]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@usertype", UserType); DataSet dsprojectallocationdetails = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetShortProfileDetails, sqlParameters); if (dsprojectallocationdetails != null && dsprojectallocationdetails.Tables.Count > 0) { return dsprojectallocationdetails; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } #endregion #region Attendance /***************** Get Week Attendance Record ******************/ public DataTable getWeekAttendanceReport(string UserId, string strStartDate, string strEndDate) { DataTable dtAttendance = new DataTable("Attendance"); DateTime startDate = DateTime.Now; DateTime endDate = DateTime.Now; //IFormatProvider provider = new System.Globalization.CultureInfo("es-ES", true); try { //SqlParameter[] _para = new SqlParameter[2]; dtAttendance.Columns.Add("Employee_Name", Type.GetType("System.String")); dtAttendance.Columns.Add("Employee_Id", Type.GetType("System.String")); dtAttendance.Columns.Add("Date", Type.GetType("System.String")); dtAttendance.Columns.Add("In_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("Out_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchOut_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchIn_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("Other_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("Total_Hr", Type.GetType("System.String")); dtAttendance.Columns.Add("TotalWorksheet_Hr", Type.GetType("System.String")); dtAttendance.Columns.Add("diff", Type.GetType("System.String")); dtAttendance.Columns.Add("status", Type.GetType("System.String")); dtAttendance.Columns.Add("InId", Type.GetType("System.String")); dtAttendance.Columns.Add("OutId", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchOutId", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchInId", Type.GetType("System.String")); dtAttendance.Columns.Add("OtherId", Type.GetType("System.String")); dtAttendance.Columns.Add("TotalId", Type.GetType("System.String")); string strEmployee_Name = GetEmployee_Name(UserId); startDate = convertStrToDate(strStartDate); endDate = convertStrToDate(strEndDate); //_para[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); //_para[1] = new SqlParameter("@Date", startDate.ToString("yyyymmdd")); SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@Date", startDate.ToString("yyyymmdd")); //DataSet dsTripLeave = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetLeaveFormDetail, _para); DataSet DashboardDataSet = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); TimeSpan tsDays = endDate - startDate; int totalDays = tsDays.Days + 1; for (int i = 0; i < totalDays; i++) { string strDate = startDate.ToString("yyyy-MM-dd"); string[] arrDate = strDate.Split('/'); sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@Date", startDate.ToString("yyyymmdd")); //DataSet dsNWD = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetNWDHistoryForEmpForDate, sqlParameters); DataSet dsNWD = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (dsNWD != null && dsNWD.Tables.Count > 0 && dsNWD.Tables[0].Rows.Count > 0) { if (dsNWD.Tables[0].Columns.Contains("leaveType") == true) { if (DashboardDataSet != null && DashboardDataSet.Tables.Count > 0 && DashboardDataSet.Tables[0].Rows.Count > 0) { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "OnTrip/" + Convert.ToString(dsNWD.Tables[0].Rows[0]["leaveType"]), false, false, dtAttendance); } else { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "NWD/" + Convert.ToString(dsNWD.Tables[0].Rows[0]["leaveType"]), false, false, dtAttendance); } } else { if (DashboardDataSet != null && DashboardDataSet.Tables.Count > 0 && DashboardDataSet.Tables[0].Rows.Count > 0) { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "OnTrip/" + Convert.ToString(dsNWD.Tables[0].Rows[0]["leaveType"]), false, false, dtAttendance); } else { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "", true, false, dtAttendance); } } } else { sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter("@EmployeeID", UserId); sqlParameters[1] = new SqlParameter("@LeaveDate", startDate.ToString("yyyyMMdd")); //DataSet dsLeave = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetEmpLeaveLedgerForDate, sqlParameters); DataSet dsLeave = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { DataTable dt = GetLeaveDetailsByDate(Convert.ToInt32(UserId), startDate.ToString("yyyyMMdd")); if (dt != null && dt.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dt.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dt.Rows[0]["leaveType"].ToString(); dr["approveType"] = dt.Rows[0]["approveType"].ToString(); dr["shortLeaveType"] = dt.Rows[0]["shortLeaveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave != null && dsLeave.Tables.Count > 0 && dsLeave.Tables[0].Rows.Count > 0) { if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { //New change.. dtAttendance = getweekattendancerecord(strDate, UserId, false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false, dtAttendance); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); dtAttendance = getweekattendancerecord(strDate, UserId, true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true, dtAttendance); } else { dtAttendance = getweekattendancerecord(strDate, UserId, true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false, dtAttendance); } } } else { sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter("@Date", strDate); //DataSet dsHoliDay = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetEmpHolidayListForDate, _para); DataSet dsHoliDay = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (dsHoliDay != null && dsHoliDay.Tables.Count > 0 && dsHoliDay.Tables[0].Rows.Count > 0 && dsHoliDay.Tables[0].Columns.Contains("holidayName") == true) { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", dsHoliDay.Tables[0].Rows[0]["holidayName"].ToString(), false, false, dtAttendance); } else { sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter("@Date", strDate); //dsHoliDay = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetHolidayForDate, _para); dsHoliDay = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetHolidayForDate, sqlParameters); if (dsHoliDay != null && dsHoliDay.Tables.Count > 0 && dsHoliDay.Tables[0].Rows.Count > 0 && dsHoliDay.Tables[0].Columns.Contains("holidayName") == true) { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", dsHoliDay.Tables[0].Rows[0]["holidayName"].ToString(), false, false, dtAttendance); } else { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "", true, false, dtAttendance); } } dsHoliDay = null; } dsLeave = null; } dsNWD = null; dtAttendance.Rows[i]["Employee_Name"] = strEmployee_Name; startDate = startDate.AddDays(1); } } catch (Exception ex) { string lineNum = ex.StackTrace.Substring(ex.StackTrace.Length - 10, 10); throw new Exception(ex.Message.ToString()); } return dtAttendance; } protected DataTable getweekattendancerecord(string date, string empid, Boolean halfleave, string leavetype, string approvetype, Boolean checkhrs, Boolean twohalfleavesameday, DataTable dtattendance) { //Proccaltotalattendancereport => this is the sp which can be called to remove logic below. try { DataRow dr; #region new changes //DateTime getdaterecord = Convert.ToDateTime(date, provider); SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter("@EmployeeID", empid); sqlParameters[1] = new SqlParameter("@Date", date); DataSet dstemp = ReturnDataSetFromSP(DashboardConstsants.const_Proc_Getweekattendancerecord, sqlParameters); if (dstemp.Tables.Count > 0 && dstemp.Tables[0].Rows.Count > 0) { dr = dtattendance.NewRow(); dr["employee_id"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["employeeid"].ToString()) ? dstemp.Tables[0].Rows[0]["employeeid"].ToString() : ""; dr["employee_name"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["employeename"].ToString()) ? dstemp.Tables[0].Rows[0]["employeename"].ToString() : ""; dr["date"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["date"].ToString()) ? dstemp.Tables[0].Rows[0]["date"].ToString() : ""; if (!string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["intime"].ToString())) { dr["inid"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["intimeid"].ToString()) ? dstemp.Tables[0].Rows[0]["intimeid"].ToString() : ""; dr["in_time"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["intime"].ToString()) ? dstemp.Tables[0].Rows[0]["intime"].ToString() : ""; if (dr["inid"].ToString() != "") { int intPunchInID = Convert.ToInt32(dr["inid"]); SqlParameter[] _para = new SqlParameter[1]; _para[0] = new SqlParameter("PunchInId", intPunchInID); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetActualEntryTimeAndGraceForPunchInId, _para); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { string[] arr = ds.Tables[0].Rows[0]["actualentrytime"].ToString().Split(':'); if (arr.Length > 1) { TimeSpan punchinactual = new TimeSpan(Convert.ToInt32(arr[0]), Convert.ToInt32(arr[1]), 0); TimeSpan tsgrace; TimeSpan actualinwithgrace; DateTime dtpunchin = Convert.ToDateTime(dr["in_time"]); TimeSpan punchin = new TimeSpan(dtpunchin.Hour, dtpunchin.Minute, dtpunchin.Second); string strgrace = ""; DateTime dtgetdate = Convert.ToDateTime(date); strgrace = ds.Tables[0].Rows[0]["grace"].ToString(); tsgrace = new TimeSpan(0, Convert.ToInt32(strgrace), 0); actualinwithgrace = punchinactual.Add(tsgrace); if (halfleave) { } else { if (punchin > actualinwithgrace) { dr["diff"] = dr["diff"].ToString() + "i"; } } } } } Boolean isinoffice = Convert.ToBoolean(dstemp.Tables[0].Rows[0]["isinoffice"]); Boolean isinbreak = Convert.ToBoolean(dstemp.Tables[0].Rows[0]["isinbreak"]); Boolean isinlunch = Convert.ToBoolean(dstemp.Tables[0].Rows[0]["isinlunch"]); if (isinoffice || isinbreak || isinlunch) { dr["out_time"] = ""; dr["outid"] = ""; } else { dr["out_time"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["outtime"].ToString()) ? dstemp.Tables[0].Rows[0]["outtime"].ToString() : ""; dr["outid"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["outtimeid"].ToString()) ? dstemp.Tables[0].Rows[0]["outtimeid"].ToString() : ""; } dr["lunchout_time"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["lunchouttime"].ToString()) ? dstemp.Tables[0].Rows[0]["lunchouttime"].ToString() : ""; dr["lunchoutid"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["lunchouttimeid"].ToString()) ? dstemp.Tables[0].Rows[0]["lunchouttimeid"].ToString() : ""; if (isinlunch) { dr["lunchin_time"] = ""; dr["lunchinid"] = ""; } else { dr["lunchin_time"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["lunchintime"].ToString()) ? dstemp.Tables[0].Rows[0]["lunchintime"].ToString() : ""; dr["lunchinid"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["lunchintimeid"].ToString()) ? dstemp.Tables[0].Rows[0]["lunchintimeid"].ToString() : ""; } dr["otherid"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["othertimeid"].ToString()) ? dstemp.Tables[0].Rows[0]["othertimeid"].ToString() : ""; dr["other_time"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["totalothertime"].ToString()) ? dstemp.Tables[0].Rows[0]["totalothertime"].ToString() : ""; string strworksheethours = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["totalworksheethours"].ToString()) ? dstemp.Tables[0].Rows[0]["totalworksheethours"].ToString() : ""; strworksheethours = strworksheethours.Replace('.', ':') + ":00"; string[] arrworksheethours = strworksheethours.Split(':'); TimeSpan tsworksheethours = new TimeSpan(); tsworksheethours = new TimeSpan(Convert.ToInt32(arrworksheethours[0]), Convert.ToInt32(arrworksheethours[1]), 0); //dr["totalworksheet_hr"] = tsworksheethours.tostring(); dr["totalworksheet_hr"] = strworksheethours.ToString(); if (checkhrs) { if (halfleave) { if (string.Compare(approvetype, "uupl", true) == 0) { dr["status"] = approvetype + "/" + leavetype; } else { if (approvetype.Split('/')[0] == "official trip") { dr["status"] = "ontrip" + "/" + leavetype; } else { dr["status"] = approvetype; } } } else { dr["status"] = "present"; } } else { if (dr["inid"].ToString() != "") { dr["status"] = "present"; } else { dr["status"] = approvetype; } } dr["other_time"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["totalothertime"].ToString()) ? dstemp.Tables[0].Rows[0]["totalothertime"].ToString() : ""; ; dr["total_hr"] = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["totalworkingtime"].ToString()) ? dstemp.Tables[0].Rows[0]["totalworkingtime"].ToString() : ""; string strtotalofficetime = !string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["totalofficetime"].ToString()) ? dstemp.Tables[0].Rows[0]["totalofficetime"].ToString() : ""; TimeSpan tstotalofficetime = new TimeSpan(); if (dr["total_hr"].ToString() != "") { string[] arrtotalofficetime = dr["total_hr"].ToString().Split(':'); tstotalofficetime = new TimeSpan(Convert.ToInt32(arrtotalofficetime[0]), Convert.ToInt32(arrtotalofficetime[1]), Convert.ToInt32(arrtotalofficetime[2])); } else { tstotalofficetime = new TimeSpan(0, 0, 0); } TimeSpan tstotalworkingtime = new TimeSpan(); if (strtotalofficetime != "") { string[] arrtotalworksheet_hr = strtotalofficetime.Split(':'); tstotalworkingtime = new TimeSpan(Convert.ToInt32(arrtotalworksheet_hr[0]), Convert.ToInt32(arrtotalworksheet_hr[1]), Convert.ToInt32(arrtotalworksheet_hr[2])); } else { tstotalworkingtime = new TimeSpan(0, 0, 0); } if (halfleave) { TimeSpan temp = new TimeSpan(4, 15, 0); // for working hrs... if (tstotalofficetime < temp) { if (checkhrs) { dr["diff"] = dr["diff"].ToString() + "t"; } } temp = new TimeSpan(5, 0, 0); // for total hrs... if (tstotalworkingtime < temp) { if (checkhrs) { dr["diff"] = dr["diff"].ToString() + "o"; } } } else { TimeSpan temp = new TimeSpan(8, 30, 0); // for working hrs... if (checkhrs && isinoffice == false && isinbreak == false && isinlunch == false) { if (tstotalofficetime < temp) { dr["diff"] = dr["diff"].ToString() + "t"; } temp = new TimeSpan(9, 30, 0); // for total hrs... if (tstotalworkingtime < temp) { dr["diff"] = dr["diff"].ToString() + "o"; } } //created by darshan 14/03/2011... //this if condition check which not apply leave application //and taken half leave so status will be change if less then 2 hours then "uupl" // or less then 7 hours then "0.5/uupl" if (!isinoffice && !isinlunch && !isinbreak) { temp = new TimeSpan(7, 0, 0); if (tstotalofficetime < temp) { temp = new TimeSpan(2, 0, 0); if (tstotalofficetime < temp) { dr["status"] = "uupl"; } else { dr["status"] = "0.5/uupl"; } } } } dr["totalid"] = "0"; if (dr["outid"].ToString() == "") { dr["total_hr"] = ""; } if (string.IsNullOrEmpty(dstemp.Tables[0].Rows[0]["othertimeid"].ToString())) { dr["other_time"] = ""; } if (dr["in_time"].ToString() != "") { dr["in_time"] = Convert.ToDateTime(dr["in_time"].ToString()).ToString("hh:mm:ss"); } if (dr["out_time"].ToString() != "") { dr["out_time"] = Convert.ToDateTime(dr["out_time"].ToString()).ToString("hh:mm:ss"); } } else { if (checkhrs) { if (twohalfleavesameday) { //oldnew//dr["status"] = approvetype; if (string.Compare(approvetype, "uupl", true) == 0) { dr["status"] = approvetype + "/" + leavetype; } else { if (approvetype.Split('/')[0] == "official trip") { dr["status"] = "ontrip" + "/" + leavetype; } else { dr["status"] = approvetype; } } } else { if (halfleave && checkhrs) { dr["status"] = leavetype == "fh" ? approvetype + " , uupl/sh" : "uupl/fh , " + approvetype; } else { dr["status"] = "uupl/fl"; } } } else { if (approvetype.Split('/')[0] == "official trip") { dr["status"] = "ontrip/fl"; } else { dr["status"] = approvetype; } } dr["in_time"] = ""; dr["inid"] = ""; dr["out_time"] = ""; dr["outid"] = ""; dr["lunchout_time"] = ""; dr["lunchin_time"] = ""; dr["other_time"] = ""; dr["total_hr"] = ""; dr["diff"] = ""; dr["totalid"] = ""; } dtattendance.Rows.Add(dr); } #endregion } catch (Exception ex) { string lineNum = ex.StackTrace.Substring(ex.StackTrace.Length - 10, 10); throw new Exception(ex.Message.ToString()); } finally { } return dtattendance; } /***************** End ******************/ /**************** Get Month Attendanace Report ***********************/ public DataTable getMonthAttendanaceReport(string UserId, string strMonthStartDate, string strMonthEndDate) { DataTable dtAttendance = new DataTable("Attendance"); DateTime startDate = DateTime.Now; DateTime endDate = DateTime.Now; try { string strEmployeeName = GetEmployee_Name(UserId); startDate = convertStrToDate(strMonthStartDate); endDate = convertStrToDate(strMonthEndDate); dtAttendance.Columns.Add("Employee_Name", Type.GetType("System.String")); dtAttendance.Columns.Add("Employee_Id", Type.GetType("System.String")); dtAttendance.Columns.Add("Date", Type.GetType("System.String")); dtAttendance.Columns.Add("In_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("Out_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchOut_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchIn_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("Other_Time", Type.GetType("System.String")); dtAttendance.Columns.Add("Total_Hr", Type.GetType("System.String")); dtAttendance.Columns.Add("TotalWorksheet_Hr", Type.GetType("System.String")); dtAttendance.Columns.Add("diff", Type.GetType("System.String")); dtAttendance.Columns.Add("status", Type.GetType("System.String")); dtAttendance.Columns.Add("InId", Type.GetType("System.String")); dtAttendance.Columns.Add("OutId", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchOutId", Type.GetType("System.String")); dtAttendance.Columns.Add("LunchInId", Type.GetType("System.String")); dtAttendance.Columns.Add("OtherId", Type.GetType("System.String")); dtAttendance.Columns.Add("TotalId", Type.GetType("System.String")); dtAttendance.Columns.Add("color", Type.GetType("System.String")); SqlParameter[] _para = new SqlParameter[2]; _para[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); _para[1] = new SqlParameter("@Date", startDate.ToString("yyyymmdd")); DataSet dsTripLeave = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetLeaveFormDetail, _para); TimeSpan tsDays = endDate - startDate; int totalDays = tsDays.Days + 1; bool IsNWD = false; bool IsHolyDay = false; bool IsLeave = false; string strLeaveType = ""; string strApproveType = ""; for (int i = 0; i < totalDays; i++) { string strDate = startDate.ToString("yyyy-MM-dd"); string[] arrDate = strDate.Split('/'); _para[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); _para[1] = new SqlParameter("@Date", startDate.ToString("yyyymmdd")); DataSet dsNWD = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetNWDHistoryForEmpForDate, _para); IsNWD = false; IsHolyDay = false; IsLeave = false; strLeaveType = ""; if (dsNWD != null && dsNWD.Tables.Count > 0 && dsNWD.Tables[0].Rows.Count > 0) { IsNWD = true; if (dsNWD.Tables[0].Columns.Contains("leaveType") == true) { if (dsTripLeave != null && dsTripLeave.Tables.Count > 0 && dsTripLeave.Tables[0].Rows.Count > 0) { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "OnTrip/" + Convert.ToString(dsNWD.Tables[0].Rows[0]["leaveType"]), false, false, dtAttendance); } else { dtAttendance = getMonthAttendanaceRecord(strDate, UserId, false, "", "NWD/" + dsNWD.Tables[0].Rows[0]["leaveType"].ToString(), false, false, dtAttendance); } } else { if (dsTripLeave != null && dsTripLeave.Tables.Count > 0 && dsTripLeave.Tables[0].Rows.Count > 0) { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "OnTrip/" + Convert.ToString(dsNWD.Tables[0].Rows[0]["leaveType"]), false, false, dtAttendance); } else { dtAttendance = getweekattendancerecord(strDate, UserId, false, "", "", true, false, dtAttendance); } } } else { _para = new SqlParameter[2]; _para[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); _para[1] = new SqlParameter("@Date", startDate.ToString("yyyymmdd")); DataSet dsLeave = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetEmpLeaveLedgerForDate, _para); if (dsLeave == null || dsLeave.Tables[0].Rows.Count == 0) { DataTable dt = GetLeaveDetailsByDate(Convert.ToInt32(UserId), startDate.ToString("yyyyMMdd")); if (dt != null && dt.Rows.Count > 0) { DataRow dr = dsLeave.Tables[0].NewRow(); dr["leaveDuration"] = dt.Rows[0]["leaveDuration"].ToString(); dr["leaveType"] = dt.Rows[0]["leaveType"].ToString(); dr["approveType"] = dt.Rows[0]["approveType"].ToString(); dr["shortLeaveType"] = dt.Rows[0]["shortLeaveType"].ToString(); dsLeave.Tables[0].Rows.Add(dr); } } if (dsLeave != null && dsLeave.Tables.Count > 0 && dsLeave.Tables[0].Rows.Count > 0) { IsLeave = true; if (dsLeave.Tables[0].Columns.Contains("shortLeaveType") == true && dsLeave.Tables[0].Columns.Contains("approveType") == true) { strLeaveType = dsLeave.Tables[0].Rows[0]["shortLeaveType"].ToString(); strApproveType = dsLeave.Tables[0].Rows[0]["approveType"].ToString(); } if (dsLeave.Tables[0].Rows[0]["leaveDuration"].ToString() == "Full") { //New change.. dtAttendance = getMonthAttendanaceRecord(strDate, UserId, false, "", dsLeave.Tables[0].Rows[0]["approveType"].ToString(), false, false, dtAttendance); } else { if (dsLeave.Tables[0].Rows.Count > 1) { string StrApproveTypeName = dsLeave.Tables[0].Rows[0]["approveType"].ToString() + " , " + dsLeave.Tables[0].Rows[1]["approveType"].ToString(); dtAttendance = getMonthAttendanaceRecord(strDate, UserId, true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), StrApproveTypeName, true, true, dtAttendance); } else { dtAttendance = getMonthAttendanaceRecord(strDate, UserId, true, dsLeave.Tables[0].Rows[0]["leaveType"].ToString(), dsLeave.Tables[0].Rows[0]["approveType"].ToString(), true, false, dtAttendance); } } } else { _para = new SqlParameter[1]; _para[0] = new SqlParameter("@Date", strDate); DataSet dsHoliDay = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetEmpHolidayListForDate, _para); if ((dsHoliDay != null) && (dsHoliDay.Tables.Count > 0) && (dsHoliDay.Tables[0].Rows.Count > 0) && (dsHoliDay.Tables[0].Columns.Contains("holidayName") == true)) { IsHolyDay = true; dtAttendance = getMonthAttendanaceRecord(strDate, UserId, false, "", dsHoliDay.Tables[0].Rows[0]["holidayName"].ToString(), false, false, dtAttendance); } else { _para = new SqlParameter[1]; _para[0] = new SqlParameter("@Date", strDate); dsHoliDay = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetHolidayForDate, _para); if ((dsHoliDay != null) && (dsHoliDay.Tables.Count > 0) && (dsHoliDay.Tables[0].Rows.Count > 0) && (dsHoliDay.Tables[0].Columns.Contains("holidayName") == true)) { IsHolyDay = true; dtAttendance = getMonthAttendanaceRecord(strDate, UserId, false, "", dsHoliDay.Tables[0].Rows[0]["holidayName"].ToString(), false, false, dtAttendance); } else { dtAttendance = getMonthAttendanaceRecord(strDate, UserId, false, "", "", true, false, dtAttendance); } } dsLeave = null; dsHoliDay = null; } } dsNWD = null; string strTotal_hr = dtAttendance.Rows[i]["Total_Hr"].ToString(); string strTotal_Worksheet_hr = dtAttendance.Rows[i]["TotalWorksheet_Hr"].ToString(); TimeSpan TotalWorkSheetHr = new TimeSpan(); TimeSpan totalWorkingHr = new TimeSpan(); TimeSpan Below = new TimeSpan(1, 0, 0); TimeSpan Above = new TimeSpan(0, 30, 0); String[] StrWorksheetHrTemp = strTotal_Worksheet_hr.Split(':'); String[] StrWorkingHr = strTotal_hr.Split(':'); bool isIncorrect = false; if (strTotal_hr != null && strTotal_hr != "" && strTotal_Worksheet_hr == "") { isIncorrect = true; } //isIncorrect = strTotal_hr.Contains("-"); if ((!isIncorrect) && (strTotal_Worksheet_hr != "")) { if (StrWorksheetHrTemp.Length > 2) { if (StrWorksheetHrTemp[1].Length < 2) { StrWorksheetHrTemp[1] = StrWorksheetHrTemp[1] + "0"; } TotalWorkSheetHr = new TimeSpan(Convert.ToInt32(StrWorksheetHrTemp[0]), Convert.ToInt32(StrWorksheetHrTemp[1]), 0); if (StrWorkingHr.Length > 1) { totalWorkingHr = new TimeSpan(Convert.ToInt32(StrWorkingHr[0]), Convert.ToInt32(StrWorkingHr[1]), 0); } else { totalWorkingHr = new TimeSpan(0, 0, 0); } if (totalWorkingHr <= TotalWorkSheetHr) { if ((TotalWorkSheetHr - totalWorkingHr) > Above) { dtAttendance.Rows[i]["color"] = "0x3f9dd6"; } else { dtAttendance.Rows[i]["color"] = "0xFFFFFF"; } } else if (TotalWorkSheetHr < totalWorkingHr) { if ((totalWorkingHr - TotalWorkSheetHr) > Below) { dtAttendance.Rows[i]["color"] = "0xD6CF2B"; } else { dtAttendance.Rows[i]["color"] = "0xFFFFFF"; } } else { dtAttendance.Rows[i]["color"] = "0x77797A"; } } else { dtAttendance.Rows[i]["color"] = "0xFFFFFF"; } } else { dtAttendance.Rows[i]["TotalWorksheet_Hr"] = ""; if (IsNWD) { dtAttendance.Rows[i]["color"] = "0x3C7E1A"; } else if (IsHolyDay) { dtAttendance.Rows[i]["color"] = "0x73334B"; } else if (isIncorrect) { dtAttendance.Rows[i]["color"] = "0xFF0000"; } else if (IsLeave) { if (strLeaveType == "CL") { dtAttendance.Rows[i]["color"] = "0x47D447"; } else if (strLeaveType == "SL") { dtAttendance.Rows[i]["color"] = "0xFB643E"; } else if (strLeaveType == "UnPaid") { dtAttendance.Rows[i]["color"] = "0x3595D1"; } else if (strLeaveType == "CO") { dtAttendance.Rows[i]["color"] = "0xC2C239"; } if (strApproveType == "AUPL/FL") { dtAttendance.Rows[i]["color"] = "0xE48701"; } else if (strApproveType == "UUPL") { dtAttendance.Rows[i]["color"] = "0xAAFFAA"; } } else { dtAttendance.Rows[i]["color"] = "0x77797A"; } } dtAttendance.Rows[i]["Employee_Name"] = strEmployeeName; startDate = startDate.AddDays(1); strTotal_hr = ""; strTotal_Worksheet_hr = ""; } } catch (Exception ex) { string lineNum = ex.StackTrace.Substring(ex.StackTrace.Length - 10, 10); throw new Exception(ex.Message.ToString()); } return dtAttendance; } protected DataTable getMonthAttendanaceRecord(string date, string empID, Boolean halfLeave, string leaveType, string approveType, Boolean checkHrs, Boolean TwoHalfLeaveSameDay, DataTable dtAttendance) { //ProcCalTotalAttendanceReport => This is the SP which can be called to remove logic below. DataRow dr; try { #region New Changes //DateTime getdaterecord = Convert.ToDateTime(date, provider); SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter("@EmployeeID", empID); sqlParameters[1] = new SqlParameter("@Date", date); DataSet dsTemp = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetMonthAttendanaceRecord, sqlParameters); if (dsTemp.Tables.Count > 0 && dsTemp.Tables[0].Rows.Count > 0) { dr = dtAttendance.NewRow(); dr["Employee_Id"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["EmployeeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["EmployeeID"].ToString() : ""; dr["Employee_Name"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["EmployeeName"].ToString()) ? dsTemp.Tables[0].Rows[0]["EmployeeName"].ToString() : ""; dr["Date"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["Date"].ToString()) ? dsTemp.Tables[0].Rows[0]["Date"].ToString() : ""; if (!String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTIme"].ToString())) { dr["InId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["InTimeID"].ToString() : ""; dr["In_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["InTIme"].ToString() : ""; if (dr["InId"].ToString() != "") { int intPunchInID = Convert.ToInt32(dr["InId"]); SqlParameter[] _para = new SqlParameter[1]; _para[0] = new SqlParameter("PunchInId", intPunchInID); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetActualEntryTimeAndGraceForPunchInId, _para); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { string[] arr = ds.Tables[0].Rows[0]["actualEntryTime"].ToString().Split(':'); if (arr.Length > 1) { TimeSpan punchInActual = new TimeSpan(Convert.ToInt32(arr[0]), Convert.ToInt32(arr[1]), 0); TimeSpan tsgrace; TimeSpan actualInWithGrace; DateTime dtPunchIN = Convert.ToDateTime(dr["In_Time"]); TimeSpan punchIn = new TimeSpan(dtPunchIN.Hour, dtPunchIN.Minute, dtPunchIN.Second); string strGrace = ""; DateTime dtGetDate = Convert.ToDateTime(date); strGrace = ds.Tables[0].Rows[0]["grace"].ToString(); tsgrace = new TimeSpan(0, Convert.ToInt32(strGrace), 0); actualInWithGrace = punchInActual.Add(tsgrace); if (halfLeave) { } else { if (punchIn > actualInWithGrace) { dr["diff"] = dr["diff"].ToString() + "I"; } } } } } Boolean IsInOffice = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInOffice"]); Boolean IsInBreak = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInBreak"]); Boolean IsInLunch = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInLunch"]); if (IsInOffice || IsInBreak || IsInLunch) { dr["Out_Time"] = ""; dr["OutId"] = ""; } else { dr["Out_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OutTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["OutTIme"].ToString() : ""; dr["OutId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OutTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["OutTimeID"].ToString() : ""; } dr["LunchOut_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchOutTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchOutTIme"].ToString() : ""; dr["LunchOutId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchOutTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchOutTimeID"].ToString() : ""; if (IsInLunch) { dr["LunchIn_Time"] = ""; dr["LunchInId"] = ""; } else { dr["LunchIn_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchInTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchInTIme"].ToString() : ""; dr["LunchInId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchInTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchInTimeID"].ToString() : ""; } dr["OtherId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString() : ""; dr["Other_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString() : ""; string strWorksheetHours = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalWorksheetHours"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalWorksheetHours"].ToString() : ""; strWorksheetHours = strWorksheetHours.Replace('.', ':') + ":00"; string[] arrWorksheetHours = strWorksheetHours.Split(':'); TimeSpan tsWorksheetHours = new TimeSpan(); tsWorksheetHours = new TimeSpan(Convert.ToInt32(arrWorksheetHours[0]), Convert.ToInt32(arrWorksheetHours[1]), 0); //dr["TotalWorksheet_Hr"] = tsWorksheetHours.ToString(); dr["TotalWorksheet_Hr"] = strWorksheetHours.ToString(); if (checkHrs) { if (halfLeave) { if (String.Compare(approveType, "UUPL", true) == 0) { dr["status"] = approveType + "/" + leaveType; } else { if (approveType.Split('/')[0] == "Official Trip") { dr["status"] = "OnTrip" + "/" + leaveType; } else { dr["status"] = approveType; } } } else { dr["status"] = "Present"; } } else { if (dr["InId"].ToString() != "") { dr["status"] = "Present"; } else { dr["status"] = approveType; } } dr["Other_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString() : ""; ; dr["Total_Hr"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalWorkingTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalWorkingTime"].ToString() : ""; string strTotalOfficeTime = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString() : ""; TimeSpan tsTotalOfficeTime = new TimeSpan(); if (dr["Total_Hr"].ToString() != "") { string[] arrTotalOfficeTime = dr["Total_Hr"].ToString().Split(':'); tsTotalOfficeTime = new TimeSpan(Convert.ToInt32(arrTotalOfficeTime[0]), Convert.ToInt32(arrTotalOfficeTime[1]), Convert.ToInt32(arrTotalOfficeTime[2])); } else { tsTotalOfficeTime = new TimeSpan(0, 0, 0); } TimeSpan tsTotalWorkingTime = new TimeSpan(); if (strTotalOfficeTime != "") { string[] arrTotalWorksheet_Hr = strTotalOfficeTime.Split(':'); tsTotalWorkingTime = new TimeSpan(Convert.ToInt32(arrTotalWorksheet_Hr[0]), Convert.ToInt32(arrTotalWorksheet_Hr[1]), Convert.ToInt32(arrTotalWorksheet_Hr[2])); } else { tsTotalWorkingTime = new TimeSpan(0, 0, 0); } if (halfLeave) { TimeSpan temp = new TimeSpan(4, 15, 0); // for working Hrs... if (tsTotalOfficeTime < temp) { if (checkHrs) { dr["diff"] = dr["diff"].ToString() + "T"; } } temp = new TimeSpan(5, 0, 0); // for Total Hrs... if (tsTotalWorkingTime < temp) { if (checkHrs) { dr["diff"] = dr["diff"].ToString() + "O"; } } } else { TimeSpan temp = new TimeSpan(8, 30, 0); // for working Hrs... if (checkHrs && IsInOffice == false && IsInBreak == false && IsInLunch == false) { if (tsTotalOfficeTime < temp) { dr["diff"] = dr["diff"].ToString() + "T"; } temp = new TimeSpan(9, 30, 0); // for Total Hrs... if (tsTotalWorkingTime < temp) { dr["diff"] = dr["diff"].ToString() + "O"; } } //Created by Darshan 14/03/2011... //This If Condition Check which not Apply Leave Application //and taken Half Leave so Status will be change if less then 2 hours then "UUPL" // or Less then 7 hours then "0.5/UUPL" if (!IsInOffice && !IsInLunch && !IsInBreak) { temp = new TimeSpan(7, 0, 0); if (tsTotalOfficeTime < temp) { temp = new TimeSpan(2, 0, 0); if (tsTotalOfficeTime < temp) { dr["status"] = "UUPL"; } else { dr["status"] = "0.5/UUPL"; } } } } dr["TotalId"] = "0"; if (dr["OutId"].ToString() == "") { dr["Total_Hr"] = ""; } if (String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString())) { dr["Other_Time"] = ""; } if (dr["In_Time"].ToString() != "") { dr["In_Time"] = Convert.ToDateTime(dr["In_Time"].ToString()).ToString("hh:mm:ss"); } if (dr["Out_Time"].ToString() != "") { dr["Out_Time"] = Convert.ToDateTime(dr["Out_Time"].ToString()).ToString("hh:mm:ss"); } } else { if (checkHrs) { if (TwoHalfLeaveSameDay) { //OldNew//dr["status"] = approveType; if (String.Compare(approveType, "UUPL", true) == 0) { dr["status"] = approveType + "/" + leaveType; } else { if (approveType.Split('/')[0] == "Official Trip") { dr["status"] = "OnTrip" + "/" + leaveType; } else { dr["status"] = approveType; } } } else { if (halfLeave && checkHrs) { dr["status"] = leaveType == "FH" ? approveType + " , UUPL/SH" : "UUPL/FH , " + approveType; } else { dr["status"] = "UUPL/FL"; } } } else { if (approveType.Split('/')[0] == "Official Trip") { dr["status"] = "OnTrip/FL"; } else { dr["status"] = approveType; } } dr["In_Time"] = ""; dr["InId"] = ""; dr["Out_Time"] = ""; dr["OutId"] = ""; dr["LunchOut_Time"] = ""; dr["LunchIn_Time"] = ""; dr["Other_Time"] = ""; dr["Total_Hr"] = ""; dr["diff"] = ""; dr["TotalId"] = ""; } dtAttendance.Rows.Add(dr); } #endregion } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return dtAttendance; } /***************** End ******************/ public DataTable GetLeaveDetailsByDate(int UserID, string strDate) { //ProcGetLeaveDetailsByDate => This is the SP which can be called to remove logic below. DataTable dt = new DataTable(); dt.Columns.Add("leaveDuration", Type.GetType("System.String")); dt.Columns.Add("leaveType", Type.GetType("System.String")); dt.Columns.Add("approveType", Type.GetType("System.String")); dt.Columns.Add("shortLeaveType", Type.GetType("System.String")); SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserID); sqlParameters[1] = new SqlParameter("@StrDate", strDate); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (ds != null && ds.Tables[0].Rows.Count > 0) { DataRow dr = dt.NewRow(); int CalendarDays = Convert.ToInt32(ds.Tables[0].Rows[0]["CalendarDays"].ToString()); dr["shortLeaveType"] = ds.Tables[0].Rows[0]["LeaveStatus"].ToString(); if (CalendarDays == 0) { if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsFullDay"])) { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } else if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsFirstHalf"])) { dr["leaveDuration"] = "FirstHalf"; dr["leaveType"] = "FH"; } else if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsSecondHalf"])) { dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SH"; } } else { DateTime dtFrom = Convert.ToDateTime(ds.Tables[0].Rows[0]["FromDate"].ToString()); DateTime dtTo = Convert.ToDateTime(ds.Tables[0].Rows[0]["ToDate"].ToString()); DateTime dtCurr = DateTime.ParseExact(strDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); if (dtCurr == dtFrom) { if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsFullDay"])) { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } else if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsSecondHalf"])) { dr["leaveDuration"] = "SecondHalf"; dr["leaveType"] = "SH"; } } else if (dtCurr == dtTo) { if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsFullDay"])) { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } else if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsFirstHalf"])) { dr["leaveDuration"] = "FirstHalf"; dr["leaveType"] = "FH"; } } else { dr["leaveDuration"] = "Full"; dr["leaveType"] = "FL"; } } dr["approveType"] = dr["shortLeaveType"].ToString() + "/" + dr["leaveType"].ToString(); if (dr["shortLeaveType"].ToString() == "Present") { return null; } else { dt.Rows.Add(dr); return dt; } } else { return null; } } #endregion #region Worksheet //blworksheet public DataTable GetMonthWorkSheetReport() { //procGetLeaveFormDetail => this is the sp which can be called to remove logic below. //procGetNWDHistoryForEmpForDate => this is the sp which can be called to remove logic below. //ProcCalTotalAttendanceReport => this is the sp which can be called to remove logic below. //procGetEmpLeaveLedgerForDate => this is the sp which can be called to remove logic below. //ProcGetLeaveDetailsByDate => this is the sp which can be called to remove logic below. Int32 userid = 21; string strmonthstartdate = "2015-06-01"; string strmonthenddate = "2015-06-07"; DataSet dsresult = new DataSet(); DataTable dtattendance = new DataTable("attendance"); DateTime startdate = DateTime.Now; DateTime enddate = DateTime.Now; try { SqlParameter[] _para = new SqlParameter[2]; _para = new SqlParameter[2]; _para[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, userid); _para[1] = new SqlParameter("@Date", startdate.ToString("yyyymmdd")); DataSet dstripleave = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, _para); dtattendance.Columns.Add("employee_name", Type.GetType("system.string")); dtattendance.Columns.Add("employee_id", Type.GetType("system.string")); dtattendance.Columns.Add("date", Type.GetType("system.string")); dtattendance.Columns.Add("in_time", Type.GetType("system.string")); dtattendance.Columns.Add("out_time", Type.GetType("system.string")); dtattendance.Columns.Add("lunchout_time", Type.GetType("system.string")); dtattendance.Columns.Add("lunchin_time", Type.GetType("system.string")); dtattendance.Columns.Add("other_time", Type.GetType("system.string")); dtattendance.Columns.Add("total_hr", Type.GetType("system.string")); dtattendance.Columns.Add("totalworksheet_hr", Type.GetType("system.string")); dtattendance.Columns.Add("diff", Type.GetType("system.string")); dtattendance.Columns.Add("status", Type.GetType("system.string")); dtattendance.Columns.Add("inid", Type.GetType("system.string")); dtattendance.Columns.Add("outid", Type.GetType("system.string")); dtattendance.Columns.Add("lunchoutid", Type.GetType("system.string")); dtattendance.Columns.Add("lunchinid", Type.GetType("system.string")); dtattendance.Columns.Add("otherid", Type.GetType("system.string")); dtattendance.Columns.Add("totalid", Type.GetType("system.string")); dtattendance.Columns.Add("color", Type.GetType("system.string")); dtattendance.Columns.Add("year", Type.GetType("system.string")); dtattendance.Columns.Add("month", Type.GetType("system.string")); dtattendance.Columns.Add("todaydate", Type.GetType("system.string")); dtattendance.Columns.Add("fulldate", Type.GetType("system.string")); startdate = convertStrToDate(strmonthstartdate); enddate = convertStrToDate(strmonthenddate); TimeSpan tsdays = enddate - startdate; int totaldays = tsdays.Days + 1; bool isnwd = false; bool isholyday = false; bool isleave = false; bool isontrip = false; string strleavetype = ""; string strApproveType = ""; for (int i = 0; i < totaldays; i++) { string strdate = startdate.ToString("yyyy-mm-dd"); string[] arrdate = strdate.Split('/'); _para = new SqlParameter[2]; _para[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, userid); _para[1] = new SqlParameter("@Date", startdate.ToString("yyyymmdd")); DataSet dsnwd = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, _para); isnwd = false; isholyday = false; isleave = false; isontrip = false; strleavetype = ""; if (dsnwd != null && dsnwd.Tables.Count > 0 && dsnwd.Tables[0].Rows.Count > 0) { isnwd = true; if (dstripleave != null && dstripleave.Tables.Count > 0 && dstripleave.Tables[0].Rows.Count > 0) { strApproveType = "ontrip/" + dsnwd.Tables[0].Rows[0]["leavetype"].ToString(); isontrip = true; } else { strApproveType = "nwd/" + dsnwd.Tables[0].Rows[0]["leavetype"].ToString(); } dtattendance = getMonthWorksheetRecord(strdate, userid, false, "", strApproveType, false, false, dtattendance); } else { _para = new SqlParameter[2]; _para[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, userid); _para[1] = new SqlParameter("@Date", startdate.ToString("yyyymmdd")); DataSet dsleave = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, _para); if (dsleave == null || dsleave.Tables[0].Rows.Count == 0) { DataTable dt = GetLeaveDetailsByDate(Convert.ToInt32(userid), startdate.ToString("yyyymmdd")); if (dt != null && dt.Rows.Count > 0) { DataRow dr = dsleave.Tables[0].NewRow(); dr["leaveduration"] = dt.Rows[0]["leaveduration"].ToString(); dr["leavetype"] = dt.Rows[0]["leavetype"].ToString(); dr["approvetype"] = dt.Rows[0]["approvetype"].ToString(); dr["shortleavetype"] = dt.Rows[0]["shortleavetype"].ToString(); dsleave.Tables[0].Rows.Add(dr); } } if (dsleave != null && dsleave.Tables.Count > 0 && dsleave.Tables[0].Rows.Count > 0) { isleave = true; if (dsleave.Tables[0].Columns.Contains("shortleavetype") == true && dsleave.Tables[0].Columns.Contains("approvetype") == true) { strleavetype = dsleave.Tables[0].Rows[0]["shortleavetype"].ToString(); strApproveType = dsleave.Tables[0].Rows[0]["approvetype"].ToString(); } if (dsleave.Tables[0].Rows[0]["leaveduration"].ToString() == "full") { //new change.. dtattendance = getMonthWorksheetRecord(strdate, userid, false, "", dsleave.Tables[0].Rows[0]["approvetype"].ToString(), false, false, dtattendance); } else { if (dsleave.Tables[0].Rows.Count > 1) { string strapprovetypename = dsleave.Tables[0].Rows[0]["approvetype"].ToString() + " , " + dsleave.Tables[0].Rows[1]["approvetype"].ToString(); dtattendance = getMonthWorksheetRecord(strdate, userid, true, dsleave.Tables[0].Rows[0]["leavetype"].ToString(), strapprovetypename, true, true, dtattendance); } else { dtattendance = getMonthWorksheetRecord(strdate, userid, true, dsleave.Tables[0].Rows[0]["leavetype"].ToString(), dsleave.Tables[0].Rows[0]["approvetype"].ToString(), true, false, dtattendance); } } } else { _para = new SqlParameter[1]; _para[0] = new SqlParameter("@Date", strdate); DataSet dsholiday = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, _para); if (dsholiday != null && dsholiday.Tables.Count > 0 && dsholiday.Tables[0].Rows.Count > 0) { isholyday = true; if (dstripleave != null && dstripleave.Tables.Count > 0 && dstripleave.Tables[0].Rows.Count > 0) { isontrip = true; dtattendance = getMonthWorksheetRecord(strdate, userid, false, "", "ontrip/" + dsnwd.Tables[0].Rows[0]["leavetype"].ToString(), false, false, dtattendance); } else { dtattendance = getMonthWorksheetRecord(strdate, userid, false, "", dsholiday.Tables[0].Rows[0]["holidayname"].ToString(), false, false, dtattendance); } } else { _para = new SqlParameter[1]; _para[0] = new SqlParameter("@Date", strdate); dsholiday = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, _para); if (dsholiday != null && dsholiday.Tables.Count > 0 && dsholiday.Tables[0].Rows.Count > 0) { isholyday = true; if (dstripleave != null && dstripleave.Tables.Count > 0 && dstripleave.Tables[0].Rows.Count > 0) { isontrip = true; dtattendance = getMonthWorksheetRecord(strdate, userid, false, "", "ontrip/" + dsnwd.Tables[0].Rows[0]["leavetype"].ToString(), false, false, dtattendance); } else { dtattendance = getMonthWorksheetRecord(strdate, userid, false, "", dsholiday.Tables[0].Rows[0]["holidayname"].ToString(), false, false, dtattendance); } } else { dtattendance = getMonthWorksheetRecord(strdate, userid, false, "", "", true, false, dtattendance); } } } } string strtotal_hr = dtattendance.Rows[i]["total_hr"].ToString(); string strtotal_worksheet_hr = dtattendance.Rows[i]["totalworksheet_hr"].ToString(); TimeSpan totalworksheethr = new TimeSpan(); TimeSpan totalworkinghr = new TimeSpan(); TimeSpan below = new TimeSpan(1, 0, 0); TimeSpan above = new TimeSpan(0, 30, 0); string[] strworksheethrtemp = strtotal_worksheet_hr.Split(':'); string[] strworkinghr = strtotal_hr.Split(':'); bool isincorrect = false; if (strtotal_hr != null && strtotal_hr != "" && strtotal_worksheet_hr == "") { isincorrect = true; } if ((!isincorrect) && (strtotal_worksheet_hr != "")) { if (strworksheethrtemp.Length > 1) { if (strworksheethrtemp[1].Length < 2) { strworksheethrtemp[1] = strworksheethrtemp[1] + "0"; } totalworksheethr = new TimeSpan(Convert.ToInt32(strworksheethrtemp[0]), Convert.ToInt32(strworksheethrtemp[1]), 0); if (strworkinghr.Length > 1) { totalworkinghr = new TimeSpan(Convert.ToInt32(strworkinghr[0]), Convert.ToInt32(strworkinghr[1]), 0); } else { totalworkinghr = new TimeSpan(0, 0, 0); } if (totalworkinghr <= totalworksheethr) { if ((totalworksheethr - totalworkinghr) > above) { dtattendance.Rows[i]["color"] = "0x3f9dd6"; } else { dtattendance.Rows[i]["color"] = "0xffffff"; } } else if (totalworksheethr < totalworkinghr) { if ((totalworkinghr - totalworksheethr) > below) { dtattendance.Rows[i]["color"] = "0xd6cf2b"; } else { dtattendance.Rows[i]["color"] = "0xffffff"; } } else { dtattendance.Rows[i]["color"] = "0x77797a"; } } else { dtattendance.Rows[i]["color"] = "0xffffff"; } } else { dtattendance.Rows[i]["totalworksheet_hr"] = ""; if (isnwd) { if (isontrip) { dtattendance.Rows[i]["color"] = "0x3399cc"; } else { dtattendance.Rows[i]["color"] = "0x3c7e1a"; } } else if (isholyday) { if (isontrip) { dtattendance.Rows[i]["color"] = "0x3399cc"; } else { dtattendance.Rows[i]["color"] = "0x73334b"; } } else if (isincorrect) { dtattendance.Rows[i]["color"] = "0xff0000"; } else if (isleave) { if (strleavetype == "cl") { dtattendance.Rows[i]["color"] = "0x47d447"; } else if (strleavetype == "sl") { dtattendance.Rows[i]["color"] = "0xfb643e"; } else if (strleavetype == "aupl") { dtattendance.Rows[i]["color"] = "0xe48701"; } else if (strleavetype == "uupl") { dtattendance.Rows[i]["color"] = "0xaaffaa"; } if (strApproveType == "aupl") { dtattendance.Rows[i]["color"] = "0xe48701"; } else if (strApproveType == "uupl") { dtattendance.Rows[i]["color"] = "0xaaffaa"; } else if (strApproveType == "uupl/fl") { dtattendance.Rows[i]["color"] = "0xaaffaa"; } else if (strApproveType == "official trip/fl") { dtattendance.Rows[i]["color"] = "0x3399cc"; } } else { dtattendance.Rows[i]["color"] = "0xffffff"; } } dtattendance.Rows[i]["todaydate"] = startdate.Day.ToString(); dtattendance.Rows[i]["month"] = (startdate.Month - 1).ToString(); dtattendance.Rows[i]["year"] = (startdate.Year).ToString(); ; dtattendance.Rows[i]["fulldate"] = ""; startdate = startdate.AddDays(1); } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } finally { //connobj.closeconn(); } return dtattendance; } protected DataTable getMonthWorksheetRecord(string date, Int32 empID, Boolean halfLeave, string leaveType, string approveType, Boolean checkHrs, Boolean TwoHalfLeaveSameDay, DataTable dtAttendance) { // ProcCalTotalAttendanceReport => This is the SP which can be called to remove logic below. DataRow dr; try { #region New Changes //DateTime getDateRecord = Convert.ToDateTime(date, provider); SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter("@EmployeeID", empID); sqlParameters[1] = new SqlParameter("@Date", date); DataSet dsTemp = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (dsTemp.Tables.Count > 0 && dsTemp.Tables[0].Rows.Count > 0) { dr = dtAttendance.NewRow(); dr["Employee_Id"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["EmployeeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["EmployeeID"].ToString() : ""; dr["Employee_Name"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["EmployeeName"].ToString()) ? dsTemp.Tables[0].Rows[0]["EmployeeName"].ToString() : ""; dr["Date"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["Date"].ToString()) ? dsTemp.Tables[0].Rows[0]["Date"].ToString() : ""; if (!String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTIme"].ToString())) { dr["InId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["InTimeID"].ToString() : ""; dr["In_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["InTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["InTIme"].ToString() : ""; if (dr["InId"].ToString() != "") { int intPunchInID = Convert.ToInt32(dr["InId"]); SqlParameter[] _para = new SqlParameter[1]; _para[0] = new SqlParameter("PunchInId", intPunchInID); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, _para); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { string[] arr = ds.Tables[0].Rows[0]["actualEntryTime"].ToString().Split(':'); if (arr.Length > 1) { TimeSpan punchInActual = new TimeSpan(Convert.ToInt32(arr[0]), Convert.ToInt32(arr[1]), 0); TimeSpan tsgrace; TimeSpan actualInWithGrace; DateTime dtPunchIN = Convert.ToDateTime(dr["In_Time"]); TimeSpan punchIn = new TimeSpan(dtPunchIN.Hour, dtPunchIN.Minute, dtPunchIN.Second); string strGrace = ""; DateTime dtGetDate = Convert.ToDateTime(date); strGrace = ds.Tables[0].Rows[0]["grace"].ToString(); tsgrace = new TimeSpan(0, Convert.ToInt32(strGrace), 0); actualInWithGrace = punchInActual.Add(tsgrace); if (halfLeave) { } else { if (punchIn > actualInWithGrace) { dr["diff"] = dr["diff"].ToString() + "I"; } } } } } Boolean IsInOffice = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInOffice"]); Boolean IsInBreak = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInBreak"]); Boolean IsInLunch = Convert.ToBoolean(dsTemp.Tables[0].Rows[0]["IsInLunch"]); if (IsInOffice || IsInBreak || IsInLunch) { dr["Out_Time"] = ""; dr["OutId"] = ""; } else { dr["Out_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OutTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["OutTIme"].ToString() : ""; dr["OutId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OutTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["OutTimeID"].ToString() : ""; } dr["LunchOut_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchOutTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchOutTIme"].ToString() : ""; dr["LunchOutId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchOutTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchOutTimeID"].ToString() : ""; if (IsInLunch) { dr["LunchIn_Time"] = ""; dr["LunchInId"] = ""; } else { dr["LunchIn_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchInTIme"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchInTIme"].ToString() : ""; dr["LunchInId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["LunchInTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["LunchInTimeID"].ToString() : ""; } dr["OtherId"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString()) ? dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString() : ""; dr["Other_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString() : ""; string strWorksheetHours = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalWorksheetHours"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalWorksheetHours"].ToString() : ""; strWorksheetHours = strWorksheetHours.Replace('.', ':') + ":00"; string[] arrWorksheetHours = strWorksheetHours.Split(':'); TimeSpan tsWorksheetHours = new TimeSpan(); tsWorksheetHours = new TimeSpan(Convert.ToInt32(arrWorksheetHours[0]), Convert.ToInt32(arrWorksheetHours[1]), 0); dr["TotalWorksheet_Hr"] = strWorksheetHours.ToString(); if (checkHrs) { if (halfLeave) { if (String.Compare(approveType, "UUPL", true) == 0) { dr["status"] = approveType + "/" + leaveType; } else { dr["status"] = approveType; } } else { dr["status"] = "Present"; } } else { if (dr["InId"].ToString() != "") { dr["status"] = "Present"; } else { dr["status"] = approveType; } } dr["Other_Time"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOtherTime"].ToString() : ""; ; dr["Total_Hr"] = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalWorkingTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalWorkingTime"].ToString() : ""; string strTotalOfficeTime = !String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString()) ? dsTemp.Tables[0].Rows[0]["TotalOfficeTime"].ToString() : ""; TimeSpan tsTotalOfficeTime = new TimeSpan(); if (dr["Total_Hr"].ToString() != "") { string[] arrTotalOfficeTime = dr["Total_Hr"].ToString().Split(':'); tsTotalOfficeTime = new TimeSpan(Convert.ToInt32(arrTotalOfficeTime[0]), Convert.ToInt32(arrTotalOfficeTime[1]), Convert.ToInt32(arrTotalOfficeTime[2])); } else { tsTotalOfficeTime = new TimeSpan(0, 0, 0); } TimeSpan tsTotalWorkingTime = new TimeSpan(); if (strTotalOfficeTime != "") { string[] arrTotalWorksheet_Hr = strTotalOfficeTime.Split(':'); tsTotalWorkingTime = new TimeSpan(Convert.ToInt32(arrTotalWorksheet_Hr[0]), Convert.ToInt32(arrTotalWorksheet_Hr[1]), Convert.ToInt32(arrTotalWorksheet_Hr[2])); } else { tsTotalWorkingTime = new TimeSpan(0, 0, 0); } if (halfLeave) { TimeSpan temp = new TimeSpan(4, 15, 0); // for working Hrs... if (tsTotalOfficeTime < temp) { if (checkHrs) { dr["diff"] = dr["diff"].ToString() + "T"; } } temp = new TimeSpan(5, 0, 0); // for Total Hrs... if (tsTotalWorkingTime < temp) { if (checkHrs) { dr["diff"] = dr["diff"].ToString() + "O"; } } } else { TimeSpan temp = new TimeSpan(8, 30, 0); // for working Hrs... if (checkHrs && IsInOffice == false && IsInBreak == false && IsInLunch == false) { if (tsTotalOfficeTime < temp) { dr["diff"] = dr["diff"].ToString() + "T"; } temp = new TimeSpan(9, 30, 0); // for Total Hrs... if (tsTotalWorkingTime < temp) { dr["diff"] = dr["diff"].ToString() + "O"; } } //Created by Darshan 14/03/2011... //This If Condition Check which not Apply Leave Application //and taken Half Leave so Status will be change if less then 2 hours then "UUPL" // or Less then 7 hours then "0.5/UUPL" if (!IsInOffice && !IsInLunch && !IsInBreak) { temp = new TimeSpan(7, 0, 0); if (tsTotalOfficeTime < temp) { temp = new TimeSpan(2, 0, 0); if (tsTotalOfficeTime < temp) { dr["status"] = "UUPL"; } else { dr["status"] = "0.5/UUPL"; } } } } dr["TotalId"] = "0"; if (dr["OutId"].ToString() == "") { dr["Total_Hr"] = ""; } if (String.IsNullOrEmpty(dsTemp.Tables[0].Rows[0]["OtherTimeID"].ToString())) { dr["Other_Time"] = ""; } if (dr["In_Time"].ToString() != "") { dr["In_Time"] = Convert.ToDateTime(dr["In_Time"].ToString()).ToString("hh:mm:ss"); } if (dr["Out_Time"].ToString() != "") { dr["Out_Time"] = Convert.ToDateTime(dr["Out_Time"].ToString()).ToString("hh:mm:ss"); } } else { if (checkHrs) { if (TwoHalfLeaveSameDay) { //OldNew//dr["status"] = approveType; if (String.Compare(approveType, "UUPL", true) == 0) { dr["status"] = approveType + "/" + leaveType; } else { dr["status"] = approveType; } } else { if (halfLeave && checkHrs) { dr["status"] = leaveType == "FH" ? approveType + " , UUPL/SH" : "UUPL/FH , " + approveType; } else { dr["status"] = "UUPL/FL"; } } } else { if (approveType.Split('/')[0] == "Official Trip") { dr["status"] = "OnTrip/FL"; } else { dr["status"] = approveType; } } dr["In_Time"] = ""; dr["InId"] = ""; dr["Out_Time"] = ""; dr["OutId"] = ""; dr["LunchOut_Time"] = ""; dr["LunchIn_Time"] = ""; dr["Other_Time"] = ""; dr["Total_Hr"] = ""; dr["diff"] = ""; dr["TotalId"] = ""; } dtAttendance.Rows.Add(dr); } #endregion } catch (Exception ex) { throw new Exception(ex.ToString()); } return dtAttendance; } public DataSet GetWorksheetDetailsReport(int UserId, string strStartDate, string strEndDate) { // ProcGetWorksheetDetailsReport => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[3]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@StartDate", strStartDate); sqlParameters[2] = new SqlParameter("@EndDate", strEndDate); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetWorksheetDetailsReport, sqlParameters); if (ds != null && ds.Tables.Count > 0) { return ds; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } public DataTable GetProjectNameByUserId(int UserId) { // ProcGetProjectNameByUserId => This is the SP which can be called to remove logic below. DataTable dt = new DataTable(); try { SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetProjectNameByUserId, sqlParameters); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return dt; } #endregion #region Leave //BLLeave public DataSet LeaveReportById(string userId, int year) { DataSet dsResult = new DataSet("Dataset"); DataTable dtResult = new DataTable(); dtResult.Columns.Add("MonthNumber", Type.GetType("System.Int32")); dtResult.Columns.Add("Month", Type.GetType("System.String")); dtResult.Columns.Add("CL", Type.GetType("System.String")); dtResult.Columns.Add("SL", Type.GetType("System.String")); dtResult.Columns.Add("OnTrip", Type.GetType("System.String")); dtResult.Columns.Add("AUPL", Type.GetType("System.String")); dtResult.Columns.Add("UUPL", Type.GetType("System.String")); dtResult.Columns.Add("PendingLeave", Type.GetType("System.String")); dtResult.Columns.Add("Total", Type.GetType("System.String")); try { int count = 1; for (int i = 0; i < 12; i++) { DateTime dtStart = new DateTime(year, count, 01); DateTime dtEnd = LastDayOfMonthFromDateTime(dtStart); DataRow dr = dtResult.NewRow(); dr["MonthNumber"] = count; dr["Month"] = getMonthName(count); if (year > 2012) { DataTable dt = GetLeaveSummary_New(userId, "User", "CL", dtStart, dtEnd); dr["CL"] = dt.Rows[0]["TotalCL"].ToString(); dr["SL"] = dt.Rows[0]["TotalSL"].ToString(); dr["AUPL"] = dt.Rows[0]["TotalAUPL"].ToString(); dr["UUPL"] = dt.Rows[0]["TotalUUPL"].ToString(); dr["OnTrip"] = "0"; dr["PendingLeave"] = dt.Rows[0]["TotalPending"].ToString(); } else { dr["CL"] = GetLeaveSummary(userId, "CL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), true); dr["SL"] = GetLeaveSummary(userId, "SL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), true); dr["AUPL"] = GetLeaveSummary(userId, "AUPL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), true); dr["UUPL"] = GetLeaveSummary(userId, "UUPL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), true); double PendingCL = GetLeaveSummary(userId, "CL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), false); double PendingSL = GetLeaveSummary(userId, "SL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), false); double PendingAUPL = GetLeaveSummary(userId, "AUPL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), false); double PendingUUPL = GetLeaveSummary(userId, "UUPL", Convert.ToString(dtStart.ToString("yyyyMMdd")), Convert.ToString(dtEnd.ToString("yyyyMMdd")), false); dr["PendingLeave"] = PendingCL + PendingSL + PendingAUPL + PendingUUPL; } dr["Total"] = Convert.ToDouble(dr["CL"]) + Convert.ToDouble(dr["SL"]) + Convert.ToDouble(dr["AUPL"]) + Convert.ToDouble(dr["UUPL"]) + Convert.ToDouble(dr["PendingLeave"]); count += 1; dtResult.Rows.Add(dr); } dtResult.TableName = "Table1"; dsResult = new DataSet(); dsResult.Tables.Add(dtResult); //dsResult.Tables[1].Merge(dtResult2); if (dsResult != null && dsResult.Tables.Count > 0) { return dsResult; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } protected double GetLeaveSummary(string UserId, string LeaveType, string strStartDate, string strEndDate, bool isPendingLeave) { //procGetLeaveSummary => This is the SP which can be called to remove logic below. double result = 0; try { SqlParameter[] sqlParameters = new SqlParameter[5]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@LeaveType", LeaveType); sqlParameters[2] = new SqlParameter("@StartDate", strStartDate); sqlParameters[3] = new SqlParameter("@EndDate", strEndDate); sqlParameters[4] = new SqlParameter("@IsPendingLeave", isPendingLeave); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetLeaveSummary, sqlParameters); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { result = Convert.ToDouble(ds.Tables[0].Rows[0][0].ToString()); } } catch (Exception ex) { Console.Write(ex.Message.ToString()); return 0; } return 0; } protected DataTable GetLeaveSummary_New(string UserID, string userType, string LeaveType, DateTime dtStartDate, DateTime dtEndDate) { //procGetLeaveSummary_New => This is the SP which can be called to remove logic below. //procGetPresentDaysBetweenDateForEmp => This is the SP which can be called to remove logic below. //procGetEmployeeLeaveRelatedDetailForDate => This is the SP which can be called to remove logic below. try { double TotalCL = 0; double TotalSL = 0; double TotalAUPL = 0; double TotalUUPL = 0; double TotalPending = 0; //(SELECT IsNWD FROM Leaveledger where LeaveFormID=LeaveForm.ID ) AS IsNWD, SqlParameter[] _para = new SqlParameter[3]; _para[0] = new SqlParameter("@EmployeeID", UserID); _para[1] = new SqlParameter("@FromDate", dtStartDate); _para[2] = new SqlParameter("@ToDate", dtEndDate); _para[3] = new SqlParameter("@userType", userType); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetLeaveSummary_New, _para); if (ds != null && ds.Tables[0].Rows.Count > 0) { string _leaveType = ""; string _leaveStatus = ""; DateTime _dtFrom; DateTime _dtTo; double _balance; int _leaveDays; bool _isFullDays; bool _isFirstHalf; // bool _isNwd; bool _isSecondHalf; bool _IsConfirmed; DateTime _ConfirmationDate = DateTime.Now; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { _leaveStatus = ds.Tables[0].Rows[i]["Status"].ToString(); if (_leaveStatus == "Approved") { _balance = Convert.ToDouble(ds.Tables[0].Rows[i]["Balance"].ToString()); } else { _balance = 0.0; } _IsConfirmed = Convert.ToBoolean(ds.Tables[0].Rows[i]["IsConfirmed"]); if (_IsConfirmed) { _ConfirmationDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["ConfirmationDate"].ToString()); } _leaveType = ds.Tables[0].Rows[i]["LeaveType"].ToString(); _dtFrom = Convert.ToDateTime(ds.Tables[0].Rows[i]["FromDate"].ToString()); _dtTo = Convert.ToDateTime(ds.Tables[0].Rows[i]["ToDate"].ToString()); _leaveDays = Convert.ToInt32(ds.Tables[0].Rows[i]["LeaveDay"].ToString()); _isFullDays = Convert.ToBoolean(ds.Tables[0].Rows[i]["IsFullDay"]); _isFirstHalf = Convert.ToBoolean(ds.Tables[0].Rows[i]["IsFirstHalf"]); _isSecondHalf = Convert.ToBoolean(ds.Tables[0].Rows[i]["IsSecondHalf"]); SqlParameter[] _paraoneAttendance = new SqlParameter[3]; _paraoneAttendance[0] = new SqlParameter("@EmployeeID", UserID); _paraoneAttendance[1] = new SqlParameter("@fromdate", _dtFrom); _paraoneAttendance[2] = new SqlParameter("@todate", _dtTo); DataSet Attendance = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetPresentDaysBetweenDateForEmp, _paraoneAttendance); double leaveToBeAdded = 0; leaveToBeAdded = _isFullDays ? 1.0 : 0.5; if (_leaveDays == 1) { if (_leaveStatus == "Approved" && _balance >= 0) { if (_IsConfirmed && _dtFrom >= _ConfirmationDate) { if (_leaveType == "CL") { TotalCL += leaveToBeAdded; } else if (_leaveType == "SL") { TotalSL += leaveToBeAdded; } } else { TotalAUPL += leaveToBeAdded; } } else { if (_leaveStatus == "Approved") { TotalAUPL += leaveToBeAdded; } else { if (_leaveStatus == "New") { TotalPending += leaveToBeAdded; } else if (_leaveStatus == "Cancel") { if (_leaveType == "CL") { TotalCL += leaveToBeAdded; } else if (_leaveType == "SL") { TotalSL += leaveToBeAdded; } } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[0]["isPresent"]) > 0) { } else { TotalUUPL += leaveToBeAdded; } } else { TotalUUPL += leaveToBeAdded; } } } } else { int totalDays = Convert.ToInt32((_dtTo - _dtFrom).TotalDays + 1); DateTime dtTemp = _dtFrom; for (int j = 0; j < totalDays; j++) { if (dtTemp.Month == dtStartDate.Month && dtTemp.Month == dtEndDate.Month) { SqlParameter[] _paraAttendance = new SqlParameter[2]; _paraAttendance[0] = new SqlParameter("@LeaveDate", dtTemp.ToString("yyyyMMdd")); _paraAttendance[1] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserID); DataSet dsAttendance = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetEmployeeLeaveRelatedDetailForDate, _paraAttendance); if (dsAttendance != null && dsAttendance.Tables[0].Rows.Count > 0) { bool isFullDays = Convert.ToBoolean(dsAttendance.Tables[0].Rows[0]["IsFullDay"]); bool isFirstHalf = Convert.ToBoolean(dsAttendance.Tables[0].Rows[0]["IsFirstHalf"]); bool isSecondHalf = Convert.ToBoolean(dsAttendance.Tables[0].Rows[0]["IsSecondHalf"]); double balance = Convert.ToDouble(dsAttendance.Tables[0].Rows[0]["Balance"].ToString()); bool IsConfirmed = Convert.ToBoolean(dsAttendance.Tables[0].Rows[0]["IsConfirmed"]); DateTime ConfirmationDate = DateTime.Now; //Convert.ToDateTime(dsAttendance.Tables[0].Rows[0]["ConfirmationDate"].ToString()); if (IsConfirmed) { ConfirmationDate = Convert.ToDateTime(dsAttendance.Tables[0].Rows[0]["ConfirmationDate"].ToString()); } if (Convert.ToInt32(dsAttendance.Tables[0].Rows[0]["Present"]) > 0) { //Employee Present on dtTemp Date } else { if (_leaveStatus == "Approved" && balance >= 0) { if (isFullDays) { if (IsConfirmed && dtTemp >= ConfirmationDate) { if (_leaveType == "CL") { TotalCL += 1; } else if (_leaveType == "SL") { TotalSL += 1; } } else { TotalAUPL += 1; } } else { if (isFirstHalf) { if (IsConfirmed && dtTemp >= ConfirmationDate) { if (_leaveType == "CL") { TotalCL += 0.5; } else if (_leaveType == "SL") { TotalSL += 0.5; } } else { TotalAUPL += 0.5; } } if (isSecondHalf) { if (IsConfirmed && dtTemp >= ConfirmationDate) { if (_leaveType == "CL") { TotalCL += 0.5; } else if (_leaveType == "SL") { TotalSL += 0.5; } } else { TotalAUPL += 0.5; } } } } else { if (isFullDays) { if (_leaveStatus == "Approved") { TotalAUPL += 1; } else if (_leaveStatus == "New") { TotalPending += 1; } else if (_leaveStatus == "Cancel") { if (_leaveType == "CL") { TotalCL += 1; } else if (_leaveType == "SL") { TotalSL += 1; } } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[0]["isPresent"]) > 0) { } else { TotalUUPL += 1; } } else { TotalUUPL += 1; } } else { if (isFirstHalf) { if (_leaveStatus == "Approved") { TotalAUPL += 0.5; } else if (_leaveStatus == "New") { TotalPending += 1; } else if (_leaveStatus == "Cancel") { if (_leaveType == "CL") { TotalCL += 1; } else if (_leaveType == "SL") { TotalSL += 1; } } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[0]["isPresent"]) > 0) { } else { TotalUUPL += 0.5; } } else { TotalUUPL += 0.5; } } if (isSecondHalf) { if (_leaveStatus == "Approved") { TotalAUPL += 0.5; } else if (_leaveStatus == "New") { TotalPending += 1; } else if (_leaveStatus == "Cancel") { if (_leaveType == "CL") { TotalCL += 1; } else if (_leaveType == "SL") { TotalSL += 1; } } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[0]["isPresent"]) > 0) { } else { TotalUUPL += 0.5; } } else { TotalUUPL += 0.5; } } } } } } else { if (_leaveDays == 1) { if (_leaveStatus == "New") { if (_isFullDays) { TotalPending += 1; } else { if (_isFirstHalf) { TotalPending += 0.5; } if (_isSecondHalf) { TotalPending += 0.5; } } } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[j]["isPresent"]) > 0) { } else { if (_isFullDays) { TotalUUPL += 1; } else { TotalUUPL += 0.5; } } } else { if (_isFullDays) { TotalUUPL += 1; } else { if (_isFirstHalf) { TotalUUPL += 0.5; } if (_isSecondHalf) { TotalUUPL += 0.5; } } } } else { if (dtTemp == _dtFrom) { if (_isSecondHalf) { if (_leaveStatus == "New") { TotalPending += 0.5; } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[j]["isPresent"]) > 0) { } else { TotalUUPL += 0.5; } } else { TotalUUPL += 0.5; } } else { if (_leaveStatus == "New") { TotalPending += 1; } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[j]["isPresent"]) > 0) { } else { TotalUUPL += 1; } } else { TotalUUPL += 1; } } } else if (dtTemp == _dtTo) { if (_isFirstHalf) { if (_leaveStatus == "New") { TotalPending += 0.5; } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(dsAttendance.Tables[0].Rows[0]["Present"]) > 0) { } else { TotalUUPL += 0.5; } } else { TotalUUPL += 0.5; } } else { if (_leaveStatus == "New") { TotalPending += 1; } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[j]["isPresent"]) > 0) { } else { TotalUUPL += 1; } } else { TotalUUPL += 1; } } } else { if (_leaveStatus == "New") { TotalPending += 1; } else if (_leaveStatus == "Cancel Approved") { } else if (_leaveStatus == "Rejected") { if (Convert.ToInt32(Attendance.Tables[0].Rows[j]["isPresent"]) > 0) { } else { TotalUUPL += 1; } } else { TotalUUPL += 1; } } } } } dtTemp = dtTemp.AddDays(1); } //} } } } DataTable dt = new DataTable(); dt.Columns.Add("TotalCL", Type.GetType("System.String")); dt.Columns.Add("TotalSL", Type.GetType("System.String")); dt.Columns.Add("TotalAUPL", Type.GetType("System.String")); dt.Columns.Add("TotalUUPL", Type.GetType("System.String")); dt.Columns.Add("TotalPending", Type.GetType("System.String")); DataRow dr = dt.NewRow(); dr["TotalCL"] = TotalCL.ToString(); dr["TotalSL"] = TotalSL.ToString(); dr["TotalAUPL"] = TotalAUPL.ToString(); dr["TotalUUPL"] = TotalUUPL.ToString(); dr["TotalPending"] = TotalPending.ToString(); dt.Rows.Add(dr); return dt; } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } } public DataSet GetLeaveReportByYear(string UserId, int year, string UserType) { //ProcGetLeaveReportByYear => This is the SP which can be called to remove logic below. DataTable dtResult = new DataTable(); try { SqlParameter[] sqlParameters = new SqlParameter[3]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@Year", year); sqlParameters[2] = new SqlParameter("@UserType", UserType); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetLeaveReportByYear, sqlParameters); if (ds != null && ds.Tables.Count > 0) { return ds; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } #endregion #region Allocation //BLAllocation public DataSet ProjectAllocationByUserId(Int32 UserId) { //ProcProjectAllocationByUserId => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetProjectAllocationByUserId, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } #endregion #region Team //BLMyTeam public DataSet MyTeamByUserId(Int32 userId, bool IsLineManager) { //ProcMyTeamByUserId => This is the SP which can be called to remove logic below. DataSet dsResult = new DataSet(); DataTable dtResult = new DataTable("Table"); dtResult.Columns.Add(new DataColumn("EmployeeId", Type.GetType("System.Int32"))); dtResult.Columns.Add(new DataColumn("EmployeeName", Type.GetType("System.String"))); dtResult.Columns.Add(new DataColumn("ProjectName", Type.GetType("System.String"))); try { SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, userId); sqlParameters[1] = new SqlParameter("@IsLineManager", IsLineManager); List<int> lstEmpIds = new List<int>(); List<string> lstEmpNames = new List<string>(); DataSet ds = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if (lstEmpIds.Contains(Convert.ToInt32(ds.Tables[0].Rows[i]["EmployeeId"])) == false) { lstEmpIds.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["EmployeeId"])); lstEmpNames.Add(Convert.ToString(ds.Tables[0].Rows[i]["EmployeeName"])); } } string strProjectName = ""; for (int intIndex = 0; intIndex < lstEmpIds.Count; intIndex++) { strProjectName = ""; DataRow[] dataRow = ds.Tables[0].Select("[EmployeeId] = " + Convert.ToInt32(lstEmpIds[intIndex])); if (dataRow != null && dataRow.Length > 0) { for (int i = 0; i < dataRow.Length; i++) { if (strProjectName != "") { strProjectName += ","; } strProjectName += Convert.ToString(dataRow[i]["ProjectName"]); } } DataRow dr = dtResult.NewRow(); dr["EmployeeId"] = Convert.ToInt32(lstEmpIds[intIndex]); dr["EmployeeName"] = Convert.ToString(lstEmpNames[intIndex]); dr["ProjectName"] = strProjectName; dtResult.Rows.Add(dr); } } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } dsResult.Tables.Add(dtResult); return dsResult; } #endregion #region Alert public DataSet GetAlertList(Int32 UserId, bool IsAdmin) { //ProcGetAlertList => This is the SP which can be called to remove logic below. DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Label", Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("Count", Type.GetType("System.Int32"))); DataSet ds = new DataSet(); try { DataRow dr = dt.NewRow(); dr = dt.NewRow(); dr["Label"] = "All"; DataSet dsAlldetails = GetAllDetails(UserId, IsAdmin); dr["Count"] = Convert.ToInt32(dsAlldetails.Tables[0].Rows.Count); dt.Rows.Add(dr); if (IsAdmin) { dr = dt.NewRow(); dr["Label"] = "Project Unplanned"; DataSet dsProjectUnplanned = GetProjectUnplanned(); dr["Count"] = Convert.ToInt32(dsProjectUnplanned.Tables[0].Rows.Count); dt.Rows.Add(dr); } dr = dt.NewRow(); dr["Label"] = "Leave Pending"; DataSet dsPendingLeave = GetPendingLeave(UserId, IsAdmin); dr["Count"] = Convert.ToInt32(dsPendingLeave.Tables[0].Rows.Count); dt.Rows.Add(dr); if (IsAdmin) { dr = dt.NewRow(); dr["Label"] = "Opportunity Pending"; DataSet dsOpportunity = GetOpportunityPending(UserId, IsAdmin); dr["Count"] = Convert.ToInt32(dsOpportunity.Tables[0].Rows.Count); dt.Rows.Add(dr); } if (IsAdmin) { dr = dt.NewRow(); dr["Label"] = "Invoice Pending"; DataSet dsInvoicePending = GetInvoicePending(UserId); dr["Count"] = Convert.ToInt32(dsInvoicePending.Tables[0].Rows.Count); dt.Rows.Add(dr); } if (IsAdmin) { dr = dt.NewRow(); dr["Label"] = "Collection Pending"; DataSet dsCollectionPending = GetCollectionPending(UserId); dr["Count"] = Convert.ToInt32(dsCollectionPending.Tables[0].Rows.Count); dt.Rows.Add(dr); } dr = dt.NewRow(); dr["Label"] = "Appraisal Pending"; DataSet dsAppraisalPending = GetAppraisalPending(UserId); dr["Count"] = dsAppraisalPending.Tables[0].Rows.Count; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Label"] = "Tickets"; DataSet dsSuggestions = GetSuggestion(UserId, IsAdmin); dr["Count"] = dsSuggestions.Tables[0].Rows.Count; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Label"] = "Pending Task"; DataSet dsPendingTask = GetPendingTask(UserId); dr["Count"] = dsPendingTask.Tables[0].Rows.Count; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Label"] = "Pending Signoff"; DataSet dsPendingSignoff = GetPendingSignoff(UserId); dr["Count"] = dsPendingSignoff.Tables[0].Rows.Count; dt.Rows.Add(dr); ds.Tables.Add(dt); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return ds; } /********** Project Unplanned **********/ public DataSet GetAllDetails(Int32 UserId, bool isAdmin) { //ProcGetAlertList => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@IsAdmin", isAdmin); DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetAllDetails, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Project Unplanned **********/ public DataSet GetProjectUnplanned() { //fnGetProjectUnplanned This is the Function which can be called to remove logic below. try { DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetProjectUnplanned, null); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Leave Pending **********/ public DataSet GetPendingLeave(Int32 UserId, bool IsAdmin) { //ProcGetAlertList => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@IsAdmin", IsAdmin); //DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetPendingLeave, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Invoice Pending **********/ public DataSet GetInvoicePending(Int32 UserId) { //fnGetInvoicePendingAlert => This is the Function which can be called to remove logic below. try { //string strQuery += " ORDER BY CONVERT(DATETIME,[MilestoneMaster].[MilestoneDate],103) DESC,[MilestoneMaster].[id] DESC "; SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetInvoicePending, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Appraisal Unplanned **********/ public DataSet GetAppraisalPending(Int32 UserId) { //fnGetAppraisalPendingAlert => This is the Function which can be called to remove logic below. try { //string strQuery = "ORDER BY [setup_appraisal].AppraisalDate DESC"; SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetAppraisalPending, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Collection Pending **********/ public DataSet GetCollectionPending(Int32 UserId) { //fnGetCollectionPendingAlert => This is the Function which can be called to remove logic below. try { //string strQuery = " ORDER BY CONVERT(DATETIME,InvoiceMaster.InvoiceDate,103) DESC "; SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetCollectionPending, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Suggestions **********/ public DataSet GetSuggestion(Int32 UserId, bool IsAdmin) { //fnGetSuggestionAlert => This is the Function which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@IsAdmin", IsAdmin); DataSet dsSuggestion = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetSuggestion, sqlParameters); if (IsAdmin) { } else { //strQuery += " WHERE [Employee_Master].[id]=" + UserId } //strQuery += " ORDER BY [Suggestions].[SuggestionGivenDate] DESC"; } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Opportunity Pending **********/ public DataSet GetOpportunityPending(Int32 UserId, bool IsAdmin) { //fnGetOpportunityPending => This is the FUNCTION which can be called to remove logic below. try { //string str = 'ORDER BY CONVERT(DATETIME,[OpportunityMaster].[TentativeStartDate],103) DESC'; DataSet dsOpportunityPending = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetOpportunityPending, null); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Pending Task **********/ public DataSet GetPendingTask(Int32 UserId) { //fnGetPendingTaskAlert => This is the FUNCTION which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet dsPendingTask = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetPendingTask, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } /********** Pending Signoff **********/ public DataSet GetPendingSignoff(Int32 UserId) { //WBS_GetPendingSignOffList => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter("@MgrID", UserId); DataSet dsPendingSignoff = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetPendingTask, sqlParameters); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } #endregion // check #region Skill public DataSet UserSkillById(Int32 UserId, bool IsApproved) { //ProcUserSkillById => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[2]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); sqlParameters[1] = new SqlParameter("@IsApproved", IsApproved); DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); if (dsResult != null && dsResult.Tables.Count > 0 && dsResult.Tables[0].Rows.Count > 0) { return dsResult; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } public DataSet SkillReportByUserId(Int32 UserId) { //ProcSkillReportByUserId => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[1]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, UserId); DataSet dsResult = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetSkillReportByUserId, sqlParameters); if (dsResult != null && dsResult.Tables.Count > 0 && dsResult.Tables[0].Rows.Count > 0) { return dsResult; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } return null; } #endregion #region Common Functions public string GetEmployee_Name(string UserId) { // => This is the Function which can be called to remove logic below. string strEmployee_Name = ""; try { strEmployee_Name = ReturnScalarValueFromFunction("select [dbo].[fnGetEmployeeNameFromId](" + UserId + ")").ToString(); } catch (Exception ex) { throw new Exception(ex.Message.ToString() + Environment.NewLine + ex.StackTrace); } return strEmployee_Name; } public string getEmployeeIds_LM(Int32 UserId) { object objListOfEmpForLM = ReturnScalarValueFromFunction("select [dbo].[fnGetCommaSeparatedListOfEmployeeForLM](" + UserId + ")"); string strResult = objListOfEmpForLM == null ? string.Empty : objListOfEmpForLM.ToString(); return strResult; } public DateTime convertStrToDate(string strDate) { DateTime dt = new DateTime(); try { string[] strArrDate = strDate.Split('-'); string strCurr = strArrDate[1] + "-" + strArrDate[2] + "-" + strArrDate[0] + " 00:00:00"; dt = Convert.ToDateTime(strDate); } catch (Exception ex) { throw new Exception(ex.Message.ToString() + Environment.NewLine + ex.StackTrace); } return dt; } public DateTime LastDayOfMonthFromDateTime(DateTime dateTime) { DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1); return firstDayOfTheMonth.AddMonths(1).AddDays(-1); } public string getMonthName(int intMonth) { return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(intMonth); } #endregion public void Dispose() { throw new NotImplementedException(); } public DataSet GetLevelsList() { //ProcLevels_GetLevelsList => This is the SP which can be called to remove logic below. try { SqlParameter[] sqlParameters = new SqlParameter[0]; DataSet DashboardDataSet = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); return DashboardDataSet; } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } } public DataSet GetPointsDetails() { try { SqlParameter[] sqlParameters = new SqlParameter[0]; DataSet DashboardDataSet = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); return DashboardDataSet; } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } } public DataSet GetPointsDetails(int iForEmpId) { try { bool bIsPointDetails = true; bool bIsPeriodic = false; bool bIsMonthRange = false; bool bIsDetail = true; bool bAllDates = true; string sViewType = ""; DateTime dtMonday = DateTime.Today; DateTime dtStartMonth = DateTime.Today; DateTime dtEndMonth = DateTime.Today; SqlParameter[] sqlParameters = new SqlParameter[10]; sqlParameters[0] = new SqlParameter(VISBaseEntityConstants.const_Field_Id, iForEmpId); sqlParameters[1] = new SqlParameter("@pointDetails", bIsPointDetails); sqlParameters[2] = new SqlParameter("@isDetail", bIsDetail); sqlParameters[3] = new SqlParameter("@viewType", sViewType); sqlParameters[4] = new SqlParameter("@startDate", dtMonday); sqlParameters[5] = new SqlParameter("@isPeriodic", bIsPeriodic); sqlParameters[6] = new SqlParameter("@monthRange", bIsMonthRange); sqlParameters[7] = new SqlParameter("@isAllDates", bAllDates); sqlParameters[8] = new SqlParameter("@monthStart", dtStartMonth); sqlParameters[9] = new SqlParameter("@monthEnd", dtEndMonth); DataSet DashboardDataSet = ReturnDataSetFromSP(DashboardConstsants.const_Proc_GetDashboardDataSets, sqlParameters); return DashboardDataSet; } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } //EmployeeLevelsBAL levelsBAL = new EmployeeLevelsBAL(); //if (rbtlistReport.SelectedValue == "Detail") //{ // bIsPointDetails = true; //} //else //{ // bIsDetail = false; // sViewType = rbtlistReport.SelectedValue; // if (sViewType == "Weekly") // { // dtMonday = GetMonday(levelsBAL.GetPointStartDate(iEmpId)); // } //} //connection conn = new connection(); //conn.GetConnectionString(); //SqlCommand cmd = new SqlCommand(); //cmd.CommandText = "Levels_ReportAdmin"; //cmd.CommandType = CommandType.StoredProcedure; //cmd.Connection = conn.conn; //cmd.Parameters.AddWithValue("@empId", iForEmpId); //cmd.Parameters.AddWithValue("@pointDetails", bIsPointDetails); //cmd.Parameters.AddWithValue("@isDetail", bIsDetail); //cmd.Parameters.AddWithValue("@viewType", sViewType); //cmd.Parameters.AddWithValue("@startDate", dtMonday); //cmd.Parameters.AddWithValue("@isPeriodic", bIsPeriodic); //cmd.Parameters.AddWithValue("@monthRange", bIsMonthRange); //cmd.Parameters.AddWithValue("@isAllDates", bAllDates); //cmd.Parameters.AddWithValue("@monthStart", dtStartMonth); //cmd.Parameters.AddWithValue("@monthEnd", dtEndMonth); //DataSet dsReport = new DataSet(); //SqlDataAdapter sda = new SqlDataAdapter(); //sda.SelectCommand = cmd; //sda.Fill(dsReport); //if (dsReport != null) //{ // if (dsReport.Tables[0].Rows.Count > 0) // //List<Levels_ReportAdmin> listReport = levelsBAL.GetAdminReport(Convert.ToInt32(ddlEmployee.SelectedValue),bIsDetail,sViewType,dtMonday); // //if (listReport != null && listReport.Count > 0) // { // lblGridEmpty.Visible = false; // lblResult.Visible = true; // gvReport.DataSource = dsReport; // gvReport.DataBind(); // iCount = dsReport.Tables[0].Rows.Count; // trpaging.Visible = true; // int iTotalPoints = Convert.ToInt32(dsReport.Tables[0].Rows[iCount - 1]["Points Gained"].ToString()); // string sCurrLevel = levelsBAL.GetCurrentLevel(iTotalPoints); // Employee_MasterBAL employeeBAL = new Employee_MasterBAL(); // Employee_Master empMaster = employeeBAL.GetEmployeeById(iForEmpId); // if (empMaster != null) // { // sUserName = empMaster.Employee_Name; // } // if (sCurrLevel != null) // { // lblResult.Text = sUserName + " is at Level: " + sCurrLevel + " with " + iTotalPoints + " points."; // } // else // { // lblResult.Text = sUserName + " gained: " + iTotalPoints + " points."; // } // } // else // { // //gvReport.DataSource = listReport; // gvReport.DataSource = dsReport; // gvReport.DataBind(); // lblGridEmpty.Visible = true; // iCount = 0; // trpaging.Visible = false; // } // Paging(); //} } public DataTable GetAttendanceDetail(int Id,string Date) { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { for (int i = 0; i < 8; i++) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = DashboardConstsants.const_ProcCalTotalAttendanceReport; base.objSqlCommand.Parameters.AddWithValue("@EmployeeID", Id); base.objSqlCommand.Parameters.AddWithValue("@Date", Date); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } } } }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var TicketListOpen_service_1 = require("../../service/Notification/TicketListOpen.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); var pager_index_1 = require("../../Shared/pager.index"); var TicketListOpenComponent = (function () { function TicketListOpenComponent(fb, _TicketListOpenService, pagerService) { this.fb = fb; this._TicketListOpenService = _TicketListOpenService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'Subject'; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; //Variables for Filter this.ShowHideSearch = false; } TicketListOpenComponent.prototype.ngOnInit = function () { this.TicketListOpenFrm = this.fb.group({ CompanyId: [''], Id: 0, Subject: [''], Message: [''], Remarks: [''], AddressToGroup: [''], AssignTo: [''], CreatedByName: [''], UpdatedByName: [''], Priority: [''], Status: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], Mode: [''], HelpTicketId: [''], FileName: [''], UserType: [''], RoleType: [''], EntityMessage: [''] }); this.LoadGetTicketDetailUser(21); }; TicketListOpenComponent.prototype.TicketListOpenFilterCriteriaChange = function (value) { if (value != '[object Event]') this.TicketListOpenFilter = value; }; TicketListOpenComponent.prototype.TicketListOpenSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; TicketListOpenComponent.prototype.loadcount = function () { this.OpenTicketCount = this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "open"; }).length; this.UnderReviewTicketCount = this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "underReview"; }).length; this.SuspendedTicketCount = this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "suspended"; }).length; this.ResolvedTicketCount = this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "resolved"; }).length; }; TicketListOpenComponent.prototype.FilterByStatus = function (event) { if (event.target.value == 'TicketAddressedToMe') { this.LoadGetTicketDetailUser(21); } else if (event.target.value == 'AllTicket') { this.LoadGetTicketDetailAdminAllTicket(); } }; TicketListOpenComponent.prototype.LoadGetTicketDetailUser = function (UserId) { var _this = this; this.indLoading = true; this._TicketListOpenService.getTicketuser(global_1.Global.BASE_MyTicketListOpen_ENDPOINT, UserId) .subscribe(function (data) { // console.log(data) _this.TicketListOpens = data; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchSubject = document.getElementById("searchSubject").value; if (_this.strSearchSubject != '') { _this.strSearchSubject = _this.strSearchSubject.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(_this.strSearchSubject) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchAddressToGroup = document.getElementById("searchAddressToGroup").value; if (_this.strSearchAddressToGroup != '') { _this.strSearchAddressToGroup = _this.strSearchAddressToGroup.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.AddressToGroup != null && x.AddressToGroup.toLocaleLowerCase().indexOf(_this.strSearchAddressToGroup) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchAssignTo = document.getElementById("searchAssignTo").value; if (_this.strSearchAssignTo != '') { _this.strSearchAssignTo = _this.strSearchAssignTo.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.AssignTo != null && x.AssignTo.toLocaleLowerCase().indexOf(_this.strSearchAssignTo) != -1; }); } if (_this.ShowHideSearch) { _this.strSearchPriority = document.getElementById("searchPriority").value; if (_this.strSearchPriority != '') { _this.strSearchPriority = _this.strSearchPriority.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(_this.strSearchPriority) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchStatus = document.getElementById("searchStatus").value; if (_this.strSearchStatus != '') { _this.strSearchStatus = _this.strSearchStatus.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.Status != null && x.Status.toLocaleLowerCase().indexOf(_this.strSearchStatus) != -1; }); } } } //Logic for searching - End _this.OpenTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "open"; }).length; _this.UnderReviewTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "underReview"; }).length; _this.SuspendedTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "suspended"; }).length; _this.ResolvedTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "resolved"; }).length; _this.indLoading = false; _this.JumpOnPage(1); }); }; TicketListOpenComponent.prototype.LoadGetTicketDetail = function (id) { var _this = this; this.indLoading = true; this._TicketListOpenService.getTicketDetail(global_1.Global.BASE_MyTicketListOpen_ENDPOINT, id) .subscribe(function (DATADP) { _this.GetDetail = DATADP; }); }; TicketListOpenComponent.prototype.LoadGetTicketDetailAdminAllTicket = function () { var _this = this; this.indLoading = true; this._TicketListOpenService.getTicketAdmin(global_1.Global.BASE_MyTicketListOpen_ENDPOINT) .subscribe(function (data) { // console.log(data) _this.TicketListOpens = data; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchSubject = document.getElementById("searchSubject").value; if (_this.strSearchSubject != '') { _this.strSearchSubject = _this.strSearchSubject.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(_this.strSearchSubject) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchAddressToGroup = document.getElementById("searchAddressToGroup").value; if (_this.strSearchAddressToGroup != '') { _this.strSearchAddressToGroup = _this.strSearchAddressToGroup.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.AddressToGroup != null && x.AddressToGroup.toLocaleLowerCase().indexOf(_this.strSearchAddressToGroup) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchAssignTo = document.getElementById("searchAssignTo").value; if (_this.strSearchAssignTo != '') { _this.strSearchAssignTo = _this.strSearchAssignTo.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.AssignTo != null && x.AssignTo.toLocaleLowerCase().indexOf(_this.strSearchAssignTo) != -1; }); } if (_this.ShowHideSearch) { _this.strSearchPriority = document.getElementById("searchPriority").value; if (_this.strSearchPriority != '') { _this.strSearchPriority = _this.strSearchPriority.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(_this.strSearchPriority) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchStatus = document.getElementById("searchStatus").value; if (_this.strSearchStatus != '') { _this.strSearchStatus = _this.strSearchStatus.toLocaleLowerCase(); _this.TicketListOpens = _this.TicketListOpens.filter(function (x) { return x.Status != null && x.Status.toLocaleLowerCase().indexOf(_this.strSearchStatus) != -1; }); } } } //Logic for searching - End _this.OpenTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "open"; }).length; _this.UnderReviewTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "underReview"; }).length; _this.SuspendedTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "suspended"; }).length; _this.ResolvedTicketCount = _this.TicketListOpens.filter(function (x) { return x.Status.toLowerCase() == "resolved"; }).length; _this.indLoading = false; _this.JumpOnPage(1); }); }; TicketListOpenComponent.prototype.addTicketListOpen = function () { this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New News"; this.modalBtnTitle = "Add"; this.TicketListOpenFrm.reset(); this.modal.open(); }; TicketListOpenComponent.prototype.editTicketListOpen = function (id) { this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit News"; this.modalBtnTitle = "Update"; this.TicketListOpen = this.TicketListOpens.filter(function (x) { return x.Id == id; })[0]; this.TicketListOpenFrm.setValue(this.TicketListOpen); this.modal.open(); this.LoadGetTicketDetail(id); }; TicketListOpenComponent.prototype.ViewTicketListOpen = function (id) { this.dbops = enum_1.DBOperation.View; this.SetControlsState(true); this.modalTitle = "Conversation Ticket"; this.TicketListOpen = this.TicketListOpens.filter(function (x) { return x.Id == id; })[0]; this.TicketListOpenFrm.setValue(this.TicketListOpen); this.LoadViwHistory(id); this.modal1.open(); this.modal.dismiss(); }; TicketListOpenComponent.prototype.deleteTicketListOpen = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.TicketListOpen = this.TicketListOpens.filter(function (x) { return x.Id == id; })[0]; this.TicketListOpenFrm.setValue(this.TicketListOpen); this.modal.open(); }; TicketListOpenComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.TicketListOpenFrm.enable() : this.TicketListOpenFrm.disable(); }; TicketListOpenComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; TicketListOpenComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.TicketListOpens); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; TicketListOpenComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; TicketListOpenComponent.prototype.LoadViwHistory = function (id) { var _this = this; this.indLoading = true; this._TicketListOpenService.getViewHistory(global_1.Global.BASE_MyTicket_ENDPOINT, id) .subscribe(function (DATADP) { _this.ViewHistory = DATADP; }); }; TicketListOpenComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._TicketListOpenService.post(global_1.Global.BASE_MyTicketListOpen_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadGetTicketDetailUser(21); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._TicketListOpenService.put(global_1.Global.BASE_MyTicketListOpen_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadGetTicketDetailUser(21); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._TicketListOpenService.delete(global_1.Global.BASE_MyTicketListOpen_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "TicketListOpen status changed successfully."; _this.LoadGetTicketDetailUser(21); } else { _this.msg = "Error has occurred while changing status of existing TicketListOpen!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], TicketListOpenComponent.prototype, "modal", void 0); __decorate([ core_1.ViewChild('modal1'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], TicketListOpenComponent.prototype, "modal1", void 0); TicketListOpenComponent = __decorate([ core_1.Component({ providers: [TicketListOpen_service_1.TicketListOpenService], templateUrl: 'app/Components/Notification/TicketListOpen.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, TicketListOpen_service_1.TicketListOpenService, pager_index_1.PagerService]) ], TicketListOpenComponent); return TicketListOpenComponent; }()); exports.TicketListOpenComponent = TicketListOpenComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; using VIS_Repository.Reports.Attendance; using VIS_Repository.Dashboard; using VIS_Repository.Reports; namespace VIS_App.Controllers.Masters.Configuration { public class OutReportAPIController : BaseAPIController { OutReportRepository objOutReportRepository = null; public OutReportAPIController() { objOutReportRepository = new OutReportRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/OutReportAPI/GetEmployee")] [HttpGet] public HttpResponseMessage GetEmployee() { return ToJson(objOutReportRepository.GetEmployee()); } [Route("api/OutReportAPI/GetAllEmployee")] [HttpGet] public HttpResponseMessage GetAllEmployee() { return ToJson(objOutReportRepository.GetAllEmployee()); } [Route("api/OutReportAPI/GetDepartment")] [HttpGet] public HttpResponseMessage GetDepartment() { return ToJson(objOutReportRepository.GetDepartment()); } [Route("api/OutReportAPI/GetCompany")] [HttpGet] public HttpResponseMessage GetCompany() { return ToJson(objOutReportRepository.GetCompany()); } [Route("api/OutReportAPI/GetLineManager")] [HttpGet] public HttpResponseMessage GetLineManager() { return ToJson(objOutReportRepository.GetLineManager()); } [Route("api/OutReportAPI/GetReportByEmployeeId")] [HttpPost] public HttpResponseMessage GetReportByEmployeeId(OutReport entityobject) { return ToJson(objOutReportRepository.GetOutReportByEmployeeId(entityobject)); } [Route("api/OutReportAPI/GetEmployeeIdByLM")] [HttpGet] public HttpResponseMessage GetEmployeeIdByLM(int LineManagerId) { return ToJson(objOutReportRepository.GetEmployeeIdByLM(LineManagerId)); } [Route("api/OutReportAPI/GetEmployeeIdByCompany")] [HttpGet] public HttpResponseMessage GetEmployeeIdByCompany(int CompanyId) { return ToJson(objOutReportRepository.GetEmployeeIdByCompany(CompanyId)); } [Route("api/OutReportAPI/GetEmployeeIdByDepartment")] [HttpGet] public HttpResponseMessage GetEmployeeIdByDepartment(int ParentId) { return ToJson(objOutReportRepository.GetEmployeeIdByDepartment(ParentId)); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var login_service_1 = require("../../Service/UserManagement/login.service"); var forms_1 = require("@angular/forms"); var http_1 = require("@angular/http"); var router_1 = require("@angular/router"); var app_component_1 = require("../../app.component"); var sharedcontents_1 = require("../../Shared/sharedcontents"); var login_1 = require("../../Model/UserManagement/login"); var global_1 = require("../../../app/Shared/global"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var LoginComponent = (function () { function LoginComponent(LoginService, _fb, http, router, AppComponent, service) { this.LoginService = LoginService; this._fb = _fb; this.http = http; this.router = router; this.AppComponent = AppComponent; this.service = service; this.submitted = false; this.logged = false; this.LoginObj = new login_1.LoginData(); this.service.setData('page-wrapper', false); } LoginComponent.prototype.GetRandomImagePath = function () { var _this = this; this.LoginService.GetActivateImagePath().subscribe(function (data) { _this.RandomImagePath = '../../../Upload/HomePageImage/' + data; }); }; LoginComponent.prototype.DynamicHomePageStyle = function () { var styles = { 'background': 'url(' + this.RandomImagePath + ')', 'background-size': 'cover', 'width': 'auto', 'height': 'auto', 'position': 'fixed', 'top': '0', 'right': '0', 'bottom': '0', 'left': '0', 'margin': '0', 'background-repeat': 'no-repeat' }; return styles; }; LoginComponent.prototype.Login = function () { var _this = this; if (this.LoginObj.VISUsername == null || this.LoginObj.VISPassword == null) { //this.toasterService.pop('info', 'Please Input User Id', 'Please Input Password') } else { this.UserData = null; this.LoginService.doLogin(this.LoginObj).subscribe(function (data) { _this.UserData = data; if (_this.UserData.Id > 0) { _this.UserData.ArrayUserType = _this.UserData.UserRoleTypeName.split(','); var tempDepartmentId = _this.UserData.DepartmentId.split(','); _this.UserData.ArrayDepartmentId = []; for (var _i = 0, tempDepartmentId_1 = tempDepartmentId; _i < tempDepartmentId_1.length; _i++) { var item = tempDepartmentId_1[_i]; _this.UserData.ArrayDepartmentId.push(Number(item)); } _this.service.setData('page-wrapper', true); sessionStorage.setItem('VISUsername', _this.UserData.VISUsername); sessionStorage.setItem('VISPassword', <PASSWORD>.VIS<PASSWORD>); sessionStorage.setItem('UserFullName', _this.UserData.UserFullName); sessionStorage.setItem('LastName', _this.UserData.LastName); sessionStorage.setItem('Id', _this.UserData.Id.toString()); sessionStorage.setItem('Email', _this.UserData.Email); sessionStorage.setItem('UserType', _this.UserData.UserType); sessionStorage.setItem('UserRoleTypeName', _this.UserData.UserRoleTypeName); sessionStorage.setItem('IsAdmin', JSON.stringify(_this.UserData.IsAdmin)); sessionStorage.setItem('IsLineManager', JSON.stringify(_this.UserData.IsLineManager)); sessionStorage.setItem('DepartmentId', _this.UserData.DepartmentId.toString()); sessionStorage.setItem('IsOnStypend', JSON.stringify(_this.UserData.IsOnStypend)); sessionStorage.setItem('IsFormerEmployee', JSON.stringify(_this.UserData.IsFormerEmployee)); sessionStorage.setItem('IsWebAccess', JSON.stringify(_this.UserData.IsWebAccess)); sessionStorage.setItem('validForLogin', JSON.stringify(_this.UserData.validForLogin)); sessionStorage.setItem('WebAccessURL', _this.UserData.WebAccessURL); sessionStorage.setItem('ArrayUserType', JSON.stringify(_this.UserData.ArrayUserType)); sessionStorage.setItem('ArrayDepartmentId', JSON.stringify(_this.UserData.ArrayDepartmentId)); _this.AppComponent.objLoginData = _this.UserData; _this.AppComponent.ngOnInit(); _this.router.navigate(['/dashboard']); } else { alert('Authentication failed.'); } }); } }; LoginComponent.prototype.ngOnInit = function () { this.GetRandomImagePath(); this.UserData = null; this.LoginForm = this._fb.group({ VISUsername: ['', forms_1.Validators.required], VISPassword: ['', forms_1.Validators.required], }); }; LoginComponent.prototype.ForgotPassword = function (name) { this.modal.open(); }; LoginComponent.prototype.onSubmit = function (formData) { var _this = this; this.LoginService.ForgotPassword(global_1.Global.BASE_FORGOTPASSWORD_ENDPOINT, formData._value).subscribe(function (data) { //this.UserData = data; //formData._value.VISUsername == "sa"; _this.msg = data; }, function (error) { _this.msg = error; }); }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], LoginComponent.prototype, "modal", void 0); LoginComponent = __decorate([ core_1.Component({ selector: 'login-page', templateUrl: 'app/Components/UserManagement/login.component.html', providers: [login_service_1.LoginService] }), __metadata("design:paramtypes", [login_service_1.LoginService, forms_1.FormBuilder, http_1.Http, router_1.Router, app_component_1.AppComponent, sharedcontents_1.SharedContents]) ], LoginComponent); return LoginComponent; }()); exports.LoginComponent = LoginComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Reports.Attendance { // model For Send Parameter public class OfficialWorkReportParamterModel { public string Mode { get; set; } public Int64 EmployeeId { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } public string ReportSort { get; set; } public int Sort { get; set; } public Int64 UserId { get; set; } public string UserType { get; set; } public string FromMonth { get; set; } public string FromYear { get; set; } public string ToMonth { get; set; } public string ToYear { get; set; } public bool MonthWise { get; set; } } // model for Bind Data public class OfficialWorkReport : VISBaseEntity { public string Employee_Name { get; set; } public string Date { get; set; } public string OutTime { get; set; } public string InTime { get; set; } public string Total_Time { get; set; } public string Out_Remark { get; set; } public string In_Remark { get; set; } public string Line_Manager { get; set; } public string ApprovalSentTo { get; set; } public string Status { get; set; } public string ActionBy { get; set; } public string Action_DateTime { get; set; } } public static class OfficialWorkReportConstant { // Constance For Parameter public const string const_Mode = "Mode"; public const string const_EmployeeId = "EmployeeId"; public const string const_FromDate = "FromDate"; public const string const_ToDate = "ToDate"; public const string const_ReportSort = "ReportSort"; public const string const_Sort = "Sort"; public const string const_UserId = "UserId"; public const string const_UserType = "UserType"; // Constance For Store Procedure public const string const_ProcAttendanceReportBindDropdown = "ProcAttendanceReportBindDropdown"; public const string const_procFinancialYear_SelectAll = "procGetYear"; public const string const_procUSP_OfficeWorkInOut = "procUSP_OfficeWorkInOut"; } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IEmployeeFeedback } from '../../../Model/HumanResource/Attendance/EmployeeFeedback'; @Pipe ({ name: 'EmployeeFeedbackFilter' }) export class EmployeeFeedbackFilterPipe implements PipeTransform { transform(value: IEmployeeFeedback[], filter: string): IEmployeeFeedback[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IEmployeeFeedback) => app.Remarks != null && app.Remarks.toLocaleLowerCase().indexOf(filter) != -1 || app.EmployeeName != null && app.EmployeeName.toLocaleLowerCase().indexOf(filter) != -1 || app.SenderName != null && app.SenderName.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.Other { public class Reports_OtherRepository : VISDbCommand { private static Reports_OtherRepository instance = new Reports_OtherRepository(string.Empty); private Reports_OtherRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_OtherRepository getInstance() { return instance; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class EventCountDown : VISBaseEntity { /// <summary> /// EventCountDown Entity Fields. /// </summary> /// public string EventName { get; set; } public string CountDownText { get; set; } public string CountDownDate { get; set; } public string CountDownTime { get; set; } public DateTime CountDownDateTime { get; set; } public int NoOfDay { get; set; } public bool Active { get; set; } } public static class EventCountDownnConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_Employee_EventCountDown_Table = "EventCountDown"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_EventName = "EventName"; public const string const_CountDownText = "CountDownText"; public const string const_CountDownDateTime = "CountDownDateTime"; public const string const_NoOfDay = "NoOfDay"; public const string const_Active = "Active"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procEmployee_EventCountDown_Add = "procEventCountDown_Add"; public const string const_procEmployee_EventCountDown_Update = "procEventCountDown_Update"; public const string const_procEmployee_EventCountDown_ActiveInActive = "procEventCountDown_ActiveInActive"; public const string const_procEmployee_EventCountDown_SelectAll = "procEventCountDown_SelectAll"; public const string const_procEmployee_EventCountDown_SelectById = "procEventCountDown_SelectById"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var LevelCriteriaSetup_service_1 = require("../../../service/Masters/EmployeeLevels/LevelCriteriaSetup.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var LevelCriteriaSetupComponent = (function () { function LevelCriteriaSetupComponent(fb, _LevelCriteriaSetupService, pagerService) { this.fb = fb; this._LevelCriteriaSetupService = _LevelCriteriaSetupService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'Full_Name'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; this.ArbCriteriaType = "Automatic"; this.ArbManualType = "PerformanceBased"; this.ArbSubType = "Range"; } LevelCriteriaSetupComponent.prototype.ngOnInit = function () { this.LevelCriteriaSetup = ({ Id: 0, IsAutomatic: false, IsRange: false, IsRepeated: false, IsOnce: false, IsPerformanceBased: false, IsEnable: false, ArbSubType: "", ArbCriteriaType: "", ArbIsProgressive: "", ArbCascading: "", ArbEnable: "", CriteriaID: 0, Criteria: '', Category: '', AIsRange: "", FromLimit: 0, ToLimit: 0, AIsRepeated: "", Units: 0, AIsOnce: "", // rbPerformanceBasedType: false, ArbManualType: "", IsPercentage: false, Point: 0, Active: false, IsProgressive: false, ProgressiveDays: 0, ProgressivePoints: 0, //CalculatedOn: 0, // CompanyId: 0, CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, dtFromDate: null, dtToDate: null, Name: '', CriteriaType: '', CalculatedOn: '', SelectPoint: 0, EntityMessage: '' }); this.LoadLevelCriteriaSetups(); this.LoadCriteria(); this.LoadCalculatedOn(); this.LoadCategory(); }; LevelCriteriaSetupComponent.prototype.ClearModel = function () { this.LevelCriteriaSetup = ({ Id: 0, IsAutomatic: false, IsRange: false, IsRepeated: false, IsOnce: false, IsPerformanceBased: false, IsEnable: false, ArbSubType: "", ArbCriteriaType: "", ArbIsProgressive: "", ArbCascading: "", ArbEnable: "", CriteriaID: 0, Criteria: '', Category: '', AIsRange: "", FromLimit: 0, ToLimit: 0, AIsRepeated: "", Units: 0, AIsOnce: "", // rbPerformanceBasedType: false, ArbManualType: "", IsPercentage: false, Point: 0, Active: false, IsProgressive: false, ProgressiveDays: 0, ProgressivePoints: 0, //CalculatedOn: 0, // CompanyId: 0, CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, dtFromDate: null, dtToDate: null, Name: '', CriteriaType: '', CalculatedOn: '', SelectPoint: 0, EntityMessage: '' }); }; LevelCriteriaSetupComponent.prototype.LoadCriteria = function () { var _this = this; this.indLoading = true; this._LevelCriteriaSetupService.getCriteria(global_1.Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(function (DATA) { _this.LevelCriteriaSetupForDll = DATA; } //,error => this.msg = <any>error ); }; LevelCriteriaSetupComponent.prototype.LoadCalculatedOn = function () { var _this = this; this.indLoading = true; this._LevelCriteriaSetupService.getCalculatedOn(global_1.Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(function (DATA) { _this.CalculatedOnDllData = DATA; } //,error => this.msg = <any>error ); }; LevelCriteriaSetupComponent.prototype.LoadCategory = function () { var _this = this; this.indLoading = true; this._LevelCriteriaSetupService.getCategory(global_1.Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(function (DATA) { _this.CategoryDllData = DATA; } //,error => this.msg = <any>error ); }; LevelCriteriaSetupComponent.prototype.LevelCriteriaSetupFilterCriteriaChange = function (value) { if (value != '[object Event]') this.LevelCriteriaSetupFilter = value; }; LevelCriteriaSetupComponent.prototype.LevelCriteriaSetupSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; LevelCriteriaSetupComponent.prototype.LoadLevelCriteriaSetups = function () { var _this = this; this.indLoading = true; this._LevelCriteriaSetupService.get(global_1.Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(function (LevelCriteriaSetups) { debugger; _this.LevelCriteriaSetups = LevelCriteriaSetups; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchName = document.getElementById("searchName").value; if (_this.strSearchName != '') { _this.strSearchName = _this.strSearchName.toLocaleLowerCase(); _this.LevelCriteriaSetups = _this.LevelCriteriaSetups.filter(function (x) { return x.Name != null && x.Name.toLocaleLowerCase().indexOf(_this.strSearchName) != -1; }); } _this.strSearchType = document.getElementById("searchType").value; if (_this.strSearchType != '') { _this.strSearchType = _this.strSearchType.toLocaleLowerCase(); _this.LevelCriteriaSetups = _this.LevelCriteriaSetups.filter(function (x) { return x.CriteriaType != null && x.CriteriaType.toLocaleLowerCase().indexOf(_this.strSearchType) != -1; }); } _this.strCalculatedOn = document.getElementById("searchCalculatedOn").value; if (_this.strCalculatedOn != '') { _this.strCalculatedOn = _this.strCalculatedOn.toLocaleLowerCase(); _this.LevelCriteriaSetups = _this.LevelCriteriaSetups.filter(function (x) { return x.CalculatedOn != null && x.CalculatedOn.toLocaleLowerCase().indexOf(_this.strCalculatedOn) != -1; }); } //this.strPoints = (<HTMLInputElement>document.getElementById("searchPoints")).value; //if (this.strPoints != '') { // this.strPoints = this.strPoints.toLocaleLowerCase(); // this.LevelCriteriaSetups = this.LevelCriteriaSetups.filter( // x => x.Point != null && x.Point.toLocaleLowerCase().indexOf(this.strPoints) != -1); //} } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; LevelCriteriaSetupComponent.prototype.addLevelCriteriaSetup = function () { this.EditData = false; this.ClearModel(); this.dbops = enum_1.DBOperation.create; //this.SetControlsState(true); this.modalTitle = "Add New Criteria"; this.modalBtnTitle = "Add"; // this.LevelCriteriaSetup.reset(); this.modal.open(); }; LevelCriteriaSetupComponent.prototype.editLevelCriteriaSetup = function (id) { this.ClearModel(); this.EditData = true; this.dbops = enum_1.DBOperation.update; this.modalTitle = "Edit Criteria"; this.modalBtnTitle = "Update"; this.LevelCriteriaSetup = this.LevelCriteriaSetups.filter(function (x) { return x.Id == id; })[0]; this.ArbEnable = "Yes"; if (this.LevelCriteriaSetup.IsAutomatic) { this.ArbCriteriaType = "Automatic"; if (this.LevelCriteriaSetup.IsRange) { this.ArbSubType = "Range"; } else if (this.LevelCriteriaSetup.IsRepeated) { this.ArbSubType = "Repeated"; } else { this.ArbSubType = "once"; } } else { this.ArbCriteriaType = "Manual"; } //cascadding if (this.LevelCriteriaSetup.IsProgressive) { this.ArbIsProgressive = "Yes"; } else { this.ArbIsProgressive = "No"; } // this.LevelCriteriaSetupFrm.setValue(this.LevelCriteriaSetup); this.modal.open(); }; LevelCriteriaSetupComponent.prototype.deleteLevelCriteriaSetup = function (id, status) { this.dbops = enum_1.DBOperation.delete; // this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } debugger; this.LevelCriteriaSetup = this.LevelCriteriaSetups.filter(function (x) { return x.Id == id; })[0]; // this.LevelCriteriaSetupFrm.setValue(this.LevelCriteriaSetup); this.modal.open(); }; //SetControlsState(isEnable: boolean) { // isEnable ? this.LevelCriteriaSetupFrm.enable() : this.LevelCriteriaSetupFrm.disable(); //} LevelCriteriaSetupComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; LevelCriteriaSetupComponent.prototype.ChangeCriteria = function (CriteriaId) { this.LevelCriteriaSetupFilterDDL = this.LevelCriteriaSetups.filter(function (x) { return x.Id == CriteriaId; })[0]; //this.SelectedCalculatedOn = this.LevelCriteriaSetupFilterDDL.CalculatedOn this.LevelCriteriaSetup.CalculatedOn = this.LevelCriteriaSetupFilterDDL.CalculatedOn; }; LevelCriteriaSetupComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.LevelCriteriaSetups); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; LevelCriteriaSetupComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; LevelCriteriaSetupComponent.prototype.onSubmit = function (formData) { var _this = this; debugger; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: formData.CalculatedOn = this.LevelCriteriaSetup.CalculatedOn; this._LevelCriteriaSetupService.post(global_1.Global.BASE_LEVELCRITERIASETUP_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadLevelCriteriaSetups(); _this.modal.dismiss(); _this.ClearModel(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: formData.Id = this.LevelCriteriaSetup.Id; formData.CriteriaID = this.LevelCriteriaSetup.CriteriaID; this._LevelCriteriaSetupService.put(global_1.Global.BASE_LEVELCRITERIASETUP_ENDPOINT, formData.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadLevelCriteriaSetups(); _this.modal.dismiss(); _this.ClearModel(); _this.EditData = false; } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: debugger; this._LevelCriteriaSetupService.delete(global_1.Global.BASE_LEVELCRITERIASETUP_ENDPOINT, this.LevelCriteriaSetup.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "LevelCriteriaSetup status changed successfully."; _this.LoadLevelCriteriaSetups(); } else { _this.msg = "Error has occurred while changing status of existing LevelCriteriaSetup!"; } _this.modal.dismiss(); _this.ClearModel(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], LevelCriteriaSetupComponent.prototype, "modal", void 0); LevelCriteriaSetupComponent = __decorate([ core_1.Component({ selector: "level-criteria-setup", providers: [LevelCriteriaSetup_service_1.LevelCriteriaSetupService], templateUrl: 'app/Components/Masters/EmployeeLevels/LevelCriteriaSetup.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, LevelCriteriaSetup_service_1.LevelCriteriaSetupService, pager_index_1.PagerService]) ], LevelCriteriaSetupComponent); return LevelCriteriaSetupComponent; }()); exports.LevelCriteriaSetupComponent = LevelCriteriaSetupComponent; <file_sep>export interface IAttendanceEntry { Id: number; Employee_Id: number; Entry_Type: number; Remarks: string; Entry_Time: Date; Date: string; actualEntryTime: string; grace: number; macID: string; forWhichDate: Date; ipAddress: string; source: string; isApproved: boolean; groupId: number; attendancePolicy: string; Grade: number; ImportRemarks: string; Days: string; forWhichEntryType: number; } export interface IAttendanceEntryGet { Id: number; Employee_Name: string; Password: string; Email: string; In_Mon_Fri: string; Out_Mon_Fri: string; In_Sat: string; Out_Sat: string; Grace: number; Active: boolean; userType: string; joiningDate: Date; relevingDate: Date; totalCL: number; totalSL: number; additionalRights: number; validForLogin: boolean; leaveApproveBy: number; employeeCode: string; probationTill: Date; ActivityId: number; CompanyId: number; Gender: boolean; IsConfirmed: boolean; JoiningSalary: number; PhotographFileName: string; SalaryAfterRevision: number; IsSLASigned: boolean; ConfirmationDate: Date; AppraisalDate: Date; IsAppraisalRequired: boolean; SLAYear: number; FirstName: string; MiddleName: string; LastName: string; JoiningDesignation: number; Technology: string; IsPasswordChange: boolean; OtherTechnology: string; SalaryRangeId: number; LineManagerId: number; TotalCOff: number; enrollnumber: number; AllowScreenCapture: boolean; ActiveDashboard: boolean; IsSwitchUser: boolean; WorkingLocation: number; WorkingLocationAddress: string; Education: number; CommunicationID: string; SatGrace: number; IsWebAccess: boolean; OtherRemark: string; WorksheetThruWeb: boolean; IsWorksheetFill: boolean; CL: number; SL: number; IsjoiningLeave: boolean; IsConfirmationLeave: boolean; EmployeeGradeID: number; IsResigned: boolean; isMailAlert: boolean; IsAllowMouseMovement: boolean; accessCardId: number; CreatedBy: number; CreatedDateTime: Date; UpdatedBy: number; UpdatedDateTime: Date; IsMouseTracking: boolean; IsScreenCaptureRemarks: boolean; IsHost: boolean; IsProductivityTracker: boolean; WorkFromHome: boolean; attendancePolicy: string; IsHostForEmpMaster: boolean; ResignedDate: Date; CreatedOn: Date; UpdatedOn: Date; IsActive: boolean; } export interface IGetTimeDetails { TotalOfficeTime: Date; TotalPunchInHours: Date; TotalBreakTime: Date; TotalWorkingTime: Date; PunchIn: number; InBreak: number; } export interface IPunchOutOnNextDay { Id: number; Employee_Id: number; FromDt: Date; ToDt: Date; Active: Boolean; OpenedBy: number; } export interface IGetEmployeeName { Employee_Id: number; Employee_Name: string; } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../app/Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../app/Shared/global'; import { PagerService } from '../../../app/Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; import { AttendanceEntryService } from '../../Service/UserManagement/AttendanceEntry.Service'; import { IAttendanceEntry, IGetTimeDetails, IPunchOutOnNextDay, IGetEmployeeName } from '../../../app/Model/UserManagement/AttendanceEntry'; import { DatePipe } from '@angular/common'; @Component({ providers: [AttendanceEntryService], templateUrl: 'app/Components/UserManagement/AttendanceEntry.component.html' }) export class AttendanceEntryComponent implements OnInit { @ViewChild('modalAttendanceEntry') modal: ModalComponent; AttendanceEntrys: IAttendanceEntry[]; AttendanceEntry: IAttendanceEntry; AttendanceEntryTimer: IGetTimeDetails[]; AttendanceEntryTime: IGetTimeDetails; AttendancePunchOutonNextDay: IPunchOutOnNextDay[]; AttendanceEmployeeName: IGetEmployeeName; AttendanceEmployee: IGetEmployeeName[]; dbops: DBOperation; msg: string; AttendanceEntryFrm: FormGroup; Entry_Type: number; indLoading: boolean = false; Datetime: Date; Id: number; Date: string; BreakTime: Date; PunchInHours: Date; WorkingTime: Date; forewhichdate: string; EmployeeName: string; constructor(private fb: FormBuilder, private _AttendanceEntryService: AttendanceEntryService, public http: Http, private router: Router, private pagerService: PagerService) { } ngOnInit(): void { this.modal.open(); $("#rdbpunchout").prop("disabled", true); $("#rdbLunchout").prop("disabled", true); $("#rdbLunchin").prop("disabled", true); $("#rdbotherout").prop("disabled", true); $("#rdbotherin").prop("disabled", true); $("#rdbmeetingout").prop("disabled", true); $("#rdbmeetingin").prop("disabled", true); $("#rdbOffworkout").prop("disabled", true); $("#rdbOffworkin").prop("disabled", true); this.GetEmployeeName(); this.CheckIsPunchOutOnNextDay(); setInterval(() => { this.Datetime = new Date(); }, 1000); this.Datetime = new Date(); let month = this.Datetime.getMonth() + 1; let year = this.Datetime.getFullYear(); let date1 = this.Datetime.getDate(); this.Date = + month + '/' + this.Datetime.getDate() + '/' + this.Datetime.getFullYear(); this.forewhichdate = + month + '/' + this.Datetime.getDate() + '/' + this.Datetime.getFullYear(); this.GetTimer(); if (this.Entry_Type == 0) { this.DisableEntry_Type(); } else { this.EnableEntry_Type(); } this.AttendanceEntryFrm = this.fb.group({ Employee_Id: [''], Entry_Type: [''], Remarks: [''], Entry_Time: [''], Date: [''], actualEntryTime: [''], grace: [''], macID: [''], forWhichDate: [''], ipAddress: [''], source: [''], isApproved: [''], groupId: [''], attendancePolicy: [''], Grade: [''], ImportRemarks: [''], Days: [''], forWhichEntryType: [''] }); this.AttendanceEntryTimer = [{ TotalOfficeTime: null, TotalPunchInHours: null, TotalBreakTime: null, TotalWorkingTime: null, PunchIn: 0, InBreak: 0 }]; this.AttendanceEmployeeName = ({ Employee_Id: 0, Employee_Name: '' }); } DisableEntry_Type() { var punchout = <HTMLInputElement>document.getElementById("rdbpunchout"); var LunchOut = <HTMLInputElement>document.getElementById("rdbLunchout"); var Lunchin = <HTMLInputElement>document.getElementById("rdbLunchin"); var Otherchout = <HTMLInputElement>document.getElementById("rdbotherout"); var OtherIn = <HTMLInputElement>document.getElementById("rdbotherin"); var MeetingOut = <HTMLInputElement>document.getElementById("rdbmeetingout"); var meetingIn = <HTMLInputElement>document.getElementById("rdbmeetingin"); var Officialworkout = <HTMLInputElement>document.getElementById("rdbOffworkout"); var Officialworkin = <HTMLInputElement>document.getElementById("rdbOffworkin"); punchout.disabled = true; LunchOut.disabled = true; Lunchin.disabled = true; Otherchout.disabled = true; OtherIn.disabled = true; MeetingOut.disabled = true; meetingIn.disabled = true; Officialworkout.disabled = true; Officialworkin.disabled = true; } EnableEntry_Type() { var punchout = <HTMLInputElement>document.getElementById("rdbpunchout"); var LunchOut = <HTMLInputElement>document.getElementById("rdbLunchout"); var Lunchin = <HTMLInputElement>document.getElementById("rdbLunchin"); var Otherchout = <HTMLInputElement>document.getElementById("rdbotherout"); var OtherIn = <HTMLInputElement>document.getElementById("rdbotherin"); var MeetingOut = <HTMLInputElement>document.getElementById("rdbmeetingout"); var meetingIn = <HTMLInputElement>document.getElementById("rdbmeetingin"); var Officialworkout = <HTMLInputElement>document.getElementById("rdbOffworkout"); var Officialworkin = <HTMLInputElement>document.getElementById("rdbOffworkin"); punchout.disabled = false; LunchOut.disabled = false; Lunchin.disabled = false; Otherchout.disabled = false; OtherIn.disabled = false; MeetingOut.disabled = false; meetingIn.disabled = false; Officialworkout.disabled = false; Officialworkin.disabled = false; } GetTimer(): void { this.indLoading = true; this._AttendanceEntryService.getTime(Global.BASE_AttendanceEntry_ENDPOINT, 21, this.Date) .subscribe(sucess => { this.AttendanceEntryTimer = sucess; this.AttendanceEntryTime = sucess; this.indLoading = false; this.AttendanceEntryTimer.forEach((sucess) => { this.PunchInHours = sucess.TotalPunchInHours; this.WorkingTime = sucess.TotalWorkingTime; this.BreakTime = sucess.TotalBreakTime; if (this.PunchInHours == null) { document.getElementById("lblPunchTime").innerHTML = "00:00:00"; } else { this.PunchInHours; } if (this.WorkingTime == null) { document.getElementById("lblWorkTime").innerHTML = "00:00:00"; } else { this.WorkingTime; } if (this.BreakTime == null) { document.getElementById("lblBreakTime").innerHTML = "00:00:00"; } else { this.BreakTime; } }) }, error => { alert("Error"); }); } CheckIsPunchOutOnNextDay(): void { this.indLoading = true; this._AttendanceEntryService.GetPunchOutNextDay(Global.BASE_AttendanceEntry_ENDPOINT, 199,'04/01/2016') .subscribe(data => { this.AttendancePunchOutonNextDay = data; this.indLoading = false; }); } GetEmployeeName(): void { this.indLoading = true; this._AttendanceEntryService.GetEmployeeName(Global.BASE_AttendanceEntry_ENDPOINT, 21) .subscribe(success => { this.AttendanceEmployee = success; console.log(this.AttendanceEmployeeName); }, error => { alert("error"); }); } onsubmit(formData: IAttendanceEntry) { this.msg = ""; this._AttendanceEntryService.post(Global.BASE_AttendanceEntry_ENDPOINT, formData) .subscribe(data => { if (data.startsWith("Success: "))// Success { this.msg = data; this.AttendanceEntrys = data; } else { alert(data); } }, error => { this.msg = error; }); } } <file_sep>export interface ISkill { Id: number; SkillName: string; Description: string; Level: any[]; SkillGroupID: number; SkillGroupName: string; RatingGroup: string; Status: boolean; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string; IsActive: boolean; } export interface ISkillViewModel { Id: number; SkillName: string; Description: string; Level: string; SkillGroupID: number; SkillGroupName: string; RatingGroup: string; Status: boolean; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string; IsActive: boolean; } export interface ISkillList { id: number; name: string; }<file_sep>using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.IO; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.UI; using System.Web.UI.WebControls; using SD = System.Drawing; using System.Collections; //using System.Windows.Forms; using System.Drawing; using System.Net.Mail; using System.Web.UI.HtmlControls; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Xml.Linq; using System.Linq; using VIS_Domain.HumanResource.EmployeeManagement; using VIS_Domain; namespace VIS_Repository.HumanResource.EmployeeManagement { public class EmpInfoTabularRepository : VISDbCommand, VISIBaseRepository<EmpInfoTabular> { IFormatProvider provider = new System.Globalization.CultureInfo("es-ES", true); public long returnid; public Int32 intAffectedRecords { get; set; } public int nwdId; public HttpServerUtility Server { get; } public HttpPostedFile PostedFile { get; } public DataRow dr; string lastYear = System.DateTime.Now.Year.ToString(); string id; //UserID get string Mode; public EmpInfoTabularRepository(string _connectionstring) : base(_connectionstring) { } #region commonmethod public string DeleteEntity(Int64 ExpRoleId) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procExperienceRoleAdd; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "DeleteExpRole"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ExpRoleId, ExpRoleId); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public EmpInfoTabular GetEntityByID(Int64 entityId) { return null; } public IEnumerable<EmpInfoTabular> GetEntityList() { return null; } public string AddEntity(EmpInfoTabular entityObject) { try { return null; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(EmpInfoTabular entityObject) { return null; } public string Delete() { try { return null; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #endregion #region MainSave public string SaveMain(EmpInfoTabular entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNewEmployeeAdd; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, 21); string name = entityObject.FirstName + " " + entityObject.LastName; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_EmployeeName, name); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_FirstName, entityObject.FirstName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_LastName, entityObject.LastName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_MiddleName, entityObject.MiddleName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Password, entityObject.Password); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Gender, entityObject.Gender); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserType, entityObject.UserType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Email, entityObject.Email); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_LineManagerID, entityObject.EmployeeID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_WorkingLocation, entityObject.WID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_WorkingLocationAddress, entityObject.WorkingLocationAddress); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_CommunicationID, entityObject.CommunicationID); if (entityObject.OtherRemark !=null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherRemark, entityObject.OtherRemark); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherRemark, null); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsWebAccess, entityObject.IsWebAccess); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsWorksheetWeb, entityObject.IsWorksheetWeb); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ValidForLogin, entityObject.ValidForLogin); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AllowScreenCapture, entityObject.AllowScreenCapture); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsSwitchUser, entityObject.IsSwitchUser); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsWorksheetFill, entityObject.IsWorksheetFill); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_EmployeeGradeID, entityObject.EID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsAllowMouseMovement, entityObject.IsAllowMouseMovement); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsMouseTracking, entityObject.IsMouseTracking); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsScreenCaptureRemar, entityObject.IsScreenCaptureRemarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_isInvisibleUser, entityObject.isInvisibleUser); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsHostForEmpMaster, entityObject.IsHostForEmpMaster); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsProductivityTracker, entityObject.IsProductivityTracker); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_WorkFromHome, entityObject.WorkFromHome); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Active, entityObject.Active); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_JoiningDate, entityObject.JoiningDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RelevingDate, entityObject.RelevingDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ResignedDate, entityObject.ResignedDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_TotalCL, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_TotalSL, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Employeecode, entityObject.Employeecode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ProbationTill, entityObject.ProbationTill); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CompanyId, entityObject.CompanyId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsConfirmed, entityObject.IsConfirmed); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ConfirmationDate, entityObject.ConfirmationDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_JoiningSalary, entityObject.JoiningSalary); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_JoiningDesignation, entityObject.PositionId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_PhotographFileName, entityObject.PhotographFileName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Sar, entityObject.Sar); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsSLASigned, entityObject.IsSLASigned); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsAppraisalRequired, entityObject.IsAppraisalRequired); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AppraisalDate, entityObject.AppraisalDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SLAYear, entityObject.SLAYear); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsConfirmationLeave, entityObject.IsConfirmationLeave); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsResigned, entityObject.IsResigned); objVISDbCommand.objSqlCommand.Parameters.Add("@returnid", SqlDbType.Int).Direction = ParameterDirection.Output; objVISDbCommand.objSqlCommand.Connection.Open(); // returnid = 489; //objVISDbCommand.objSqlCommand.Parameters.Add("@returnid", SqlDbType.Int); // objVISDbCommand.objSqlCommand.Parameters["@returnid"].Direction = ParameterDirection.Output; intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); long returnid = Convert.ToInt64(objVISDbCommand.objSqlCommand.Parameters["@returnid"].Value); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #endregion #region Personal public string SavePersonal(EmpInfoTabular entityObject) { try { id = entityObject.EditEmployeeid; //UserID get Edit Mode = entityObject.Editmode; //mode pass Edit VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procPersonalInformation_Add; if (Mode != null) { if (id != null && Mode == "e") { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procPersonalInformation_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "PersonalDeatilget"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter sda = new SqlDataAdapter(base.objSqlCommand); DataSet dsPersonalInformation = new DataSet(); sda.Fill(dsPersonalInformation); base.objSqlCommand.Connection.Close(); if (dsPersonalInformation.Tables[0].Rows.Count == 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, returnid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } else if (id != null && Mode == "Convert") { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, returnid); } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, returnid); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_FatherName, entityObject.FatherName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Grandfathername, entityObject.Grandfathername); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Birthdate, entityObject.Birthdate); if (entityObject.Paddress != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Paddress, entityObject.Paddress); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Paddress, ""); } if (entityObject.Caddress != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Caddress, entityObject.Caddress); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Caddress, ""); } if (entityObject.Landlineno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Landlineno, entityObject.Landlineno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Landlineno, ""); } if (entityObject.Mobileno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Mobileno, entityObject.Mobileno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Mobileno, ""); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Emergencyno, entityObject.Emergencyno); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Age, entityObject.Age); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Bloodgroup, entityObject.Bloodgroup); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Status, entityObject.Status); if (entityObject.Status != "Unmarried") { if (entityObject.Status != "Engaged") { if (entityObject.Numberofchild != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Numberofchild, entityObject.Numberofchild); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Numberofchild, 0); } if (entityObject.Childname != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Childname, entityObject.Childname); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Childname, ""); } if (entityObject.AnniversaryDate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AnniversaryDate, entityObject.AnniversaryDate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AnniversaryDate, null); } } if (entityObject.Spouse != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Spouse, entityObject.Spouse); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Spouse, ""); } if (entityObject.SpouseOccupation != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SpouseOccupation, entityObject.SpouseOccupation); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SpouseOccupation, null); } if (entityObject.Spousedob != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Spousedob, entityObject.Spousedob); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Spousedob, ""); } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Status, "Unmarried"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Spouse, ""); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SpouseOccupation, null); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Numberofchild, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Childname, ""); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AnniversaryDate, null); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Spousedob, ""); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_MotherName, entityObject.MotherName); if (entityObject.BrotherName != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_BrotherName, entityObject.BrotherName); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_BrotherName, null); } if (entityObject.BrotherOccupation != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_BrotherOccupation, entityObject.BrotherOccupation); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_BrotherOccupation, null); } if (entityObject.SisterName != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SisterName, entityObject.SisterName); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SisterName, null); } if (entityObject.SisterOccupation != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SisterOccupation, entityObject.SisterName); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SisterOccupation, null); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_FatherOccupation, entityObject.FatherOccupation); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_MotherOccupation, entityObject.MotherOccupation); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #endregion #region Education public string SaveEducation(EmpInfoTabular entityObject) { try { id = entityObject.EditEmployeeid; //UserID get Edit Mode = entityObject.Editmode; //mode pass Edit VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_ProcEducation; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Education, entityObject.EducationID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); objVISDbCommand.objSqlCommand.Connection.Open(); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procPersonalInformation_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EducatioDeatilget"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter sda = new SqlDataAdapter(base.objSqlCommand); DataSet DsEducation = new DataSet(); sda.Fill(DsEducation); base.objSqlCommand.Connection.Close(); if (entityObject.Schoolinstitute != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procEducationAdd; if (Mode != null) { if (id != null && Mode == "e") { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Eduid, Convert.ToInt32(DsEducation.Tables[0].Rows[0][0])); int i = Convert.ToInt32(DsEducation.Tables[0].Rows[0][0]); } else { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procPersonalInformation_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EducatioDeatilget"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter sdaEducation = new SqlDataAdapter(base.objSqlCommand); DataSet DsEducation1 = new DataSet(); sdaEducation.Fill(DsEducation1); base.objSqlCommand.Connection.Close(); if (DsEducation1.Tables[0].Rows.Count == 0) { if (id != null && (Mode == "e" || Mode == "Convert")) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } } } } else if (Mode != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Eduid, Convert.ToInt32(DsEducation.Tables[0].Rows[0][0])); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_HighestEducation, entityObject.HighestEducation); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ClassDegree, entityObject.ClassDegree); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Schoolinstitute, entityObject.Schoolinstitute); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Medium, entityObject.Medium); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Passingyear, entityObject.Passingyear); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Boarduniversity, entityObject.Boarduniversity); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Percentage, entityObject.Percentage); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #endregion #region Experiences public string AddRole(EmpInfoTabular entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procExperienceRoleAdd; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "AddExpRole"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RoleId, entityObject.RoleId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Efficiency, entityObject.Efficiency); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<EmpInfoTabular> GetRoleAdd() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procExperienceRoleAdd; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "GetUserExpRole"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public string AddPastExperience(EmpInfoTabular entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procExperienceRoleAdd; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "AddExpRole"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RoleId, entityObject.RoleId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Efficiency, entityObject.Efficiency); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } protected void checkExperience(EmpInfoTabular entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); int checkvar = 0, checkvar2 = 0; int flag = 0; string id = "21"; System.TimeSpan resultofj = new TimeSpan(0, 0, 0, 0, 0); if (entityObject.Joiningdate != null) { checkvar = 1; DateTime joinExperience = Convert.ToDateTime(entityObject.Joiningdate); int Enodate = joinExperience.Day; int Enomonth = joinExperience.Month; int Enoyear = joinExperience.Year; System.DateTime dtjoiningE = new System.DateTime(Enoyear, Enomonth, Enodate, 0, 0, 0); //joining must greater than last releving if (id != null) { flag = 1; } else { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procCheckExperience; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "ExperienceCheck"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daExperience = new SqlDataAdapter(base.objSqlCommand); DataSet dsExperience = new DataSet(); daExperience.Fill(dsExperience); if (dsExperience.Tables[0].Rows.Count > 0) { DateTime rdate = Convert.ToDateTime(dsExperience.Tables[0].Rows[0]["relievingdate"].ToString()); rdate = rdate.AddDays(1); resultofj = dtjoiningE.Subtract(rdate); flag = 0; } else { flag = 1; } //end releving } } if (entityObject.Relievingdate != null) { checkvar2 = 1; } if (checkvar == 1 && checkvar2 == 1) { DateTime joindate = Convert.ToDateTime(entityObject.Joiningdate); int JoDate = joindate.Day; int JoMonth = joindate.Month; int JoYear = joindate.Year; DateTime releavingExperience = Convert.ToDateTime(entityObject.Relievingdate); int Enodate1 = releavingExperience.Day; int Enomonth1 = releavingExperience.Month; int Enoyear1 = releavingExperience.Year; DateTime currentdateexperience = DateTime.Today; int nodate = currentdateexperience.Day; int nomonth = currentdateexperience.Month; int noyear = currentdateexperience.Year; DateTime dtjoining = new DateTime(Enoyear, Enomonth, Enodate, 0, 0, 0); DateTime currentdate1 = new DateTime(noyear, nomonth, nodate, 0, 0, 0); DateTime dtrelevingE = new DateTime(Enoyear1, Enomonth1, Enodate1, 0, 0, 0); TimeSpan resultrelnjoining = dtjoiningE.Subtract(dtrelevingE); TimeSpan resultofjoining = dtjoiningE.Subtract(currentdate1); TimeSpan resultofreleaving = dtrelevingE.Subtract(currentdate1); if (resultofjoining.Days <= 0) { if (resultofreleaving.Days <= 0) { if (resultrelnjoining.Days <= 0) { if (resultofj.Days > 0) { id = entityObject.EditEmployeeid; Mode = entityObject.Editmode; string experienceid = ""; objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperience_Add; if (Mode != null) { if (id != null && experienceid != null && ((Mode == "e") || (Mode == "Convert"))) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } else { if (id != null && experienceid != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } if (entityObject.Org != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, entityObject.Org); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, ""); } if (entityObject.Url != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, entityObject.Url); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, ""); } if (entityObject.Designation != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, entityObject.Designation); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, ""); } if (entityObject.Joiningdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, entityObject.Joiningdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, ""); } if (entityObject.Relievingdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, entityObject.Relievingdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, ""); } if (entityObject.Reportingto != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, entityObject.Reportingto); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, ""); } if (entityObject.Contactno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, entityObject.Contactno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, ""); } if (entityObject.Reason != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, entityObject.Reason); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, ""); } if (entityObject.Lastsalary != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, entityObject.Lastsalary); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, ""); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Totalexp, entityObject.Totalexp); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); // SetData(); } else { id = entityObject.EditEmployeeid; Mode = entityObject.Editmode; string experienceid = ""; objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperience_Add; if (Mode != null) { if (id != null && experienceid != null && ((Mode == "e") || (Mode == "Convert"))) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } else { if (id != null && experienceid != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } } if (entityObject.Org != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, entityObject.Org); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, ""); } if (entityObject.Url != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, entityObject.Url); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, ""); } if (entityObject.Designation != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, entityObject.Designation); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, ""); } if (entityObject.Joiningdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, entityObject.Joiningdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, ""); } if (entityObject.Relievingdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, entityObject.Relievingdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, ""); } if (entityObject.Reportingto != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, entityObject.Reportingto); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, ""); } if (entityObject.Contactno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, entityObject.Contactno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, ""); } if (entityObject.Reason != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, entityObject.Reason); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, ""); } if (entityObject.Lastsalary != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, entityObject.Lastsalary); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, ""); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Totalexp, entityObject.Totalexp); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } } } } } else if (checkvar2 == 1) { DateTime releavingExperience = Convert.ToDateTime(entityObject.Relievingdate); int Enodate1 = releavingExperience.Day; int Enomonth1 = releavingExperience.Month; int Enoyear1 = releavingExperience.Year; DateTime currentdateexperience = DateTime.Today; int nodate = currentdateexperience.Day; int nomonth = currentdateexperience.Month; int noyear = currentdateexperience.Year; System.DateTime currentdate1 = new System.DateTime(noyear, nomonth, nodate, 0, 0, 0); System.DateTime dtrelevingE = new System.DateTime(Enoyear1, Enomonth1, Enodate1, 0, 0, 0); System.TimeSpan resultofreleaving = dtrelevingE.Subtract(currentdate1); if (resultofreleaving.Days <= 0) { if (id != null && (Mode == "e" || Mode == "Convert")) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procCheckExperience; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "ExperienceCheck"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daExperienceMaster = new SqlDataAdapter(base.objSqlCommand); DataSet dsExperienceMaster = new DataSet(); daExperienceMaster.Fill(dsExperienceMaster); base.objSqlCommand.Connection.Close(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperience_Add; if (dsExperienceMaster.Tables[0].Rows.Count == 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } if (entityObject.expyear != 0 || entityObject.expmonth != 0) { int expyear = 0; int expMonth = 0; if (entityObject.expyear != 0) { expyear = Convert.ToInt32(entityObject.relevanceExpYear); } if (entityObject.relevanceExpMonth != null) { expMonth = Convert.ToInt32(entityObject.relevanceExpMonth); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RelevanceExp, expyear + "." + expMonth); } if (!string.IsNullOrEmpty(entityObject.hdnProjectsToSave.ToString())) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ProjectHandled, entityObject.hdnProjectsToSave.Substring(0, entityObject.hdnProjectsToSave.Length - 1)); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_experiencesummary, entityObject.experiencesummary); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Skills, entityObject.Skills); } } else if (checkvar == 1) { DateTime joinExperience1 = Convert.ToDateTime(entityObject.Joiningdate); int Enodate1 = joinExperience1.Day; int Enomonth1 = joinExperience1.Month; int Enoyear1 = joinExperience1.Year; DateTime currentdateexperience = DateTime.Today; int nodate = currentdateexperience.Day; int nomonth = currentdateexperience.Month; int noyear = currentdateexperience.Year; DateTime dtjoining = new DateTime(Enoyear1, Enomonth1, Enodate1, 0, 0, 0); DateTime currentdate1 = new DateTime(noyear, nomonth, nodate, 0, 0, 0); TimeSpan resultofjoining = dtjoining.Subtract(currentdate1); if (resultofjoining.Days <= 0) { id = entityObject.EditEmployeeid; Mode = entityObject.Editmode; string experienceid = ""; objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperience_Add; if (Mode != null) { if (id != null && experienceid != null && ((Mode == "e") || (Mode == "Convert"))) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } else { if (id != null && experienceid != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } if (entityObject.Org != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, entityObject.Org); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, ""); } if (entityObject.Url != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, entityObject.Url); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, ""); } if (entityObject.Designation != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, entityObject.Designation); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, ""); } if (entityObject.Joiningdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, entityObject.Joiningdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, ""); } if (entityObject.Relievingdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, entityObject.Relievingdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, ""); } if (entityObject.Reportingto != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, entityObject.Reportingto); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, ""); } if (entityObject.Contactno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, entityObject.Contactno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, ""); } if (entityObject.Reason != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, entityObject.Reason); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, ""); } if (entityObject.Lastsalary != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, entityObject.Lastsalary); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, ""); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Totalexp, entityObject.Totalexp); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); // SetData(); } } else { id = entityObject.EditEmployeeid; Mode = entityObject.Editmode; string experienceid = null; objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperience_Add; if (Mode != null) { if (id != null && experienceid != null && ((Mode == "e") || (Mode == "Convert"))) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } else { if (id != null && experienceid != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expid, experienceid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } if (entityObject.Org != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, entityObject.Org); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, ""); } if (entityObject.Url != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, entityObject.Url); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, ""); } if (entityObject.Designation != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, entityObject.Designation); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, ""); } if (entityObject.Joiningdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, entityObject.Joiningdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, ""); } if (entityObject.Relievingdate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, entityObject.Relievingdate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, ""); } if (entityObject.Reportingto != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, entityObject.Reportingto); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, ""); } if (entityObject.Contactno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, entityObject.Contactno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, ""); } if (entityObject.Reason != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, entityObject.Reason); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reason, ""); } if (entityObject.Lastsalary != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, entityObject.Lastsalary); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, ""); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Totalexp, entityObject.Totalexp); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); // SetData(); } } } catch (Exception ex) { //return ex.Message + Environment.NewLine + ex.StackTrace; } } public string btnAddExp(EmpInfoTabular entityObject) { id = entityObject.EditEmployeeid; Mode = entityObject.Editmode; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperience_Add; try { if (Mode != null) { if (Mode == "Convert") { using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procprojectListGet; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "NonWbsProject"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter sda = new SqlDataAdapter(base.objSqlCommand); DataSet dsCandidatePreviousDetails = new DataSet(); sda.Fill(dsCandidatePreviousDetails); base.objSqlCommand.Connection.Close(); if (dsCandidatePreviousDetails.Tables[0].Rows.Count > 0) { for (int i = 0; i < dsCandidatePreviousDetails.Tables[0].Rows.Count; i++) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procprojectListGet; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "GetPosition"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_positionName, dsCandidatePreviousDetails.Tables[0].Rows[i]["Designation"].ToString()); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daposition = new SqlDataAdapter(base.objSqlCommand); DataSet dsposition = new DataSet(); daposition.Fill(dsposition); base.objSqlCommand.Connection.Close(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperience_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Org, dsCandidatePreviousDetails.Tables[0].Rows[i]["OrganizationName"].ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Url, null); if (dsposition.Tables[0].Rows.Count > 0) { if (dsposition.Tables[0].Rows[0]["id"] != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, Convert.ToInt32(dsposition.Tables[0].Rows[0]["id"].ToString())); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, null); } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designation, null); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastsalary, Convert.ToInt32(dsCandidatePreviousDetails.Tables[0].Rows[i]["Salary"].ToString())); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Joiningdate, Convert.ToDateTime(dsCandidatePreviousDetails.Tables[0].Rows[i]["JoiningDate"].ToString())); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, Convert.ToDateTime(dsCandidatePreviousDetails.Tables[0].Rows[i]["RelievingDate"].ToString())); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Reportingto, null); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Contactno, null); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Relievingdate, null); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); SetExperienceData(id); } } } } else { checkExperience(entityObject); } } else { checkExperience(entityObject); } } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } return null; } protected void SavePastExperience(EmpInfoTabular entityObject) { } private string GetProjects() { DataSet dsProjects = new DataSet(); string hdnProject; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procExperienceProjectGet; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "GetProjects"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter sda = new SqlDataAdapter(base.objSqlCommand); sda.Fill(dsProjects); base.objSqlCommand.Connection.Close(); if (dsProjects != null && dsProjects.Tables[0].Rows.Count > 0) { foreach (DataRow dr1 in dsProjects.Tables[0].Rows) { hdnProject = dr1.ItemArray[0].ToString() + ","; var var = hdnProject; return var; } } } return null; } protected DataTable SetExperienceData(string id) { List<EmpInfoTabular> objListToReturn1 = new List<EmpInfoTabular>(); try { GetProjects(); DataSet dsExp = new DataSet(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procprojectListGet; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "GetExperience"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = dsExp.Tables[0]; da.Fill(dsExp); base.objSqlCommand.Connection.Close(); if (dsExp != null) { if (dsExp.Tables[2].Rows.Count > 0) { DataTable Detail = new DataTable(); string name = dsExp.Tables[2].Rows[0]["Employee_Name"].ToString(); string lblmsgRecordExist = "Employee Name: " + name.ToString(); string lbltotalExp = dsExp.Tables[2].Rows[0]["TotalExp"].ToString().Split('.')[0] + " Year " + dsExp.Tables[2].Rows[0]["TotalExp"].ToString().Split('.')[1] + " Month"; string technology = dsExp.Tables[2].Rows[0]["Technology"].ToString(); string[] techarr = technology.Split(','); List<ListItem> RemoveEmployeeIndex = new List<ListItem>(); List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procTechnologyListboxbind; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daSkill = new SqlDataAdapter(base.objSqlCommand); DataSet dtSkill = new DataSet(); daSkill.Fill(dtSkill); for (int i = 0; i < techarr.Length; i++) { for (int k = 0; k < dtSkill.Tables[0].Rows.Count; k++) { if (dtSkill.Tables[0].Rows[i].ToString() == techarr[i].ToString()) { List<ListItem> lsbTechnicalSkill = new List<ListItem>(); ListItem item = new ListItem(); item.Text = dtSkill.Tables[0].Rows[i]["TechnologyID"].ToString(); item.Value = dtSkill.Tables[0].Rows[i]["technologyName"].ToString(); lsbTechnicalSkill.Add(item); RemoveEmployeeIndex.Add(item); } } for (int iCount = 0; iCount < RemoveEmployeeIndex.Count; iCount++) { string dtskill = dtSkill.Tables[0].Rows.ToString(); string Removeid = Convert.ToString(RemoveEmployeeIndex[iCount]); dtskill.Remove(Convert.ToInt32(Removeid)); } } string txtTechnicalExpertise = dsExp.Tables[2].Rows[0]["OtherTechnology"].ToString(); } if (dsExp.Tables[0].Rows.Count > 0) { return dt; } if (dsExp.Tables[1].Rows.Count > 0) { string txtExperienceSummary = dsExp.Tables[1].Rows[0]["ExperienceSummary"].ToString(); string txtSkillRemarks = dsExp.Tables[1].Rows[0]["Skills"].ToString(); // var experience = dsExperienceMaster.Tables[0].Rows[0]["RelevanceExperience"].ToString().Split(',')[0]; if (dsExp.Tables[1].Rows[0]["RelevanceExperience"].ToString() != "") { string txtrelevanceExpYear = dsExp.Tables[1].Rows[0]["RelevanceExperience"].ToString().Split('.')[0]; string txtrelevanceExpMonth = dsExp.Tables[1].Rows[0]["RelevanceExperience"].ToString().Split('.')[1]; } else { // txtrelevanceExpYear.Text = "0"; // txtrelevanceExpMonth.Text = "0"; } if (dsExp.Tables[1].Rows[0]["Projectshandled"] != null) { string[] tagarr = dsExp.Tables[1].Rows[0]["Projectshandled"].ToString().Split(','); for (int i = 0; i < tagarr.Length; i++) { HtmlGenericControl newLi = new HtmlGenericControl("li"); string targetid = tagarr[i].ToString(); UList(targetid); } } } } return null; } catch (Exception) { } return null; } private HtmlGenericControl UList(string targetid) // For <ul> tag { HtmlGenericControl newLi = new HtmlGenericControl("li"); newLi.InnerHtml += targetid; return newLi; } #endregion #region Salary public string SaveSalary(EmpInfoTabular entityObject) { try { Mode = entityObject.Editmode; id = entityObject.EditEmployeeid; string mode = ""; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); using (base.objSqlCommand.Connection) { if (Mode != null) { if (id != null && (Mode == "e" || Mode == "Convert")) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procCurrentSalary_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "checksalarydata"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daCurrentSalary = new SqlDataAdapter(base.objSqlCommand); DataSet dsCurrentSalary = new DataSet(); daCurrentSalary.Fill(dsCurrentSalary); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procCurrentSalary_Add; if (dsCurrentSalary.Tables[0].Rows.Count == 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); mode = "add"; } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); mode = "update"; } } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } if (mode == "add") { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procCurrentSalary_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "JoiningDesignation"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daJoiDesig = new SqlDataAdapter(base.objSqlCommand); DataSet dsJoiDesig = new DataSet(); daJoiDesig.Fill(dsJoiDesig); if (dsJoiDesig != null && dsJoiDesig.Tables.Count > 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_CurrentDesignation, dsJoiDesig.Tables[0].Rows[0]["JoiningDesignation"].ToString()); } } if (mode == " ") { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procCurrentSalary_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "JoiningDesignationSelect"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daJoiDesig = new SqlDataAdapter(base.objSqlCommand); DataSet dsJoiDesig = new DataSet(); daJoiDesig.Fill(dsJoiDesig); if (dsJoiDesig != null && dsJoiDesig.Tables.Count > 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_CurrentDesignation, dsJoiDesig.Tables[0].Rows[0]["JoiningDesignation"].ToString()); } } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Salary, entityObject.Salary); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Bankname, entityObject.Bankname); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Accountno, entityObject.Accountno); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ISPFApplicable, entityObject.ISPFApplicable); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_PFAccountNo, entityObject.PFAccountNo); if (entityObject.AdharNumber != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AdharNumber, entityObject.AdharNumber); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AdharNumber, 0); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UANNumber, entityObject.UANNumber); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procManagesalary; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SalaryRangeId, entityObject.SalaryRangeId); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #endregion #region Attendance public string SaveAttendance(EmpInfoTabular entityObject) { try { Mode = entityObject.Editmode; id = entityObject.EditEmployeeid; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procAttendance_Add; if (Mode != null) { if (id != null && (Mode == "e" || Mode == "Convert")) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Intime, entityObject.Intime); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Outitme, entityObject.Outitme); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Intimesat, entityObject.Intimesat); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Outtimesat, entityObject.Outtimesat); if (entityObject.Grace != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Grace, entityObject.Grace); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Grace, 0); } if (entityObject.SatGrace != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SatGrace, entityObject.SatGrace); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SatGrace, 0); } if (entityObject.EmployeeID != 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Leaveapproveby, entityObject.EmployeeID); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Leaveapproveby, 0); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsAlertRequired, entityObject.IsAlertRequired); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AccessCardId, entityObject.AccessCardId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AttendancePolicy, entityObject.AttendancePolicy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); string value = entityObject.Nwdday; SaveNwdDay(entityObject.Nwdday); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public DataTable GetAttendanceDetail(int AccessCardId, long UserId) { DataTable dt = new DataTable(); DataRow dr = dt.NewRow(); DataSet dataSet = new DataSet(); dt.Columns.Add(new DataColumn("Output", typeof(string))); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procAttencessdeatilcheck; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AccessCardId, AccessCardId); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaProject1 = new SqlDataAdapter(base.objSqlCommand); DaProject1.Fill(dataSet); if (dataSet != null && dataSet.Tables[0].Rows.Count > 0) { if (dataSet.Tables[0].Rows[0]["Output"].ToString() == "Already") { string value = "true"; dr["Output"] = value; } else { string value = "false"; dr["Output"] = value; } } else { string value = "Null"; dr["Output"] = value; } dt.Rows.Add(dr); } return dt; } public string SaveNwdDay(string Nwdday) { string[] NWDday = Nwdday.Split(','); string id = "484"; string mode = ""; if (id != null && mode == "e") { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNowworkingcheck; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EmployeeNwd"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daEmpNwd = new SqlDataAdapter(base.objSqlCommand); DataSet dsEmpNwd = new DataSet(); daEmpNwd.Fill(dsEmpNwd); if (dsEmpNwd.Tables[0].Rows.Count > 0) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNowworkingcheck; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "DeleteEmplyeeNwd"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); objVISDbCommand.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNowworkingcheck; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "SelectEmplyeeNwd"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daNwdHistory = new SqlDataAdapter(base.objSqlCommand); DataSet dsNwdHistory = new DataSet(); daNwdHistory.Fill(dsNwdHistory); if (dsNwdHistory.Tables[0].Rows.Count > 0) { objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNowworkingcheck; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "deleteEmplyeeNwd"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } } } } // start : add Non working days else { DateTime dtNow = System.DateTime.Now; string strNow = dtNow.ToString("yyyyMMdd"); int daysInMonth = System.DateTime.DaysInMonth(dtNow.Year, dtNow.Month); DateTime dtEnd = new DateTime(dtNow.Year, 12, daysInMonth); string strEnd = dtEnd.ToString("yyyyMMdd"); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); //int nwdId = 12; foreach (string day in NWDday) { nwdId = Convert.ToInt32(day); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNowworkingcheck; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "NwdDaySelect"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, nwdId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daNwd = new SqlDataAdapter(base.objSqlCommand); DataSet dsNwd = new DataSet(); daNwd.Fill(dsNwd); string strDay = dsNwd.Tables[0].Rows[0]["day"].ToString(); string strDuration = dsNwd.Tables[0].Rows[0]["duration"].ToString(); string strOcc = dsNwd.Tables[0].Rows[0]["occurrence"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procFunctioncallNwd; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_strNow, strNow); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_strEnd, strEnd); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_strDay, strDay); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daList = new SqlDataAdapter(base.objSqlCommand); DataSet dsList = new DataSet(); daList.Fill(dsList); string val = "484"; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNowworkingcheck; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "insertNwdDay"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, val); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_nwdId, nwdId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); for (int j = 0; j < dsList.Tables[0].Rows.Count; j++) { string stDate = dsList.Tables[0].Rows[j]["Dt"].ToString(); DateTime dtFromNon = DateTime.Parse(stDate, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault); Boolean addRecord = false; //string duration = lstNonWorkingDays.Items[i].Attribut if (strOcc == "Every") { addRecord = true; } else if (strOcc == "Even") { int weekNum = weekOfYear(dtFromNon.Year, dtFromNon.Month, dtFromNon.Day); if (weekNum % 2 == 0) { addRecord = true; } } else if (strOcc == "Odd") { int weekNum = weekOfYear(dtFromNon.Year, dtFromNon.Month, dtFromNon.Day); if (weekNum % 2 != 0) { addRecord = true; } } else if (strOcc == "Last") { int year = dtFromNon.Year; int month = dtFromNon.Month; int days = System.DateTime.DaysInMonth(year, month); DateTime dtStart = new DateTime(year, month, 1); int totalWeek = Weeks(year, month, dtStart.DayOfWeek); DateTime date = dtFromNon; DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1); while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) date = date.AddDays(1); int tempInt = (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1; if (tempInt == totalWeek) { addRecord = true; } } else { DateTime date = dtFromNon; DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1); while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) date = date.AddDays(1); int tempInt = (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1; //int intPart = dtFromNon.Day / 7; if (tempInt.ToString() == strOcc) { addRecord = true; } } if (addRecord) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procNowworkingcheck; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "InsertNwdHistory"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, val); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_dtFromNon, dtFromNon.ToString("yyyyMMdd")); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_strDuration, strDuration); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_nwdId, nwdId); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } } } break; } } return "Save data"; } protected int weekOfYear(int year, int month, int date) { DateTime dt = new DateTime(year, month, date); DateTime dt2 = new DateTime(dt.Year, 1, 1); int intDiff = 0; if (dt2.DayOfWeek == DayOfWeek.Sunday) { intDiff = 0; } else if (dt2.DayOfWeek == DayOfWeek.Monday) { intDiff = 6; } else if (dt2.DayOfWeek == DayOfWeek.Tuesday) { intDiff = 5; } else if (dt2.DayOfWeek == DayOfWeek.Wednesday) { intDiff = 4; } else if (dt2.DayOfWeek == DayOfWeek.Thursday) { intDiff = 3; } else if (dt2.DayOfWeek == DayOfWeek.Friday) { intDiff = 2; } else if (dt2.DayOfWeek == DayOfWeek.Saturday) { intDiff = 1; } int i = dt.DayOfYear; int j = i % 7; int k = i / 7; int answer = 0; if (j > intDiff) { answer = 1 + k + 1; } else { answer = 1 + k; } return answer; } private static int Weeks(int year, int month, DayOfWeek wkstart) { DateTime first = new DateTime(year, month, 1); int firstwkday = (int)first.DayOfWeek; int otherwkday = (int)wkstart; int offset = ((otherwkday + 7) - firstwkday) % 7; double weeks = (double)(DateTime.DaysInMonth(year, month) - offset) / 7d; return (int)Math.Ceiling(weeks); } #endregion #region OfficialDeatil public string SaveOfficial(EmpInfoTabular entityObject) { try { id = entityObject.EditEmployeeid; //UserID get Edit Mode = entityObject.Editmode; //mode pass Edit VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procOfficialDetail_Add; if (id != null) { using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procOfficialDetail_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "OfficialDetail"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataSet ds = new DataSet(); da.Fill(ds); base.objSqlCommand.Connection.Close(); if (Mode != null) { if (ds.Tables.Count > 0) { if (id != null && Mode == "e") { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procOfficialDetail_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "OfficialDetail"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daOfficialDetail = new SqlDataAdapter(base.objSqlCommand); DataSet dsOfficialDetail = new DataSet(); daOfficialDetail.Fill(dsOfficialDetail); base.objSqlCommand.Connection.Close(); if (dsOfficialDetail.Tables[0].Rows.Count == 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, ds.Tables[0].Rows[0]["Id"]); } } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } } } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } if (entityObject.Verveemail != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Verveemail, entityObject.Verveemail); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Verveemail, ""); } if (entityObject.Vervepassword != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Vervepassword, entityObject.Vervepassword); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Vervepassword, ""); } if (entityObject.Gmail != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Gmail, entityObject.Gmail); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Gmail, ""); } if (entityObject.Gmailpassword != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Gmailpassword, entityObject.Gmailpassword); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Gmailpassword, ""); } if (entityObject.Yahoo != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Yahoo, entityObject.Yahoo); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Yahoo, ""); } if (entityObject.Yahoopassword != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Yahoopassword, entityObject.Yahoopassword); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Yahoopassword, ""); } if (entityObject.Skype != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Skype, entityObject.Skype); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Skype, ""); } if (entityObject.Skypepassword != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Skypepassword, entityObject.Skypepassword); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Skypepassword, ""); } if (entityObject.Othersitename != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Othersitename, entityObject.Othersitename); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Othersitename, ""); } if (entityObject.Otherid != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Otherid, entityObject.Otherid); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Otherid, ""); } if (entityObject.Otherpassword != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Otherpassword, entityObject.Otherpassword); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Otherpassword, ""); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #endregion #region Joining public string SaveJoining(EmpInfoTabular entityObject) { try { id = entityObject.EditEmployeeid; Mode = entityObject.Editmode; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; if (!string.IsNullOrEmpty(Mode)) { if (id != null && Mode == "e" || Mode == "Convert") { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "joingdetailscheck"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daJoiningDocument = new SqlDataAdapter(base.objSqlCommand); DataSet dsJoiningDocument = new DataSet(); daJoiningDocument.Fill(dsJoiningDocument); base.objSqlCommand.Parameters.Clear(); if (dsJoiningDocument.Tables[0].Rows.Count == 0) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); } } } } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } if (entityObject.Panno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Panno, entityObject.Panno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Panno, ""); } if (entityObject.Passportno != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Passportno, entityObject.Passportno); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Passportno, ""); } if (entityObject.Placeofissue != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Placeofissue, entityObject.Placeofissue); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Placeofissue, ""); } if (entityObject.Issuedate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Issuedate, entityObject.Issuedate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Issuedate, ""); } if (entityObject.Expirydate != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expirydate, entityObject.Expirydate); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Expirydate, ""); } if (entityObject.Other != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Other, entityObject.Other); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Other, ""); } if (entityObject.Other0 != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Other0, entityObject.Other0); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Other0, ""); } if (entityObject.Other1 != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Other1, entityObject.Other1); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Other1, ""); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "JoingCheck"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaJoiningDocument = new SqlDataAdapter(base.objSqlCommand); DataSet DsJoiningDocument = new DataSet(); DaJoiningDocument.Fill(DsJoiningDocument); base.objSqlCommand.Parameters.Clear(); if (DsJoiningDocument.Tables[0].Rows[0]["IsRelevingLetter"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["IsRelevingLetter"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["RelievingLetterFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveRelievingLetter"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RelievingLetterFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isrelevingletter, entityObject.Isrelevingletter); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.RelievingLetterFileName != null) { string filename = entityObject.RelievingLetterFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveRelievingLetter"); string[] arr = filename.Split('.'); string prefix = arr[0].ToString(); filename = ""; filename += prefix.ToString() + "-Rel-" + id + "." + type.ToString(); string filedir = "upload/JoiningDocuments/" + filename; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RelievingLetterFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isrelevingletter, entityObject.Isrelevingletter); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["IsExperienceLetter"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["IsExperienceLetter"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["ExperienceLetterFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveExperienceLetter"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ExperienceLetterFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isexperienceletter, entityObject.Isexperienceletter); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.ExperienceLetterFileName != null) { string filename = entityObject.ExperienceLetterFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveExperienceLetter"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RelievingLetterFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isrelevingletter, entityObject.Isrelevingletter); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["IsSalarySlip"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["IsSalarySlip"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["LastSalarySlipFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveLastSalarySlip"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_LastSalarySlipFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Issalaryslip, entityObject.Issalaryslip); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.LastMarksheetFileName != null) { string filename = entityObject.ExperienceLetterFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveLastSalarySlip"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_LastSalarySlipFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Issalaryslip, entityObject.Issalaryslip); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["IsDegreeCertificate"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["IsDegreeCertificate"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["DegreeCertificateFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveDegreeCertificate"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RelievingLetterFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsDegreeCertificate, entityObject.IsDegreeCertificate); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.DegreeCertificateFileName != null) { string filename = entityObject.DegreeCertificateFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveDegreeCertificate"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_RelievingLetterFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsDegreeCertificate, entityObject.IsDegreeCertificate); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["IsMarkSheet"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["IsMarkSheet"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["LastMarksheetFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveLastMarksheet"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_LastMarksheetFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsMarkSheet, entityObject.IsMarkSheet); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.LastMarksheetFileName != null) { string filename = entityObject.LastMarksheetFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveLastMarksheet"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_LastMarksheetFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsMarkSheet, entityObject.IsMarkSheet); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["IsPassport"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["IsPassport"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["PassportFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemovePassport"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_PassportFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsPassport, entityObject.IsPassport); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.PassportFileName != null) { string filename = entityObject.PassportFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemovePassport"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_PassportFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_IsPassport, entityObject.IsPassport); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["Isdrivinglicense"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["Isdrivinglicense"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["DrivingLicenseFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveDrivingLicense"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_DrivingLicenseFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isdrivinglicense, entityObject.Isdrivinglicense); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.DrivingLicenseFileName != null) { string filename = entityObject.DrivingLicenseFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveDrivingLicense"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_DrivingLicenseFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isdrivinglicense, entityObject.Isdrivinglicense); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["Ispancard"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["Ispancard"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["PANCardFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemovePANCard"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_DrivingLicenseFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Ispancard, entityObject.Ispancard); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.PANCardFileName != null) { string filename = entityObject.PANCardFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemovePANCard"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_PANCardFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Ispancard, entityObject.Ispancard); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["IsCurriculamVitae"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["IsCurriculamVitae"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["CurriculamVitaeFilName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveCurriculamVitae"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_CurriculamVitaeFilName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Iscv, entityObject.Iscv); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.CurriculamVitaeFilName != null) { string filename = entityObject.CurriculamVitaeFilName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveCurriculamVitae"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_CurriculamVitaeFilName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Iscv, entityObject.Iscv); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["Isother"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["Isother"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["OtherFileName"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveOther"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherFileName, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isother, entityObject.Isother); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.OtherFileName != null) { string filename = entityObject.OtherFileName; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveOther"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherFileName, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isother, entityObject.Isother); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["Isother0"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["Isother0"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["OtherFileName0"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveOther0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherFileName0, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isother0, entityObject.Isother0); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.OtherFileName0 != null) { string filename = entityObject.OtherFileName0; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveOther0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherFileName0, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isother0, entityObject.Isother0); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } if (DsJoiningDocument.Tables[0].Rows[0]["Isother1"].ToString() == "True" && DsJoiningDocument.Tables[0].Rows[0]["Isother1"] != null) { string FileName = DsJoiningDocument.Tables[0].Rows[0]["OtherFileName1"].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveOther1"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherFileName1, FileName.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isother1, entityObject.Isother1); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } else { if (entityObject.OtherFileName1 != null) { string filename = entityObject.OtherFileName1; string type = filename.Substring(filename.LastIndexOf(".") + 1); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procJoiningDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "RemoveOther1"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_OtherFileName1, filename.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isother1, entityObject.Isother1); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #endregion #region leave public string AddLeave(EmpInfoTabular entityObject) { try { id = entityObject.EditEmployeeid; //UserID get VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procAdjustedLeaveAdd; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "InsertLeave"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Leavetype, entityObject.Leavetype); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AdjustedValue, entityObject.AdjustedValue); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Transactiontype, entityObject.Transactiontype); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isadjusted, entityObject.Isadjusted); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Remarks, entityObject.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); return intAffectedRecords >= 2 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public DataTable FillLeaveDeatil() { DataTable dtleave = new DataTable(); dtleave = new System.Data.DataTable(); dtleave.Columns.Add("OpeningSL", Type.GetType("System.String")); dtleave.Columns.Add("OpeningCL", Type.GetType("System.String")); dtleave.Columns.Add("availedcl", Type.GetType("System.String")); dtleave.Columns.Add("availedsl", Type.GetType("System.String")); dtleave.Columns.Add("AvailPLSL", Type.GetType("System.String")); dtleave.Columns.Add("balancecl", Type.GetType("System.String")); dtleave.Columns.Add("balancesl", Type.GetType("System.String")); dtleave.Columns.Add("CarryCL", Type.GetType("System.String")); dtleave.Columns.Add("CarryForwardCL", Type.GetType("System.String")); dtleave.Columns.Add("CarrySL", Type.GetType("System.String")); dtleave.Columns.Add("CarryForwardSL", Type.GetType("System.String")); dtleave.Columns.Add("BalLeft", Type.GetType("System.String")); dtleave.Columns.Add("ExpireLeaveSL", Type.GetType("System.String")); dtleave.Columns.Add("ExpireLeaveCL", Type.GetType("System.String")); dtleave.Columns.Add("accuredUCL", Type.GetType("System.String")); dtleave.Columns.Add("AccuredUSL", Type.GetType("System.String")); dtleave.Columns.Add("AccuredCCL", Type.GetType("System.String")); dtleave.Columns.Add("AccuredCSL", Type.GetType("System.String")); dtleave.Columns.Add("TotalCL", Type.GetType("System.String")); dtleave.Columns.Add("TotalSL", Type.GetType("System.String")); dtleave.Columns.Add("AvailableCL", Type.GetType("System.String")); dtleave.Columns.Add("AvailableSL", Type.GetType("System.String")); dtleave.Columns.Add("AvailAUPLCL", Type.GetType("System.String")); dtleave.Columns.Add("AvailAUPLSL", Type.GetType("System.String")); dtleave.Columns.Add("AvailPLCL", Type.GetType("System.String")); dtleave.Columns.Add("AdjustmentCL", Type.GetType("System.String")); dtleave.Columns.Add("AdjustmentSL", Type.GetType("System.String")); dtleave.Columns.Add("BalanceCurCL", Type.GetType("System.String")); dtleave.Columns.Add("BalanceCurSL", Type.GetType("System.String")); dtleave.Columns.Add("leavestartdate", Type.GetType("System.String")); dtleave.Columns.Add("leaveenddate", Type.GetType("System.String")); dr = dtleave.NewRow(); DateTime leavestartdate; int enddatedays; DateTime leaveenddate; double month; double op_sl; if (System.DateTime.Today.Month == 1) { leavestartdate = new DateTime(System.DateTime.Today.Year, System.DateTime.Today.Month, 1); dr["leavestartdate"] = leavestartdate.ToString("dd/MM/yyyy"); enddatedays = System.DateTime.DaysInMonth(System.DateTime.Today.Year, System.DateTime.Today.Month); leaveenddate = new DateTime(System.DateTime.Today.Year, System.DateTime.Today.Month, enddatedays); dr["leaveenddate"] = leaveenddate.ToString("dd/MM/yyyy"); } else { leavestartdate = new DateTime(System.DateTime.Today.Year, System.DateTime.Today.Month - 1, 1); dr["leavestartdate"] = leavestartdate.ToString("dd/MM/yyyy"); enddatedays = System.DateTime.DaysInMonth(System.DateTime.Today.Year, System.DateTime.Today.Month - 1); leaveenddate = new DateTime(System.DateTime.Today.Year, System.DateTime.Today.Month - 1, enddatedays); dr["leaveenddate"] = leaveenddate.ToString("dd/MM/yyyy"); } string id = "484"; if (id != null) { dr["OpeningSL"] = "0.00"; dr["OpeningCL"] = "0.00"; int empid_leave = Convert.ToInt32(id); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "getjoiningdate"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaEmpLeave = new SqlDataAdapter(base.objSqlCommand); DataSet DsEmpLeave = new DataSet(); DaEmpLeave.Fill(DsEmpLeave); base.objSqlCommand.Connection.Close(); DateTime joiningdate = (Convert.ToDateTime(DsEmpLeave.Tables[0].Rows[0]["joiningDate"])); if (joiningdate >= Convert.ToDateTime("01/01/" + DateTime.Now.Year.ToString()) && joiningdate <= Convert.ToDateTime("31/12/" + DateTime.Now.Year.ToString())) { if (Convert.ToInt16(joiningdate.Day) <= 10) { dr["OpeningCL"] = "0.5"; month = Convert.ToDouble(joiningdate.Month.ToString()); op_sl = 0.5; dr["OpeningSL"] = op_sl.ToString(); //for balancesheet dr["OpeningCL"] = "0.5"; dr["OpeningSL"] = op_sl.ToString(); } else if (Convert.ToInt16(joiningdate.Day) >= 11 && Convert.ToInt16(joiningdate.Day) <= 20) { dr["OpeningCL"] = "0"; month = Convert.ToDouble(joiningdate.Month.ToString()); // op_sl = (6 - (month / 2)); op_sl = 0; dr["OpeningSL"] = op_sl.ToString(); dr["OpeningCL"] = "0"; dr["OpeningSL"] = op_sl.ToString(); } else { dr["OpeningCL"] = "0"; month = Convert.ToDouble(joiningdate.Month.ToString()); op_sl = 0; dr["OpeningSL"] = op_sl.ToString(); dr["OpeningCL"] = "0"; dr["OpeningSL"] = op_sl.ToString(); } } else { dr["OpeningSL"] = "0"; dr["OpeningCL"] = "0"; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "availedCL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaAvailedCl = new SqlDataAdapter(base.objSqlCommand); DataSet DsAvailedCl = new DataSet(); DaAvailedCl.Fill(DsAvailedCl); base.objSqlCommand.Connection.Close(); string availedcl = DsAvailedCl.Tables[0].Rows[0]["availedcl"].ToString(); if (availedcl != null && availedcl != "") { dr["availedcl"] = availedcl; } else { dr["availedcl"] = "0.00"; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "availedSL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaAvailedSl = new SqlDataAdapter(base.objSqlCommand); DataSet DsAvailedSl = new DataSet(); DaAvailedSl.Fill(DsAvailedSl); base.objSqlCommand.Connection.Close(); string availedsl = DsAvailedSl.Tables[0].Rows[0]["availedsl"].ToString(); if (availedsl != null && availedsl != "") { dr["availedsl"] = availedsl; } else { dr["availedsl"] = "0.00"; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "availPLSL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaAvailPLSL = new SqlDataAdapter(base.objSqlCommand); DataSet DsAvailPLSL = new DataSet(); DaAvailPLSL.Fill(DsAvailPLSL); base.objSqlCommand.Connection.Close(); string availPLSL = DsAvailPLSL.Tables[0].Rows[0]["availPLSL"].ToString(); dr["AvailPLSL"] = availPLSL; base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "leavebalanceclnew"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter Dabalancecl = new SqlDataAdapter(base.objSqlCommand); DataSet Dsbalancecl = new DataSet(); Dabalancecl.Fill(Dsbalancecl); base.objSqlCommand.Connection.Close(); string balancecl = Dsbalancecl.Tables[0].Rows[0]["CL"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "leavebalanceslnew"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter Dabalancesl = new SqlDataAdapter(base.objSqlCommand); DataSet Dsbalancesl = new DataSet(); Dabalancesl.Fill(Dsbalancesl); base.objSqlCommand.Connection.Close(); string balancesl = Dsbalancesl.Tables[0].Rows[0]["SL"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "carryleaves"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaCarryBalance = new SqlDataAdapter(base.objSqlCommand); DataSet DsCarryBalance = new DataSet(); DaCarryBalance.Fill(DsCarryBalance); base.objSqlCommand.Connection.Close(); string carryforward; if (DsCarryBalance.Tables.Count > 0) // if Yes { if (DsCarryBalance.Tables[0].Rows.Count > 0) { carryforward = DsCarryBalance.Tables[0].Rows[0]["carrybalance"].ToString(); } else { carryforward = "0.00"; } } else { carryforward = "0.00"; } if (carryforward != null && carryforward != "") { dr["CarryCL"] = carryforward; dr["CarryForwardCL"] = carryforward; } else { dr["CarryCL"] = "0.00"; dr["CarryForwardCL"] = "0.00"; } dr["CarrySL"] = "0.00"; dr["CarryForwardSL"] = "0.00"; base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "getballeft"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Lastyear, lastYear); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter Da = new SqlDataAdapter(base.objSqlCommand); DataSet ds = new DataSet(); Da.Fill(ds); base.objSqlCommand.Connection.Close(); if (ds != null && ds.Tables[0].Rows.Count > 0) { dr["BalLeft"] = ds.Tables[0].Rows[0][0].ToString(); } else { dr["BalLeft"] = "0"; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "ExpiredLeaveSL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaExpireLeaveSL = new SqlDataAdapter(base.objSqlCommand); DataSet dsExpireLeaveSL = new DataSet(); DaExpireLeaveSL.Fill(dsExpireLeaveSL); base.objSqlCommand.Connection.Close(); dr["ExpireLeaveSL"] = dsExpireLeaveSL.Tables[0].Rows[0]["SL"].ToString(); // Leave balance sheet base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "ExpiredLeaveCL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaExpireLeaveCL = new SqlDataAdapter(base.objSqlCommand); DataSet dsExpireLeaveCL = new DataSet(); DaExpireLeaveCL.Fill(dsExpireLeaveCL); base.objSqlCommand.Connection.Close(); dr["ExpireLeaveCL"] = dsExpireLeaveCL.Tables[0].Rows[0]["CL"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "accuredUCL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaaccuredUCL = new SqlDataAdapter(base.objSqlCommand); DataSet dsaccuredUCL = new DataSet(); DaaccuredUCL.Fill(dsaccuredUCL); base.objSqlCommand.Connection.Close(); string accuredUCL = dsaccuredUCL.Tables[0].Rows[0]["accuredUCL"].ToString(); dr["accuredUCL"] = accuredUCL; base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "accuredccl"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter Daaccuredccl = new SqlDataAdapter(base.objSqlCommand); DataSet dsaccuredccl = new DataSet(); Daaccuredccl.Fill(dsaccuredccl); base.objSqlCommand.Connection.Close(); string accuredccl = dsaccuredccl.Tables[0].Rows[0]["accuredccl"].ToString(); dr["AccuredCCL"] = accuredccl; dr["AccuredUSL"] = accuredccl; if (joiningdate >= Convert.ToDateTime("01/01/" + DateTime.Now.Year.ToString()) && joiningdate <= Convert.ToDateTime("31/01/" + DateTime.Now.Year.ToString())) { dr["accuredUCL"] = Convert.ToString((Convert.ToDecimal(accuredUCL) - Convert.ToDecimal(0.5))); dr["AccuredUSL"] = Convert.ToString((Convert.ToDecimal(accuredUCL) - Convert.ToDecimal(0.5))); } dr["AccuredCCL"] = accuredccl; dr["AccuredCSL"] = accuredccl; dr["TotalCL"] = (Convert.ToDouble(dr["CarryForwardCL"]) + Convert.ToDouble(dr["OpeningCL"]) + Convert.ToDouble(dr["accuredUCL"]) + Convert.ToDouble(dr["AccuredCCL"])).ToString(); dr["TotalSL"] = (Convert.ToDouble(dr["CarryForwardSL"]) + Convert.ToDouble(dr["OpeningSL"]) + Convert.ToDouble(dr["AccuredUSL"]) + Convert.ToDouble(dr["AccuredCSL"])).ToString(); dr["AvailableCL"] = dr["TotalCL"]; dr["AvailableSL"] = dr["TotalSL"]; base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "availAUPL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaavailAUPL = new SqlDataAdapter(base.objSqlCommand); DataSet dsavailAUPL = new DataSet(); DaavailAUPL.Fill(dsavailAUPL); base.objSqlCommand.Connection.Close(); dr["AvailAUPLCL"] = dsavailAUPL.Tables[0].Rows[0]["availAUPL"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "availAUPLSL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaAvailAUPLSL = new SqlDataAdapter(base.objSqlCommand); DataSet dsAvailAUPLSL = new DataSet(); DaAvailAUPLSL.Fill(dsAvailAUPLSL); base.objSqlCommand.Connection.Close(); dr["AvailAUPLSL"] = dsAvailAUPLSL.Tables[0].Rows[0]["availAUPLSL"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "availPL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaAvailPLCL = new SqlDataAdapter(base.objSqlCommand); DataSet dsAvailPLCL = new DataSet(); DaAvailPLCL.Fill(dsAvailPLCL); base.objSqlCommand.Connection.Close(); dr["AvailPLCL"] = dsAvailPLCL.Tables[0].Rows[0]["availPL"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "isconfirmed"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaisconfirmedL = new SqlDataAdapter(base.objSqlCommand); DataSet dsisconfirmed = new DataSet(); DaisconfirmedL.Fill(dsisconfirmed); base.objSqlCommand.Connection.Close(); int isconfirmed = Convert.ToInt16(dsisconfirmed.Tables[0].Rows[0]["isconfirmed"]); if (isconfirmed == 1) { if (Convert.ToDouble(dr["TotalCL"]) < Convert.ToDouble(dr["AvailPLCL"])) { dr["AvailAUPLCL"] = (Convert.ToDouble(dr["AvailPLCL"]) - Convert.ToDouble(dr["TotalCL"])).ToString(); dr["AvailPLCL"] = dr["TotalCL"]; } } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "GetTotalAdjustedCL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaAdjustmentCL = new SqlDataAdapter(base.objSqlCommand); DataSet dsAdjustmentCL = new DataSet(); DaAdjustmentCL.Fill(dsAdjustmentCL); base.objSqlCommand.Connection.Close(); dr["AdjustmentCL"] = dsAdjustmentCL.Tables[0].Rows[0]["TotalAdjustedCL"].ToString(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "adjustedvalueSL"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaAdjustmentSL = new SqlDataAdapter(base.objSqlCommand); DataSet dsAdjustmentSL = new DataSet(); DaAdjustmentSL.Fill(dsAdjustmentSL); base.objSqlCommand.Connection.Close(); dr["AdjustmentSL"] = dsAdjustmentSL.Tables[0].Rows[0]["TotalAdjustedSL"].ToString(); dr["BalanceCurCL"] = balancecl; dr["BalanceCurSL"] = balancesl; } else { if (Convert.ToInt32(System.DateTime.Now.Day) <= 10) { dr["OpeningCL"] = "1"; dr["OpeningSL"] = "0.5"; } else if (Convert.ToInt32(System.DateTime.Now.Day) >= 11 && Convert.ToInt32(System.DateTime.Now.Day) <= 20) { dr["OpeningCL"] = "0.5"; dr["OpeningSL"] = "0"; } else { dr["OpeningCL"] = "0"; dr["OpeningSL"] = "0"; } dr["AvailCL"] = "0.00"; dr["AvailSL"] = "0.00"; } dtleave.Rows.Add(dr); return dtleave; } public DataTable GetAdustmentleave(long UserId) { DataTable dt = new DataTable(); List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procLeaveDeatilMaster; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "adjustedleavelist"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId,UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } #endregion #region Increment public string SaveIncrement(EmpInfoTabular entityObject) { try { id = entityObject.EditEmployeeid; Mode = entityObject.Editmode; string IncrementHistoryId = ""; DateTime dtFrom = Convert.ToDateTime(entityObject.Incrementdate, provider); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procIncrementHistoryMaster_Add; if (!string.IsNullOrEmpty(Mode)) { if (id != null && IncrementHistoryId != null && Mode == "e") { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Incrementid, IncrementHistoryId); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } } else { if (id != null && IncrementHistoryId != null && IncrementHistoryId != "") { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Incrementid, IncrementHistoryId); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); } } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Incrementdate, entityObject.Incrementdate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designationchange, entityObject.Designationchange); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Increment, entityObject.Increment); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Salarychange, entityObject.Salarychange); if (entityObject.Remarks != null) { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Remarks, entityObject.Remarks); } else { objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Remarks, entityObject.Remarks); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Isfirst, entityObject.Isfirst); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "AppraisalDateupdate"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AppraisalDate, entityObject.AppraisalDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, 21); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procIncrementHistoryMaster_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "organizationcheck"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daDesignation = new SqlDataAdapter(base.objSqlCommand); DataSet dsDesignation = new DataSet(); daDesignation.Fill(dsDesignation); if (dsDesignation.Tables[0].Rows.Count > 0) { int id = Convert.ToInt32(dsDesignation.Tables[0].Rows[0]["Id"].ToString()); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Updateorganizationcheck"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designationchange, entityObject.Designationchange); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } //using (base.objSqlCommand.Connection) //{ base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procIncrementHistoryMaster_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Currentsalary"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); SqlDataAdapter daCurrentSalary = new SqlDataAdapter(base.objSqlCommand); DataSet dsCurrentSalary = new DataSet(); daCurrentSalary.Fill(dsCurrentSalary); if (dsCurrentSalary.Tables[0].Rows.Count > 0) { int id = Convert.ToInt32(dsCurrentSalary.Tables[0].Rows[0]["CurrentSalaryId"].ToString()); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "updatecurrentsalary"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_CurrentSalaryId, id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Salarychange, entityObject.Salarychange); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Designationchange, entityObject.Designationchange); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } if (entityObject.SalaryRangeId != 0) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "updateEmployeeRangeId"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SalaryRangeId, entityObject.SalaryRangeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } } string AppraisalDate = entityObject.AppraisalDate; string[] arr = AppraisalDate.Split('-'); System.DateTime dtAppraisalDateFinal = Convert.ToDateTime(AppraisalDate); string apdate = arr[2].ToString() + "/" + arr[1].ToString() + "/" + arr[0].ToString(); objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "SecondapprisalUpadate"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AppraisalDate, dtAppraisalDateFinal); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, 21); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public DataTable GetIncrementList() { string id = "484"; List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); DataTable dt = new DataTable(); DataTable table = new DataTable(); DataTable table1 = new DataTable(); DataTable table2 = new DataTable(); using (base.objSqlCommand.Connection) { if (id != null) { int ddd = 484; base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procIncrementHistoryMaster_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "IncrementGet"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daincrement1 = new SqlDataAdapter(base.objSqlCommand); DataSet dsincrement1 = new DataSet(); daincrement1.Fill(dsincrement1); daincrement1.Fill(dt); // objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); dt.Columns.Add("AppraisalDateLast"); dt.Columns.Add("lblIncrDateTo"); dt.Columns.Add("Name"); table.Columns.Add(new DataColumn("Name", typeof(string))); table.Columns.Add(new DataColumn("AppraisalDateLast", typeof(string))); table.Columns.Add(new DataColumn("lblIncrDateTo", typeof(string))); DataRow dr = dt.NewRow(); for (int i = 0; i < dsincrement1.Tables[0].Rows.Count; i++) { if (dsincrement1.Tables[0].Rows.Count > 0) { //dt.Columns.Add("Name", typeof(int)); string name = dsincrement1.Tables[0].Rows[0]["Employee_Name"].ToString(); string EmployeeName = "Employee Name :" + name.ToString(); table.Rows.Add(EmployeeName); dr["Name"] = table.Rows[i]["Name"]; } string myString = dsincrement1.Tables[0].Rows[0]["IncrementDate"].ToString(); if (i == 0) { int ID = Convert.ToInt32(dsincrement1.Tables[0].Rows[0]["IncrementHistoryId"].ToString()); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procIncrementHistoryMaster_Add; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "AppraisalDateget"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, 484); SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataSet ds = new DataSet(); da.Fill(ds); if (ds.Tables[0].Rows[0]["AppraisalDate"].ToString().Length > 0) { // dt.Columns.Add("AppraisalDate", typeof(int)); DateTime dtDate = Convert.ToDateTime(ds.Tables[0].Rows[0]["AppraisalDate"].ToString()); DateTime dtToo = dtDate.AddDays(-1); string AppraisalDate = dtToo.ToShortDateString(); table.Rows.Add(AppraisalDate); dr["AppraisalDateLast"] = table.Rows[i]["AppraisalDateLast"]; } else { //dt.Columns.Add("AppraisalDate", typeof(int)); string AppraisalDate = "-"; table.Rows.Add(AppraisalDate); dr["AppraisalDateLast"] = table.Rows[i]["AppraisalDateLast"]; } } else { // dt.Columns.Add("IncrementDate", typeof(int)); DateTime dtFrom = Convert.ToDateTime(myString); DateTime dtTo = dtFrom.AddDays(-1); string IncrementDate = dtTo.ToShortDateString(); table.Rows.Add(IncrementDate); dr["lblIncrDateTo"] = table.Rows[i]["lblIncrDateTo"]; } } } } //dt.Merge(table); // return dt; return dt; } #endregion #region Project public IEnumerable<EmpInfoTabular> FillProjectDetail(string FromDate, string ToDate, long UserId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); DataSet dsProject = new DataSet(); DataSet DsProject1 = new DataSet(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procprojectListGet; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EmployeeGetdeatil"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaProject1 = new SqlDataAdapter(base.objSqlCommand); DaProject1.Fill(DsProject1); base.objSqlCommand.Connection.Close(); if (DsProject1.Tables.Count > 0) { string name = DsProject1.Tables[0].Rows[0]["Employee_Name"].ToString(); string Name = "Employee Name: " + name.ToString(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Tech"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_FromDate, FromDate); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ToDate, ToDate); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter sda = new SqlDataAdapter(base.objSqlCommand); DaProject1.Fill(dsProject); DataTable dt = new DataTable(); sda.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); base.objSqlCommand.Connection.Close(); if (dsProject != null) { } } return objListToReturn; } public IEnumerable<EmpInfoTabular> FillProjectDetailWbs(string FromDate, string ToDate, long UserId) { DataSet dsProject2 = new DataSet(); List<EmpInfoTabular> objListToReturn1 = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procprojectListGet; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "NonWbsProject"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_FromDate, FromDate); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_ToDate, ToDate); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter sda = new SqlDataAdapter(base.objSqlCommand); sda.Fill(dsProject2); DataTable dt1 = new DataTable(); sda.Fill(dt1); objListToReturn1 = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt1); base.objSqlCommand.Connection.Close(); if (dsProject2 != null) { } } return objListToReturn1; } #endregion #region Dropdownbind public DataTable GetAccountNo(string AccountNumber, string UserId) { DataTable dt = new DataTable(); dt = new System.Data.DataTable(); dt.Columns.Add("Employee_Name", Type.GetType("System.String")); dt.Columns.Add("Type", Type.GetType("System.String")); dr = dt.NewRow(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procSalarySAccountNo; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_AccountNumber, AccountNumber); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daBankAccount = new SqlDataAdapter(base.objSqlCommand); DataSet dsBankAccount = new DataSet(); daBankAccount.Fill(dsBankAccount); if (dsBankAccount.Tables[0].Rows.Count > 0) { if (Convert.ToBoolean(dsBankAccount.Tables[0].Rows[0]["Active"]) == false) { dr["Employee_Name"] = dsBankAccount.Tables[0].Rows[0]["Employee_Name"].ToString(); dr["Type"] = "false"; } else { dr["Employee_Name"] = null; dr["Type"] = "true"; } } else { dr["Employee_Name"] = null; string value = "NotAccount"; dr["Type"] = value; } dt.Rows.Add(dr); } return dt; } public IEnumerable<EmpInfoTabular> GetCompany() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "ComapnyName"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { //base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetWorking() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Working"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetJoiningDesignation() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "JoiningDesignation"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetDepartmentname() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Departmentname"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetPositionName() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "PositionName"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetEmployeeGrade() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EmployeeGrade"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetUserRole() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "UserRole"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetLinemanager(string Usertype, long UserId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeedropdownbind; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Usertype, Usertype); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetEducationType() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeEducation; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetTechnology() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procTechnologyListboxbind; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetRole() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procRoleBind; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetSalaryRangeDropDown(long Salary) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procSalaryRange; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Salary, Salary); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetSalaryBrakup(long SalaryRangeId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procSalaryBreakUpSalaryRangeWise; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SalaryRangeId, SalaryRangeId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> FillEmployee() { string id; string UserId = "21"; int parentid = 0; string ids = ""; List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { try { if (UserId != null) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procEmployeeListAttandancetabBind; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "organization"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataSet dsEmp = new DataSet(); da.Fill(dsEmp); if (dsEmp.Tables[0].Rows.Count > 0 || dsEmp != null) { parentid = Convert.ToInt32(dsEmp.Tables[0].Rows[0]["parent_id"].ToString()); if (parentid != 0) { while (parentid != 0) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "organizationFilterParent"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_Parentid, parentid); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daid = new SqlDataAdapter(base.objSqlCommand); DataSet dsid = new DataSet(); daid.Fill(dsid); ids = ids + "," + dsid.Tables[0].Rows[0]["UserId"].ToString(); parentid = Convert.ToInt32(dsid.Tables[0].Rows[0]["parent_id"].ToString()); } ids = ids.Substring(1, ids.Length - 1); } else { ids = UserId.ToString(); } if (ids.Length > 0) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EmployeeListId"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, ids); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daemployeeList = new SqlDataAdapter(base.objSqlCommand); DataSet dsemployee = new DataSet(); /* daemployee.Fill(dsemploye*/ DataTable dtemployeeList = new DataTable(); daemployeeList.Fill(dtemployeeList); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dtemployeeList); } } else { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Employee"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daemployee = new SqlDataAdapter(base.objSqlCommand); DataSet dsemployee = new DataSet(); /* daemployee.Fill(dsemploye*/ DataTable dtemployee = new DataTable(); daemployee.Fill(dtemployee); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dtemployee); } } else { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Employee"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daemployee = new SqlDataAdapter(base.objSqlCommand); DataSet dsemployee = new DataSet(); /* daemployee.Fill(dsemploye*/ DataTable dtemployee = new DataTable(); daemployee.Fill(dtemployee); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dtemployee); } //objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } catch (Exception ex) { } } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetNonWorking() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procNonWorking; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetInTimeOutTimeSelected() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procIntimeSelected; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetEmployeeTime(long CompanyId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_procGetEmployeeCodeComapanyWise; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CompanyId, CompanyId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetIncrementType() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procIncrementtype; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetPendingList(long UserId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procPendingTask; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dtPendintTask = new DataTable(); da.Fill(dtPendintTask); DataSet dsPendintTask = new DataSet(); da.Fill(dsPendintTask); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dtPendintTask); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetFeedbackList(long UserId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procEmployeeFeedback; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daEmployeeFeed = new SqlDataAdapter(base.objSqlCommand); DataTable dtEmployeeFeed = new DataTable(); daEmployeeFeed.Fill(dtEmployeeFeed); DataSet dsEmployeeFeed = new DataSet(); daEmployeeFeed.Fill(dsEmployeeFeed); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dtEmployeeFeed); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetLeaveType() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procAdjustedLeaveAdd; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "LeaveType"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { //base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } #endregion public DataTable FillPassingYear(string id, string mode) { DateTime d = new DateTime(); using (base.objSqlCommand.Connection) { DataTable table = new DataTable(); List<int> lstyear = new List<int>(); try { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procGetEducationYear; if (mode != null) { if (mode == "Convert") { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "ConvertEmployee"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daCanBirthdate = new SqlDataAdapter(base.objSqlCommand); DataSet dsCanBirthdate = new DataSet(); daCanBirthdate.Fill(dsCanBirthdate); base.objSqlCommand.Connection.Close(); if (dsCanBirthdate != null && dsCanBirthdate.Tables[0].Rows.Count > 0) { string[] strBirthdate = dsCanBirthdate.Tables[0].Rows[0]["Birthdate"].ToString().Split(' '); d = Convert.ToDateTime(strBirthdate[0]); } } else { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EmployeeBirthdate"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daPerBirthdate = new SqlDataAdapter(base.objSqlCommand); DataSet dsPerBirthdate = new DataSet(); daPerBirthdate.Fill(dsPerBirthdate); base.objSqlCommand.Connection.Close(); if (dsPerBirthdate != null && dsPerBirthdate.Tables[0].Rows.Count > 0) { string[] strBirthdate = dsPerBirthdate.Tables[0].Rows[0]["Birthdate"].ToString().Split(' '); d = Convert.ToDateTime(strBirthdate[0]); } } } else { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Employeecheck"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daPerNewRecord = new SqlDataAdapter(base.objSqlCommand); DataSet dsPerNewRecord = new DataSet(); daPerNewRecord.Fill(dsPerNewRecord); base.objSqlCommand.Connection.Close(); if (dsPerNewRecord != null && dsPerNewRecord.Tables[0].Rows.Count > 0) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EmployeeBirthdate"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, Convert.ToInt32(dsPerNewRecord.Tables[0].Rows[0]["id"].ToString())); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daPerBirthdate = new SqlDataAdapter(base.objSqlCommand); DataSet dsPerBirthdate = new DataSet(); daPerBirthdate.Fill(dsPerBirthdate); base.objSqlCommand.Connection.Close(); if (dsPerBirthdate != null && dsPerBirthdate.Tables[0].Rows.Count > 0) { string[] strBirthdate = dsPerBirthdate.Tables[0].Rows[0]["Birthdate"].ToString().Split(' '); d = Convert.ToDateTime(strBirthdate[0]); } } } int year = d.Year; int j = year; int l = 1; table.Columns.Add("YearEducation", typeof(int)); if (d.Year != 1) { for (int i = DateTime.Today.Year; i > j; i--) { int YearEducation = i; lstyear.Add(YearEducation); l++; table.Rows.Add(YearEducation); } } } catch (Exception ex) { } return table; } } public DataTable FillPassingYear() { DateTime d = new DateTime(); using (base.objSqlCommand.Connection) { DataTable table = new DataTable(); List<int> lstyear = new List<int>(); try { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procGetEducationYear; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Employeecheck"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataSet dsEmp = new DataSet(); da.Fill(dsEmp); if (dsEmp.Tables[0].Rows.Count > 0 || dsEmp != null) { long id = Convert.ToInt32(dsEmp.Tables[0].Rows[0]["id"].ToString()); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "EmployeeBirthdate"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daid = new SqlDataAdapter(base.objSqlCommand); DataSet dsid = new DataSet(); daid.Fill(dsid); if (dsid != null && dsid.Tables[0].Rows.Count > 0) { string[] strBirthdate = dsid.Tables[0].Rows[0]["Birthdate"].ToString().Split(' '); d = Convert.ToDateTime(strBirthdate[0]); } } int year = d.Year; int j = year; int l = 1; table.Columns.Add("YearEducation", typeof(int)); if (d.Year != 1) { for (int i = DateTime.Today.Year; i > j; i--) { int YearEducation = i; lstyear.Add(YearEducation); l++; table.Rows.Add(YearEducation); } } } catch (Exception ex) { } return table; } } #region offerdetail public DataTable GetOfferdeatils(long UserId) { DataTable dt = new DataTable(); dt = new System.Data.DataTable(); dt.Columns.Add("EmployeeName", Type.GetType("System.String")); dt.Columns.Add("joingdate", Type.GetType("System.String")); dt.Columns.Add("Designation", Type.GetType("System.String")); dt.Columns.Add("SalaryAfterRevision", Type.GetType("System.String")); dt.Columns.Add("JoiningSalary", Type.GetType("System.String")); dt.Columns.Add("SLASigned", Type.GetType("System.String")); dt.Columns.Add("Department", Type.GetType("System.String")); dr = dt.NewRow(); List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procOfferdeatils; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "AllDeatailJoing"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable DaOffer = new DataTable(); da.Fill(DaOffer); DataSet DsOffer = new DataSet(); da.Fill(DsOffer); // objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(DaOffer); base.objSqlCommand.Connection.Close(); if (DsOffer.Tables[0].Rows.Count > 0) { dt.Rows.Add(dr); //joiningdate if (DsOffer.Tables[0].Rows[0]["joiningDate"].ToString() != null) { DateTime Jdate = Convert.ToDateTime(DsOffer.Tables[0].Rows[0]["joiningDate"]); int jday = Jdate.Day; int jmonth = Jdate.Month; int jyear = Jdate.Year; dr["joingdate"] = Jdate.ToShortDateString(); } else { dr["joingdate"] = ""; } dr["EmployeeName"] = DsOffer.Tables[0].Rows[0]["Employee_Name"].ToString(); if ((DsOffer.Tables[0].Rows[0]["joiningDesignation"].ToString() != null)) { dr["Designation"] = DsOffer.Tables[0].Rows[0]["joiningDesignation"].ToString(); } dr["SalaryAfterRevision"] = DsOffer.Tables[0].Rows[0]["SalaryAfterRevision"].ToString(); dr["JoiningSalary"] = DsOffer.Tables[0].Rows[0]["JoiningSalary"].ToString(); if ((DsOffer.Tables[0].Rows[0]["IsSLASigned"].ToString() == "True" && DsOffer.Tables[0].Rows[0]["IsSLASigned"] != null)) { dr["SLASigned"] = DsOffer.Tables[0].Rows[0]["IsSLASigned"].ToString(); } else { dr["SLASigned"] = DsOffer.Tables[0].Rows[0]["IsSLASigned"].ToString(); } } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Department"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daOrganization = new SqlDataAdapter(base.objSqlCommand); DataTable dtOrganization = new DataTable(); daOrganization.Fill(dtOrganization); DataSet dsOrganization = new DataSet(); daOrganization.Fill(dsOrganization); base.objSqlCommand.Connection.Close(); string departmentoffer = ""; if (dsOrganization != null && dsOrganization.Tables[0].Rows.Count > 0) { for (int counter = 0; counter < dsOrganization.Tables[0].Rows.Count; counter++) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "Department"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daDepartment = new SqlDataAdapter(base.objSqlCommand); DataTable dtDepartment = new DataTable(); daDepartment.Fill(dtDepartment); DataSet dsDepartment = new DataSet(); daDepartment.Fill(dsDepartment); base.objSqlCommand.Connection.Close(); if (dsDepartment != null && dsDepartment.Tables[0].Rows.Count > 0) { dr["Department"] = dsDepartment.Tables[0].Rows[0]["Department_Name"].ToString(); if (!departmentoffer.Contains(dsDepartment.Tables[0].Rows[0]["Department_Name"].ToString())) { departmentoffer += dsDepartment.Tables[0].Rows[0]["Department_Name"].ToString() + ","; } } } if(departmentoffer !=null && departmentoffer != "") { departmentoffer = departmentoffer.Remove(departmentoffer.Length - 1); } else { departmentoffer = ""; } dr["Department"] = departmentoffer; //gvDept.DataSource = dt; //gvDept.DataBind(); } } return dt; } #endregion public DataTable GetEmployeeDeatils(string UserId) { DataTable dt = new DataTable(); dt = new System.Data.DataTable(); dt.Columns.Add("Employee_Name", Type.GetType("System.String")); dt.Columns.Add("JoiningDate", Type.GetType("System.String")); dt.Columns.Add("IsConfirmed", Type.GetType("System.String")); dt.Columns.Add("ConfirmationDateJoin", Type.GetType("System.String")); dr = dt.NewRow(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procEmployeeMasterGet; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter DaEmpLeave = new SqlDataAdapter(base.objSqlCommand); DataTable DtEmpLeave = new DataTable(); DaEmpLeave.Fill(DtEmpLeave); DataSet DsEmpLeave = new DataSet(); DaEmpLeave.Fill(DsEmpLeave); // objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(DaOffer); base.objSqlCommand.Connection.Close(); if (DsEmpLeave.Tables[0].Rows.Count > 0) { //joiningdate dr["Employee_Name"] = DsEmpLeave.Tables[0].Rows[0]["Employee_Name"].ToString(); dr["joiningDate"] = DsEmpLeave.Tables[0].Rows[0]["joiningDate"].ToString(); if (Convert.ToBoolean(DsEmpLeave.Tables[0].Rows[0]["IsConfirmed"].ToString()) == true) { dr["IsConfirmed"] = " Yes"; dr["ConfirmationDateJoin"] = DsEmpLeave.Tables[0].Rows[0]["ConfirmationDate"].ToString(); } else { dr["IsConfirmed"] = "No"; } } } dt.Rows.Add(dr); return dt; } #region skill public IEnumerable<EmpInfoTabular> GetSkill() { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procGetMySkill; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "dropdownGroupBind"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public IEnumerable<EmpInfoTabular> GetPopupSkill(long lookupSkilId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procGetMySkill; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "dropdownSkillNameBind"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_skillgroupid, lookupSkilId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } public string Saveskill(EmpInfoTabular entityObject) { try { if (entityObject.EditEmployeeid != null) { id = entityObject.EditEmployeeid; //UserID } else { id = "440"; } Mode = entityObject.Editmode; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procSkillAddtab; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "AddSkills"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_EmployeeID, 21); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_SkillID, entityObject.id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, id); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<EmpInfoTabular> GetGridViewList(long UserId) { List<EmpInfoTabular> objListToReturn = new List<EmpInfoTabular>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmpInfoTabularConstants.const_Field_procSkillAddtab; base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_mode, "SkillList"); base.objSqlCommand.Parameters.AddWithValue(EmpInfoTabularConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmpInfoTabular>(dt); } return objListToReturn; } #endregion #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~EmpInfoTabularRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Master.CompanyRelated; using VIS_Repository; namespace VIS_App.Controllers.Masters.CompanyRelated { public class GroupNameAPIController : BaseAPIController { VISIBaseRepository<GroupName> GroupNameRepository; List<GroupName> EntityList = new List<GroupName>(); public GroupNameAPIController(VISIBaseRepository<GroupName> _GroupNameRepositiory) { GroupNameRepository = _GroupNameRepositiory; } public HttpResponseMessage Get() { return ToJson(GroupNameRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]GroupName value) { return ToJson(GroupNameRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]GroupName value) { return ToJson(GroupNameRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(GroupNameRepository.DeleteEntity(Id)); } } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IContactMaster } from '../../../Model/Masters/CompanyRelated/ContactMaster'; @Pipe({ name: 'contactmasterFilter' }) export class ContactMasterFilterPipe implements PipeTransform { transform(value: IContactMaster[], filter: string): IContactMaster[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IContactMaster) => app.Name != null && app.Name.toLocaleLowerCase().indexOf(filter) != -1 || app.Designation != null && app.Designation.toLocaleLowerCase().indexOf(filter) != -1 || app.Email != null && app.Email.toLocaleLowerCase().indexOf(filter) != -1 || app.phone != null && app.phone.toLocaleLowerCase().indexOf(filter) != -1 || app.SkypeId != null && app.SkypeId.toLocaleLowerCase().indexOf(filter) != -1 || app.MsnId != null && app.MsnId.toLocaleLowerCase().indexOf(filter) != -1 || app.GtalkId != null && app.GtalkId.toLocaleLowerCase().indexOf(filter) != -1 || app.AolId != null && app.AolId.toLocaleLowerCase().indexOf(filter) != -1 || app.Other != null && app.Other.toLocaleLowerCase().indexOf(filter) != -1 //|| app.ProspectId != null && app.ProspectId.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } /* 1. In the first line, we are importing the PipeTransform and Pipe interfaces that we are implementing to achieve filtering functionality. 2. In the second line, we are importing the IContactMaster interface that we created in first part to hold the list of currencys. Over here, we are also using it to hold the list of currencys that is the source data for filtering. 3. In next line, we are specifying the pipe selector/name currencyFilter through which we will use the pipe (you will find in future steps, how). 4. Next, we are creating the ContactMasterFilterPipe class that is implementing the PipeTransform interface (implementing interface means providing the body to all methods mentioned in the interface). 5. Right click on PipeTransform and select the option Go To Definition: 6. You will be landed to the pipe_transform_d.ts file where you will find the nice brief description how to use the pipe with an example and transform method that we must need to implement: 7. So let’s go back to currency.pipe.ts where can see we have transform method with first argument as IContactMaster array and second is named as filter that is the input string to be searched in the IContactMaster array. 8. In transform method, the first line is only to check if the filter is not null. 9. The next statement is the actual implementation of search, if you are C# developer, you can compare it to the LINQ to Object. We are calling Array’s filter method, checking through conditional operator that if any of IContactMaster member (FirstName, LastName or Gender) is matching with currency input search string and if YES, returning the filtered result. toLocaleLowerCase method is converting string to lower case, to read more about it, click here. If there is no matching record in User list, we are returning the all rows.Now that we have our filter ready, let’s add it to */<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var EmployeeList_service_1 = require("../../../Service/HumanResource/EmployeeManagement/EmployeeList.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var router_1 = require("@angular/router"); var EmployeeListComponent = (function () { function EmployeeListComponent(fb, _EmployeeListService, pagerService, router) { this.fb = fb; this._EmployeeListService = _EmployeeListService; this.pagerService = pagerService; this.router = router; this.indLoading = false; this.isDesc = false; this.column = ''; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; //Variables for Filter this.ShowHideSearch = false; this.ShowHideSearchNew = false; //declare id this.tempUserId = 21; this.tempUSertype = "Admin"; this.Status = "Active"; this.someValue = "hey"; } EmployeeListComponent.prototype.ngOnInit = function () { this.EmployeeListFrm = this.fb.group({ CompanyId: [''], UserId: [''], Usertype: [''], Id: [''], EmployeeCode: [''], CompanyName: [''], Employee_Name: [''], Email: [''], Department: [''], TotalExp: [''], JoiningDate: [''], RelevingDate: [''], Grace: [''], SL_CL: [''], }); this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, "%"); }; EmployeeListComponent.prototype.SaveEmployee = function () { alert('Fristtab'); }; EmployeeListComponent.prototype.EmployeeListFilterCriteriaChange = function (value) { if (value != '[object Event]') this.EmployeeListFilter = value; }; EmployeeListComponent.prototype.EmployeeListSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; EmployeeListComponent.prototype.LoadValue = function (event) { debugger; var x = ($('input[name="Status"]:checked').val()); if (x == "InActive") { if (event.target.value == "E%") { this.LoadEmployeeModeInActive(this.tempUSertype, this.tempUserId); } else { this.LoadEmployeeListInActive(this.tempUSertype, this.tempUserId, event.target.value); } } else if (x == "ALL") { if (event.target.value == "E%") { this.LoadEmployeeModeAll(this.tempUSertype, this.tempUserId); } else { this.LoadEmployeeListAll(this.tempUSertype, this.tempUserId, event.target.value); } } else { if (event.target.value == "E%") { this.LoadEmployeeModeActive(this.tempUSertype, this.tempUserId); } else { this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, event.target.value); } } }; EmployeeListComponent.prototype.FilterByStatus = function (event) { if (event.target.value == "InActive") { this.LoadEmployeeListInActive(this.tempUSertype, this.tempUserId, "%"); } if (event.target.value == "ALL") { this.LoadEmployeeListAll(this.tempUSertype, this.tempUserId, "%"); } else { this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, "%"); } }; EmployeeListComponent.prototype.LoadEmployeelistActive = function (Usertype, UserId, EmployeeCode) { var _this = this; this.indLoading = true; this._EmployeeListService.GetEmployeeListActive(global_1.Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId, EmployeeCode) .subscribe(function (EmployeeLists) { _this.EmployeeLists = EmployeeLists; if (_this.ShowHideSearch) { _this.searchID = document.getElementById("searchID").value; if (_this.searchID != '') { _this.searchID = _this.searchID.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(_this.searchID) != -1; }); } } if (_this.ShowHideSearch) { _this.searchCompanyName = document.getElementById("searchCompanyName").value; if (_this.searchCompanyName != '') { _this.searchCompanyName = _this.searchCompanyName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(_this.searchCompanyName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmployeeName = document.getElementById("searchEmployeeName").value; if (_this.searchEmployeeName != '') { _this.searchEmployeeName = _this.searchEmployeeName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(_this.searchEmployeeName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmail = document.getElementById("searchEmail").value; if (_this.searchEmail != '') { _this.searchEmail = _this.searchEmail.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Email != null && x.Email.toLocaleLowerCase().indexOf(_this.searchEmail) != -1; }); } } if (_this.ShowHideSearch) { _this.searchDepartment = document.getElementById("searchDepartment").value; if (_this.searchDepartment != '') { _this.searchDepartment = _this.searchDepartment.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Department != null && x.Department.toLocaleLowerCase().indexOf(_this.searchDepartment) != -1; }); } if (_this.ShowHideSearch) { _this.searchTotalExp = document.getElementById("searchTotalExp").value; if (_this.searchTotalExp != '') { _this.searchTotalExp = _this.searchTotalExp.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(_this.searchTotalExp) != -1; }); } } } _this.indLoading = false; _this.JumpOnPage(1); }); }; EmployeeListComponent.prototype.LoadEmployeeListAll = function (Usertype, UserId, EmployeeCode) { var _this = this; debugger; this.indLoading = true; this._EmployeeListService.GetEmployeeListAll(global_1.Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId, EmployeeCode) .subscribe(function (EmployeeLists) { _this.EmployeeLists = EmployeeLists; console.log(_this.EmployeeLists); if (_this.ShowHideSearch) { _this.searchID = document.getElementById("searchID").value; if (_this.searchID != '') { _this.searchID = _this.searchID.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(_this.searchID) != -1; }); } } if (_this.ShowHideSearch) { _this.searchCompanyName = document.getElementById("searchCompanyName").value; if (_this.searchCompanyName != '') { _this.searchCompanyName = _this.searchCompanyName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(_this.searchCompanyName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmployeeName = document.getElementById("searchEmployeeName").value; if (_this.searchEmployeeName != '') { _this.searchEmployeeName = _this.searchEmployeeName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(_this.searchEmployeeName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmail = document.getElementById("searchEmail").value; if (_this.searchEmail != '') { _this.searchEmail = _this.searchEmail.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Email != null && x.Email.toLocaleLowerCase().indexOf(_this.searchEmail) != -1; }); } } if (_this.ShowHideSearch) { _this.searchDepartment = document.getElementById("searchDepartment").value; if (_this.searchDepartment != '') { _this.searchDepartment = _this.searchDepartment.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Department != null && x.Department.toLocaleLowerCase().indexOf(_this.searchDepartment) != -1; }); } if (_this.ShowHideSearch) { _this.searchTotalExp = document.getElementById("searchTotalExp").value; if (_this.searchTotalExp != '') { _this.searchTotalExp = _this.searchTotalExp.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(_this.searchTotalExp) != -1; }); } } } _this.indLoading = false; _this.JumpOnPage(1); }); }; EmployeeListComponent.prototype.LoadEmployeeListInActive = function (Usertype, UserId, EmployeeCode) { var _this = this; debugger; this.indLoading = true; this._EmployeeListService.GetEmployeeListInActive(global_1.Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId, EmployeeCode) .subscribe(function (EmployeeLists) { _this.EmployeeLists = EmployeeLists; console.log(_this.EmployeeLists); if (_this.ShowHideSearch) { _this.searchID = document.getElementById("searchID").value; if (_this.searchID != '') { _this.searchID = _this.searchID.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(_this.searchID) != -1; }); } } if (_this.ShowHideSearch) { _this.searchCompanyName = document.getElementById("searchCompanyName").value; if (_this.searchCompanyName != '') { _this.searchCompanyName = _this.searchCompanyName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(_this.searchCompanyName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmployeeName = document.getElementById("searchEmployeeName").value; if (_this.searchEmployeeName != '') { _this.searchEmployeeName = _this.searchEmployeeName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(_this.searchEmployeeName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmail = document.getElementById("searchEmail").value; if (_this.searchEmail != '') { _this.searchEmail = _this.searchEmail.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Email != null && x.Email.toLocaleLowerCase().indexOf(_this.searchEmail) != -1; }); } } if (_this.ShowHideSearch) { _this.searchDepartment = document.getElementById("searchDepartment").value; if (_this.searchDepartment != '') { _this.searchDepartment = _this.searchDepartment.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Department != null && x.Department.toLocaleLowerCase().indexOf(_this.searchDepartment) != -1; }); } if (_this.ShowHideSearch) { _this.searchTotalExp = document.getElementById("searchTotalExp").value; if (_this.searchTotalExp != '') { _this.searchTotalExp = _this.searchTotalExp.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(_this.searchTotalExp) != -1; }); } } } _this.indLoading = false; _this.JumpOnPage(1); }); }; EmployeeListComponent.prototype.LoadEmployeeModeActive = function (Usertype, UserId) { var _this = this; this.indLoading = true; this._EmployeeListService.GetEmployeeModeActive(global_1.Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId) .subscribe(function (EmployeeLists) { _this.EmployeeLists = EmployeeLists; console.log(_this.EmployeeLists); if (_this.ShowHideSearch) { _this.searchID = document.getElementById("searchID").value; if (_this.searchID != '') { _this.searchID = _this.searchID.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(_this.searchID) != -1; }); } } if (_this.ShowHideSearch) { _this.searchCompanyName = document.getElementById("searchCompanyName").value; if (_this.searchCompanyName != '') { _this.searchCompanyName = _this.searchCompanyName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(_this.searchCompanyName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmployeeName = document.getElementById("searchEmployeeName").value; if (_this.searchEmployeeName != '') { _this.searchEmployeeName = _this.searchEmployeeName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(_this.searchEmployeeName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmail = document.getElementById("searchEmail").value; if (_this.searchEmail != '') { _this.searchEmail = _this.searchEmail.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Email != null && x.Email.toLocaleLowerCase().indexOf(_this.searchEmail) != -1; }); } } if (_this.ShowHideSearch) { _this.searchDepartment = document.getElementById("searchDepartment").value; if (_this.searchDepartment != '') { _this.searchDepartment = _this.searchDepartment.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Department != null && x.Department.toLocaleLowerCase().indexOf(_this.searchDepartment) != -1; }); } if (_this.ShowHideSearch) { _this.searchTotalExp = document.getElementById("searchTotalExp").value; if (_this.searchTotalExp != '') { _this.searchTotalExp = _this.searchTotalExp.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(_this.searchTotalExp) != -1; }); } } } _this.indLoading = false; _this.JumpOnPage(1); }); }; EmployeeListComponent.prototype.LoadEmployeeModeAll = function (Usertype, UserId) { var _this = this; debugger; this.indLoading = true; this._EmployeeListService.GetEmployeeModeAll(global_1.Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId) .subscribe(function (EmployeeLists) { _this.EmployeeLists = EmployeeLists; console.log(_this.EmployeeLists); if (_this.ShowHideSearch) { _this.searchID = document.getElementById("searchID").value; if (_this.searchID != '') { _this.searchID = _this.searchID.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(_this.searchID) != -1; }); } } if (_this.ShowHideSearch) { _this.searchCompanyName = document.getElementById("searchCompanyName").value; if (_this.searchCompanyName != '') { _this.searchCompanyName = _this.searchCompanyName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(_this.searchCompanyName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmployeeName = document.getElementById("searchEmployeeName").value; if (_this.searchEmployeeName != '') { _this.searchEmployeeName = _this.searchEmployeeName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(_this.searchEmployeeName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmail = document.getElementById("searchEmail").value; if (_this.searchEmail != '') { _this.searchEmail = _this.searchEmail.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Email != null && x.Email.toLocaleLowerCase().indexOf(_this.searchEmail) != -1; }); } } if (_this.ShowHideSearch) { _this.searchDepartment = document.getElementById("searchDepartment").value; if (_this.searchDepartment != '') { _this.searchDepartment = _this.searchDepartment.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Department != null && x.Department.toLocaleLowerCase().indexOf(_this.searchDepartment) != -1; }); } if (_this.ShowHideSearch) { _this.searchTotalExp = document.getElementById("searchTotalExp").value; if (_this.searchTotalExp != '') { _this.searchTotalExp = _this.searchTotalExp.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(_this.searchTotalExp) != -1; }); } } } _this.indLoading = false; _this.JumpOnPage(1); }); }; EmployeeListComponent.prototype.LoadEmployeeModeInActive = function (Usertype, UserId) { var _this = this; this.indLoading = true; this._EmployeeListService.GetEmployeeModeInActive(global_1.Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId) .subscribe(function (EmployeeLists) { _this.EmployeeLists = EmployeeLists; console.log(_this.EmployeeLists); if (_this.ShowHideSearch) { _this.searchID = document.getElementById("searchID").value; if (_this.searchID != '') { _this.searchID = _this.searchID.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(_this.searchID) != -1; }); } } if (_this.ShowHideSearch) { _this.searchCompanyName = document.getElementById("searchCompanyName").value; if (_this.searchCompanyName != '') { _this.searchCompanyName = _this.searchCompanyName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(_this.searchCompanyName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmployeeName = document.getElementById("searchEmployeeName").value; if (_this.searchEmployeeName != '') { _this.searchEmployeeName = _this.searchEmployeeName.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(_this.searchEmployeeName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchEmail = document.getElementById("searchEmail").value; if (_this.searchEmail != '') { _this.searchEmail = _this.searchEmail.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Email != null && x.Email.toLocaleLowerCase().indexOf(_this.searchEmail) != -1; }); } } if (_this.ShowHideSearch) { _this.searchDepartment = document.getElementById("searchDepartment").value; if (_this.searchDepartment != '') { _this.searchDepartment = _this.searchDepartment.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.Department != null && x.Department.toLocaleLowerCase().indexOf(_this.searchDepartment) != -1; }); } if (_this.ShowHideSearch) { _this.searchTotalExp = document.getElementById("searchTotalExp").value; if (_this.searchTotalExp != '') { _this.searchTotalExp = _this.searchTotalExp.toLocaleLowerCase(); _this.EmployeeLists = _this.EmployeeLists.filter(function (x) { return x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(_this.searchTotalExp) != -1; }); } } } _this.indLoading = false; _this.JumpOnPage(1); }); }; EmployeeListComponent.prototype.addEmployeeList = function () { this.router.navigate(['/EmpInfoTabular']); // this.SetControlsState(true); this.modalTitle = "Add New EmployeeList"; this.modalBtnTitle = "Add"; }; EmployeeListComponent.prototype.editEmployeeList = function (id) { debugger; // this.EmployeeList = this.EmployeeLists.filter(x => x.Id == id)[0]; this.router.navigate(['/EmpInfoTabular'], { queryParams: { UserId: id, mode: "e" } }); }; EmployeeListComponent.prototype.deleteEmployee = function (id) { var msg1 = "Are you sure you want to Delete this Employee?"; if (confirm(msg1) == true) { this.deleteEmployeeId(id); } else { this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, "%"); } }; EmployeeListComponent.prototype.deleteEmployeeId = function (id) { var _this = this; this.indLoading = true; this._EmployeeListService.delete(global_1.Global.BASE_EmployeeList_ENDPOINT, id) .subscribe(function (Data) { if (Data.startsWith("Success: ")) { _this.msg = Data; _this.LoadEmployeelistActive(_this.tempUSertype, _this.tempUserId, "%"); } else { alert(Data); } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; EmployeeListComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.EmployeeListFrm.enable() : this.EmployeeListFrm.disable(); }; EmployeeListComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; EmployeeListComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeLists); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; EmployeeListComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; EmployeeListComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._EmployeeListService.post(global_1.Global.BASE_EmployeeList_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: debugger; this._EmployeeListService.put(global_1.Global.BASE_EmployeeList_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._EmployeeListService.delete(global_1.Global.BASE_EmployeeList_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], EmployeeListComponent.prototype, "modal", void 0); EmployeeListComponent = __decorate([ core_1.Component({ providers: [EmployeeList_service_1.EmployeeListService], templateUrl: 'app/Components/HumanResource/EmployeeManagement/EmployeeList.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, EmployeeList_service_1.EmployeeListService, pager_index_1.PagerService, router_1.Router]) ], EmployeeListComponent); return EmployeeListComponent; }()); exports.EmployeeListComponent = EmployeeListComponent; <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IEducationType } from '../../../Model/Masters/CompanyRelated/EducationType'; @Pipe ({ name: 'EducationTypeFilter' }) export class EducationTypeFilterPipe implements PipeTransform { transform(value: IEducationType[], filter: string): IEducationType[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IEducationType) => app.Name != null && app.Name.toLocaleLowerCase().indexOf(filter) != -1 || app.FullName != null && app.FullName.toLocaleLowerCase().indexOf(filter) != -1 || app.Type != null && app.Type.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Domain.DocCentre; using VIS_Repository.Masters; namespace VIS_Repository.DocCenter { public class DocumentTemplateRepository : VISDbCommand { public Int32 intAffectedRecords { get; set; } string mode; public DocumentTemplateRepository(string _connectionstring) : base(_connectionstring) { } // Step 1 public IEnumerable<DocumentTemplateViewModel> GetEntityListApproved(int EmployeeId,string EmployeeRole,string ApprovedStatus) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); List<DocumentTemplateViewModel> objListToReturn = new List<DocumentTemplateViewModel>(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDOC_GetAllDocumentTemplate; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_PageIndex, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_PageSize, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_SortBy,""); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_SortOrder, ""); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_SearchField, ""); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_SearchText, ""); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsShowAll, true); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_EmployeeId, EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_EmployeeRole, EmployeeRole); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ApprovedStatus, ApprovedStatus); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<DocumentTemplateViewModel>(dt); return objListToReturn; } catch (Exception ex) { throw; } } public List<DocTemplateModule> GetAllModule() { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); List<DocTemplateModule> objListToReturn = new List<DocTemplateModule>(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procGetAllModule; if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<DocTemplateModule>(dt); return objListToReturn; } catch (Exception ex) { throw; } } public DocumentTemplateModel GetById(Int64 Id) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); DocumentTemplateModel objListToReturn = new DocumentTemplateModel(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocumentTemplateGetById; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_Id, Id); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<DocumentTemplateModel>(dt)[0]; return objListToReturn; } catch (Exception ex) { throw; } } public string AddDocumentTemplate(DocumentTemplateModel entityObject) { try { mode = "Insert"; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocumentTemplateAddEditStep1; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_mode, mode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, entityObject.DocTemplateId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_TemplateName, entityObject.TemplateName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_TemplateDescription, entityObject.TemplateDescription); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ModuleId, entityObject.ModuleId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsRecurrence, entityObject.IsRecurrence); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsSelf, entityObject.IsSelf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsBehalf, entityObject.IsBehalf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_SharingVariableType, entityObject.SharingVariableType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_StartingVariableRole, entityObject.StartingVariableRole); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDownloadWord, entityObject.IsDownloadWord); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDownloadPdf, entityObject.IsDownloadPdf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDMSPdf, entityObject.IsDMSPdf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDMSWord, entityObject.IsDMSWord); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsEmailPdf, entityObject.IsEmailPdf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsEmailWord, entityObject.IsEmailWord); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DateFormat, entityObject.DateFormat); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsPortrait, entityObject.IsPortrait); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsApproved, entityObject.IsApproved); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ApprovedOn, entityObject.ApprovedOn); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsFinalSubmited, entityObject.IsFinalSubmited); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_OwnerId, entityObject.OwnerId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_CreatedBy, entityObject.CreatedBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public Int64 GetMaxDocTempId() { Int64 DocTempId; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procGetMaxDocId; if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); DocTempId = Convert.ToInt64(dt.Rows[0][0]); return DocTempId; } public string UpdateDocumentTemplate(DocumentTemplateModel entityObject) { try { mode = "Update"; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocumentTemplateAddEditStep1; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_mode, mode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, entityObject.DocTemplateId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_TemplateName, entityObject.TemplateName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_TemplateDescription, entityObject.TemplateDescription); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ModuleId, entityObject.ModuleId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsRecurrence, entityObject.IsRecurrence); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsSelf, entityObject.IsSelf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsBehalf, entityObject.IsBehalf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_SharingVariableType, entityObject.SharingVariableType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_StartingVariableRole, entityObject.StartingVariableRole); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDownloadWord, entityObject.IsDownloadWord); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDownloadPdf, entityObject.IsDownloadPdf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDMSPdf, entityObject.IsDMSPdf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsDMSWord, entityObject.IsDMSWord); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsEmailPdf, entityObject.IsEmailPdf); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsEmailWord, entityObject.IsEmailWord); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DateFormat, entityObject.DateFormat); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsPortrait, entityObject.IsPortrait); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsApproved, entityObject.IsApproved); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ApprovedOn, entityObject.ApprovedOn); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsFinalSubmited, entityObject.IsFinalSubmited); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_OwnerId, entityObject.OwnerId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_CreatedBy, entityObject.CreatedBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string ActiveInActiveDocumentTemplate(Int64 Id) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocumentTemplateActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_Id,Id); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } // Step 2 public string AddDocumentField(DocMasterFieldDataContract entityObject) { try { mode = "Insert"; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocMasterFieldAddEdit; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_mode, mode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldName, entityObject.FieldName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldDescription, entityObject.FieldDescription); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldType, entityObject.FieldType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ListType, entityObject.ListType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DataSourceTable, entityObject.DataSourceTable); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DataSourceColumn, entityObject.DataSourceColumn); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_PageContent, entityObject.PageContent); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageName, entityObject.ImageName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageHeight, entityObject.ImageHeight); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageWidth, entityObject.ImageWidth); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageAlign, entityObject.ImageAlign); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldId, entityObject.FieldId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsCustomField, entityObject.IsCustomField); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, entityObject.DocTemplateId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_AttachmentList, entityObject.AttachmentList); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_CreatedBy, entityObject.CreatedBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateDocumentField(DocMasterFieldDataContract entityObject) { try { mode = "Update"; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocMasterFieldAddEdit; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_mode, mode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldName, entityObject.FieldName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldDescription, entityObject.FieldDescription); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ListType, entityObject.ListType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DataSourceTable, entityObject.DataSourceTable); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DataSourceColumn, entityObject.DataSourceColumn); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_PageContent, entityObject.PageContent); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageName, entityObject.ImageName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageHeight, entityObject.ImageHeight); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageWidth, entityObject.ImageWidth); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_ImageAlign, entityObject.ImageAlign); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldId, entityObject.FieldId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_IsCustomField, entityObject.IsCustomField); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, entityObject.DocTemplateId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_AttachmentList, entityObject.AttachmentList); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_CreatedBy, entityObject.CreatedBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string DeleteDocumentField(Int64 Id,Int64 UpdatedBy) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocMasterFieldActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_Id,Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public List<DocMasterFieldDataContract> GetByDocTemplateId(Int64 DocTemplateId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); List<DocMasterFieldDataContract> listListToReturn = new List<DocMasterFieldDataContract>(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocMasterFieldSelectByDocTempId; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, DocTemplateId); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if(dt.Rows.Count > 0 ) { listListToReturn = VISAutoMapper.ConvertDataTable<DocMasterFieldDataContract>(dt); } return listListToReturn; } catch (Exception ex) { throw; } } public DocMasterFieldDataContract GetByFieldId(Int64 Id) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); DocMasterFieldDataContract objListToReturn = new DocMasterFieldDataContract(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocMasterFieldSelectById; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_Id, Id); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if(dt.Rows.Count > 0) { objListToReturn = VISAutoMapper.ConvertDataTable<DocMasterFieldDataContract>(dt)[0]; } return objListToReturn; } catch (Exception ex) { throw; } } public DataTable BindTableFieldDropdown(string TableName) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procGetDocTemplateModuleVariables; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_TableName, TableName); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); return dt; } catch (Exception ex) { throw; } } public DataTable BindCustomFieldDropdown(Int64 DocumentTemplateId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDOC_GetCustomTokenList; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, DocumentTemplateId); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); return dt; } catch (Exception ex) { throw; } } // Step 3 public List<DocMasterFieldDataContract> BindDocumentContainer(Int64 DocTemplateId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); List<DocMasterFieldDataContract> listListToReturn = new List<DocMasterFieldDataContract>(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procBindDocumentContainer; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, DocTemplateId); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { listListToReturn = VISAutoMapper.ConvertDataTable<DocMasterFieldDataContract>(dt); } return listListToReturn; } catch (Exception ex) { throw; } } public string AddDocumentMasterField(List<DocMasterFieldDataContract> entitylist) { try { string Response = DeleteMasterField(entitylist[0].DocTemplateId); if(Response.StartsWith("Success")) { mode = "Insert"; foreach(var item in entitylist) { AddDocumentField(item); } } string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string DeleteMasterField(Int64? DocTempId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDeleteDocMasterFieldByDocTempId; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, DocTempId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 0 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string DeleteFormBuiler(Int64? DocTempId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDeleteDocFormBuilder; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, DocTempId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 0 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string AddFormBuilder(DocMasterFieldDataContract entityobject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocFormBuilderAdd; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_MasterFieldId,entityobject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId,entityobject.DocTemplateId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_CreatedBy, entityobject.CreatedBy); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string AddDocumentContainerField(List<DocMasterFieldDataContract> entitylist) { try { string Response = DeleteFormBuiler(entitylist[0].DocTemplateId); if(entitylist[0].FieldName!="") { if (Response.StartsWith("Success")) { foreach (var item in entitylist) { if (item.Id == 0) { item.Id = AddPageBreakField(item.FieldName, item.FieldType, item.DocTemplateId, item.CreatedBy); } if (item.Id > 0) { AddFormBuilder(item); } } } } string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public Int64 AddPageBreakField(string FieldName,string FieldType,Int64? DocTemplateId,Int64 CreatedBy) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DocumentTemplateViewModelConstant.const_procDocMasterFieldPageLineBreakAdd; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldName, FieldName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_FieldType, FieldType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_DocTemplateId, DocTemplateId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DocumentTemplateViewModelConstant.const_CreatedBy, CreatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(DocumentTemplateViewModelConstant.const_MasterFieldId)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddMasterFieldIdParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); Int64 MasterFieldId = 0; if (intAffectedRecords > 0 ) { MasterFieldId = Convert.ToInt64(objVISDbCommand.objSqlCommand.Parameters[DocumentTemplateViewModelConstant.const_MasterFieldId].Value); } return MasterFieldId; } catch (Exception ex) { return 0; } } public SqlParameter AddMasterFieldIdParameter() { SqlParameter objSqlEntityMessageParameter = new SqlParameter(); objSqlEntityMessageParameter.SqlDbType = System.Data.SqlDbType.BigInt; objSqlEntityMessageParameter.Size = 1000; objSqlEntityMessageParameter.Direction = System.Data.ParameterDirection.Output; objSqlEntityMessageParameter.ParameterName = DocumentTemplateViewModelConstant.const_MasterFieldId; objSqlEntityMessageParameter.Value = 0; return objSqlEntityMessageParameter; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var router_1 = require("@angular/router"); var AttendanceReportNew_service_1 = require("../../../Service/Report/Attendance/AttendanceReportNew.service"); var AttendanceReportNewcomponent = (function () { function AttendanceReportNewcomponent(fb, _AttendanceReportNewService, router, pagerService) { this.fb = fb; this._AttendanceReportNewService = _AttendanceReportNewService; this.router = router; this.pagerService = pagerService; this.indLoading = false; this.CurrentRecordsPerPage = 10; this.pager = {}; this.lastday = function (y, m) { return new Date(y, m + 1, 0).getDate(); }; this.GetSystemDateTime(); } AttendanceReportNewcomponent.prototype.ngOnInit = function () { $("#depart").hide(); $("#company").hide(); $("#LineManager").hide(); $("#usertType").hide(); $("#emp").show(); $("#empAll").show(); $("#date").hide(); $("#rbtemployee").prop("checked", true); $("#rbtMonth").prop("checked", true); $("#rbtsortname").prop("checked", true); $("#rbtgrid").prop("checked", true); this.Yearval = new Date().getFullYear(); $("#tdAdmin").hide(); $('#ddlmonth option:eq(' + (new Date).getMonth() + ')').prop('selected', true); $('#ddlemp option[value="0"]').attr("selected", "SelectALL"); this.Month = new Date().getMonth() + 1; this.FillDepartMent(); this.FillEmployee(); this.FillCompany(); this.FillAllLineManager(); this.FillUserType(); this.FillYear(); }; AttendanceReportNewcomponent.prototype.HideECLU = function () { $("#emp").hide(-300); $("#empAll").hide(-300); $("#company").hide(-300); $("#LineManager").hide(-300); $("#usertType").hide(-300); $("#depart").show(-300); }; AttendanceReportNewcomponent.prototype.HideDCLU = function () { $("#depart").hide(-300); $("#company").hide(-300); $("#LineManager").hide(-300); $("#usertType").hide(-300); $("#emp").show(-300); $("#empAll").show(-300); }; AttendanceReportNewcomponent.prototype.HideDELU = function () { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#LineManager").hide(-300); $("#usertType").hide(-300); $("#company").show(-300); }; AttendanceReportNewcomponent.prototype.HideDECU = function () { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#company").hide(-300); $("#usertType").hide(-300); $("#LineManager").show(-300); }; AttendanceReportNewcomponent.prototype.HideDECL = function () { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#company").hide(-300); $("#LineManager").hide(-300); $("#usertType").show(-300); }; AttendanceReportNewcomponent.prototype.HideDate = function () { $("#date").hide(-300); $("#month").show(-300); }; AttendanceReportNewcomponent.prototype.HideMonth = function () { $("#date").show(-300); $("#month").hide(-300); }; AttendanceReportNewcomponent.prototype.FillDepartMent = function () { var _this = this; this._AttendanceReportNewService.FillDepartMent(global_1.Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(function (data) { _this.indLoading = false; _this.Department = data; }, function (error) { _this.msg = error; }); }; AttendanceReportNewcomponent.prototype.FillEmployee = function () { var _this = this; var UserId = 21; var UserType = 'Admin'; this._AttendanceReportNewService.FillEmployee(global_1.Global.BASE_AttendanceReportNew_ENDPOINT, UserId, UserType) .subscribe(function (data) { _this.indLoading = false; _this.Employee = data; }, function (error) { _this.msg = error; }); }; AttendanceReportNewcomponent.prototype.FillAllEmployee = function (event) { var _this = this; if ($('#chkallemployee').is(':checked')) { this._AttendanceReportNewService.FillAllEmployee(global_1.Global.BASE_AttendanceReportNew_ENDPOINT, true, 21) .subscribe(function (data) { _this.indLoading = false; _this.Employee = data; }, function (error) { _this.msg = error; }); } else { this._AttendanceReportNewService.FillEmployee(global_1.Global.BASE_AttendanceReportNew_ENDPOINT, 21, 'Admin') .subscribe(function (data) { _this.indLoading = false; _this.Employee = data; }, function (error) { _this.msg = error; }); } }; AttendanceReportNewcomponent.prototype.FillCompany = function () { var _this = this; this._AttendanceReportNewService.FillCompany(global_1.Global.BASE_AttendanceReportNew_ENDPOINT, true) .subscribe(function (data) { _this.indLoading = false; _this.Company = data; }, function (error) { _this.msg = error; }); }; AttendanceReportNewcomponent.prototype.FillAllLineManager = function () { var _this = this; this._AttendanceReportNewService.FillAllLineManager(global_1.Global.BASE_AttendanceReportNew_ENDPOINT, true, 21) .subscribe(function (data) { _this.indLoading = false; _this.LineManager = data; }, function (error) { _this.msg = error; }); }; AttendanceReportNewcomponent.prototype.FillUserType = function () { var _this = this; this._AttendanceReportNewService.FillUserType(global_1.Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(function (data) { _this.indLoading = false; _this.User = data; }, function (error) { _this.msg = error; }); }; AttendanceReportNewcomponent.prototype.FillYear = function () { var _this = this; this._AttendanceReportNewService.FillYear(global_1.Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(function (data) { _this.indLoading = false; _this.Year = data; }, function (error) { _this.msg = error; }); }; AttendanceReportNewcomponent.prototype.GetSystemDateTime = function () { var _this = this; this._AttendanceReportNewService.GetSystemDateTime(global_1.Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(function (data) { _this.indLoading = false; _this.SystemDate = data; }, function (error) { _this.msg = error; }); }; AttendanceReportNewcomponent.prototype.ChangeId = function (event) { this.ModeId = event.target.value; }; AttendanceReportNewcomponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.Attendance); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; AttendanceReportNewcomponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; AttendanceReportNewcomponent.prototype.btnAttendanceApprovePunchIn = function (ATRPNEW) { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.PunchIntime != null) { this.EntryHr = ATRPNEW.PunchIntime.trim().slice(11, 13); this.EntryMin = ATRPNEW.PunchIntime.trim().slice(14, 16); } this.modalAttendanceApprovalPunchIn.open(); } }; AttendanceReportNewcomponent.prototype.btnAttendanceApprovePunchOut = function (ATRPNEW) { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.PunchOuttime != null) { this.EntryHr = ATRPNEW.PunchOuttime.trim().slice(11, 13); this.EntryMin = ATRPNEW.PunchOuttime.trim().slice(14, 16); } this.modalAttendanceApprovalLunchOut.open(); } }; AttendanceReportNewcomponent.prototype.btnAttendanceApproveLunchOut = function (ATRPNEW) { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.LunchOutTime != null) { this.EntryHr = ATRPNEW.LunchOutTime.trim().slice(11, 13); this.EntryMin = ATRPNEW.LunchOutTime.trim().slice(14, 16); } this.modalAttendanceApprovalLunchOut.open(); } }; AttendanceReportNewcomponent.prototype.btnAttendanceApproveLunchIn = function (ATRPNEW) { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.LunchInTime != null) { this.EntryHr = ATRPNEW.LunchInTime.trim().slice(11, 13); this.EntryMin = ATRPNEW.LunchInTime.trim().slice(14, 16); } this.modalAttendanceApprovalLunchIn.open(); } }; AttendanceReportNewcomponent.prototype.btnAttendanceApproveOtherwork = function (ATRPNEW) { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.OtherWork != null) { this.EntryHr = ATRPNEW.OtherWork.trim().slice(0, 2); this.EntryMin = ATRPNEW.OtherWork.trim().slice(3, 5); } this.modalAttendanceApprovalOtherWork.open(); } }; AttendanceReportNewcomponent.prototype.RedirectToTimeSheet = function (ATRPNEW) { }; AttendanceReportNewcomponent.prototype.RedirectToRecordPerEmp = function (ATRPNEW) { this.router.navigate(['/DailyEntryReport'], { queryParams: { EmployeeId: ATRPNEW.EmployeeId, EmployeeName: ATRPNEW.EmployeeName, Date: ATRPNEW.Date, EntryTime: ATRPNEW.PunchIntime, Remarks: ATRPNEW.In_Remarks } }); }; AttendanceReportNewcomponent.prototype.RedirectToAddEmpRecord = function (ATRPNEW) { var d1 = ATRPNEW.Date.split('/'); var datval = d1[1] + '/' + d1[0] + '/' + d1[2]; this.router.navigate(['/AddEmployeeRecord'], { queryParams: { EmployeeId: ATRPNEW.EmployeeId, EmployeeName: ATRPNEW.EmployeeName, Date: datval, EntryTime: ATRPNEW.PunchIntime, Remarks: ATRPNEW.In_Remarks } }); }; AttendanceReportNewcomponent.prototype.onSubmit = function (formData) { var _this = this; var month = formData.Month; var year = formData.year; year = jQuery("#ddlyear option:selected").text(); var day = 1; var SortBy; var Mode; if ($('#rbtDate').is(':checked')) { if ($('#txtfromdate').val() != "") { this.StartDate = $('#txtfromdate').val(); } else { this.StartDate = this.SystemDate.toString(); } if ($('#txttodate').val() != "") { this.EndDate = $('#txttodate').val(); } else { this.EndDate = this.StartDate; } } if ($('#rbtMonth').is(':checked')) { this.StartDate = year + '/' + month + '/' + day + ' '.concat('12:00:00 AM'); var y = this.SystemDate.toString().trim(); y = y.slice(6, 10); var dat = this.SystemDate.toString().trim(); var mon = this.SystemDate.toString().trim(); var lastDate = this.lastday(year, month).toString(); if (year == y) { mon = mon.slice(0, 2); if (month == mon) { dat = dat.slice(3, 5); this.EndDate = year + '/' + month + '/' + lastDate + ' '.concat('12:00:00 AM'); var diff = Date.parse(this.EndDate) - Date.parse(this.StartDate); day = diff / 1000 / 60 / 60 / 24; } else { this.EndDate = year + '/' + month + '/' + lastDate + ' '.concat('12:00:00 AM'); } } else { this.EndDate = year + '/' + month + '/' + lastDate + ' '.concat('12:00:00 AM'); } } if ($('#rbtsortdate').is(':checked')) { SortBy = "Date"; } else { SortBy = "Name"; } if ($('#rbtdepartment').is(':checked')) { Mode = "department"; this.ModeId = formData.Department; } else if ($('#rbtemployee').is(':checked')) { Mode = "employee"; if (formData.Employee == '') { if ($('#chkallemployee').is(':checked')) { this.ModeId = -1; } else { this.ModeId = 0; } } else { this.ModeId = formData.Employee; } } else if ($('#rbtcompany').is(':checked')) { Mode = "company"; if (formData.Company == '') { this.ModeId = 0; } else { this.ModeId = formData.Company; } } else if ($('#rbtlinemanager').is(':checked')) { Mode = "linemanager"; if (formData.LineManager == '') { this.ModeId = 0; } else { this.ModeId = formData.LineManager; } } else if ($('#rbtusertype').is(':checked')) { Mode = "usertype"; if (formData.UserType == '') { this.ModeId = 0; } else { this.ModeId = formData.UserType; } } this.IsAdmin = true; if ($('#rbtreport').is(':checked')) { this._AttendanceReportNewService.GetAllAttendanceReport(global_1.Global.BASE_AttendanceReportNew_ENDPOINT, Mode, this.ModeId, this.StartDate, this.EndDate, SortBy, this.IsAdmin) .subscribe(function (data) { _this.indLoading = false; _this.Attendance = data; if (data != '' && data.length > 0) { _this.JumpOnPage(1); //Report Generated } }); } else { this._AttendanceReportNewService.GetAllAttendanceData(global_1.Global.BASE_AttendanceReportNew_ENDPOINT, Mode, this.ModeId, this.StartDate, this.EndDate, SortBy, this.IsAdmin) .subscribe(function (data) { _this.indLoading = false; _this.Attendance = data; if (data != '' && data.length > 0) { if ($('#rbtgrid').is(':checked')) { _this.JumpOnPage(1); } else if ($('#rbtexcel').is(':checked')) { // Download } else { //rdlc Report Generate } } }, function (error) { _this.msg = error; }); } }; __decorate([ core_1.ViewChild('modalAttendanceApprovalPunchIn'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportNewcomponent.prototype, "modalAttendanceApprovalPunchIn", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalPunchOut'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportNewcomponent.prototype, "modalAttendanceApprovalPunchOut", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalLunchOut'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportNewcomponent.prototype, "modalAttendanceApprovalLunchOut", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalLunchIn'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportNewcomponent.prototype, "modalAttendanceApprovalLunchIn", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalOtherWork'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportNewcomponent.prototype, "modalAttendanceApprovalOtherWork", void 0); AttendanceReportNewcomponent = __decorate([ core_1.Component({ providers: [AttendanceReportNew_service_1.AttendanceReportNewService], templateUrl: 'app/Components/Report/Attendance/AttendanceReportNew.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, AttendanceReportNew_service_1.AttendanceReportNewService, router_1.Router, pager_index_1.PagerService]) ], AttendanceReportNewcomponent); return AttendanceReportNewcomponent; }()); exports.AttendanceReportNewcomponent = AttendanceReportNewcomponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class FinancialYear : VISBaseEntity { /// <summary> /// FinancialYear Entity Fields. /// </summary> public string FromMonth { get; set; } public string ToMonth { get; set; } public string CurrentYear { get; set; } public string Nextyear { get; set; } } public static class FinancialYearConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_FinancialYear = "FinancialYear"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_FromMonth = "FromMonth"; public const string const_Field_ToMonth = "ToMonth"; public const string const_Field_CurrentYear = "CurrentYear"; public const string const_Field_Nextyear = "Nextyear"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procFinancialYear_Add = "procFinancialYear_Add"; public const string const_procFinancialYear_Update = "procFinancialYear_Update"; public const string const_procFinancialYear_ActiveInActive = "procFinancialYear_ActiveInActive"; public const string const_procFinancialYear_SelectAll = "procFinancialYear_SelectAll"; public const string const_procFinancialYear_SelectBaseNonBase = "procFinancialYear_SelectBaseNonBase"; public const string const_procFinancialYear_SelectById = "procFinancialYear_SelectById"; } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { ConfigureWorksheetService } from '../../../service/Masters/Configuration/ConfigureWorksheet.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IConfigureWorkSheet } from '../../../Model/Masters/Configuration/ConfigureWorksheet'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; import { PagerService } from '../../../Shared/pager.index'; @Component ({ providers: [ConfigureWorksheetService], templateUrl: 'app/Components/Masters/Configuration/ConfigureWorkSheet.component.html', }) export class ConfigureWorkSheetComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; configureworksheets: IConfigureWorkSheet[]; configureworksheet: IConfigureWorkSheet; msg: string; indLoading: boolean = false; ConfigureWorksheetFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; ConfigureWorkSheetFilter: string; isDesc: boolean = false; column: any = 'EventName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; nums: number[]; constructor(private fb: FormBuilder, private _ConfigureWorksheetService: ConfigureWorksheetService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.LoadConfigureWorkSheet(); this.configureworksheet = ({ Id: 0, SrNo:'', Fromm: 0, Too: 0, HexadecimalValue:'', CreatedOn: null, CreatedBy: '', UpdatedOn: null, UpdatedBy: '', IsActive: false }) } LoadConfigureWorkSheet(): void { this.indLoading = true; this._ConfigureWorksheetService.get(Global.BASE_CONFIGUREWORKSHEET_ENDPOINT) .subscribe(data => { this.configureworksheets = data; this.indLoading = false; } //,error => this.msg = <any>error ); } SetControlsState(isEnable: boolean) { isEnable ? this.ConfigureWorksheetFrm.enable() : this.ConfigureWorksheetFrm.disable(); } EditConfigureWorksheet(id: number) { this.dbops = DBOperation.update; this.modalTitle = "Edit Configure Worksheet"; this.modalBtnTitle = "Update"; this.configureworksheet = this.configureworksheets.filter(x => x.Id == id)[0]; this.modal.open(); } CancelConfig() { this.modal.dismiss(); this.configureworksheet.HexadecimalValue = this.configureworksheet.HexadecimalValue; } onSubmit(formData: IConfigureWorkSheet) { debugger; this.msg = ""; this._ConfigureWorksheetService.put(Global.BASE_CONFIGUREWORKSHEET_ENDPOINT, formData.Id, formData).subscribe( data => { //if (data == "Success") if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadConfigureWorkSheet(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Web; using VIS_Domain.Master.Configuration; using System.Net.Http; using System.IO; using System.Security.Cryptography; namespace VIS_App.Infrastructure { public class CommonCode { string[] key = new string[5]; DataSet ds = new DataSet(); private static Random random = new Random(); public string GenrateUniqueKey(SecurityKey _SecurityKey) { string UniqueKey; key[0] = StringToBinary(_SecurityKey.Key1.ToString().Trim()); key[1] = StringToBinary(_SecurityKey.Key2.ToString().Trim()); key[2] = StringToBinary(_SecurityKey.Key3.ToString().Trim()); key[3] = StringToBinary(_SecurityKey.Key4.ToString().Trim()); key[4] = StringToBinary(_SecurityKey.Key5.ToString().Trim()); string s = AddBinary(key[4], AddBinary(key[3], AddBinary(key[2], AddBinary(key[1], key[0])))); //--------------------------------------- Add value in the key to increase the size ------------- char[] a = s.ToCharArray(); Array.Reverse(a); string RKey = new string(a); byte[] Ascii = Encoding.ASCII.GetBytes(BinaryToString(RKey)); for (int i = 0; i < Ascii.Length; i++) { if (Ascii[i] < 33 || Ascii[i] > 126) { RKey = AddBinary(RKey, "01101101011000010111100101110101"); break; } } //_SecurityKey.UniqueKey = BinaryToString(s) + BinaryToString(RKey); UniqueKey = BinaryToString(s) + BinaryToString(RKey); for (int i = 0; i < Ascii.Length; i++) { if (Ascii[i] < 33 || Ascii[i] > 126) { // Error Message break; } } //return _SecurityKey; return UniqueKey; } public string AddBinary(String a, String b) { Char[] one = new char[32]; Char[] two = new char[32]; one = a.ToCharArray(); two = b.ToCharArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 32; i++) { if ((one[i] == '0' && two[i] == '0') || (one[i] == '1' && two[i] == '1')) { sb.Append('0'); } else { sb.Append('1'); } } return sb.ToString(); } public static string StringToBinary(string data) { StringBuilder sb = new StringBuilder(); foreach (char c in data.ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); } return sb.ToString(); } public static string BinaryToString(string data) { List<Byte> byteList = new List<Byte>(); for (int i = 0; i < data.Length; i += 8) { byteList.Add(Convert.ToByte(data.Substring(i, 8), 2)); } return Encoding.ASCII.GetString(byteList.ToArray()); } public static string GetRandomNumber(int length) { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*/"; var result = new string( Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]) .ToArray()); return result; } public static string Encrypt(string strData, string strKey) { string strValue = ""; if (strKey != "") { if (strKey.Length == 16) { strKey = strKey + "XXXXXXXXXXXXXXXX".Substring(0, 16 - strKey.Length); } else if (strKey.Length == 16) { strKey = strKey.Substring(0, 16); } byte[] byteKey = Encoding.UTF8.GetBytes(strKey.Substring(0, 8)); byte[] byteVector = Encoding.UTF8.GetBytes(strKey.Substring(strKey.Length - 8)); byte[] byteData = Encoding.UTF8.GetBytes(strData); System.Security.Cryptography.DESCryptoServiceProvider objDES = new DESCryptoServiceProvider(); MemoryStream objMemoryStream = new MemoryStream(); CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write); objCryptoStream.Write(byteData, 0, byteData.Length); objCryptoStream.FlushFinalBlock(); strValue = Convert.ToBase64String(objMemoryStream.ToArray()); } else { strValue = strData; } return strValue; } public static string Decrypt(string strData, string strKey) { string strValue = ""; if (strKey != "") { if (strKey.Length == 16) { strKey = strKey + "XXXXXXXXXXXXXXXX".Substring(0, 16 - strKey.Length); } else if (strKey.Length == 16) { strKey = strKey.Substring(0, 16); } byte[] byteKey = Encoding.UTF8.GetBytes(strKey.Substring(0, 8)); byte[] byteVector = Encoding.UTF8.GetBytes(strKey.Substring(strKey.Length - 8)); byte[] byteData = new byte[strData.Length]; try { byteData = Convert.FromBase64String(strData); } catch { strValue = strData; } if (strValue == "") { try { System.Security.Cryptography.DESCryptoServiceProvider objDES = new DESCryptoServiceProvider(); MemoryStream objMemoryStream = new MemoryStream(); CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write); objCryptoStream.Write(byteData, 0, byteData.Length); objCryptoStream.FlushFinalBlock(); System.Text.Encoding objEncoding = System.Text.Encoding.UTF8; strValue = objEncoding.GetString(objMemoryStream.ToArray()); } catch { strValue = ""; } } } else { strValue = strData; } return strValue; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.HumanResource.Attendance; namespace VIS_Repository.HumanResource.Attendace { public class EmployeeFeedbackRepository : VISDbCommand, VISIBaseRepository<EmployeeFeedback> { public Int32 intAffectedRecords { get; set; } public EmployeeFeedbackRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { return null; } public EmployeeFeedback GetEntityByID(Int64 entityId) { return null; } public IEnumerable<EmployeeFeedback> GetEntityList() { return null; } public string AddEntity(EmployeeFeedback entityObject) { try { return null; //VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); //objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; //objVISDbCommand.objSqlCommand.CommandText =EmployeeFeedbackConstants.const_procSkillUser_Add; //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId, 21); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_SkillID, entityObject.id); //if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) //{ // objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); //} //objVISDbCommand.objSqlCommand.Connection.Open(); //intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); //objSqlCommand.Connection.Close(); ////return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(EmployeeFeedback entityObject) { return null; } public string UpdateFeedback(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeFeedbackConstants.const_procEmployeeFeedbackAction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_mode, "Approve"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_Id,Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId,21); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string RejectFeedback(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeFeedbackConstants.const_procEmployeeFeedbackAction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_mode, "Reject"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId, 21); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<EmployeeFeedback> GetEmployeeFeedbackList(long UserId) { List<EmployeeFeedback> objListToReturn = new List<EmployeeFeedback>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeFeedbackConstants.const_procEmployeeFeedbackDetailUser; base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeFeedback>(dt); } return objListToReturn; } public IEnumerable<EmployeeFeedback> GetMyTeam(long UserId) { List<EmployeeFeedback> objListToReturn = new List<EmployeeFeedback>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeFeedbackConstants.const_procEmployeeFeedbackTeamWiseLm; base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_mode, "MyTeam"); base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeFeedback>(dt); } return objListToReturn; } public IEnumerable<EmployeeFeedback> GetEmployeewiseSelect(long TeamEmployeeId , long UserId) { List<EmployeeFeedback> objListToReturn = new List<EmployeeFeedback>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeFeedbackConstants.const_procEmployeeFeedbackTeamWiseLm; base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_mode,"EmployeeWisefilter"); base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_TeamEmployeeId, TeamEmployeeId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeFeedback>(dt); } return objListToReturn; } public IEnumerable<EmployeeFeedback> GetEmployeeList(long UserId) { List<EmployeeFeedback> objListToReturn = new List<EmployeeFeedback>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeFeedbackConstants.const_procTeamMemberlist; base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeFeedback>(dt); } return objListToReturn; } public IEnumerable<EmployeeFeedback> GetPendingListEmployee(long UserId) { List<EmployeeFeedback> objListToReturn = new List<EmployeeFeedback>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeFeedbackConstants.const_procEmployeeFeedbackPending; base.objSqlCommand.Parameters.AddWithValue(EmployeeFeedbackConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeFeedback>(dt); } return objListToReturn; } public string Delete() { try { return null; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~EmployeeFeedbackRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { EmployeeFeedbackService } from '../../../Service/HumanResource/Attendance/EmployeeFeedback.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IEmployeeFeedback } from '../../../Model/HumanResource/Attendance/EmployeeFeedback'; import { IEmployee } from '../../../Model/HumanResource/Attendance/EmployeeFeedback'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; @Component({ providers: [EmployeeFeedbackService], templateUrl: 'app/Components/HumanResource/Attendance/EmployeeFeedback.component.html' }) export class EmployeeFeedbackComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; EmployeeFeedbacks: IEmployeeFeedback[]; EmployeeFeedback: IEmployeeFeedback; MyTeamFeedbacks: IEmployeeFeedback[]; MyTeamFeedback: IEmployeeFeedback; employeelist: IEmployee[]; msg: string; indLoading: boolean = false; EmployeeFeedbackFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; EmployeeFeedbackFilter: string; isDesc: boolean = false; column: any = ''; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; Status: string; //Variables for Filter ShowHideSearch: boolean = false; ShowHideSearchNew: boolean = false; //second table searchRemarks: string; searchEmployeeName: string; searchSenderName: string; constructor(private fb: FormBuilder, private _EmployeeFeedbackService: EmployeeFeedbackService, private pagerService: PagerService) { this.Status = "MyFeedback" } ngOnInit(): void { this.EmployeeFeedbackFrm = this.fb.group({ CompanyId: [''], Id:[''], mode: [''], UserID: [''], Remarks: [''], IsLike:[''], CreatedOn: [''], EmployeeName: [''], EmployeeId: [''], SenderName: [''], Employee_Name: [''], TeamEmployeeId:[''], }); this.LoadEmployeeFeedbacks(21); } clearSearch() { this.EmployeeFeedbacks = null; } FilterByStatus(event) { if (event.target.value == "MyTeam") { $("#MyFeedback").hide(); $("#MyTeam").show(); $("#TeamMember").show(); $("#MYPending").hide(); this.clearSearch(); this.LoadEmployeeteamWise(21); this.LoadEmployeeList(21); } else if (event.target.value == "Pending") { $("#MyFeedback").hide(); $("#MyTeam").hide(); $("#TeamMember").hide(); $("#MYPending").show(); this.clearSearch(); this.LoadEmployeependingList(21); } else { $("#MyFeedback").show(); $("#MyTeam").hide(); $("#TeamMember").hide(); $("#MYPending").hide(); this.clearSearch(); this.LoadEmployeeFeedbacks(21); } } LoadEmployeeList(UserId :number) { this.indLoading = true; this._EmployeeFeedbackService.getEmployeeList(Global.BASE_EmployeeFeedback_ENDPOINT, UserId) .subscribe(data => { this.employeelist = data this.indLoading = false; } ); } EmployeeFeedbackFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.EmployeeFeedbackFilter = value; } EmployeeFeedbackSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } LoadEmployeeteamwisedata(event, UserId: number): void { debugger; this.indLoading = true; this._EmployeeFeedbackService.GetEmployeewiseSelect(Global.BASE_EmployeeFeedback_ENDPOINT, event.target.value, 21) .subscribe(EmployeeFeedbacks => { this.EmployeeFeedbacks = EmployeeFeedbacks; //Logic for searching - start if (this.ShowHideSearch) { this.searchRemarks = (<HTMLInputElement>document.getElementById("searchRemarks")).value; if (this.searchRemarks != '') { this.searchRemarks = this.searchRemarks.toLocaleLowerCase(); this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( x => x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(this.searchRemarks) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( x => x.EmployeeName != null && x.EmployeeName.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } LoadEmployeeFeedbacks(UserId: number): void { $("#MyFeedback").show(); $("#MyTeam").hide(); $("#TeamMember").hide(); $("#MYPending").hide(); this.indLoading = true; this._EmployeeFeedbackService.GetEmployeeFeedback(Global.BASE_EmployeeFeedback_ENDPOINT, UserId) .subscribe(EmployeeFeedbacks => { this.EmployeeFeedbacks = EmployeeFeedbacks; //Logic for searching - start if (this.ShowHideSearch) { this.searchRemarks = (<HTMLInputElement>document.getElementById("searchRemarks")).value; if (this.searchRemarks != '') { this.searchRemarks = this.searchRemarks.toLocaleLowerCase(); this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( x => x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(this.searchRemarks) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } LoadEmployeeteamWise(UserId: number): void { this.indLoading = true; this._EmployeeFeedbackService.GetMyTeam(Global.BASE_EmployeeFeedback_ENDPOINT, UserId) .subscribe(EmployeeFeedbacks => { this.EmployeeFeedbacks = EmployeeFeedbacks; //Logic for searching - start if (this.ShowHideSearch) { this.searchRemarks = (<HTMLInputElement>document.getElementById("searchRemarks")).value; if (this.searchRemarks != '') { this.searchRemarks = this.searchRemarks.toLocaleLowerCase(); this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( x => x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(this.searchRemarks) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( x => x.EmployeeName != null && x.EmployeeName.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } LoadEmployeependingList(UserId: number): void { this.indLoading = true; this._EmployeeFeedbackService.GetPendingListEmployee(Global.BASE_EmployeeFeedback_ENDPOINT, UserId) .subscribe(EmployeeFeedbacks => { this.EmployeeFeedbacks = EmployeeFeedbacks; //Logic for searching - start //if (this.ShowHideSearch) { // this.searchRemarks = (<HTMLInputElement>document.getElementById("searchRemarks")).value; // if (this.searchRemarks != '') { // this.searchRemarks = this.searchRemarks.toLocaleLowerCase(); // this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( // x => x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(this.searchRemarks) != -1); // } // this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; // if (this.searchEmployeeName != '') { // this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); // this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( // x => x.EmployeeName != null && x.EmployeeName.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); // } // this.searchSenderName = (<HTMLInputElement>document.getElementById("searchSenderName")).value; // if (this.searchSenderName != '') { // this.searchSenderName = this.searchSenderName.toLocaleLowerCase(); // this.EmployeeFeedbacks = this.EmployeeFeedbacks.filter( // x => x.SenderName != null && x.SenderName.toLocaleLowerCase().indexOf(this.searchSenderName) != -1); // } //} //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addEmployeeFeedback() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New EmployeeFeedback"; this.modalBtnTitle = "Add"; this.EmployeeFeedbackFrm.reset(); this.modal.open(); } editEmployeeFeedback(Id: number) { debugger; var msg1 = "Are you sure you want to approve this feedback?"; if (confirm(msg1) == true) { this.getupdateEmplyeeFedback(Id); this.LoadEmployeependingList(21); } else { this.LoadEmployeependingList(21); } // this.getupdateEmplyeeFedback(id); } RejectEmployeeFeedback(Id: number) { debugger; var msg1 = "Are you sure you want to reject this feedback?"; if (confirm(msg1) == true) { this.getrejectEmplyeeFedback(Id); this.indLoading = true; this.LoadEmployeependingList(21); } else { this.indLoading = true; this.LoadEmployeependingList(21); } // this.getupdateEmplyeeFedback(id); } getrejectEmplyeeFedback(Id: number): void { debugger; this.indLoading = true; this._EmployeeFeedbackService.RejectFeedback(Global.BASE_EmployeeFeedback_ENDPOINT, Id, 21) .subscribe(EmployeeFeedbacks => { this.EmployeeFeedbacks = EmployeeFeedbacks; //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } getupdateEmplyeeFedback(Id: number): void{ debugger; this.indLoading = true; this._EmployeeFeedbackService.UpdateFeedback(Global.BASE_EmployeeFeedback_ENDPOINT, Id,21) .subscribe(EmployeeFeedbacks => { this.EmployeeFeedbacks = EmployeeFeedbacks; //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } getApprovedFeedback(UserId: number): void { debugger; this.indLoading = true; this._EmployeeFeedbackService.GetPendingListEmployee(Global.BASE_EmployeeFeedback_ENDPOINT, UserId) .subscribe(EmployeeFeedbacks => { this.EmployeeFeedbacks = EmployeeFeedbacks; //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } deleteEmployeeFeedback(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.EmployeeFeedbackFrm.setValue(this.EmployeeFeedback); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.EmployeeFeedbackFrm.enable() : this.EmployeeFeedbackFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeFeedbacks); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._EmployeeFeedbackService.post(Global.BASE_EmployeeFeedback_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadEmployeeFeedbacks(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: debugger; this._EmployeeFeedbackService.UpdateFeedback(Global.BASE_EmployeeFeedback_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadEmployeeFeedbacks(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._EmployeeFeedbackService.delete(Global.BASE_EmployeeFeedback_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadEmployeeFeedbacks(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class OutReport : VISBaseEntity { public string Employee_Name { get; set; } public string Department_Name { get; set; } public string CompanyName { get; set; } public string LineManager { get; set; } public string mode { get; set; } //-------BIND DATA Out Report Data -------// public int EmployeeId { get; set; } public int Active { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } public string OutType { get; set; } public int Minute { get; set; } public bool AllDate { get; set; } public string Employeelist { get; set; } public string Consolidated { get; set; } public string Sort { get; set; } } public static class OutReportConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Employee_Master = "Employee_Master"; public const string const_Table_Attendance_Transaction = "Attendance_Transaction"; public const string const_Table_Organization = "Organization"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Id = "Id"; public const string const_Field_DepartmentName = "Department_Name"; public const string const_Field_EmployeeName = "Employee_Name"; public const string const_Field_CompanyName = "CompanyName"; public const string const_Field_LineManager = "LineManager"; public const string const_Field_mode = "mode"; public const string const_Field_LineManagerId = "LineManagerId"; public const string const_Field_CompanyId = "CompanyId"; public const string const_Field_ParentId = "ParentId"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_EmployeeId = "empId"; public const string const_Field_Active = "active"; public const string const_Field_FromDate = "fromDate"; public const string const_Field_ToDate = "toDate"; public const string const_Field_OutType = "outType"; public const string const_Field_Minute = "Minute"; public const string const_Field_AllDate = "AllDate"; public const string const_Field_Employeelist = "employeelist"; public const string const_Field_Consolidated = "Consolidated"; public const string const_Field_Sort = "sort"; // procedure Constant public const string const_procAttendanceReport_SelectAll = "ProcAttendanceReportBindDropdown"; public const string const_ProcAttendanceReport_BindAttendanceData = "ProcCalTotalAttendanceReport"; public const string const_procOutReport = "procOutReport"; public const string const_procOutReportByLM = "procOutReportByLM"; public const string const_procOutReportByCompany = "procOutReportByCompany"; public const string const_procOutReportByDepartment = "procOutReportByDepartment"; } } <file_sep>export interface IMyTeam { id: number; mode: string; UserId: number; Name: string; NumberOfSkill: number; NumberToBeApproved: number; SkillName: string; } export interface ILinemanager { mode: string; SkillID: number; UserId: number; SkillName: string; SkillGroup: string; SkillText: number; leavel: string; IsApproved: boolean; Status: string; } export interface ISkillLevel { SkillID: number; LevelText: string; Levelorder: number; }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var MyProfiles_service_1 = require("../../../Service/HumanResource/ProfileAttendance/MyProfiles.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var router_1 = require("@angular/router"); var http_1 = require("@angular/http"); var MyProfilesComponent = (function () { function MyProfilesComponent(fb, _MyProfilesService, http, router, pagerService) { this.fb = fb; this._MyProfilesService = _MyProfilesService; this.http = http; this.router = router; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; } MyProfilesComponent.prototype.ngOnInit = function () { this.MyProfilesFrm = this.fb.group({ Mode: [''], UserId: [''], Employee_Name: [''], LineManagerName: [''], FirstName: [''], MiddleName: [''], LastName: [''], Gender: [''], PhotographFileName: [''], CompanyName: [''], Email: [''], JoiningDesignation: [''], DepartmentName: [''], FatherName: [''], MotherName: [''], PermenantAddres: [''], CommunicationAddress: [''], LandlineNumber: [''], MobileNumber: [''], BirthDate: [''], BloodGroup: [''], MaritalStatus: [''], }); this.LoadGetUserProfiles(21); this.LoadEducationDetail(21); this.LoadEmployeeList(); }; MyProfilesComponent.prototype.LoadGetUserProfiles = function (UserId) { var _this = this; this.ImgGlobalPath = global_1.Global.WebAccessURL; this.indLoading = true; this._MyProfilesService.getuserProfile(global_1.Global.BASE_MyProfiles_ENDPOINT, UserId) .subscribe(function (DATADP) { _this.ViewHistory = DATADP; _this.indLoading = false; }); }; MyProfilesComponent.prototype.LoadEducationDetail = function (UserId) { var _this = this; this.indLoading = true; this._MyProfilesService.getEducatinDeatils(global_1.Global.BASE_MyProfiles_ENDPOINT, UserId) .subscribe(function (DATADP) { _this.ViewEducation = DATADP; _this.indLoading = false; }); }; MyProfilesComponent.prototype.LoadSelectValue = function (event) { var _this = this; debugger; this.indLoading = true; this.Dropdownlist = this.employeeheadlist.filter(function (x) { return x.UserId == event.target.value; })[0]; console.log(this.Dropdownlist); this._MyProfilesService.getuserProfile(global_1.Global.BASE_MyProfiles_ENDPOINT, this.Dropdownlist.UserId) .subscribe(function (DATADP) { _this.ViewHistory = DATADP; console.log(DATADP); _this.indLoading = false; }); this._MyProfilesService.getEducatinDeatils(global_1.Global.BASE_MyProfiles_ENDPOINT, this.Dropdownlist.UserId) .subscribe(function (DATADP) { _this.ViewEducation = DATADP; console.log(DATADP); _this.indLoading = false; }); //this.LoadGetUserProfiles(event.traget.value); //this.LoadEducationDetail(event.traget.value); // this.indLoading = false; }; MyProfilesComponent.prototype.LoadEmployeeList = function () { var _this = this; this.indLoading = true; this._MyProfilesService.getEmployeeList(global_1.Global.BASE_MyProfiles_ENDPOINT) .subscribe(function (data) { _this.employeeheadlist = data; _this.indLoading = false; }); }; MyProfilesComponent.prototype.onSubmit = function (formData) { }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], MyProfilesComponent.prototype, "modal", void 0); MyProfilesComponent = __decorate([ core_1.Component({ providers: [MyProfiles_service_1.MyProfilesService], templateUrl: 'app/Components/HumanResource/ProfileAttendance/MyProfiles.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, MyProfiles_service_1.MyProfilesService, http_1.Http, router_1.Router, pager_index_1.PagerService]) ], MyProfilesComponent); return MyProfilesComponent; }()); exports.MyProfilesComponent = MyProfilesComponent; <file_sep>import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { LevelCriteriaSetupService } from '../../../service/Masters/EmployeeLevels/LevelCriteriaSetup.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ILevelCriteriaSetup, ICalculatedOnDLL,ICategoryDLL,ICriteriaDLL } from '../../../Model/Masters/EmployeeLevels/LevelCriteriaSetup'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component({ selector:"level-criteria-setup", providers: [LevelCriteriaSetupService], templateUrl: 'app/Components/Masters/EmployeeLevels/LevelCriteriaSetup.component.html' }) export class LevelCriteriaSetupComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; // @ViewChild('modal') modal: ModalComponent; LevelCriteriaSetups: ILevelCriteriaSetup[]; LevelCriteriaSetup: ILevelCriteriaSetup; LevelCriteriaSetupFilterDDL: ILevelCriteriaSetup; LevelCriteriaSetupForDll: ILevelCriteriaSetup[]; CriteriaDllData: ICriteriaDLL; CategoryDllData: ICategoryDLL; CalculatedOnDllData: ICalculatedOnDLL; msg: string; indLoading: boolean = false; LevelCriteriaSetupFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; LevelCriteriaSetupFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strSearchName: string; strSearchType: string; strCalculatedOn: string; strPoints: string; strSearchCriteriaDetails: string; SelectedCalculatedOn: string; EditData: boolean; ArbCriteriaType: string; ArbSubType: string; ArbEnable: string; ArbCascading: string; ArbIsProgressive: string; ArbManualType: string; constructor(private fb: FormBuilder, private _LevelCriteriaSetupService: LevelCriteriaSetupService, private pagerService: PagerService) { this.ArbCriteriaType = "Automatic" this.ArbManualType = "PerformanceBased"; this.ArbSubType = "Range"; } ngOnInit(): void { this.LevelCriteriaSetup = ({ Id: 0, IsAutomatic: false, IsRange: false, IsRepeated: false, IsOnce:false, IsPerformanceBased: false, IsEnable: false, ArbSubType: "", ArbCriteriaType: "", ArbIsProgressive: "", ArbCascading:"", ArbEnable:"", CriteriaID: 0, Criteria: '', Category:'', AIsRange: "", FromLimit: 0, ToLimit: 0, AIsRepeated: "", Units: 0, AIsOnce: "", // rbPerformanceBasedType: false, ArbManualType: "", IsPercentage: false, Point: 0, Active:false, IsProgressive: false, ProgressiveDays: 0, ProgressivePoints: 0, //CalculatedOn: 0, // CompanyId: 0, CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, dtFromDate:null, dtToDate:null, Name: '', CriteriaType: '', CalculatedOn: '', SelectPoint: 0, EntityMessage: '' }); this.LoadLevelCriteriaSetups(); this.LoadCriteria(); this.LoadCalculatedOn(); this.LoadCategory(); } ClearModel(): void { this.LevelCriteriaSetup = ({ Id: 0, IsAutomatic: false, IsRange: false, IsRepeated: false, IsOnce: false, IsPerformanceBased: false, IsEnable: false, ArbSubType: "", ArbCriteriaType: "", ArbIsProgressive: "", ArbCascading:"", ArbEnable: "", CriteriaID: 0, Criteria: '', Category: '', AIsRange: "", FromLimit: 0, ToLimit: 0, AIsRepeated: "", Units: 0, AIsOnce: "", // rbPerformanceBasedType: false, ArbManualType: "", IsPercentage: false, Point: 0, Active: false, IsProgressive: false, ProgressiveDays: 0, ProgressivePoints: 0, //CalculatedOn: 0, // CompanyId: 0, CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, dtFromDate:null, dtToDate:null, Name: '', CriteriaType: '', CalculatedOn: '', SelectPoint: 0, EntityMessage: '' }); } LoadCriteria(): void { this.indLoading = true; this._LevelCriteriaSetupService.getCriteria(Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(DATA => { this.LevelCriteriaSetupForDll = DATA; } //,error => this.msg = <any>error ); } LoadCalculatedOn(): void { this.indLoading = true; this._LevelCriteriaSetupService.getCalculatedOn(Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(DATA => { this.CalculatedOnDllData = DATA; } //,error => this.msg = <any>error ); } LoadCategory(): void { this.indLoading = true; this._LevelCriteriaSetupService.getCategory(Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(DATA => { this.CategoryDllData = DATA; } //,error => this.msg = <any>error ); } LevelCriteriaSetupFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.LevelCriteriaSetupFilter = value; } LevelCriteriaSetupSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadLevelCriteriaSetups(): void { this.indLoading = true; this._LevelCriteriaSetupService.get(Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(LevelCriteriaSetups => { debugger; this.LevelCriteriaSetups = LevelCriteriaSetups; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchName = (<HTMLInputElement>document.getElementById("searchName")).value; if (this.strSearchName != '') { this.strSearchName = this.strSearchName.toLocaleLowerCase(); this.LevelCriteriaSetups = this.LevelCriteriaSetups.filter( x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strSearchName) != -1); } this.strSearchType = (<HTMLInputElement>document.getElementById("searchType")).value; if (this.strSearchType != '') { this.strSearchType = this.strSearchType.toLocaleLowerCase(); this.LevelCriteriaSetups = this.LevelCriteriaSetups.filter( x => x.CriteriaType != null && x.CriteriaType.toLocaleLowerCase().indexOf(this.strSearchType) != -1); } this.strCalculatedOn = (<HTMLInputElement>document.getElementById("searchCalculatedOn")).value; if (this.strCalculatedOn != '') { this.strCalculatedOn = this.strCalculatedOn.toLocaleLowerCase(); this.LevelCriteriaSetups = this.LevelCriteriaSetups.filter( x => x.CalculatedOn != null && x.CalculatedOn.toLocaleLowerCase().indexOf(this.strCalculatedOn) != -1); } //this.strPoints = (<HTMLInputElement>document.getElementById("searchPoints")).value; //if (this.strPoints != '') { // this.strPoints = this.strPoints.toLocaleLowerCase(); // this.LevelCriteriaSetups = this.LevelCriteriaSetups.filter( // x => x.Point != null && x.Point.toLocaleLowerCase().indexOf(this.strPoints) != -1); //} } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addLevelCriteriaSetup() { this.EditData = false; this.ClearModel(); this.dbops = DBOperation.create; //this.SetControlsState(true); this.modalTitle = "Add New Criteria"; this.modalBtnTitle = "Add"; // this.LevelCriteriaSetup.reset(); this.modal.open(); } editLevelCriteriaSetup(id: number) { this.ClearModel(); this.EditData = true; this.dbops = DBOperation.update; this.modalTitle = "Edit Criteria"; this.modalBtnTitle = "Update"; this.LevelCriteriaSetup = this.LevelCriteriaSetups.filter(x => x.Id == id)[0]; this.ArbEnable = "Yes"; if (this.LevelCriteriaSetup.IsAutomatic) { this.ArbCriteriaType = "Automatic" if (this.LevelCriteriaSetup.IsRange) { this.ArbSubType = "Range"; } else if (this.LevelCriteriaSetup.IsRepeated) { this.ArbSubType = "Repeated"; } else { this.ArbSubType = "once"; } } else { this.ArbCriteriaType = "Manual" } //cascadding if (this.LevelCriteriaSetup.IsProgressive) { this.ArbIsProgressive = "Yes"; } else { this.ArbIsProgressive = "No"; } // this.LevelCriteriaSetupFrm.setValue(this.LevelCriteriaSetup); this.modal.open(); } deleteLevelCriteriaSetup(id: number, status: boolean) { this.dbops = DBOperation.delete; // this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } debugger; this.LevelCriteriaSetup = this.LevelCriteriaSetups.filter(x => x.Id == id)[0]; // this.LevelCriteriaSetupFrm.setValue(this.LevelCriteriaSetup); this.modal.open(); } //SetControlsState(isEnable: boolean) { // isEnable ? this.LevelCriteriaSetupFrm.enable() : this.LevelCriteriaSetupFrm.disable(); //} ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ChangeCriteria(CriteriaId: number) { this.LevelCriteriaSetupFilterDDL = this.LevelCriteriaSetups.filter(x => x.Id == CriteriaId)[0] //this.SelectedCalculatedOn = this.LevelCriteriaSetupFilterDDL.CalculatedOn this.LevelCriteriaSetup.CalculatedOn = this.LevelCriteriaSetupFilterDDL.CalculatedOn; } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.LevelCriteriaSetups); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { debugger; this.msg = ""; switch (this.dbops) { case DBOperation.create: formData.CalculatedOn = this.LevelCriteriaSetup.CalculatedOn; this._LevelCriteriaSetupService.post(Global.BASE_LEVELCRITERIASETUP_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLevelCriteriaSetups(); this.modal.dismiss(); this.ClearModel(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: formData.Id = this.LevelCriteriaSetup.Id; formData.CriteriaID = this.LevelCriteriaSetup.CriteriaID; this._LevelCriteriaSetupService.put(Global.BASE_LEVELCRITERIASETUP_ENDPOINT, formData.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLevelCriteriaSetups(); this.modal.dismiss(); this.ClearModel(); this.EditData = false; } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: debugger; this._LevelCriteriaSetupService.delete(Global.BASE_LEVELCRITERIASETUP_ENDPOINT, this.LevelCriteriaSetup.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "LevelCriteriaSetup status changed successfully."; this.LoadLevelCriteriaSetups(); } else { this.msg = "Error has occurred while changing status of existing LevelCriteriaSetup!" } this.modal.dismiss(); this.ClearModel(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.UserManagement { public class LoginData { public string VISUsername { get; set; } public string VISPassword { get; set; } public string UserFullName { get; set; } public string LastName { get; set; } public Int64 Id { get; set; } public string Email { get; set; } public string UserType { get; set; } public string UserRoleTypeName { get; set; } public string[] ArrayUserType { get; set; } public bool IsAdmin { get; set; } public bool IsLineManager { get; set; } public string DepartmentId { get; set; } public bool IsOnStypend { get; set; } public bool IsFormerEmployee { get; set; } public bool IsWebAccess { get; set; } public bool validForLogin { get; set; } public string WebAccessURL { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master.Configuration; namespace VIS_Repository.Reports { public class DailyEntrySheetRepository : VISDbCommand { int intAffectedRecords; public DataSet DailyEntrysheetdata { get; set; } public DailyEntrySheetRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<EmployeeMaster> GetAllEmployees() { List<EmployeeMaster> objListToReturn = new List<EmployeeMaster>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = DailyEntrysheetConstant.const_procEmployee_Master_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeMaster>(dt); } return objListToReturn; } public IEnumerable<DailyEntrysheetEmployee> GetDailyEntrySheetData(Int64 Id, string Date) { List<DailyEntrysheetEmployee> objListToReturn = new List<DailyEntrysheetEmployee>(); string mode = null; try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = DailyEntrysheetConstant.const_procReportPerEmp; base.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_Mode,mode); base.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_EmployeeId, Id); base.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_ForWhichDate, Date); base.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_LoginUserId, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<DailyEntrysheetEmployee>(dt); } } catch (Exception) { } return objListToReturn; } public DataTable GetDailyEntrySheetTime(Int64 Id, string Date) { DataTable dt = new DataTable(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = DailyEntrysheetConstant.const_ProcCalTotalAttendanceReport; base.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_EmployeeID, Id); base.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_Date, Date); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } catch (Exception) { } return dt; } public DataTable GetDailyEntrySheetTimeAllEmployee(string Date) { string dd; string mm; string yy; yy = Date.Substring(0,4); mm = Date.Substring(8,2); dd = Date.Substring(5,2); Date = mm + "/" + dd + "/" + yy; DataTable dt = new DataTable(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = DailyEntrysheetConstant.const_ProcCalTotalAttendanceReportAllEmployee; base.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_Date, Date); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch (Exception ex) { string errormsg = ex.Message + Environment.NewLine + ex.StackTrace; } return dt; } public string UpdateReportDetail(DailyEntrysheetEmployee entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = DailyEntrysheetConstant.const_procreportRecordUpdate; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Transaction_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_Time, entityObject.Entry_Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_actualEntryTime, entityObject.actualEntryTime); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_Remarks, entityObject.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(DailyEntrysheetParamaterConstant.const_grace, entityObject.Grace); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } } }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var PolicyFilterPipe = (function () { function PolicyFilterPipe() { } PolicyFilterPipe.prototype.transform = function (value, filter) { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter(function (app) { return app.Policy_Name != null && app.Policy_Name.toLocaleLowerCase().indexOf(filter) != -1 || app.Description != null && app.Description.toLocaleLowerCase().indexOf(filter) != -1; }) : value; }; PolicyFilterPipe = __decorate([ core_1.Pipe({ name: 'PolicyFilter' }) ], PolicyFilterPipe); return PolicyFilterPipe; }()); exports.PolicyFilterPipe = PolicyFilterPipe; /* 1. In the first line, we are importing the PipeTransform and Pipe interfaces that we are implementing to achieve filtering functionality. 2. In the second line, we are importing the IContactMaster interface that we created in first part to hold the list of Policys. Over here, we are also using it to hold the list of Policys that is the source data for filtering. 3. In next line, we are specifying the pipe selector/name PolicyFilter through which we will use the pipe (you will find in future steps, how). 4. Next, we are creating the PolicyFilterPipe class that is implementing the PipeTransform interface (implementing interface means providing the body to all methods mentioned in the interface). 5. Right click on PipeTransform and select the option Go To Definition: 6. You will be landed to the pipe_transform_d.ts file where you will find the nice brief description how to use the pipe with an example and transform method that we must need to implement: 7. So let’s go back to Policy.pipe.ts where can see we have transform method with first argument as IContactMaster array and second is named as filter that is the input string to be searched in the IContactMaster array. 8. In transform method, the first line is only to check if the filter is not null. 9. The next statement is the actual implementation of search, if you are C# developer, you can compare it to the LINQ to Object. We are calling Array’s filter method, checking through conditional operator that if any of IContactMaster member is matching with Policy input search string and if YES, returning the filtered result. toLocaleLowerCase method is converting string to lower case, to read more about it, click here. If there is no matching record in User list, we are returning the all rows.Now that we have our filter ready, let’s add it to */ <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.Attendance; using VIS_Repository.HumanResource.Attendace; namespace VIS_App.Controllers.HumanResource.Attendance { public class MySkillAPIController : BaseAPIController { MySkillRepository ObjMySkillRepository = null; public MySkillAPIController() { ObjMySkillRepository = new MySkillRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/MySkillAPI/GetMySkill")] [HttpGet] public HttpResponseMessage GetMySkill(long UserID) { return ToJson(ObjMySkillRepository.GetSkillUserWise(UserID)); } [Route("api/MySkillAPI/GetNewSkill")] [HttpGet] public HttpResponseMessage GetNewSkill(long UserID) { return ToJson(ObjMySkillRepository.GetAddNewSkill(UserID)); } [Route("api/MySkillAPI/GetPopupChildSkill")] [HttpGet] public HttpResponseMessage GetPopupChildSkill() { return ToJson(ObjMySkillRepository.GetPopupChildSkill()); } [Route("api/MySkillAPI/GetPopupSecondSkill")] [HttpGet] public HttpResponseMessage GetPopupSecondSkill(long lookupSkilId) { return ToJson(ObjMySkillRepository.GetPopupsecondSkill(lookupSkilId)); } public HttpResponseMessage Get() { return ToJson(ObjMySkillRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]MySkill value) { return ToJson(ObjMySkillRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]MySkill value) { return ToJson(ObjMySkillRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjMySkillRepository.DeleteEntity(Id)); } [Route("api/MySkillAPI/DeleteSkill")] [HttpDelete] public HttpResponseMessage DeleteSkill(int SkillID, long UserID) { return ToJson(ObjMySkillRepository.DeleteSkill(SkillID, UserID)); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Web; using System.Web.Http; using VIS_Domain.Notification; using VIS_Repository; using VIS_Repository.Notification; namespace VIS_App.Controllers.Notification { public class TicketListOpenAPIController : BaseAPIController { //VISIBaseRepository<TicketListOpen> TicketListOpenRepository; //List<TicketListOpen> EntityList = new List<TicketListOpen>(); TicketListOpenRepository ObjTicketListOpenRepository = null; public TicketListOpenAPIController() { // TicketListOpenRepository = _TicketListOpenRepository; ObjTicketListOpenRepository = new TicketListOpenRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjTicketListOpenRepository.GetEntityList().AsEnumerable()); } [Route("api/TicketListOpenapi/GetDetailTicket")] [HttpGet] public HttpResponseMessage GetDetailTicket(int UserId) { return ToJson(ObjTicketListOpenRepository.GetTicketByUserOpen(UserId)); } [Route("api/TicketListOpenapi/GetViewHistoryTicket")] [HttpGet] public HttpResponseMessage GetViewHistoryTicket(int id) { return ToJson(ObjTicketListOpenRepository.GetViewHistory(id)); } [Route("api/TicketListOpenapi/GetDetailTicketByID")] [HttpGet] public HttpResponseMessage GetDetailTicketByID(int id) { return ToJson(ObjTicketListOpenRepository.GetTicketDetail(id)); } [Route("api/TicketListOpenapi/GetDetailTicketAdmin")] [HttpGet] public HttpResponseMessage GetDetailTicketAdmin() { return ToJson(ObjTicketListOpenRepository.GetTicketByAllTicket()); } public HttpResponseMessage Post([FromBody]TicketListOpen value) { return ToJson(ObjTicketListOpenRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]TicketListOpen value) { return ToJson(ObjTicketListOpenRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjTicketListOpenRepository.DeleteEntity(Id)); } } } <file_sep>export interface IDocumentTemplateModel { DocTemplateId: number; TemplateName: string; AddRecurrenceType: boolean; IsRecurrence: boolean; DateFormat: string; TemplateDescription: string; IsDownloadWord: boolean; IsDownloadPdf: boolean; IsDMSPdf: boolean; IsDMSWord: boolean; IsEmailPdf: boolean; IsEmailWord: boolean; TemplateRightsData: string; IsPortrait: boolean; IsSelf: boolean; IsBehalf: boolean; SharingVariableType: string; StartingVariableRole: string; AllowHeader: boolean; AllowFooter: boolean; HeaderContent: string; FooterContent: string; OwnerId: number; ContributorsId: string; IsApproved: boolean; ApprovedOn: Date; IsFinalSubmited: boolean; ModuleId: string; PublishDate: string; stringDate: Date; DocRightsId: number; ModuleName: string; EmployeeName: string; DocTemplateInProgressId: number; EmployeeId: number; CreatedBy: number; } export interface IDocumentTemplateViewModel { DocTemplateId: number; TemplateName: string; OwnerName: string; ModuleName: string; IsRecurrence: boolean; IsSelf: boolean; IsBehalf: boolean; PublishDate: string; ApprovedStatus: string; CreatedOn: string; IsActive: boolean; } export interface IDocTemplateModule { ModuleId: number; ModuleName: string; ModuleValue: string; IsActive: boolean; } export interface IDropdownCustomField { TokenName: string; TokenValue: string; MasterFieldId: number; } export interface IDropdownTableField { VariableId: number; VarName: string; TableName: string; FieldName: string; ModuleId: number; IsActive: boolean; } export interface IListItem { value: string; text: string; } // Step 2 model export interface IDocMasterFieldDataContract { Id: number; FieldName: string; FieldDescription: string; FieldType: string; ListType: string; DataSourceTable: string; DataSourceColumn: string; DataSourceColumnForCustom: string; PageContent: string; ImageName: string; ImageHeight: number; ImageWidth: number; ImageAlign: string; FieldId: string; IsCustomField: boolean; DocTemplateId: number; AttachmentList: string; IsNew: boolean; IsDelete: boolean; CreatedOn: Date; CreatedBy: number; UpdatedOn: Date; UpdatedBy: number; IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Masters.EmployeeLevels; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.Masters; using VIS_Domain; namespace VIS_Repository.Masters.CompanyRelated { public class LevelConfigurationRepository : VISDbCommand, VISIBaseRepository<LevelConfiguration> { public Int32 intAffectedRecords { get; set; } public LevelConfigurationRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelConfigurationConstants.const_procLevelConfigurations_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public LevelConfiguration GetEntityByID(Int64 entityId) { LevelConfiguration objEntityToReturn = new LevelConfiguration(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LevelConfigurationConstants.const_procLevelConfigurations_SelectById; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<LevelConfiguration>(dt.Rows[0]); objEntityToReturn.StartMonth = objEntityToReturn.StartDate.Month; objEntityToReturn.StartYear = objEntityToReturn.StartDate.Year; } return objEntityToReturn; } public IEnumerable<LevelConfiguration> GetEntityList() { List<LevelConfiguration> objListToReturn = new List<LevelConfiguration>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LevelConfigurationConstants.const_procLevelConfigurations_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<LevelConfiguration>(dt); for(int intCount = 0; intCount<= objListToReturn.Count - 1; intCount++) { objListToReturn[intCount].StartMonth = objListToReturn[intCount].StartDate.Month; objListToReturn[intCount].StartYear = objListToReturn[intCount].StartDate.Year; } } return objListToReturn; } public string AddEntity(LevelConfiguration entityObject) { try { DateTime dStartDate = DateTime.Parse("1/" + entityObject.StartMonth + "/" + entityObject.StartYear).Date; entityObject.StartDate = dStartDate; entityObject.EndDate= dStartDate.AddMonths(entityObject.Period).AddDays(-1).Date; if (entityObject.Period == 1) { entityObject.PeriodName = "Monthly"; } else if (entityObject.Period == 3) { entityObject.PeriodName = "Quarterly"; } else if (entityObject.Period == 6) { entityObject.PeriodName = "Bi-Annually"; } else if (entityObject.Period == 12) { entityObject.PeriodName = "Annually"; } else if (entityObject.Period == 24) { entityObject.PeriodName = "Once In 2 Year"; } VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelConfigurationConstants.const_procLevelConfigurations_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_Period, entityObject.Period); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_PeriodName, entityObject.PeriodName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_StartDate, entityObject.StartDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_EndDate, entityObject.EndDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_Active, entityObject.Active); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(LevelConfiguration entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelConfigurationConstants.const_procLevelConfigurations_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_Period, entityObject.Period); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_PeriodName, entityObject.PeriodName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_StartDate, entityObject.StartDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_EndDate, entityObject.EndDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_Active, entityObject.Active); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelConfigurationConstants.const_Field_IsCurrentPeriod, entityObject.IsCurrentPeriod); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~LevelConfigurationRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using VIS_Domain.Reports.Attendance; using System.Data.SqlClient; using VIS_Domain; using System.Globalization; namespace VIS_Repository.Reports.Attendance { public class AddEmployeeRecordRepository : VISDbCommand { int intAffectedRecords; //AddEmployeeRecordRepository objAddEmployeeRecordRepository = null; public AddEmployeeRecordRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<EmployeeMaster> GetEmployee() { List<EmployeeMaster> objListToReturn = new List<EmployeeMaster>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AddEmployeeRecordConstant.const_procGeneralSP; base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Mode, "GetEmployeeMaster"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeMaster>(dt); } return objListToReturn; } public IEnumerable<BindEmployeeDetails> GetEmployeeDetails(Int64 EmpId, string Date, Int64 LoginUserId) { List<BindEmployeeDetails> objListToReturn = new List<BindEmployeeDetails>(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AddEmployeeRecordConstant.const_procReportPerEmp; base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_empId, EmpId); base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_forWhichDate, Date); base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_LoginUserId, LoginUserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<BindEmployeeDetails>(dt); } } catch (Exception ex) { } return objListToReturn; } public DataTable BindEmployeeAttendance(Int64 EmployeeID, string Date) { DataTable dt = new DataTable(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AddEmployeeRecordConstant.const_ProcCalTotalAttendanceReport; base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_EmployeeID,EmployeeID); base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Date, Date); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch (Exception ex) { } return dt; } public IEnumerable<BindHRAttendanceDetails> BindHRAttendanceDetails(Int64 EmployeeId, string forWhichDate) { List<BindHRAttendanceDetails> objListToReturn = new List<BindHRAttendanceDetails>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AddEmployeeRecordConstant.const_Proc_HRAttendanceDetail; base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_EmployeeID,EmployeeId); base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_forWhichDate,forWhichDate); base.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Mode, "GetHRDetails"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<BindHRAttendanceDetails>(dt); } return objListToReturn; } public DataTable GetAttendanceTransaction(Int64 EmployeeId, string Date, Int64 EntryType) { DataTable dt = new DataTable(); try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AddEmployeeRecordConstant.const_procGeneralSP; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Id, EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_StrDate, Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_EntryType, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Mode, "GetAttend_TransactionDetail"); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); da.Fill(dt); } catch (Exception ex) { } return dt; } public string GetUpdateEmployeeAttendance(Int64 id, Int64 EmployeeId, Int64 EntryType, string Remarks, string entryTime, string Date, Int64 Grace, Int64 LoginId, string ActualEntryTime) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AddEmployeeRecordConstant.const_Proc_updateTransaction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id,id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Employee_Id,EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Entry_Type,EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Remarks,Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Entry_Time,entryTime); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Date,Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_actualEntryTime, ActualEntryTime); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_grace,Grace); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_createdBy,LoginId); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string AddEmployee(Int64 EmployeeId, Int64 EntryType, string Remarks,string entryTime, string Date, string Time, Int64 Grace) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AddEmployeeRecordConstant.const_Procattendance_transaction; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, 0); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Mode,"add"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Employee_Id, EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Entry_Type, EntryType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Remarks, Remarks.Trim().ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Entry_Time,entryTime); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_Date, Date.Trim().ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_actualEntryTime,Time); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AddEmployeeRecordConstant.const_grace, Grace); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } } } <file_sep>export interface IMyAllocation { FromDate: string; ToDate: string; AllocatedHr: number; TotalHr: number; ProjectName: string; }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Opinion; using VIS_Repository.Opinion; namespace VIS_App.Controllers.Opinion { public class ConfigureSurveyAPIController : BaseAPIController { ConfigureServeyRepository objConfigureServeyRepository = null; public ConfigureSurveyAPIController() { objConfigureServeyRepository = new ConfigureServeyRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/ConfigureSurveyAPI/GetRollOfEmployee")] [HttpGet] public HttpResponseMessage GetRollOfEmployee(int EmployeeId, string RoleType) { return ToJson(objConfigureServeyRepository.GetRollOfEmployee(EmployeeId, RoleType)); } [Route("api/ConfigureSurveyAPI/GetSurveyDetails")] [HttpGet] public HttpResponseMessage GetSurveyDetails(string SearchField, string searchValue, int EmployeeId, string RoleType, string ServeyType, string Approvetype) { return ToJson(objConfigureServeyRepository.GetSurveyDetails(SearchField, searchValue, EmployeeId, RoleType, ServeyType, Approvetype)); } [Route("api/ConfigureSurveyAPI/BindSurveyType")] [HttpGet] public HttpResponseMessage BindSurveyType() { return ToJson(objConfigureServeyRepository.BindSurveyType()); } [Route("api/ConfigureSurveyAPI/BindUsersForOwnerSelection")] [HttpGet] public HttpResponseMessage BindUsersForOwnerSelection() { return ToJson(objConfigureServeyRepository.BindUsersForOwnerSelection()); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Notification; namespace VIS_Repository.Notification { public class MyTicketRepository : VISDbCommand, VISIBaseRepository<MyTicket> { public Int32 intAffectedRecords { get; set; } public MyTicketRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public MyTicket GetEntityByID(Int64 Id) { MyTicket objEntityToReturn = new MyTicket(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketDetailByUser; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<MyTicket>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<MyTicket> GetEntityList() { List<MyTicket> objListToReturn = new List<MyTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_selectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTicket>(dt); } return objListToReturn; } public string AddEntity(MyTicket entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Subject, entityObject.Subject); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Message, entityObject.Message); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Remarks, entityObject.Message); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_AddressToGroup, entityObject.AddressToGroup); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Priority, entityObject.Priority); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, 21); base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_ProcHelpTicketAssignToFind; base.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_Organization_id, entityObject.AddressToGroup); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataSet ds = new DataSet(); ds.Clear(); da.Fill(ds); base.objSqlCommand.Connection.Close(); if (ds.Tables[0].Rows.Count > 0 || ds != null) { Int64 EmpId = Convert.ToInt64(ds.Tables[0].Rows[0][0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_AssignTo, EmpId); } if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Parameters.Add("@HelpTicketId", SqlDbType.Int).Direction = ParameterDirection.Output; objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); long Check = Convert.ToInt64(objVISDbCommand.objSqlCommand.Parameters["@HelpTicketId"].Value); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_HelpTicketId, Check); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Subject, entityObject.Subject); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Message, entityObject.Message); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Remarks, entityObject.Message); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_AddressToGroup, entityObject.AddressToGroup); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_ProcHelpTicketAssignToFind; base.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_Organization_id, entityObject.AddressToGroup); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da1 = new SqlDataAdapter(base.objSqlCommand); DataSet ds1 = new DataSet(); ds1.Clear(); da1.Fill(ds1); if (ds1.Tables[0].Rows.Count > 0 || ds1 != null) { Int64 EmpId = Convert.ToInt64(ds1.Tables[0].Rows[0][0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_AssignTo, EmpId); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Priority, entityObject.Priority); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, 21); if (entityObject.FileName != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketAttachement; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_HelpTicketId, Check); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_FileName, entityObject.FileName); string FileExtension = Path.GetExtension(entityObject.FileName).ToLower(); Guid guid = Guid.NewGuid(); string[] phName = entityObject.FileName.Split('.'); string newFileName = guid.ToString().Replace("-", "").ToUpper() + FileExtension; string sFilePath = "upload\\" + newFileName; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_OriginalFileName, newFileName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, 21); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } if (entityObject.FileName1 != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketAttachement; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_HelpTicketId, Check); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_FileName1, entityObject.FileName1); string FileExtension = Path.GetExtension(entityObject.FileName1).ToLower(); Guid guid = Guid.NewGuid(); string[] phName = entityObject.FileName1.Split('.'); string newFileName = guid.ToString().Replace("-", "").ToUpper() + FileExtension; string sFilePath = "upload\\" + newFileName; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_OriginalFileName,newFileName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, 21); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } if (entityObject.FileName2 != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketAttachement; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_HelpTicketId, Check); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_FileName2, entityObject.FileName2); string FileExtension = Path.GetExtension(entityObject.FileName2).ToLower(); Guid guid = Guid.NewGuid(); string[] phName = entityObject.FileName2.Split('.'); string newFileName = guid.ToString().Replace("-", "").ToUpper() + FileExtension; string sFilePath = "upload\\" + newFileName; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_OriginalFileName, newFileName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, 21); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } //intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objVISDbCommand.objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(MyTicket entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Remarks,entityObject.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Priority, entityObject.Priority); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); #region helpTickeMsaterLog objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketMasterLog; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.cons_Filed_HelpTicketId, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Subject, entityObject.Subject); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Remarks, entityObject.Remarks); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_selectAll; base.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Mode, "SelectID"); base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da1 = new SqlDataAdapter(base.objSqlCommand); DataSet ds1 = new DataSet(); ds1.Clear(); da1.Fill(ds1); base.objSqlCommand.Connection.Close(); base.objSqlCommand.Parameters.Clear(); if (ds1.Tables[0].Rows.Count > 0 || ds1 != null) { Int64 EmpId = Convert.ToInt64(ds1.Tables[0].Rows[0][0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_AssignTo, EmpId); Int64 AdId = Convert.ToInt64(ds1.Tables[0].Rows[0][1]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_AddressToGroup, AdId); string Message = ds1.Tables[0].Rows[0]["Message"].ToString(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListOpenConstants.const_Field_Message, Message); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Priority, entityObject.Priority); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, 21); #endregion helpTickeMsaterLog base.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<MyTicket> GetTicketByUser(int CreatedId) { List<MyTicket> objListToReturn = new List<MyTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketDetailByUser; base.objSqlCommand.Parameters.AddWithValue(MyTicketConstants.const_Field_CreatedId, CreatedId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTicket>(dt); } return objListToReturn; } public IEnumerable<MyTicket> GetDepartmentOrganization() { List<MyTicket> objListToReturn = new List<MyTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketMaster_DepartmentHelpTicketDll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTicket>(dt); } return objListToReturn; } public IEnumerable<MyTicket> GetViewHistory(Int64 Id) { List<MyTicket> objListToReturn = new List<MyTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicketHistory_History; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTicket>(dt); } return objListToReturn; } public IEnumerable<MyTicket> GetTicketDetail(Int64 Id) { List<MyTicket> objListToReturn = new List<MyTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTicketConstants.const_procHelpTicket_SelectById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTicket>(dt); } return objListToReturn; } public SqlParameter AddHelpTicket() { SqlParameter objSqlIdparameter = new SqlParameter(); objSqlIdparameter.SqlDbType = System.Data.SqlDbType.BigInt; objSqlIdparameter.Direction = System.Data.ParameterDirection.Output; objSqlIdparameter.ParameterName = MyTicketConstants.cons_Filed_HelpTicketId; objSqlIdparameter.Value = String.Empty; return objSqlIdparameter; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>export interface IDailyEntrysheetEmployee { Employee_Name: string; Date: string; Entry_Type: string; Entry_Time: string; actualEntryTime: string; Remarks: string; TotalOfficeTime: string; TotalWorkingTime: string; TotalBreakTime: string; TotalWorksheetHours: string; Id: number; Grace: number; Transaction_Id: number; } export interface IDailyEntrysheetTime { TotalOfficeTime: Date; TotalWorkingTime: Date; TotalBreakTime: Date; TotalWorksheetHours: Date; } export interface IEmployees { Id: number; Employee_Name: string; } export interface IBindAttendanceReportEmp { EmployeeName: string; Date: string; EntryTime: string; Remarks: string; }<file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IDashboard = (function () { function IDashboard() { } return IDashboard; }()); exports.IDashboard = IDashboard; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; using VIS_Domain.HumanResource.Grievance; using System.Globalization; using VIS_Domain; namespace VIS_Repository.HumanResource.Grievance { public class SalaryGrievanceRepository :VISDbCommand { public Int32 intAffectedRecords { get; set; } public SalaryGrievanceRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<FillGrievance> GetGrievance(Int64 UserId, string mode) { List<FillGrievance> objListToReturn = new List<FillGrievance>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SalaryGrievanceConstants.const_ProcSalaryGrievanceProcessing_SelectAll; base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_EmployeeId,UserId); base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillGrievance>(dt); } return objListToReturn; } public IEnumerable<FillGrievanceDate> FillDeductionDate(Int64 UserId, string mode) { List<FillGrievanceDate> objListToReturn = new List<FillGrievanceDate>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SalaryGrievanceConstants.const_Proc_PA_GetGrievanceDate; base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_EmployeeId, UserId); base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillGrievanceDate>(dt); } return objListToReturn; } public DataTable LoadEmployeeDailyEntry(Int64 EmployeeId, string Date) { string[] datearray = Date.Split('/'); string strDate = datearray[1] + "/" + datearray[0] + "/" + datearray[2]; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SalaryGrievanceConstants.const_Proc_ReportPerEmp_Grievance; base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_empId, EmployeeId); base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_forWhichDate,Convert.ToDateTime(strDate)); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable LoadEmployeeAttendance(Int64 EmployeeId, string Date) { //DateTime forwhichDate = Convert.ToDateTime(Date); DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SalaryGrievanceConstants.const_Proc_GetAttendancePerEmp_Grievance; base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_empId, EmployeeId); base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_Date, Date); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public string AddGrievance(Int64 EmployeeId, string Date, string PaycutAmt, string GrievanceRemark) { try { string[] datearray = Date.Split('/'); string strDate = datearray[1] + "/" + datearray[0] + "/" + datearray[2]; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = SalaryGrievanceConstants.const_Proc_InsertupdateGrievance; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_mode, "Insert"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_EmployeeId,EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_DeductionDate,Convert.ToDateTime(strDate)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_PC_AMT,PaycutAmt); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_Grievance_Remark,GrievanceRemark); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch(Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(SalaryGrievance entityGrievance) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = SalaryGrievanceConstants.const_Proc_InsertupdateGrievance; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_mode, "Update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_Id,entityGrievance.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_Grievance_Remark,entityGrievance.Grievance_Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_UpdatedBy,entityGrievance.Employee_Id); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } public DataTable GetGrievanceData(Int64 Id) { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SalaryGrievanceConstants.const_Proc_PA_GetGrievanceDate; base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_mode, "Grievance"); base.objSqlCommand.Parameters.AddWithValue(SalaryGrievanceConstants.const_Field_Id,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Opinion { class ConfigureSurvey { } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { ChangePSWService } from '../../../Service/HumanResource/ProfileAttendance/ChangePassword.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IChangePassword } from '../../../Model/HumanResource/ProfileAttendance/ChangePassword'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; @Component({ providers: [ChangePSWService], templateUrl: 'app/Components/HumanResource/ProfileAttendance/ChangePassword.component.html' }) export class ChangePasswordComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; //@ViewChild('modal1') modal1: ModalComponent; public ChangePSW: IChangePassword; public ChangePswObj: IChangePassword[]; msg: string; indLoading: boolean = false; ChangePSWFRM: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; isDesc: boolean = false; //column: any = 'News_Name'; direction: number; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; constructor(private fb: FormBuilder, private _ChangePSWService: ChangePSWService, public http: Http, private router: Router, private pagerService: PagerService) { } ngOnInit(): void { this.ChangePSWFRM = this.fb.group({ Id: [''], VISUserName: [''], VISPassword: [''], NewPassword: [''], ConfirmNewPassword: [''] //IsNew: [''], //CreatedOn: [''], //CreatedBy: [''], //UpdatedOn: [''], //UpdatedBy: [''], //IsActive: [''], //EntityMessage: [''] }); //this.LoadChangePsw() } onSubmit(formData: any) { if (formData._value.ConfirmNewPassword == formData._value.NewPassword) { this.dbops = DBOperation.update; this.msg = ""; switch (this.dbops) { case DBOperation.update: this._ChangePSWService.ChangePassword(Global.BASE_ChhangePassword_ENDPOINT, 2, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Password Changed successfully ..."; this.ngOnInit(); } else { this.msg = "Error has occurred while modifying existing ChangePassword!" } //this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } else { this.msg = "Password does not match !!!"; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; namespace VIS_App.Controllers.Masters.Configuration { public class ConfigureWorksheetAPIController : BaseAPIController { ConfigureWorksheetRepository objConfigureWorksheetRepository = null; VISIBaseRepository<ConfigureWorksheet> ConfigureWorkSheetRepository; public ConfigureWorksheetAPIController(VISIBaseRepository<ConfigureWorksheet> _ConfigureWorkSheetRepository) { objConfigureWorksheetRepository = new ConfigureWorksheetRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); ConfigureWorkSheetRepository = _ConfigureWorkSheetRepository; } public HttpResponseMessage Get() { return ToJson(objConfigureWorksheetRepository.GetEntityList()); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]ConfigureWorksheet value) { return ToJson(ConfigureWorkSheetRepository.UpdateEntity(value)); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters; namespace VIS_Repository.Masters.Configuration { public class ConfigureTicketRepository : VISDbCommand, VISIBaseRepository<ConfigureTicket> { public Int32 intAffectedRecords { get; set; } public ConfigureTicketRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<ConfigureTicket> GetParantGroup() { List<ConfigureTicket> objListToReturn = new List<ConfigureTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSelectParent; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ConfigureTicket>(dt); } return objListToReturn; } public IEnumerable<ConfigureTicket> GetChildGroup(int Parent_Id) { List<ConfigureTicket> objListToReturn = new List<ConfigureTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSelectChildGroup; base.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Parent_Id,Parent_Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ConfigureTicket>(dt); } return objListToReturn; } public IEnumerable<ConfigureTicket> GetEmployeeHead() { List<ConfigureTicket> objListToReturn = new List<ConfigureTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSelectHead; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ConfigureTicket>(dt); } return objListToReturn; } public IEnumerable<ConfigureTicket> GetListofTicketDisplayTo(int Organization_Id) { List<ConfigureTicket> objListToReturn = new List<ConfigureTicket>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureTicketConstant.const_proSuggestionsOrganizationEmployeeMapping; base.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Organization_Id,Organization_Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ConfigureTicket>(dt); } return objListToReturn; } public string UpdateEntity(ConfigureTicket entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ConfigureTicketConstant.const_procorganization_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_IsActiveSuggestion,entityObject.IsActiveSuggestion); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_SuggestionAlie, entityObject.SuggestionAlie); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEmployeeId(List<ConfigureTicket> entityObject) { try { foreach (ConfigureTicket configticket in entityObject) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); //objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; //objVISDbCommand.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSuggestionsOrganizationEmployeeMapping_UpdateEmployeeId; objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSuggestionsOrganizationEmployeeMapping_Compare; base.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Organization_Id, configticket.Organization_Id); base.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Employee_Id, configticket.Employee_Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataSet ds = new DataSet(); da.Fill(ds); Int64 OrgId = Convert.ToInt64(ds.Tables[0].Rows[0][1]); Int64 EmpId = Convert.ToInt64(ds.Tables[0].Rows[0][2]); ds.Clear(); if (configticket.Employee_Id == EmpId && configticket.Organization_Id==OrgId) { objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSuggestionsOrganizationEmployeeMapping_UpdateEmployeeId; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Mode, "Insert"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Organization_Id, configticket.Organization_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Employee_Id, configticket.Employee_Id); } else { objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSuggestionsOrganizationEmployeeMapping_UpdateEmployeeId; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Mode, "Update"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Organization_Id, configticket.Organization_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Employee_Id, configticket.Employee_Id); } } } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } return ""; } public string UpdateEmployeeNew(List<ConfigureTicket> entityObject) { try { foreach (ConfigureTicket configticket in entityObject) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSuggestionsOrganizationEmployeeMapping_Compare; base.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Organization_Id, configticket.Organization_Id); base.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Employee_Id, configticket.Employee_Id); base.objSqlCommand.Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(objSqlCommand); DataSet ds = new DataSet(); ds.Clear(); da.Fill(ds); base.objSqlCommand.Connection.Close(); Int64 OrgId = Convert.ToInt64(ds.Tables[0].Rows[0][1]); Int64 EmpId = Convert.ToInt64(ds.Tables[0].Rows[0][2]); if (configticket.Employee_Id != EmpId && configticket.Organization_Id != OrgId) { objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ConfigureTicketConstant.const_procSuggestionsOrganizationEmployeeMapping_UpdateEmployeeId; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Mode, "Insert"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Organization_Id, configticket.Organization_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureTicketConstant.const_Employee_Id, configticket.Employee_Id); } string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } finally { base.objSqlCommand.Connection.Close(); } return "Configure Ticket Successfully Updated...."; } public string DeleteEntity(Int64 Id) { return ""; } public ConfigureTicket GetEntityByID(Int64 Id) { ConfigureTicket objEntityToReturn = new ConfigureTicket(); return objEntityToReturn; } public IEnumerable<ConfigureTicket> GetEntityList() { List<ConfigureTicket> objListToReturn = new List<ConfigureTicket>(); return objListToReturn; } public string AddEntity(ConfigureTicket entityObject) { return ""; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class RFQService { constructor(private _http: Http) { } get(url: string, UserName: string): Observable<any> { return this._http.get(url + "GetMyRFQ?CommunicationId=" + UserName) .map((response: Response) => <any>response.json()); } getAllRFQ(url: string, UserName: string): Observable<any> { return this._http.get(url + "GetAllRFQ?CommunicationId=" + UserName) .map((response: Response) => <any>response.json()); } getResponceRequestedRFQ(url: string, UserName: string): Observable<any> { return this._http.get(url + "GetResponceRequestedRFQ?CommunicationId=" + UserName) .map((response: Response) => <any>response.json()); } GetMyActionRFQ(url: string, UserName: string): Observable<any> { return this._http.get(url + "GetMyActionRFQ?CommunicationId=" + UserName) .map((response: Response) => <any>response.json()); } GetMyWatchListRFQ(url: string, UserName: string): Observable<any> { return this._http.get(url + "GetMyWatchListRFQ?CommunicationId=" + UserName) .map((response: Response) => <any>response.json()); } //GetBusinessManager FillBusinessHead(url: string): Observable<any> { return this._http.get(url + 'FillBusinessHead') .map((response: Response) => <any>response.json()); } GetBusinessManager(url: string, UserName: string): Observable<any> { return this._http.get(url + "GetBusinessManager?UserId=" + UserName) .map((response: Response) => <any>response.json()); } GetBusinessType(url: string): Observable<any> { return this._http.get(url + 'GetBusinessType') .map((response: Response) => <any>response.json()); } GetProjectType(url: string): Observable<any> { return this._http.get(url + 'GetProjectType') .map((response: Response) => <any>response.json()); } GetIndustries(url: string): Observable<any> { return this._http.get(url + 'GetIndustries') .map((response: Response) => <any>response.json()); } GetSolution(url: string): Observable<any> { return this._http.get(url + 'GetSolution') .map((response: Response) => <any>response.json()); } GetServiceOffering(url: string): Observable<any> { return this._http.get(url + 'GetServiceOffering') .map((response: Response) => <any>response.json()); } GetFileType(url: string): Observable<any> { return this._http.get(url + 'GetFileType') .map((response: Response) => <any>response.json()); } GetAuthor(url: string): Observable<any> { return this._http.get(url + 'GetAuthor') .map((response: Response) => <any>response.json()); } GetTechnology(url: string): Observable<any> { return this._http.get(url + 'GetTechnology') .map((response: Response) => <any>response.json()); } GetEmployee(url: string): Observable<any> { return this._http.get(url + 'GetEmployee') .map((response: Response) => <any>response.json()); } GetRFQStatus(url: string): Observable<any> { return this._http.get(url + 'GetRFQStatus') .map((response: Response) => <any>response.json()); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } post(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } GetProspectClient(url : string, model:any): Observable<any> { debugger; url = url + 'GetProspectClient'; let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } }<file_sep>export interface IPosition { Id: number; PositionName: string; Remarks: string; Status: boolean; SkillName: string; SkillsId: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string; IsActive: boolean; SkillId: number[]; } export interface ISkillListViewModel { PositionId: number; SkillId: number; SkillName: string; } <file_sep>export interface IDepartment { Id: number; Department_Name: string; mode: string; } export interface IEmployee { Id: number; Employee_Name: string; mode: string; } export interface IEmployeeId { Id: number; } export interface ICompany { Id: number; CompanyName: string; mode: string; } export interface ILineManager { Id: number; LineManager: string; mode: string; } export interface ICalTotalAttendance { EmployeeID: number; EmployeeName: string; Date: string; ToDate: string; InTimeID: number; InTIme: Date; OutTimeID: number; OutTIme: Date; LunchOutTimeID: number; LunchOutTIme: Date; LunchInTimeID: number; LunchInTIme: Date; OtherTimeID: number; TotalOtherTime: string; TotalOfficeTime: string; TotalLunchTime: string; TotalBreakTime: string; TotalWorkingTime: string; TotalWorksheetHours: number; IsInOffice: boolean; IsInBreak: boolean; IsInLunch: boolean; IsInMeeting: boolean; IsInOfficeWork: boolean; Days: string; ImportRemarks: string; EmployeeCode: string; MMDDYYYY_DateFormat: string; } export interface IOutReport { EmployeeId: number; Active: number; FromDate: Date; ToDate: Date; OutType: string; Minute: number; AllDate: boolean; Employeelist: string; Consolidated: string; Sort: string; } export interface IOutReportBindReport { Id: number; Employee_Name; string; CurrentDate: Date; Entry_Type: string; Entry_Time: Date; InTime: Date; Duration: number; Remarks: string; } export interface IYear { Id: number; Month: string; Year: string; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.UserManagement { public class AttendanceEntry : VISBaseEntity { //Attendance Entry public int Employee_Id { get; set; } public int Entry_Type { get; set; } public string Remarks { get; set; } public DateTime Entry_Time { get; set; } public string Date { get; set; } public string actualEntryTime { get; set; } public int grace { get; set; } public string macID { get; set; } public DateTime forWhichDate { get; set; } public string ipAddress { get; set; } public string source { get; set; } public Boolean isApproved { get; set; } public Int64 groupId { get; set; } public string attendancePolicy { get; set; } public int Grade { get; set; } public string ImportRemarks { get; set; } public string Days { get; set; } public int forWhichEntryType { get; set; } //AttendanceEntry Get public string Employee_Name { get; set; } public string Password { get; set; } public string Email { get; set; } public string In_Mon_Fri { get; set; } public string Out_Mon_Fri { get; set; } public string In_Sat { get; set; } public string Out_Sat { get; set; } public int Grace { get; set; } public Boolean Active { get; set; } public string userType { get; set; } public DateTime joiningDate { get; set; } public DateTime relevingDate { get; set; } public Decimal totalCL { get; set; } public Decimal totalSL { get; set; } public int additionalRights { get; set; } public Boolean validForLogin { get; set; } public int leaveApproveBy { get; set; } public string employeeCode { get; set; } public DateTime probationTill { get; set; } public int ActivityId { get; set; } public Boolean Gender { get; set; } public Boolean IsConfirmed { get; set; } public int JoiningSalary { get; set; } public string PhotographFileName { get; set; } public int SalaryAfterRevision { get; set; } public Boolean IsSLASigned { get; set; } public DateTime ConfirmationDate { get; set; } public DateTime AppraisalDate { get; set; } public Boolean IsAppraisalRequired { get; set; } public int SLAYear { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public int JoiningDesignation { get; set; } public string Technology { get; set; } public Boolean IsPasswordChange { get; set; } public string OtherTechnology { get; set; } public int SalaryRangeId { get; set; } public int LineManagerId { get; set; } public int TotalCOff { get; set; } public int enrollnumber { get; set; } public Boolean AllowScreenCapture { get; set; } public Boolean ActiveDashboard { get; set; } public Boolean IsSwitchUser { get; set; } public int WorkingLocation { get; set; } public string WorkingLocationAddress { get; set; } public int Education { get; set; } public string CommunicationID { get; set; } public int SatGrace { get; set; } public Boolean IsWebAccess { get; set; } public string OtherRemark { get; set; } public Boolean WorksheetThruWeb { get; set; } public Boolean IsWorksheetFill { get; set; } public float CL { get; set; } public float SL { get; set; } public Boolean IsjoiningLeave { get; set; } public Boolean IsConfirmationLeave { get; set; } public int EmployeeGradeID { get; set; } public Boolean IsResigned { get; set; } public Boolean isMailAlert { get; set; } public Boolean IsAllowMouseMovement { get; set; } public int accessCardId { get; set; } public DateTime CreatedDateTime { get; set; } public DateTime UpdatedDateTime { get; set; } public Boolean IsMouseTracking { get; set; } public Boolean IsScreenCaptureRemarks { get; set; } public Boolean IsHost { get; set; } public Boolean IsProductivityTracker { get; set; } public Boolean WorkFromHome { get; set; } public DateTime IsHostForEmpMaster { get; set; } public DateTime ResignedDate { get; set; } } public static class AttendanceEntryConstants { /// Database table name constant. /// public const string const_Table_Currency = "Attendance_Transaction"; /// Database table field Name Constants. /// public const string const_Field_Employee_Id = "Employee_Id"; public const string const_Field_Entry_Type = "Entry_Type"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_Entry_Time = "Entry_Time"; public const string const_Field_Date = "Date"; public const string const_Field_actualEntryTime = "actualEntryTime"; public const string const_Field_grace = "grace"; public const string const_Field_macID = "macID"; public const string const_Field_forWhichDate = "forWhichDate"; public const string const_Field_ipAddress = "ipAddress"; public const string const_Field_source = "source"; public const string const_Field_mouseMovement = "mouseMovement"; public const string const_Field_isApproved = "isApproved"; public const string const_Field_groupId = "groupId"; public const string const_Field_attendancePolicy = "attendancePolicy"; public const string const_Field_Grade = "Grade"; public const string const_Field_ImportRemarks = "ImportRemarks"; public const string const_Field_Days = "Days"; public const string const_Field_forWhichEntryType = "forWhichEntryType"; public const string const_Field_Mode = "mode"; /// Database Procedure and fucntion constants. /// public const string const_procAttendanceEntry_Add = "Procattendance_transaction"; public const string const_procAttendanceEntry_Update = ""; public const string const_procAttendanceEntry_SelectAll = "ProcPunchOutOnNextDays"; public const string const_procAttendanceEntry_SelectBaseNonBase = ""; public const string const_procAttendanceEntry_SelectById = ""; public const string const_procAttendanceEntry_GetTimer = "ProcLevels_GetAttendance"; //public const string const_procAttendanceEntry_GetTimer = "ProcLevels_GetAttendance_Timer"; public const string const_procAttendanceEntry_GetAttendanceEntryType = "procAttendanceEntryType"; public const string const_procAttendanceEntry_GetCommonConfiguration = "procCommonConfiguration_SelectAll"; public const string const_procAttendanceEntry_GetPointCounts = "ProcLevels_GetProgressiveDetails"; } } <file_sep>export interface ITechMultiCheckBox { id: number; name: string; } export interface ITechnology { TechnologyId: number; TechnologyName: string } export interface IRFQDoc { FileTypeID: number; FileType: string; FileName: string; AuthorId: number; Author: string; RemarkDoc: string; } export interface IRFQDocEntity { FileTypeId: number; FileType: string; FileName: string; AuthorId: number; Author: string; RemarkDoc: string; } export interface IRFQLink { RemarkLink: string; URL: string; UserId: string; Password: string; } export interface IRFQLinkEntity { RemarkLink: string; URL: string; UserId: number; Password: string; }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IUserRole } from '../../../Model/Masters/CompanyRelated/UserRole'; @Pipe ({ name: 'UserRoleFilter' }) export class UserRoleFilterPipe implements PipeTransform { transform(value: IUserRole[], filter: string): IUserRole[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IUserRole) => app.Name != null && app.Name.toLocaleLowerCase().indexOf(filter) != -1 || app.FullName != null && app.FullName.toLocaleLowerCase().indexOf(filter) != -1 || app.Type != null && app.Type.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.RFQ; namespace VIS_Repository.RFQ { public class RFQHelperRepository : VISDbCommand { public RFQHelperRepository(string _connectionstring) : base(_connectionstring) { } public string GetAuther(string Author) { string objListToReturn; if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetAuthorIdByAuthorName; base.objSqlCommand.Parameters.AddWithValue(RFQConstants.const_Field_Author, Author); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = dt.Rows[0][0].ToString(); } return objListToReturn; } public string GetFileType(string FileType) { string objListToReturn; if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetFileTypeIdByFileTypeName; base.objSqlCommand.Parameters.AddWithValue(RFQConstants.const_Field_FileType, FileType); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = dt.Rows[0][0].ToString(); } return objListToReturn; } public string GetMaxRFQInitialId() { string objListToReturn; if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetMaxRFQInitialId; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = dt.Rows[0][0].ToString(); } return objListToReturn; } public IEnumerable<RFQInitial> GetTechnology() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_Technology; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetFileType() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetFileType; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetAuthor() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetAuthor; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQDoc> GetRFQDocument() { List<RFQDoc> objListToReturn = new List<RFQDoc>(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQDocConstant.const_Field_procGetRFQDocument; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQDoc>(dt); } return objListToReturn; } public IEnumerable<RFQLink> GetRFQLink() { List<RFQLink> objListToReturn = new List<RFQLink>(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQLinkConstant.const_Field_GetRFQLink; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQLink>(dt); } return objListToReturn; } public string GetEmployeeNameById(long Id) { try { string str = string.Empty; if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQResponseConstant.const_Field_GetEmployeeNameById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); str = dt.Rows[0][0].ToString(); } return str; } catch (Exception ex) { throw; } } public string GetTechnology(string Id) { try { string str = string.Empty; if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQResponseConstant.const_Field_GetTechnologyNameById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); str = dt.Rows[0][0].ToString(); } return str; } catch (Exception ex) { throw; } } } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IMyTeam } from '../../../Model/HumanResource/Attendance/MyTeam'; @Pipe ({ name: 'MyTeamFilter' }) export class MyTeamFilterPipe implements PipeTransform { transform(value: IMyTeam[], filter: string): IMyTeam[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IMyTeam) => app.Name != null && app.Name.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Dashboard { public class DashboardData { public MyProfile UserProfileData { get; set; } public List<MySkill> UserSkillData { get; set; } public List<MyAllocation> UserAllocationData { get; set; } public List<MyTeam> UserTeamData { get; set; } public List<MyAlerts> UserAlertData { get; set; } public List<MyLeaveDetails> UserLeaveDetails { get; set; } public List<MyNwdHistory> UserNwdHistory { get; set; } public CalTotalAttendance UserCalTotalAttendanceData { get; set; } public ActualEntryTimeAndGracePeriod UserActualEntryTimeAndGracePeriod { get; set; } public List<LeaveLedgerData> UserLeaveLedgerData { get; set; } public List<LeaveDetailsByDate> UserLeaveDetailsByDate { get; set; } public List<HolidayListForEmployee> UserHolidayListForEmployeeData { get; set; } public List<HolidayForDate> HolidayForDateData { get; set; } } public class MyProfile { public string EmployeeName { get; set; } public string LineManagerName { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string Gender { get; set; } public string PhotographFileName { get; set; } public string CompanyName { get; set; } public string EmailID { get; set; } public string Designation { get; set; } public string DepartmentName { get; set; } public string FatherName { get; set; } public string PermenantAddress { get; set; } public string CommunicationAddress { get; set; } public string LandlineNumber { get; set; } public string MobileNumber { get; set; } public string MotherName { get; set; } public string BirthDate { get; set; } public string BloodGroup { get; set; } public string MaritalStatus { get; set; } public string EmplopyeeGrade { get; set; } } public class MySkill { public String Level_Text { get; set; } public String SkillName { get; set; } } public class MyAllocation { public String FromDate { get; set; } public String ToDate { get; set; } public Decimal AllocatedHr { get; set; } public Decimal TotalHr { get; set; } public String ProjectName { get; set; } } public class MyTeam { public int EmployeeId { get; set; } public int ProjectId { get; set; } public String ProjectName { get; set; } public String EmployeeName { get; set; } } public class MyAlerts { public String Name { get; set; } public String Type { get; set; } public String Status { get; set; } } public class MyLeaveDetails { public int ID { get; set; } public int EmployeeID { get; set; } public DateTime ToDate { get; set; } public DateTime FromDate { get; set; } public String Reason { get; set; } public String ContactDetail { get; set; } public int AppliedTo { get; set; } public int LeaveType { get; set; } public int Status { get; set; } public int GHID { get; set; } public DateTime EnteredDate { get; set; } public int ResponsiblePersonID { get; set; } public string Remarks { get; set; } public bool IsFullDay { get; set; } public bool IsFirstHalf { get; set; } public bool IsSecondHalf { get; set; } public DateTime CreatedDate { get; set; } public String contact { get; set; } public DateTime CallOnDate { get; set; } public string CallOnTime { get; set; } public bool EmergencyLeave { get; set; } public bool LongleaveEntry { get; set; } } public class MyNwdHistory { public int id { get; set; } public int employeeId { get; set; } public DateTime date { get; set; } public String leaveType { get; set; } public int nwdId { get; set; } } public class CalTotalAttendance { public int EmployeeID { get; set; } public String EmployeeName { get; set; } public String Date { get; set; } public int InTimeID { get; set; } public DateTime InTime { get; set; } public int OutTimeID { get; set; } public DateTime OutTime { get; set; } public int LunchOutTimeID { get; set; } public DateTime LunchOutTime { get; set; } public int LunchInTimeID { get; set; } public DateTime LunchInTime { get; set; } public int OtherTimeID { get; set; } public String TotalOtherTime { get; set; } public String TotalOfficeTime { get; set; } public String TotalLunchTime { get; set; } public String TotalBreakTime { get; set; } public String TotalWorkingTime { get; set; } public Decimal TotalWorksheetHour { get; set; } public bool IsInOffice { get; set; } public bool IsInBreak { get; set; } public bool IsInLunch { get; set; } public bool IsInMeeting { get; set; } public bool IsInOfficeWork { get; set; } public String Days { get; set; } public String ImportRemarks { get; set; } public String EmployeeCode { get; set; } public String MMDDYYYY_DateFormate { get; set; } } public class ActualEntryTimeAndGracePeriod { public String actualEntryTime { get; set; } public int grace { get; set; } } public class LeaveLedgerData { public String leaveDuration { get; set; } public String leaveType { get; set; } public String approveType { get; set; } public String shortLeaveType { get; set; } } public class LeaveDetailsByDate { public int ID { get; set; } public String LeaveType { get; set; } public String LeaveStatus { get; set; } public int EmployeeId { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } public String CalendarDays { get; set; } public bool IsFullDay { get; set; } public bool IsFirstHalf { get; set; } public bool IsSecondhalf { get; set; } } public class HolidayListForEmployee { public int id { get; set; } public String holidayName { get; set; } public DateTime fromDate { get; set; } public DateTime toDate { get; set; } public String remarks { get; set; } public bool active { get; set; } public int noOfDays { get; set; } } public class HolidayForDate { public int id { get; set; } public String holidayName { get; set; } public DateTime fromDate { get; set; } public DateTime toDate { get; set; } public String remarks { get; set; } public bool active { get; set; } public int noOfDays { get; set; } } public class LevelsList { public int levelnumber { get; set; } public String Name { get; set; } public String Icon { get; set; } public int startpoint { get; set; } public int endpoint { get; set; } } public class Levels_PointsLegend { public String Criteria { get; set; } public String CalculatedOn { get; set; } public decimal From { get; set; } public decimal To { get; set; } public int Points { get; set; } } public class PointsDetails { public String EventName { get; set; } public bool Type { get; set; } public String CalculatedOn { get; set; } public int PointsGained { get; set; } public String Date { get; set; } } public class MyAttendance { public DateTime Date { get; set; } public string Status { get; set; } public DateTime InTIme { get; set; } public DateTime OutTIme { get; set; } public DateTime TotalWorksheetHours { get; set; } } public static class DashboardConstsants { public const string const_Proc_GetDashboardDataSets = "procGetDashboardDataSets"; public const string const_Proc_GetProfileById = "procGetProfileById"; public const string const_Proc_GetAllUser = "procGetAllUesrForLoggedInUser"; public const string const_Proc_GetUserDetailById = "procGetUserDetailById"; public const string const_Proc_GetAllUserWithOutLM = "procGetAllUserWithOutLM"; public const string const_Proc_Getprojectallocationdetails = "procgetprojectallocationdetails"; public const string const_Proc_GetShortProfileDetails = "ProcGetShortProfileDetails"; //public const string const_Proc_GetWeekAttendanceReport = ""; public const string const_Proc_Getweekattendancerecord = "ProcCalTotalAttendanceReport"; //public const string const_Proc_GetMonthAttendanaceReport = ""; public const string const_Proc_GetMonthAttendanaceRecord = "ProcCalTotalAttendanceReport"; public const string const_Proc_GetLeaveDetailsByDate = "ProcGetLeaveDetailsByDate"; //public const string const_Proc_GetMonthWorksheetReport = ""; public const string const_Proc_GetMonthWorksheetRecord = "ProcCalTotalAttendanceReport"; public const string const_Proc_GetWorksheetDetailsReport = "ProcGetWorksheetDetailsReport"; public const string const_Proc_GetProjectNameByUserId = "ProcGetProjectNameByUserId"; //public const string const_Proc_GetLeaveReportById = ""; public const string const_Proc_GetLeaveSummary = "procGetLeaveSummary"; //public const string const_Proc_Getleavesummary_new = ""; public const string const_Proc_GetLeaveReportByYear = "ProcGetLeaveReportByYear"; public const string const_Proc_GetProjectAllocationByUserId = "ProcProjectAllocationByUserId"; public const string const_Proc_GetMyTeamByUserId = "ProcMyTeamByUserId"; public const string const_Proc_GetAlertList = "ProcGetAlertList"; public const string const_Proc_GetAllDetails = "ProcGetAllDetails"; public const string const_Proc_GetProjectUnplanned = "fnGetProjectUnplanned"; //public const string const_Proc_GetPendingLeave = "ProcGetAlertList"; public const string const_Proc_GetOpportunityPending = "fnGetOpportunityPending"; public const string const_Proc_GetInvoicePending = "fnGetInvoicePendingAlert"; public const string const_Proc_GetCollectionPending = "fnGetCollectionPendingAlert"; public const string const_Proc_GetAppraisalPending = "fnGetAppraisalPendingAlert"; public const string const_Proc_GetSuggestion = "fnGetSuggestionAlert"; public const string const_Proc_GetPendingTask = "fnGetPendingTaskAlert"; public const string const_Proc_GetUserSkillById = "ProcUserSkillById"; public const string const_Proc_GetSkillReportByUserId = "ProcSkillReportByUserId"; //Procedures for GetLeaveSummary_New function in code. public const string const_Proc_GetLeaveSummary_New = "procGetLeaveSummary_New"; public const string const_Proc_GetPresentDaysBetweenDateForEmp = "procGetPresentDaysBetweenDateForEmp"; public const string const_Proc_GetEmployeeLeaveRelatedDetailForDate = "procGetEmployeeLeaveRelatedDetailForDate"; public const string const_Proc_GetNWDHistoryForEmpForDate = "procGetNWDHistoryForEmpForDate"; public const string const_Proc_GetEmpHolidayListForDate = "procGetEmpHolidayListForDate"; public const string const_Proc_GetHolidayForDate = "procGetHolidayForDate"; public const string const_Proc_GetLeaveFormDetail = "procGetLeaveFormDetail"; public const string const_Proc_GetEmpLeaveLedgerForDate = "procGetEmpLeaveLedgerForDate"; public const string const_Proc_GetActualEntryTimeAndGraceForPunchInId = "procGetActualEntryTimeAndGraceForPunchInId"; public const string const_Proc_GetLevelsList = "ProcLevels_GetLevelsList"; public const string const_Proc_GetLevels_PointsLegend = "Levels_PointsLegend"; public const string const_Proc_GetProgressive = "Levels_GetProgressiveDetails"; public const string const_Proc_GetPointsDetails = "ProcLevels_ReportAdmin"; public const string const_ProcCalTotalAttendanceReport = "ProcCalTotalAttendanceReport"; } } <file_sep> import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { ContactMasterService } from '../../../service/Masters/CompanyRelated/ContactMaster.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IContactMaster } from '../../../Model/Masters/CompanyRelated/ContactMaster'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component({ providers: [ContactMasterService], templateUrl: 'app/Components/Masters/CompanyRelated/ContactMaster.component.html' }) export class ContactMasterComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; ContactMasters: IContactMaster[]; public ContactMaster: IContactMaster; msg: string; indLoading: boolean = false; ContactMasterFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; ContactMasterFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strSearchName: string; strSearchDesignation: string; strSearchContactDetails: string; constructor(private fb: FormBuilder, private _ContactMasterService: ContactMasterService, private pagerService: PagerService) { } ngOnInit(): void { this.ContactMasterFrm = this.fb.group({ Id: [''], Name: ['', Validators.required], Designation: ['', Validators.required], Email: ['', Validators.required], phone: ['', Validators.required], SkypeId: ['', Validators.required], MsnId: ['', Validators.required], GtalkId: ['', Validators.required], AolId: ['', Validators.required], Other: ['', Validators.required], ProspectId: ['', Validators.required], CompanyId : [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); this.LoadContactMasters() } ContactMasterFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.ContactMasterFilter = value; } ContactMasterSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadContactMasters(): void { this.indLoading = true; this._ContactMasterService.get(Global.BASE_CONTACTMASTER_ENDPOINT) .subscribe(ContactMasters => { this.ContactMasters = ContactMasters; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchName = (<HTMLInputElement>document.getElementById("searchName")).value; if (this.strSearchName != '') { this.strSearchName = this.strSearchName.toLocaleLowerCase(); this.ContactMasters = this.ContactMasters.filter( x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strSearchName) != -1); } this.strSearchDesignation = (<HTMLInputElement>document.getElementById("searchDesignation")).value; if (this.strSearchDesignation != '') { this.strSearchDesignation = this.strSearchDesignation.toLocaleLowerCase(); this.ContactMasters = this.ContactMasters.filter( x => x.Designation != null && x.Designation.toLocaleLowerCase().indexOf(this.strSearchDesignation) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addContactMaster() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Contact"; this.modalBtnTitle = "Add"; this.ContactMasterFrm.reset(); this.modal.open(); } editContactMaster(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Contact"; this.modalBtnTitle = "Update"; this.ContactMaster = this.ContactMasters.filter(x => x.Id == id)[0]; this.ContactMasterFrm.setValue(this.ContactMaster); this.modal.open(); } deleteContactMaster(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.ContactMaster = this.ContactMasters.filter(x => x.Id== id)[0]; this.ContactMasterFrm.setValue(this.ContactMaster); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.ContactMasterFrm.enable() : this.ContactMasterFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.ContactMasters); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._ContactMasterService.post(Global.BASE_CONTACTMASTER_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadContactMasters(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._ContactMasterService.put(Global.BASE_CONTACTMASTER_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadContactMasters(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._ContactMasterService.delete(Global.BASE_CONTACTMASTER_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "ContactMaster status changed successfully."; this.LoadContactMasters(); } else { this.msg = "Error has occurred while changing status of existing ContactMaster!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var CompanyMaster_service_1 = require("../../../service/Masters/CompanyRelated/CompanyMaster.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var http_1 = require("@angular/http"); var CompanyMasterComponent = (function () { function CompanyMasterComponent(fb, _CompanyMasterService, pagerService, http) { this.fb = fb; this._CompanyMasterService = _CompanyMasterService; this.pagerService = pagerService; this.http = http; this.indLoading = false; this.isDesc = false; this.column = 'Full_Name'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; // //this.uploaderF1 = new FileUploader({ // url: 'http://localhost:53349/api/CompanyMasterAPI/FileUpload', disableMultipart: false, maxFileSize: 50000000 //}); } //file upload event CompanyMasterComponent.prototype.fileChange1 = function (event) { this.fileList1 = event.target.files; }; CompanyMasterComponent.prototype.fileChange2 = function (event) { this.fileList2 = event.target.files; // this.CompanyMaster.Signature = this.fileList2.item(0).name; }; CompanyMasterComponent.prototype.fileChange3 = function (event) { this.fileList3 = event.target.files; // this.CompanyMaster.SignatureOther = this.fileList3.item(0).name; }; CompanyMasterComponent.prototype.ngOnInit = function () { this.CompanyMasterFrm = this.fb.group({ Id: [''], CompanyName: ['', forms_1.Validators.required], City: [''], ZipCode: [''], State: [''], Country: [''], CountryName: [''], ContactNo: ['', forms_1.Validators.required], E_mail: ['', forms_1.Validators.required], Fax: [''], CompanyURL: [''], Address: ['', forms_1.Validators.required], CompanyLogo: [''], AccountHead: [''], Designation: [''], Signature: [''], CompanyShortCode: ['', forms_1.Validators.required], Address2: [''], StartSeries: [''], FinancialYear: ['', forms_1.Validators.required], AccountHeadOther: [''], DesignationOther: [''], SignatureOther: [''], FinancialYeardll: [''], PositionName: [''], Employee_Name: [''], //SignatureOtherUpload: [''], //SignatureUpload: [''], //CompanyLogoUpload:[''], CompanyId: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); if (!this.CompanyMasterForImg) { this.ImgShowHide == false; } this.ImgShowHide = false; this.LoadCompanyMasters(); this.LoadFY(); this.LoadCountry(); this.LoadDesignation(); this.LoadHead(); //else { this.ImgShowHide = true; } }; CompanyMasterComponent.prototype.LoadFY = function () { var _this = this; this.indLoading = true; this._CompanyMasterService.getFY(global_1.Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(function (DATAFY) { _this.FinancialYear = DATAFY; } //,error => this.msg = <any>error ); }; CompanyMasterComponent.prototype.LoadCountry = function () { var _this = this; this.indLoading = true; this._CompanyMasterService.getCountry(global_1.Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(function (DATACOUNTRY) { _this.Countries = DATACOUNTRY; } //,error => this.msg = <any>error ); }; CompanyMasterComponent.prototype.LoadDesignation = function () { var _this = this; this.indLoading = true; this._CompanyMasterService.getDesignation(global_1.Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(function (DATAposition) { _this.Designation = DATAposition; } //,error => this.msg = <any>error ); }; CompanyMasterComponent.prototype.LoadHead = function () { var _this = this; this.indLoading = true; this._CompanyMasterService.getHead(global_1.Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(function (DATAHead) { _this.ForHeaddl = DATAHead; } //,error => this.msg = <any>error ); }; CompanyMasterComponent.prototype.CompanyMasterFilterCriteriaChange = function (value) { if (value != '[object Event]') this.CompanyMasterFilter = value; }; CompanyMasterComponent.prototype.CompanyMasterSort = function (property) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; }; ; CompanyMasterComponent.prototype.LoadCompanyMasters = function () { var _this = this; this.indLoading = true; this._CompanyMasterService.get(global_1.Global.BASE_COMPANYMASTER_ENDPOINT) .subscribe(function (CompanyMasters) { _this.CompanyMasters = CompanyMasters; //Logic for searching - start if (_this.ShowHideSearch) { _this.strsearchCompanyName = document.getElementById("searchCompanyName").value; if (_this.strsearchCompanyName != '') { _this.strsearchCompanyName = _this.strsearchCompanyName.toLocaleLowerCase(); _this.CompanyMasters = _this.CompanyMasters.filter(function (x) { return x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(_this.strsearchCompanyName) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchCity = document.getElementById("searchCity").value; if (_this.strSearchCity != '') { _this.strSearchCity = _this.strSearchCity.toLocaleLowerCase(); _this.CompanyMasters = _this.CompanyMasters.filter(function (x) { return x.City != null && x.City.toLocaleLowerCase().indexOf(_this.strSearchCity) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchState = document.getElementById("searchState").value; if (_this.strSearchState != '') { _this.strSearchState = _this.strSearchState.toLocaleLowerCase(); _this.CompanyMasters = _this.CompanyMasters.filter(function (x) { return x.State != null && x.State.toLocaleLowerCase().indexOf(_this.strSearchState) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchCountry = document.getElementById("searchCountry").value; if (_this.strSearchCountry != '') { _this.strSearchCountry = _this.strSearchCountry.toLocaleLowerCase(); _this.CompanyMasters = _this.CompanyMasters.filter(function (x) { return x.Country != null && x.Country.toLocaleLowerCase().indexOf(_this.strSearchCountry) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchEmail = document.getElementById("searchE-mail").value; if (_this.strSearchEmail != '') { _this.strSearchEmail = _this.strSearchEmail.toLocaleLowerCase(); _this.CompanyMasters = _this.CompanyMasters.filter(function (x) { return x.E_mail != null && x.E_mail.toLocaleLowerCase().indexOf(_this.strSearchEmail) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchCompanyURL = document.getElementById("searchCompanyURL").value; if (_this.strSearchCompanyURL != '') { _this.strSearchCompanyURL = _this.strSearchCompanyURL.toLocaleLowerCase(); _this.CompanyMasters = _this.CompanyMasters.filter(function (x) { return x.CompanyURL != null && x.CompanyURL.toLocaleLowerCase().indexOf(_this.strSearchCompanyURL) != -1; }); } } //if (this.ShowHideSearch) { // this.strSearchE_mail = (<HTMLInputElement>document.getElementById("E_mail")).value; // if (this.strSearchE_mail != '') { // this.strSearchE_mail = this.strSearchE_mail.toLocaleLowerCase(); // this.CompanyMasters = this.CompanyMasters.filter( // x => x.E_mail != null && x.E_mail.toLocaleLowerCase().indexOf(this.strSearchE_mail) != -1); // } //} //if (this.ShowHideSearch) { // this.strSearchCompanyURL = (<HTMLInputElement>document.getElementById("CompanyURL")).value; // if (this.strSearchCompanyURL != '') { // this.strSearchCompanyURL = this.strSearchCompanyURL.toLocaleLowerCase(); // this.CompanyMasters = this.CompanyMasters.filter( // x => x.CompanyURL != null && x.CompanyURL.toLocaleLowerCase().indexOf(this.strSearchCompanyURL) != -1); // } //} //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; CompanyMasterComponent.prototype.addCompanyMaster = function () { this.imagePathCompanyLogo = null; this.imagePathSignature = null; this.imagePathSignatureOther = null; this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Company"; this.modalBtnTitle = "Add"; this.CompanyMasterFrm.reset(); this.modal.open(); }; CompanyMasterComponent.prototype.editCompanyMaster = function (id) { this.ImgGlobalPath = global_1.Global.WebAccessURL; this.ImgShowHide = true; this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Company"; this.modalBtnTitle = "Update"; this.CompanyMaster = this.CompanyMasters.filter(function (x) { return x.Id == id; })[0]; this.CompanyMasterForImg = this.CompanyMaster; this.imagePathCompanyLogo = this.CompanyMaster.CompanyLogo; this.imagePathSignature = this.CompanyMaster.Signature; this.imagePathSignatureOther = this.CompanyMaster.SignatureOther; this.CompanyMaster.PositionName = null; this.CompanyMaster.FinancialYeardll = null; this.CompanyMaster.Employee_Name = null; this.CompanyMaster.CompanyLogo = null; this.CompanyMaster.Signature = null; this.CompanyMaster.SignatureOther = null; this.CompanyMasterFrm.setValue(this.CompanyMaster); //this.CompanyMaster["CompanyLogo"] = null; //this.CompanyMaster["Signature"] = null; //this.CompanyMaster["SignatureOther"] = null; this.modal.open(); }; CompanyMasterComponent.prototype.deleteCompanyMaster = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.CompanyMaster = this.CompanyMasters.filter(function (x) { return x.Id == id; })[0]; this.CompanyMaster.PositionName = null; this.CompanyMaster.FinancialYeardll = null; this.CompanyMaster.Employee_Name = null; this.CompanyMaster.CompanyLogo = null; this.CompanyMaster.Signature = null; this.CompanyMaster.SignatureOther = null; this.CompanyMasterFrm.setValue(this.CompanyMaster); this.modal.open(); }; CompanyMasterComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.CompanyMasterFrm.enable() : this.CompanyMasterFrm.disable(); }; CompanyMasterComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; CompanyMasterComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.CompanyMasters); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; CompanyMasterComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; CompanyMasterComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: if (this.fileList1 != null) { formData._value.CompanyLogo = "/Upload/CompanyMaster/" + this.fileList1.item(0).name; } else { formData._value.CompanyLogo = null; } if (this.fileList1 != null) { formData._value.Signature = "/Upload/CompanyMaster/" + this.fileList2.item(0).name; } else { formData._value.Signature = null; } if (this.fileList1 != null) { formData._value.SignatureOther = "/Upload/CompanyMaster/" + this.fileList3.item(0).name; } else { formData._value.SignatureOther = null; } this._CompanyMasterService.post(global_1.Global.BASE_COMPANYMASTER_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { if (_this.fileList1 != null) { if (_this.fileList1.length > 0) { _this.fileList1.item(0).name; var file = _this.fileList1[0]; var formData_1 = new FormData(); formData_1.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/CompanyMasterAPI/UploadJsonFile"; _this.http.post(apiUrl1, formData_1, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); _this.fileList1 = null; } } if (_this.fileList2 != null) { if (_this.fileList2.length > 0) { var file = _this.fileList2[0]; var formData_2 = new FormData(); formData_2.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/CompanyMasterAPI/UploadJsonFile"; _this.http.post(apiUrl1, formData_2, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); _this.fileList2 = null; } } if (_this.fileList3 != null) { if (_this.fileList3.length > 0) { var file = _this.fileList3[0]; var formData_3 = new FormData(); formData_3.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/CompanyMasterAPI/UploadJsonFile"; _this.http.post(apiUrl1, formData_3, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); _this.fileList3 = null; } } _this.msg = data; _this.LoadCompanyMasters(); } else { alert(data); } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._CompanyMasterService.put(global_1.Global.BASE_COMPANYMASTER_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadCompanyMasters(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._CompanyMasterService.delete(global_1.Global.BASE_COMPANYMASTER_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "Company status changed successfully."; _this.LoadCompanyMasters(); } else { _this.msg = "Error has occurred while changing status of existing CompanyMaster!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], CompanyMasterComponent.prototype, "modal", void 0); CompanyMasterComponent = __decorate([ core_1.Component({ providers: [CompanyMaster_service_1.CompanyMasterService], templateUrl: 'app/Components/Masters/CompanyRelated/CompanyMaster.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, CompanyMaster_service_1.CompanyMasterService, pager_index_1.PagerService, http_1.Http]) ], CompanyMasterComponent); return CompanyMasterComponent; }()); exports.CompanyMasterComponent = CompanyMasterComponent; <file_sep>export interface ICurrencyHistory { CompanyId: number; Id: number; Currency_Id: number; Default_Exch_Rate: number; Current_Exch_Rate: number; Month_Entered: number; Year_Entered: number; Date_Entered: Date; FromDate: Date; ToDate: Date; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.GeneralHelper { public class SessionValues { public string UserType { get; set; } public long UserId{ get; set; } } public static class SessionValuesConstant { public const string const_Field_UserType = "UserType"; public const string const_Field_UserId = "UserId"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.Attendance { public class WorkSheet : VISBaseEntity { public string mode { get; set; } public Int64 UserId { get; set; } public Int64 ActivityId { get; set; } public string ActivityName { get; set; } public Int64 SubActivityId { get; set; } public string SubActivityName { get; set; } public string Date { get; set; } public Int64 ProjectID { get; set; } public string ProjectName { get; set; } public string TaskName { get; set; } public Int64 TaskId { get; set; } public string Description { get; set; } public string Hours { get; set; } public DateTime FillDate { get; set; } public Int64 WorkSheetID { get; set; } } public static class WorkSheetConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_WorkSheetMaster = "WorkSheetMaster"; /// <summary> /// Database table field Name Constants. /// </summary> /// public const string const_Field_mode = "mode"; public const string const_Field_UserId = "UserId"; public const string const_Field_ActivityId = "ActivityId"; public const string const_Field_ActivityName = "ActivityName"; public const string const_Field_SubActivityId = "SubActivityId"; public const string const_Field_SubActivityName = "SubActivityName"; public const string const_Field_Date = "Date"; public const string const_Field_ProjectID = "ProjectID"; public const string const_Field_ProjectName = "ProjectName"; public const string const_Field_TaskName = "TaskName"; public const string const_Field_TaskId = "TaskId"; public const string const_Field_Description = "Description"; public const string const_Field_Hours = "Hours"; public const string const_Field_FillDate = "FillDate"; public const string const_Field_WorkSheetID = "WorkSheetID"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_ProcGetAllActivity = "ProcGetAllActivity"; public const string const_procGetAllSubActivity = "procGetAllSubActivity"; public const string const_procGetProjectsByUserId = "procGetProjectsByUserId"; public const string const_ProcGetWorkSheetTaskName = "ProcGetWorkSheetTaskName"; public const string const_InsertUpdateWorkSheetMaster = "InsertUpdateWorkSheetMaster"; public const string const_UpdateWorkSheetMaster = "UpdateWorkSheetMaster"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository; using VIS_Repository.Masters; namespace VIS_App.Controllers.Masters.CompanyRelated { public class LookupTypeAPIController : BaseAPIController { VISIBaseRepository<LookupType> LookupTypeRepository; List<LookupType> EntityList = new List<LookupType>(); public LookupTypeAPIController(VISIBaseRepository<LookupType> _LookupTypeRepositiory) { LookupTypeRepository = _LookupTypeRepositiory; } public HttpResponseMessage Get() { return ToJson(LookupTypeRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]LookupType value) { return ToJson(LookupTypeRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]LookupType value) { return ToJson(LookupTypeRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(LookupTypeRepository.DeleteEntity(Id)); } } } <file_sep>import { IMyProfile } from '../Dashboard/myprofile'; import { IMySkills } from '../Dashboard/myskills'; import { IMyAllocation } from '../Dashboard/myallocation'; import { IMyTeam } from '../Dashboard/myteam'; import { IMyLeaveDetails } from '../Dashboard/myworksheet'; import { INwdHistory } from '../Dashboard/myworksheet'; import { ICalTotalAttendance } from '../Dashboard/myworksheet'; import { IActualEntryTimeAndGraceForPunchInId } from '../Dashboard/myworksheet'; import { IEmpLeaveLedgerForDate } from '../Dashboard/myworksheet'; import { ILeaveDetailsByDate } from '../Dashboard/myworksheet'; import { IEmpHolidayListForDate } from '../Dashboard/myworksheet'; import { IHolidayForDate } from '../Dashboard/myworksheet'; import { IMyAlerts } from '../Dashboard/myalerts'; import { ILevels } from '../Dashboard/Levels'; import { ILegend } from '../Dashboard/Legend'; import { IPoints } from '../Dashboard/Points'; import { IMyAttendance } from '../Dashboard/MyAttendance'; export class IDashboard { UserProfileData: IMyProfile; UserSkillData: IMySkills[]; UserAllocationData: IMyAllocation[]; UserTeamData: IMyTeam[]; UserAlertData: IMyAlerts[]; WorksheetLeaveDeta: IMyLeaveDetails; WorksheetNwdHistoryData: INwdHistory[]; WorksheetCalTotalAttendanceData: ICalTotalAttendance; WorksheetGetActualEntryTimeAndGraceData: IActualEntryTimeAndGraceForPunchInId; WorksheetGetEmpLeaveLedgerData: IEmpLeaveLedgerForDate[]; WorksheetGetLeaveDetailsByDateData: ILeaveDetailsByDate[]; WorksheetGetEmpHolidayListData: IEmpHolidayListForDate[]; WorksheetGetHolidayForDateData: IHolidayForDate[]; ProfileGetLevelsListData: ILevels[]; ProfileGetPointsLegendData: ILegend[]; ProfileGetPointsDeta: IPoints[]; MyAttendanceData: IMyAttendance[]; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.Opinion { public class Reports_OpinionRepository : VISDbCommand { private static Reports_OpinionRepository instance = new Reports_OpinionRepository(string.Empty); private Reports_OpinionRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_OpinionRepository getInstance() { return instance; } } } <file_sep>export interface ISalaryGrievance { Id: number; Employee_Id: number; Employee_Name: string; Deduction_Date: Date; Grievance_Remarks: string; PaycutAmount: string; GrievanceType_PE: string; GrievanceType_PH: string; PE_Status: number; PE_Remarks: string; PE_UpdatedBy: number; PE_UpdatedDate: Date; PH_Status: number; PH_Remarks: string; PH_UpdatedBy: number; PH_UpdatedDate: Date; CreatedBy: number; CreatedOn: Date; UpdatedBy: number; UpdatedOn: Date; Active: boolean; verified_By: number; } export interface IGrievanceDate { Id: number; EmployeeId: number; Deduction_Date: string; CreatedOn: Date; PayrollCut: string; PayrollRemarks: string; LineManagerId: number; LineManagerName: string; } export interface IAttendance { Id: number; EmployeeId: number; EmployeeCode: string; EmployeeName: string; Date: string; forWhichDate: Date; LineManager: string; Grace: number; Grade: string; attendancePolicy: string; HR_In_Time: string; PunchIntime: Date; PunchInRemark: number; PunchInBackColor: string; PunchOuttime: Date; PunchOutRemark: number; PunchOutBackColor: string; LunchOutTime: Date; LunchOutRemark: number; LunchInTime: Date; LunchInRemark: string; OtherWork: string; OtherWorkRemark: number; TotalOtherWork: string; WorkingHour: string; WorkingHourBackColor: string; WorkingHourFontColor: string; TotalOfficeTime: string; WorksheetHour: string; WorksheetHourBackColor: string; IsAdmin: boolean; Diff: string; Status: string; GU_BU: number; GU_BUBackColor: string; WNE: string; PC: string; PC_Remarks: string; AUPL: string; UUPL: string; CL_H: string; CL_F: string; SL_H: string; SL_F: string; In_Remarks: string; Out_Remarks: string; Lunch_Out_Remarks: string; Lunch_In_Remarks: string; Other_Out_Remarks: string; Days: string; l1: string; l2: string; l3: string; l4: string; l5: string; l6: string; l7: string; l8: string; l9: string; l10: string; Total: string; } export interface IDailyEntry { Id: number; Employee_Name: string; Date: string; Transaction_Id: number; Entry_Type: string; Remarks: string; Entry_Time: Date; forwhichDate: string; }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.UserManagement; using System.Data; using System.Data.SqlClient; using System.Web; using System.Xml.Linq; using System.Text.RegularExpressions; using System.Net.NetworkInformation; namespace VIS_Repository.UserManagement { public class AttendanceEntryRepository : VISDbCommand, VISIBaseRepository<AttendanceEntry> { public string EntryTypedatacont = null; public string Remarks { get; set; } public string strUserId { get; set; } public HttpRequest Request { get; set; } public Int32 intAffectedRecords { get; set; } public string modedata { get; set; } public string time = DateTime.Now.ToString("HH:mm"); public XElement Element { get; set; } DataSet ds = new DataSet(); DataSet dsEntryType = new DataSet(); DataSet dstype; DataTable dtConfig = new DataTable(); public AttendanceEntryRepository(string _connectionstring) : base(_connectionstring) { } public string AddEntity(AttendanceEntry objAttendance) { try { EntryTypedatacont = Convert.ToString(objAttendance.Entry_Type); Remarks = objAttendance.Remarks; GetAttendanceEntryList(); DateTime dt = DateTime.Now; String strDate = dt.ToString("dd/MM/yyyy"); string forwhichDate = dt.ToString("yyyy-MM-dd HH:mm:ss"); string IpAddress = GetLanIPAddress(); string MacAddress = GetMACAddress(); VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "insert"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue("Id", "0"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, 21); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Entry_Type, objAttendance.Entry_Type); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Remarks, objAttendance.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Entry_Time, ""); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Date, strDate); string actualTime = "", grace = ""; if (dstype.Tables.Count > 0) { actualTime = dstype.Tables[0].Rows[0][0].ToString(); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_actualEntryTime, actualTime); if(dstype.Tables.Count > 0) { grace = dstype.Tables[0].Rows[0][1].ToString(); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_grace, grace); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_macID, MacAddress); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, forwhichDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_ipAddress, IpAddress); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_source, "W"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_mouseMovement," "); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); if (EntryTypedatacont == "1" || EntryTypedatacont == "2") { objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_GetPointCounts; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Convert.ToInt32(21)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "PointCount"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Entry_Type, EntryTypedatacont); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sdapoints = new SqlDataAdapter(); sdapoints.SelectCommand = objVISDbCommand.objSqlCommand; DataSet dspoints = new DataSet(); dspoints.Clear(); sdapoints.Fill(dspoints); objSqlCommand.Connection.Close(); } string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public String GetLanIPAddress() { String ipaddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ipaddress)) { ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } return ipaddress; } public string GetMACAddress() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); String sMacAddress = string.Empty; foreach (NetworkInterface adapter in nics) { if (sMacAddress == String.Empty)// only return MAC Address from first card { IPInterfaceProperties properties = adapter.GetIPProperties(); sMacAddress = adapter.GetPhysicalAddress().ToString(); } } return sMacAddress; } public string GetPunchOutonNextday(int Id,string Date) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "check"); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sdacheck = new SqlDataAdapter(); DataSet dscheck = new DataSet(); sdacheck.SelectCommand = objVISDbCommand.objSqlCommand; dscheck.Clear(); sdacheck.Fill(dscheck); //-------------second method--------------// objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "checktoday"); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sdaAttendance = new SqlDataAdapter(); DataSet dsAttendance = new DataSet(); sdaAttendance.SelectCommand = objVISDbCommand.objSqlCommand; dsAttendance.Clear(); sdaAttendance.Fill(dsAttendance); //-----------------Thard Method-------------// objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "checktoday"); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sdaAttendancePreviousday = new SqlDataAdapter(); DataSet dsAttendancePreviousday = new DataSet(); sdaAttendancePreviousday.SelectCommand = objVISDbCommand.objSqlCommand; dsAttendancePreviousday.Clear(); sdaAttendancePreviousday.Fill(dsAttendancePreviousday); objSqlCommand.Connection.Close(); if(dscheck != null && dscheck.Tables.Count > 0 && dscheck.Tables[0].Rows.Count > 0 && dsAttendance !=null && dsAttendance.Tables.Count > 0 && dsAttendance.Tables[0].Rows.Count == 0 && dsAttendancePreviousday != null && dsAttendancePreviousday.Tables.Count > 0 && dsAttendancePreviousday.Tables[0].Rows.Count > 0) { //ddlDateList.Visible = true; DateTime dt = DateTime.Now; DateTime dtPre = dt.AddDays(-1); //ddlDateList.Items.Add(new ListItem(dt.ToString("dd/MM/yyyy"), "0")); //ddlDateList.Items.Add(new ListItem(dtPre.ToString("dd/MM/yyyy"), "1")); //ddlDateList.SelectedIndex = 0; //btnsubmit.Enabled = false; //RadioButtonListEntryType.Enabled = false; } return ""; } public DataTable GetTimeDetails(int Id, string Date) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_GetTimer; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Date, Date); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter sdaTimer = new SqlDataAdapter(); DataTable dstimer = new DataTable(); sdaTimer.SelectCommand = objVISDbCommand.objSqlCommand; dstimer.Clear(); sdaTimer.Fill(dstimer); objSqlCommand.Connection.Close(); return dstimer; } public DataTable GetEmployeeName(int Id) { VISDbCommand Objdbcommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); Objdbcommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; Objdbcommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; Objdbcommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Id); Objdbcommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "GetEmployeeName"); if (!Objdbcommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { Objdbcommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } Objdbcommand.objSqlCommand.Connection.Open(); SqlDataAdapter sdaempname = new SqlDataAdapter(); DataTable dtemp = new DataTable(); sdaempname.SelectCommand = Objdbcommand.objSqlCommand; dtemp.Clear(); sdaempname.Fill(dtemp); Objdbcommand.objSqlCommand.Connection.Close(); return dtemp; } public string DeleteEntity(long Id) { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } public AttendanceEntry GetEntityByID(long entityId) { throw new NotImplementedException(); } public DataSet GetAttendanceEntryList() { DateTime dtt = DateTime.Now; String strDate = dtt.ToString("dd/MM/yyyy"); string day = DateTime.Now.DayOfWeek.ToString(); string time = DateTime.Now.ToString("HH:mm"); VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objSqlCommand.Connection.Open(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Convert.ToInt32(21)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "login"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, ""); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = objVISDbCommand.objSqlCommand; ds.Clear(); sda.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { dstype = new DataSet(); objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_GetCommonConfiguration; SqlDataAdapter sdaconfig = new SqlDataAdapter(); sdaconfig.SelectCommand = objVISDbCommand.objSqlCommand; dtConfig.Clear(); sdaconfig.Fill(dtConfig); SqlParameter[] Param = new SqlParameter[2]; if (Convert.ToInt32(EntryTypedatacont) == 1 || Convert.ToInt32(EntryTypedatacont) == 2) { if (Convert.ToInt32(EntryTypedatacont) == 1 && (day == "Monday" || day == "Tuesday" || day == "Wednesday" || day == "Thursday" || day == "Friday" || day == "Sunday")) { Param[0] = new SqlParameter(AttendanceEntryConstants.const_Field_Mode, "allday"); } else if (Convert.ToInt32(EntryTypedatacont) == 1 && (day == "Saturday")) { Param[0] = new SqlParameter(AttendanceEntryConstants.const_Field_Mode, "selectgrace"); } else if (Convert.ToInt32(EntryTypedatacont) == 2 && (day == "Monday" || day == "Tuesday" || day == "Wednesday" || day == "Thursday" || day == "Friday" || day == "Sunday")) { Param[0] = new SqlParameter(AttendanceEntryConstants.const_Field_Mode, "selectmon"); } else if (Convert.ToInt32(EntryTypedatacont) == 2 && (day == "Saturday")) { Param[0] = new SqlParameter(AttendanceEntryConstants.const_Field_Mode, "selectsat"); } Param[1] = new SqlParameter(AttendanceEntryConstants.const_Field_forWhichDate, strDate); if (Param[0] != null) { objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Convert.ToInt32(21)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, Param[0].Value.ToString()); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, Param[1].Value.ToString()); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sdaAdapter = new SqlDataAdapter(); sdaAdapter.SelectCommand = objVISDbCommand.objSqlCommand; //dstype.Clear(); sdaAdapter.Fill(dstype); //return dstype; } DataSet dsEntry = new DataSet(); if(Convert.ToInt32(EntryTypedatacont) == 2) { DateTime forwhichDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id,Convert.ToInt32(21)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "EntryCount"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, strDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Entry_Type,EntryTypedatacont); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sdaEntry = new SqlDataAdapter(); sdaEntry.SelectCommand = objVISDbCommand.objSqlCommand; sdaEntry.Fill(dsEntry); } if(dstype != null && dstype.Tables.Count > 0) { if(Convert.ToInt32(EntryTypedatacont) == 1 && (Convert.ToDateTime(time) > Convert.ToDateTime(dstype.Tables[0].Rows[0][0]))) { if(Remarks.Trim().ToString() == "") { //alert message => Please Enter Remarks } } } } else if(Convert.ToInt32(EntryTypedatacont) == 4) { int lunchtime = Convert.ToInt32(GetConfigValue("lunchtime")); DateTime EndTime = DateTime.Now; objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Convert.ToInt32(21)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "lunch"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, strDate); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sdaEntry = new SqlDataAdapter(); sdaEntry.SelectCommand = objVISDbCommand.objSqlCommand; DataSet dslunch = new DataSet(); sdaEntry.Fill(dslunch); if(dslunch.Tables[0].Rows.Count > 0) { DateTime dtstarttime = Convert.ToDateTime(dslunch.Tables[0].Rows[0][0].ToString()); int iMinBreak = Convert.ToInt16(dtConfig.Rows[0]["MinimumLunchBreak"]); string strstarttime = dtstarttime.ToString("HH:mm:ss"); TimeSpan difference = EndTime - dtstarttime; int TotalTime = difference.Hours * 60 + difference.Minutes; if(Convert.ToInt32(difference.TotalMinutes) >= iMinBreak) { if (TotalTime > lunchtime) { if(Remarks.Trim().ToString() == "") { //alert message => Please Enter Remarks } else { if (IsValidString(Remarks.Trim())) { //AddEntity(); } else { //alert message => Please Enter Proper Remarks } } } else { //AddEntity() } } else { //alert Message(with time difference) } } } else if(Convert.ToInt32(EntryTypedatacont) == 5) { if(Remarks.Trim().ToString() == "") { //Alert Message Please Enter remarks. } else { if (IsValidString(Remarks.Trim())) { //AddEntity(); } else { // Alert Message => Please Enter Proper remarks. } } } else if (Convert.ToInt32(EntryTypedatacont) == 6) { objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Convert.ToInt32(21)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, strDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "GetOtheroutEntryTime"); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sdaEntry = new SqlDataAdapter(); sdaEntry.SelectCommand = objVISDbCommand.objSqlCommand; DataSet dsTime = new DataSet(); sdaEntry.Fill(dsTime); //int iMinBreak = Convert.ToInt32((xElem.Element("MinimumOtherBreak").Value)); int iMinBreak = Convert.ToInt32(dtConfig.Rows[0]["MinimumOtherBreak"]); TimeSpan diff = DateTime.Now - Convert.ToDateTime(dsTime.Tables[0].Rows[0][0]); if(Convert.ToInt32(diff.TotalMinutes) >= iMinBreak) { //Add Entity(); } else { //Alert Message With Time Detials. } } else if(Convert.ToInt32(EntryTypedatacont) == 7) { if (string.IsNullOrEmpty(Remarks.Trim())) { //Alert Message Please Enter Remarks. } else { if (IsValidString(Remarks.Trim())) { //Add Entity(); } else { // Alert Message Please Enter Proper Remarks. } } } else if(Convert.ToInt32(EntryTypedatacont) == 9) { if(Remarks.Trim().ToString() == "" || Remarks.Length < 20) { //Alert Message => Please Enter Remarks With Atleast 20 Characters } else { if (IsValidString(Remarks.Trim())) { //Add Entity(); } else { //Alert message => Please Enter Proper Remarks. } //sendOfficialWorkMAil("Out"); } } else if(Convert.ToInt32(EntryTypedatacont) == 10) { if (Remarks.Trim().ToString() == "" || Remarks.Trim().Length < 20) { //Alert Message => Please Enter Remarks With Atleast 20 Characters. } else { TimeSpan MTime; objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AttendanceEntryConstants.const_procAttendanceEntry_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Employee_Id, Convert.ToInt32(21)); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_forWhichDate, DateTime.Now.ToString("yyyyMMdd")); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AttendanceEntryConstants.const_Field_Mode, "fillentry"); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } SqlDataAdapter sdaEntry = new SqlDataAdapter(); sdaEntry.SelectCommand = objVISDbCommand.objSqlCommand; DataSet dstransaction = new DataSet(); sdaEntry.Fill(dstransaction); MTime = DateTime.Parse(DateTime.Now.ToString()) - DateTime.Parse(dstransaction.Tables[0].Rows[0]["Entry_Time"].ToString()); } } } objSqlCommand.Connection.Close(); return ds; } public string UpdateEntity(AttendanceEntry entityObject) { throw new NotImplementedException(); } //Common Function public static bool IsValidString(string str) { bool valid; int charCount = Regex.Matches(str, @"[a-zA-Z0-9]").Count; if (charCount >= 3) valid = true; else valid = false; if (valid) { char prev = str[0]; int rpt = 1; for (int i = 1; i < str.Length; i++) { char curr = str[i]; if (curr == prev) rpt++; else { rpt = 1; prev = curr; } if (rpt >= 3) { valid = false; break; } } } return valid; } public static string GetConfigValue(string paramName) { String tmpS = String.Empty; try { tmpS = ConfigurationManager.AppSettings[paramName].ToString(); } catch(Exception ex) { tmpS = String.Empty; } return tmpS; } public IEnumerable<AttendanceEntry> GetEntityList() { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class LeaveType : VISBaseEntity { /// <summary> /// LeaveType Entity Fields. /// </summary> /// public string LeaveTypeName { get; set; } } public static class LeaveTypeConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_LeaveType_Table = "LeaveType"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_LeaveType = "LeaveTypeName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procLeaveType_Add = "procLeaveType_Add"; public const string const_procLeaveType_Update = "procLeaveType_Update"; public const string const_procLeaveType_ActiveInActive = "procLeaveType_ActiveInActive"; public const string const_procLeaveType_SelectAll = "procLeaveType_SelectAll"; public const string const_procLeaveType_SelectById = "procLeaveType_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.EmployeeManagement; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.HumanResource.EmployeeManagement; using VIS_Repository.Masters.CompanyRelated; namespace VIS_App.Controllers.HumanResource.EmployeeManagement { public class EducationTypeAPIController : BaseAPIController { EducationTypeRepository ObjEducationTypeRepository = null; public EducationTypeAPIController() { ObjEducationTypeRepository = new EducationTypeRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjEducationTypeRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]EducationType value) { return ToJson(ObjEducationTypeRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]EducationType value) { return ToJson(ObjEducationTypeRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 id) { return ToJson(ObjEducationTypeRepository.DeleteEntity(id)); } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { LateEarlyReportService } from '../../../Service/Report/Attendance/LateEarlyReport.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { IEmployee } from '../../../Model/Report/Attendance/LateEarlyReport'; import { ICompany } from '../../../Model/Report/Attendance/LateEarlyReport'; import { IDepartment } from '../../../Model/Report/Attendance/LateEarlyReport'; import { IYear } from '../../../Model/Report/Attendance/LateEarlyReport'; import { ILateEarlyReport } from '../../../Model/Report/Attendance/LateEarlyReport'; import { ParameterModel } from '../../../Model/Report/Attendance/LateEarlyReport'; import { Pipe } from '@angular/core'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [LateEarlyReportService], templateUrl: 'app/Components/Report/Attendance/LateEarlyReport.component.html' }) export class LateEarlyReportComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; constructor(private fb: FormBuilder, private _LateEarlyReportService: LateEarlyReportService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService ) { } pager: any = {}; pagedItems: any[]; CurrentRecordsPerPage: number = 10; Department: IDepartment[]; Employee: IEmployee[]; Employees: IEmployee[]; Company: ICompany[]; Year: IYear[]; EmployeeId: number = 0; DepartmentId: number = 0; CompanyId: number = 0; LateEarlyReport: ILateEarlyReport; LateEarlyReports: ILateEarlyReport[]; ParameterModel: ParameterModel; modalTitle: string; InLoading: boolean; frommonth: number = new Date().getMonth() + 1; fromyear: number = new Date().getFullYear(); fromdate: string; todate: string; ngOnInit() { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.Year = [({ CurrentYear: '' })] this.Department = [({ Department_Name: '', Id:0 })] this.Company = [({ CompanyName:'', Id: 0 })] this.ParameterModel = { Id: 0, Fromdate: new Date(), Todate: new Date(), MonthWise: false, FromMonth: '', FromYear:'' } this.GetDepartment(); this.GetEmployee(); this.GetCompany(); this.GetYear(); } ToogleMyProfile() { $("#alltypeoutreportdata").slideToggle(300); } CloseWidgetProfile() { $("#alltypeoutreport").hide(300); } ViewStyleToogle() { if ($("#rbtconsolidated").prop('checked')) { $("#viewstyle").show(); } else { $("#viewstyle").hide(); } } ToogleHideShowOption() { if ($("#rbtdepartment").prop('checked')) { $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); $("#ddldepartment").show(); } else if ($("#rbtcompany").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").show(); $("#ddllinemanager").hide(); } else if ($("#rbtlinemanager").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").show(); } else { $("#ddldepartment").hide(); $("#ddlemployee").show(); $("#chkallemployeediv").show(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); } } ToogleDateOption() { if ($("#rbtdate").prop("checked")) { $("#searchbydate").show(); $("#searchbymonth").hide(); } else { $("#searchbydate").hide(); $("#searchbymonth").show(); } } GetDepartment() { this._LateEarlyReportService.getdepartment(Global.BASE_LateEarlyReport_ENDPOINT). subscribe(department => { this.Department = department; }, ); } GetEmployee() { this._LateEarlyReportService.getemployee(Global.BASE_LateEarlyReport_ENDPOINT). subscribe(employee => { this.Employee = employee }, ); } GetCompany() { this._LateEarlyReportService.getcompany(Global.BASE_LateEarlyReport_ENDPOINT). subscribe(company => { this.Company = company; }, ); } GetYear() { this._LateEarlyReportService.getyear(Global.BASE_LateEarlyReport_ENDPOINT). subscribe(year => { this.Year = year }, ); } GetIdByDepartment(Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth: string, FromYear: string) { this.LateEarlyReports = null; this.InLoading = true; this._LateEarlyReportService.getemployeeidbydepartment(Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(lateearlyreports => { this.LateEarlyReports = lateearlyreports; this.JumpOnPage(1); this.InLoading = false; }, ); } GetIdByEmployee(Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth:string,FromYear: string) { this.LateEarlyReports = null; this.InLoading = true; this._LateEarlyReportService.getemployeeidbyemployee(Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(lateearlyreports => { this.LateEarlyReports = lateearlyreports; this.JumpOnPage(1); this.InLoading = false; }, ); } GetIdByCompany(Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth: string, FromYear: string) { this._LateEarlyReportService.getemployeeidbycompany(Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(employees => { this.Employees = employees this.JumpOnPage(1); }, ); } GetIdBySelectAll(Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth: string, FromYear: string) { this._LateEarlyReportService.getemployeeidbyselectall(Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(employees => { this.Employees = employees this.JumpOnPage(1); }, ); } onSubmit(formData: ParameterModel) { if (formData.Id != 0) { this.Employees = null; if ($("#rbtemployee").prop("checked")) { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdByEmployee(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } else if ($("#rbtdepartment").prop("checked")) { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdByDepartment(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } else if ($("#rbtcompany").prop("checked")) { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdByCompany(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } } else { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdBySelectAll(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.LateEarlyReports); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } } <file_sep>import { Component, OnInit, ViewChild, Directive, DirectiveDecorator, forwardRef } from '@angular/core'; import { HomePageImageService } from '../../../service/Masters/CompanyRelated/HomePageImage.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IHomePageImage } from '../../../Model/Masters/CompanyRelated/HomePageImage'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; import * as _ from 'underscore'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; @Component ({ providers: [HomePageImageService], templateUrl: 'app/Components/Masters/CompanyRelated/HomePageImage.component.html' }) export class HomePageImageComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('modal2') modal2: ModalComponent; homepageimages: IHomePageImage[]; homepageimage: IHomePageImage; imgpathshow: string; imgpath: string; activeimages: IHomePageImage[]; activeimagescount: number; strSearchImageName: string; strSearchActive: string; ShowHideSearch: boolean = false; msg: string; msg2: string; indLoading: boolean = false; HomePageImageFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; HomePageImageFilter: string; isDesc: boolean = false; column: any = 'ImagePath'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; nums: number[]; fileList1: FileList; constructor(private fb: FormBuilder, private _HomePageImageService: HomePageImageService, private pagerService: PagerService, private http: Http, private _CommonHelperService: CommonHelperService) { } ngOnInit() { this._CommonHelperService.ToogleMenu(); this.homepageimage = ({ Id: 0, ImagePath:'', Active: false, IsActive: false, CreatedOn: null, UpdatedOn: null, CreatedBy: 0, UpdatedBy: 0 }); this.GetAllImage(); this.GetActiveImage(); } AddHomePageImage() { this.dbops = DBOperation.create; this.modalTitle = "Add New Home Page Image"; this.modalBtnTitle = "Upload Image"; //this.homepageimage.ImagePath = this.homepageimage.ImagePath; this.ngOnInit(); this.modal.open(); } EditHomePageImage(id: number) { debugger; this.dbops = DBOperation.update; this.modalTitle = "Edit Home Page Image"; this.modalBtnTitle = "Update"; this.homepageimage = this.homepageimages.filter(x => x.Id == id)[0]; this.modal.open(); } DeleteHomePageImage(id: number, status: boolean) { this.dbops = DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.homepageimage = this.homepageimages.filter(x => x.Id == id)[0]; this.homepageimage.ImagePath = this.homepageimage.ImagePath; this.modal.open(); } GetAllImage() { this.indLoading = true; this._HomePageImageService.get(Global.BASE_HOMEPAGEIMAGE_ENDPOINT) .subscribe(data => { this.homepageimages = data; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchImageName = (<HTMLInputElement>document.getElementById("searchImageName")).value; if (this.strSearchImageName != '') { this.strSearchImageName = this.strSearchImageName.toLocaleLowerCase(); this.homepageimages = this.homepageimages.filter ( x => x.ImagePath != null && x.ImagePath.toLocaleLowerCase().indexOf(this.strSearchImageName) != -1); } } //Logic for searching - End this.indLoading = false; this.JumpOnPage(1); } ); } GetActiveImage() { this.indLoading = true; this._HomePageImageService.getactiveimage(Global.BASE_HOMEPAGEIMAGE_ENDPOINT) .subscribe(activeimages => { this.activeimages = activeimages; this.indLoading = false; } ); } SetControlsState(isEnable: boolean) { isEnable ? this.HomePageImageFrm.enable() : this.HomePageImageFrm.disable(); } HomePageImageSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.homepageimages); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: IHomePageImage) { this.msg = ""; switch (this.dbops) { case DBOperation.create: if (this.fileList1 != null) { formData.ImagePath = this.fileList1.item(0).name; this._HomePageImageService.post(Global.BASE_HOMEPAGEIMAGE_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.fileList1.item(0).name let file: File = this.fileList1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl = "/api/HomePageImageAPI/UploadJsonFile"; this.http.post(apiUrl, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) this.msg = data; this.GetAllImage(); this.GetActiveImage(); this.fileList1 = null; this.msg2 = ''; this.modal.dismiss(); } else { alert(data); this.fileList1 = null; } }, error => { this.msg = error; } ); } else { this.msg2 = "Please Choose Image"; } break; case DBOperation.update: this._HomePageImageService.put(Global.BASE_HOMEPAGEIMAGE_ENDPOINT, formData.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data this.GetAllImage(); this.modal.dismiss(); } else { alert(data); } this.GetActiveImage(); }, error => { this.msg = error; } ); break; case DBOperation.delete: this._HomePageImageService.delete(Global.BASE_HOMEPAGEIMAGE_ENDPOINT, formData.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Home Page Image status changed successfully."; this.GetAllImage(); } else { this.msg = "Error has occurred while changing status of existing Home Page Image!" } this.modal.dismiss(); this.GetActiveImage(); }, error => { this.msg = error; } ); break; } } fileChange(event) { this.fileList1 = event.target.files; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ViewImage(id) { this.modalTitle = "Preview Home Page Image"; this.homepageimage = this.homepageimages.filter(x => x.Id == id)[0]; this.imgpathshow = this.homepageimage.ImagePath; this.modal2.open(); } CancelPopup() { this.modal.dismiss(); this.msg2 = ''; } } <file_sep>import { Component, OnInit,ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators,ReactiveFormsModule, FormsModule } from '@angular/forms'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import { PagerService } from '../../Shared/pager.index'; import { DBOperation } from '../../Shared/enum'; import { Ng2TabModule } from 'ng2-tab'; import { ConfigureSurveyService } from '../../Service/Opinion/ConfigureSurvey.service'; import { IUserRoleById, IUserType, IAllSurveyDetails, ISurveyType, IUserForOwnerSelection } from '../../../app/Model/Opinion/ConfigureSurvey'; @Component({ providers: [ConfigureSurveyService], templateUrl: 'app/Components/Opinion/ConfigureSurvey.component.html' }) export class ConfigureSurveycomponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('Header') Header: ModalComponent; msg: string; indLoading: boolean = false; CurrentRecordsPerPage: number = 10; pager: any = {}; pagedItems: any[]; PagerInformation: string; dbops: DBOperation; ConfigureSurveyFrm: FormGroup; UserRole: IUserRoleById; UserType: IUserType[]; SurveyDetails: IAllSurveyDetails[]; SurveyType: ISurveyType[]; UsersOwnerSelected:IUserForOwnerSelection[]; IsAdmin: boolean; RoleType: string; AddButton: boolean; ServeyType: string = "Approved"; Approvetype: string; ComplitionText: string; Footer: string; constructor(private fb: FormBuilder, private _ConfigureSurveyService: ConfigureSurveyService, private pagerService: PagerService, private http: Http) { } ngOnInit(): void { $("#QueBased").prop("checked", true); $("#csdesign").prop("checked", true); $("#chkactive").prop("checked", true); $("#imgshow").hide(); $("#imgshow1").hide(); $("#video").hide(); this.GetRollOfEmployee(); this.BindServey("ALL", ''); this.BindSurveyType(); this.BindUsersForOwnerSelection(); } HideImgChecked() { if ($("#chkimage").prop("checked", true)) { $("#chkaudio").prop("checked", false); $("#chkvideo").prop("checked", false); $("#imgshow").show(); $("#imgshow1").show(); $("#video").hide(); } } HideAudioChecked() { if ($("#chkaudio").prop("checked", true)) { $("#chkimage").prop("checked", false); $("#chkvideo").prop("checked", false); $("#imgshow").show(); $("#imgshow1").show(); $("#video").hide(); } } HideVideoChecked() { if ($("#chkvideo").prop("checked", true)) { $("#chkimage").prop("checked", false); $("#chkaudio").prop("checked", false); $("#video").show(); $("#imgshow").show(); $("#imgshow1").show(); } } HideMstQueChecked() { if ($("#chkIsMasterQue").prop("checked", true)) { $("#hideMasterquestion").hide(); } } BindSurveyType():void { this._ConfigureSurveyService.BindSurveyType(Global.BASE_ConfigureSurveyAPI_ENDPOINT) .subscribe(data => { this.SurveyType = data; this.indLoading = false; }, error => { this.msg=error; }); } BindUsersForOwnerSelection(): void { this._ConfigureSurveyService.BindUsersForOwnerSelection(Global.BASE_ConfigureSurveyAPI_ENDPOINT,21) .subscribe(data => { this.UsersOwnerSelected = data; this.indLoading = false; }, error => { this.msg = error; }); } //--- Change Event Start ---// changeText(event):void { debugger; var survey = event.target.value; if (survey.length > 0) { var FilterType = $("#ddlSurveyType option:selected").text(); if (FilterType === 'Survey') { this.ComplitionText = "Thank you for submitting the Survey.\nYou can close the window now."; this.Footer = "In order to progress through this Survey/Exam, please use the following navigation buttons:" + "Click the Next button to continue to the next page." + "Click the Previous button to return to the previous page." + "Click the Finish button to complete your Survey/ Exam."; } else if (FilterType === 'Exam') { this.ComplitionText = "Thank you for submitting the Exam.\nYou can close the window now."; this.Footer = "In order to progress through this Exam, please use the following navigation buttons:" + "Click the Next button to continue to the next page.Click the Previous button to return to the previous page." + "Click the Finish button to complete your Exam."; } } } DisplayPollData(event): void { if ($("#ddlSurveyType option:selected").text() == "Poll") { $("#chkSaveasTemplate").hide(); $("#chkReview").hide(); $("#chkTimeBased").hide(); $("#rdbCustomDesign").prop("disabled", true); $("#rdbNonRandom").prop("disabled", true); $("#rdbRandom").prop("disabled", true); $("#rdbNonRandom").prop('checked', true); $("#PageSetting").hide(); $("#divTotalQue").hide(); $("#trCompletionText").hide(); $("#trHeaderFooter").hide(); $("#txtQuePerPage").prop("disabled", true); $("#txtQuePerPage").val('1'); $("#trSaveAsTemplate").hide(); $("#trTimeBased").hide(); $("#trTotalPoints").hide(); $("#trImport").hide(); $("#trRevoting").show(); if ($("#hdnSurveyId").val() == 0 || $("#hdnSurveyId").val() == " ") { $("#rdbNoPoints").prop("checked", true); } $("#trReportVisibility").show(); $("#trIsMasterQue").show(); $("#trParentQue").show(); } else { $("#chkSaveasTemplate").show(); $("#chkAllowReview").show(); $("#chkTimeBased").show(); $("#chkAllowToFillAgain").show(); $("#rdbCustomDesign").prop("disabled", false); $("#rdbNonRandom").prop("disabled", false); $("#rdbRandom").prop("disabled", false); $("#divTotalQue").hide(); $("#trCompletionText").show(); $("#trHeaderFooter").show(); $("#txtQuePerPage").prop("disabled", false); $("#trSaveAsTemplate").show(); $("#trTimeBased").show(); $("#trTotalPoints").hide(); if ($("#rdbQuestionBased").prop('checked') == true || $("#rdbAnswerBased").prop('checked') == true) { $("#trTotalPoints").show(); } $("#trImport").show(); $("#trRevoting").hide(); $("#trReportVisibility").hide(); $("#trIsMasterQue").show(); $("#trParentQue").show(); } } CheckSurveyType(event): void { if ($("#ddlSurveyType option:selected").text() == "Survey") { $("#chkIsProject").show(); this.CheckProject(); } else { $("#chkIsProject").hide(); this.CheckProject(); } } ShowNoPointSystem(event): void { if ($("#ddlSurveyType option:selected").text() == "Survey") { $("#rdbNoPoints").show(); $("#trImport").show(); if ($("#hdnSurveyId").val() == "0" || $("#hdnSurveyId").val() == " ") { $("#rdbNoPoints").prop("checked", true); } $("#trRevoting").hide(); $("#trIsMasterQue").show(); $("#trParentQue").show(); if ($("#rdbQuestionBased").prop('checked') == true || $("#rdbAnswerBased").prop('checked') == true) { $("#trTotalPoints").show(); } else { $("#trTotalPoints").hide(); } } else if ($("#ddlSurveyType option:selected").text() == "Exam") { $("#rdbNoPoints").hide(); $("#trImport").show(); if ($("#hdnSurveyId").val() == "0" || $("#hdnSurveyId").val() == " ") { $("#rdbQuestionBased").prop("checked", true); } $("#trRevoting").hide(); $("#trIsMasterQue").show(); $("#trParentQue").show(); $("#trTotalPoints").show(); } else if ($("#ddlSurveyType option:selected").text() == "Poll") { $("#rdbNoPoints").show(); $("#trImport").hide(); if ($("#hdnSurveyId").val() == "0" || $("#hdnSurveyId").val() == " ") { $("#rdbNoPoints").prop('checked', true); } $("#trRevoting").show(); $("#trReportVisibility").show(); $("#trIsMasterQue").hide(); $("#trParentQue").hide(); } } ShowAllowToFill(event): void { if ($("#ddlSurveyType option:selected").text() == "Survey") { $("#chkAllowToFillAgain").hide(); $("#AllowToFill").hide(); } else if ($("#ddlSurveyType option:selected").text() == "Exam") { $("#chkAllowToFillAgain").show(); $("#AllowToFill").hide(); } } CheckDisableTabs(event): void { if ($("#hdnMode").val() == "configure") { if ($("#ddlSurveyType option:selected").text() != "Exam" && $("#rdbNoRecurrence").prop('checked') == true) { $("#s2").prop("disabled", true); $("#s4").prop("disabled", true); } else if ($("#ddlSurveyType option:selected").text() != "Exam" && $("#rdbRecurrence").prop('checked') == true) { $("#s2").prop("disabled", true); } else if ($("#rdbNoRecurrence").prop('checked') == true) { $("#s4").prop("disabled", true); } else if ($("#rdbRecurrence").prop('checked') == true) { $("#s4").prop("disabled", true); } if ($("#hdnEdit").val() == "1") { $("#s1").prop("disabled", true); $("#s2").prop("disabled", true); $("#s4").prop("disabled", true); this.DisableStep1Control(); } //if (jQuery('[id$=hdnIsPublishAllow]').val() == "0") //{ // jQuery("#SurveyTabs").tabs("disable", 3); // jQuery("#SurveyTabs").tabs("disable", 4); //} } //else if (jQuery('[id$=hdnMode]').val() == "suggestion" || jQuery('[id$=hdnMode]').val() == "template") { // if (jQuery('[id$=ddlSurveyType] option:selected').text() == "Exam") { // jQuery("#SurveyTabs").tabs("option", "disabled", [3, 4]); // } // else { // jQuery("#SurveyTabs").tabs("option", "disabled", [2, 3, 4]); // } //} } CheckProject() { if ($("#chkIsProject").prop('checked') == true && $("#ddlSurveyType option:selected").text() == "Survey") { $("#Project").show(); } else { $("#Project").hide(); } } DisableStep1Control() { $("#ddlSurveyType").prop("disabled", true); $("#chkIsProject").prop("disabled", true); $("#ddlProject").prop("disabled", true); $("#txtName").prop("disabled", true); $("#txtDesc").prop("disabled", true); $("#chkSaveasTemp").prop("disabled", true); $("#chkAllowReview").prop("disabled", true); $("#chkTimeBase").prop("disabled", true); $("#txtTime").prop("disabled", true); $("#chkAllowToFillAgain").prop("disabled", true); $("#txtAllowToFillAgain").prop("disabled", true); $("#rdbQuestionBased").prop("disabled", true); $("#rdbAnswerBased").prop("disabled", true); $("#rdbNoPoints").prop("disabled", true); $("#txtTotalPoints").prop("disabled", true); $("#txtMinimumPoints").prop("disabled", true); $("#rdbCustomDesign").prop("disabled", true); $("#rdbNonRandom").prop("disabled", true); $("#rdbRandom").prop("disabled", true); $("#txtQuePerPage").prop("disabled", true); $("#txtTotalQue").prop("disabled", true); $("#rdbIsShowReport").prop("disabled", true); $("#rdbAutoPublish").prop("disabled", true); $("#rdbIsDontShow").prop("disabled", true); $("#chkIsRevoting").prop("disabled", true); $("#chkMandatory").prop("disabled", true); $("#chkActive").prop("disabled", true); $("#txtcompletion").prop("disabled", true); $("#ckedit123").prop("disabled", true); $("#ckeditfooter").prop("disabled", true); $("#fuImportQuestion").prop("disabled", true); $("#imgbtnDownLoadSample").prop("disabled", true); } //--- Change Event End ---// AddNewSurvey():void { this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.ConfigureSurveyFrm.enable() : this.ConfigureSurveyFrm.disable(); } GetRollOfEmployee(): boolean { this._ConfigureSurveyService.GetRollOfEmployee(Global.BASE_ConfigureSurveyAPI_ENDPOINT,21,"Admin") .subscribe(data => { this.IsAdmin = data; this.indLoading = false; }, error => { this.msg = error; }); return this.IsAdmin; } GetRollOfEmployees(EmployeeId: number, RoleType: string): void { this._ConfigureSurveyService.GetRollOfEmployee(Global.BASE_ConfigureSurveyAPI_ENDPOINT, 21, "Admin") .subscribe(success => { this.IsAdmin = success; this.indLoading = false; }, error => { this.msg = error; }); } GetApprovetype(event): void { this.Approvetype = event.target.value; } BindServey(SearchField: string, searchValue: string): void { if (this.IsAdmin == true) { this.RoleType = "Admin"; } if (this.IsAdmin == true) { $("#rdbSuggested").show(); $("#lblSuggestedCount").show(); } if ($("#tdAddButtons1").show()) { this.AddButton = true; } if (this.AddButton == this.IsAdmin || this.GetRollOfEmployees(21, "LM") || this.GetRollOfEmployees(21, "BM") || this.GetRollOfEmployees(21, "BH") || this.GetRollOfEmployees(21, "SH") || this.GetRollOfEmployees(21, "GH")) { } else { this.Approvetype = $("#ApprovedTypedata").val(); this._ConfigureSurveyService.GetSurveyDetails(Global.BASE_ConfigureSurveyAPI_ENDPOINT, SearchField, searchValue, 21, this.RoleType, this.ServeyType, this.Approvetype) .subscribe(data => { this.SurveyDetails = data; this.indLoading = false; this.JumpOnPage(1); } ,error => { this.msg = error; }); } } ToogleMyProfile() { $("#CofigureSurveyData").slideToggle(300); } CloseWidgetProfile() { $("#CofigureSurveyData").hide(300); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.SurveyDetails); this.pager = this.pagerService.pager; this.pagedItems = null; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IRFQ } from '../../Model/RFQ/RFQEstimateListing'; @Pipe ({ name: 'RFQFilter' }) export class RFQFilterPipe implements PipeTransform { transform(value: IRFQ[], filter: string): IRFQ[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IRFQ) => app.Status != null && app.Status.toLocaleLowerCase().indexOf(filter) != -1 || app.EstimateBy != null && app.EstimateBy.toLocaleLowerCase().indexOf(filter) != -1 || app.Title != null && app.Title.toLocaleLowerCase().indexOf(filter) != -1 || app.InitiatedBy != null && app.InitiatedBy.toLocaleLowerCase().indexOf(filter) != -1 || app.LastResponseBy != null && app.LastResponseBy.toLocaleLowerCase().indexOf(filter) != -1 || app.Status != null && app.Status.toLocaleLowerCase().indexOf(filter) != -1 || app.rfqStatus != null && app.rfqStatus.toLocaleLowerCase().indexOf(filter) != -1 || app.OtherComments != null && app.OtherComments.toLocaleLowerCase().indexOf(filter) != -1 || app.ActionRequestedBy != null && app.ActionRequestedBy.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var Position_service_1 = require("../../../service/Masters/VacancyRelated/Position.service"); var Skill_service_1 = require("../../../service/Masters/VacancyRelated/Skill.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var PositionComponent = (function () { function PositionComponent(fb, _PositionService, pagerService, _SkillService, _CommonHelperService) { this.fb = fb; this._PositionService = _PositionService; this.pagerService = pagerService; this._SkillService = _SkillService; this._CommonHelperService = _CommonHelperService; this.indLoading = false; this.isDesc = false; this.column = 'PositionName'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; } PositionComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.LoadPosition(); this.LoadSkills(); this.ModelReset(); }; PositionComponent.prototype.ModelReset = function () { this.position = { SkillsId: "", SkillName: "", CreatedBy: "", CreatedOn: null, Id: 0, IsActive: false, Status: false, PositionName: "", Remarks: "", UpdatedBy: "", UpdatedOn: null, SkillId: null }; }; PositionComponent.prototype.TestMultidll = function () { this.myOptions = [ { id: 6, name: 'Option 1' }, { id: 7, name: 'Option 2' }, { id: 8, name: 'Option 3' } ]; }; PositionComponent.prototype.LoadSkills = function () { var _this = this; this._PositionService.getskills(global_1.Global.BASE_POSITION_ENDPOINT) .subscribe(function (skilllist) { _this.IMultiSelectOption = skilllist; }); }; PositionComponent.prototype.PositionFilterCriteriaChange = function (value) { if (value != '[object Event]') this.PositionFilter = value; }; PositionComponent.prototype.PositionSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; PositionComponent.prototype.LoadPosition = function () { var _this = this; this.indLoading = true; this._PositionService.get(global_1.Global.BASE_POSITION_ENDPOINT) .subscribe(function (positions) { _this.positions = positions; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchPositionName = document.getElementById("searchPositionName").value; if (_this.strSearchPositionName != '') { _this.strSearchPositionName = _this.strSearchPositionName.toLocaleLowerCase(); _this.positions = _this.positions.filter(function (x) { return x.PositionName != null && x.PositionName.toLocaleLowerCase().indexOf(_this.strSearchPositionName) != -1; }); } _this.strSearchRemarks = document.getElementById("searchRemarks").value; if (_this.strSearchRemarks != '') { _this.strSearchRemarks = _this.strSearchRemarks.toLocaleLowerCase(); _this.positions = _this.positions.filter(function (x) { return x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(_this.strSearchRemarks) != -1; }); } } //Logic for searching - End _this.indLoading = false; // set items to json response // initialize to page 1 _this.JumpOnPage(1); _this.pager = _this.pagerService.pager; _this.pagedItems = _this.pagerService.pagedItems; } //,error => this.msg = <any>error ); }; PositionComponent.prototype.AddPosition = function () { this.dbops = enum_1.DBOperation.create; this.modalTitle = "Add New Position"; this.modalBtnTitle = "Add"; this.ModelReset(); this.modal.open(); }; PositionComponent.prototype.EditPosition = function (id) { this.dbops = enum_1.DBOperation.update; this.modalTitle = "Edit Position"; this.modalBtnTitle = "Update"; this.position = this.positions.filter(function (x) { return x.Id == id; })[0]; this.TempSkillId = this.position.SkillsId.split(','); this.position.SkillId = []; for (var _i = 0, _a = this.TempSkillId; _i < _a.length; _i++) { var item = _a[_i]; this.position.SkillId.push(Number(item)); } this.modal.open(); }; PositionComponent.prototype.DeletePosition = function (id, status) { this.dbops = enum_1.DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.position = this.positions.filter(function (x) { return x.Id == id; })[0]; this.TempSkillId = this.position.SkillsId.split(','); this.position.SkillId = []; for (var _i = 0, _a = this.TempSkillId; _i < _a.length; _i++) { var item = _a[_i]; this.position.SkillId.push(Number(item)); } this.modal.open(); }; PositionComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.PositionFrm.enable() : this.PositionFrm.disable(); }; PositionComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; PositionComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.positions); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; PositionComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; PositionComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; if (formData.SkillId == null) { formData.SkillId = [0]; } switch (this.dbops) { case enum_1.DBOperation.create: this._PositionService.post(global_1.Global.BASE_POSITION_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadPosition(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._PositionService.put(global_1.Global.BASE_POSITION_ENDPOINT, formData.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadPosition(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._PositionService.delete(global_1.Global.BASE_POSITION_ENDPOINT, formData.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "Position status changed successfully."; _this.LoadPosition(); } else { _this.msg = "Error has occurred while changing status of existing Position!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], PositionComponent.prototype, "modal", void 0); PositionComponent = __decorate([ core_1.Component({ providers: [Position_service_1.PositionService, Skill_service_1.SkillService], templateUrl: 'app/Components/Masters/VacancyRelated/Position.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, Position_service_1.PositionService, pager_index_1.PagerService, Skill_service_1.SkillService, CommonHelper_service_1.CommonHelperService]) ], PositionComponent); return PositionComponent; }()); exports.PositionComponent = PositionComponent; <file_sep>import { Component, OnInit } from "@angular/core"; import { SharedContents } from '../Shared/sharedcontents' @Component({ selector: "home-page", templateUrl: 'app/Components/home.component.html' }) export class HomeComponent implements OnInit { constructor(private service: SharedContents) { this.service.setData('page-wrapper', true); } ngOnInit() { } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Masters.EmployeeLevels { public class LevelCriteria:VISBaseEntity { public string Name { get; set; } public string AliasName { get; set; } public int calculatedOnID { get; set; } public int CategoryID { get; set; } public Boolean IsAutomatic { get; set; } public Boolean Active { get; set; } public string reference { get; set; } } public static class LevelCriteriaConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_LevelCriteria = "LevelCriteria"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Name = "Name"; public const string const_Field_AliasName = "AliasName"; public const string const_Field_calculatedOnID = "calculatedOnID"; public const string const_Field_CategoryID = "CategoryID"; public const string const_Field_IsAutomatic = "IsAutomatic"; public const string const_Field_Active = "Active"; public const string const_Field_reference = "reference"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procLevelCriteria_Add = "procLevelCriterias_Add"; public const string const_procLevelCriteria_Update = "procLevelCriterias_Update"; public const string const_procLevelCriteria_ActiveInActive = "procLevelCriteria_ActiveInActive"; public const string const_procLevelCriteria_SelectAll = "procLevelCriterias_SelectAll"; public const string const_procLevelCriteria_SelectBaseNonBase = "procLevelCriterias_SelectBaseNonBase"; public const string const_procLevelCriteria_SelectById = "procLevelCriterias_SelectById"; } } <file_sep>export interface IHomePageImage { Id: number; ImagePath: string; Active: boolean; CreatedOn: Date; CreatedBy: number; UpdatedOn: Date; UpdatedBy: number; IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Reports.Attendance; namespace VIS_Domain.Reports.Attendance { class AttendanceReportNew :VISBaseEntity { } public class FillDepartment { public Int64 Id { get; set; } public string Department_name { get; set; } } public class FillEmployee { public Int64 Id { get; set; } public string Employee_Name { get; set; } } public class FillCompany { public Int64 Id { get; set; } public string CompanyName { get; set; } } public class FillLineManager { public Int64 Id { get; set; } public string EmployeeName { get; set; } } public class FillUserType { public Int64 Id { get; set; } public string UserType { get; set; } } public static class AttendanceReportNewConstatnts { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Organization = "Organization"; public const string const_Table_Employee_Master = "Employee_Master"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Id = "Id"; public const string const_Field_DepartmentName = "Department_Name"; public const string const_Field_Mode = "mode"; public const string const_Field_Allow = "Allow"; public const string const_Field_UserId = "UserId"; public const string const_Field_modeId = "modeId"; public const string const_Field_fromDate = "fromDate"; public const string const_Field_toDate = "toDate"; public const string const_Field_SortBy = "SortBy"; public const string const_Field_LongLeaveValue = "LongLeaveValue"; public const string const_Field_isAdmin = "isAdmin"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procAttendanceReportNew_Add = ""; public const string const_procAttendanceReportNew_Update = ""; public const string const_procAttendanceReportNew_ActiveInActive = ""; public const string const_procAttendanceReportNew_SelectAll = "ProcAttendanceReportBindDropdown"; public const string const_procAttendanceReportNew_SelectBaseNonBase = ""; public const string const_procAttendanceReportNew_SelectById = ""; public const string const_Proc_EmployeeDetail = "Proc_EmployeeDetail"; public const string const_ProcAttendanceReport_rdlc = "ProcAttendanceReport_rdlc"; public const string const_Proc_AttendanceReport = "Proc_AttendanceReport"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.Leave { public class Reports_LeaveRepository : VISDbCommand { private static Reports_LeaveRepository instance = new Reports_LeaveRepository(string.Empty); private Reports_LeaveRepository (string _connectionstring) : base(_connectionstring) { } public static Reports_LeaveRepository getInstance() { return instance; } } } <file_sep>export interface ILevels_Achievement { Id: number; Range: number; AchievementID: number;//For select Operation AchievementName: string; SetUpID: number; CriteriaId: number; CriteriaName: string; IsCriteria:boolean AndAbove: boolean; Description: string; Help: string; Calculated: string; CalculatedIn:string; AchievedIn: number; Points: number; Image: string; Active: boolean; SelectActive: string; IsActive: boolean; LevelSetupId: number; CreatedBy: number; CreatedOn: Date; UpdatedBy: number; UpdatedOn: Date; EntityMessage: string; } export interface IForIsCriteria { Id: number; Range: string; }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master.Configuration; namespace VIS_Repository.Reports { public class OutReportRepository : VISDbCommand { int intAffectedRecords; public OutReportRepository(string _connectionstring) : base(_connectionstring) { } public DataTable GetEmployee() { string mode = "Employee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode,mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetAllEmployee() { string mode = "AllEmployee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetDepartment() { string mode = "Department"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetCompany() { string mode = "Company"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetLineManager() { string mode = "LineManager"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetEmployeeIdByLM(int LineManagerId) { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procOutReportByLM; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_LineManagerId,LineManagerId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetEmployeeIdByCompany(int CompanyId) { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procOutReportByCompany; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_CompanyId, CompanyId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetEmployeeIdByDepartment(int ParentId) { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procOutReportByDepartment; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_ParentId,ParentId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetOutReportByEmployeeId(OutReport entityobject) { DataTable dt = new DataTable(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procOutReport; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_EmployeeId, entityobject.EmployeeId); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_Active, entityobject.Active); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_FromDate, entityobject.FromDate); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_ToDate, entityobject.ToDate); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_OutType, entityobject.OutType); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_Minute, entityobject.Minute); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_AllDate, entityobject.AllDate); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_Employeelist, entityobject.Employeelist); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_Consolidated, entityobject.Consolidated); base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_Sort, entityobject.Sort); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch (Exception) { } return dt; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.HumanResource.Attendance; namespace VIS_Repository.HumanResource.Attendace { public class MyTeamRepository : VISDbCommand, VISIBaseRepository<MyTeam> { public Int32 intAffectedRecords { get; set; } public MyTeamRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { return null; } public MyTeam GetEntityByID(Int64 entityId) { return null; } public IEnumerable<MyTeam> GetEntityList() { return null; } public string AddEntity(MyTeam entityObject) { try { return null; //VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); //objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; //objVISDbCommand.objSqlCommand.CommandText = MyTeamConstants.const_procSkillUser_Add; //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_UserId, 21); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_SkillID, entityObject.id); //if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) //{ // objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); //} //objVISDbCommand.objSqlCommand.Connection.Open(); //intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); //objSqlCommand.Connection.Close(); ////return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(MyTeam entityObject) { return null; } public IEnumerable<MyTeam> GetMyTeamList(long UserId) { List<MyTeam> objListToReturn = new List<MyTeam>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTeamConstants.const_procGetMyTeam_List; base.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_mode,"MyTeam"); base.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTeam>(dt); } return objListToReturn; } public IEnumerable<MyTeam> GetHoverPopup(long UserId) { List<MyTeam> objListToReturn = new List<MyTeam>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTeamConstants.const_procGetMyTeam_List; base.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_mode, "HoverPopUpSkill"); base.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTeam>(dt); } return objListToReturn; } public IEnumerable<MyTeam> GetLinemanager(long id) { List<MyTeam> objListToReturn = new List<MyTeam>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTeamConstants.const_procgetLinemanager; base.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_mode, "ApprovedSkill"); base.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_UserId, id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTeam>(dt); } return objListToReturn; } public IEnumerable<MyTeam> GetSkill(long SkillID) { List<MyTeam> objListToReturn = new List<MyTeam>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyTeamConstants.const_procSkillLeavel; base.objSqlCommand.Parameters.AddWithValue(MyTeamConstants.const_Field_SkillID, SkillID); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyTeam>(dt); } return objListToReturn; } public string DeleteSkill(int SkillID, long UserId) { try { return null; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~MyTeamRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using VIS_Domain; using VIS_Domain.Reports.Attendance; using System.Data.SqlClient; namespace VIS_Repository.Reports.Attendance { public class ProductivityTrackerReportRepository : VISDbCommand { public ProductivityTrackerReportRepository(string _connectionstring) : base(_connectionstring){} public IEnumerable<FillDP> FillDepartment() { List<FillDP> objListToReturn = new List<FillDP>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_procAttendanceReportNew_SelectAll; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode, "Department"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillDP>(dt); } return objListToReturn; } public IEnumerable<EmployeeList> FillEmployee(Int64 UserId, Boolean InActive) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_procGetEmployeeForOutReport; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode, "allemp"); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_empid, UserId); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_InActive,InActive); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public IEnumerable<EmployeeList> FillAllEmployees(Int64 UserId, Boolean Allow) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode, "GetAllEmployee"); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_Allow, Allow); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public IEnumerable<LineManager> FillLineManager(Int64 UserId, Boolean Allow) { List<LineManager> objListToReturn = new List<LineManager>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode, "FillAllLineManager"); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_Allow, Allow); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<LineManager>(dt); } return objListToReturn; } public IEnumerable<Lookup> FillLookup() { List<Lookup> objListToReturn = new List<Lookup>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode, "GetlookupType"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<Lookup>(dt); } return objListToReturn; } public IEnumerable<YearData> FillYear() { List<YearData> objListToReturn = new List<YearData>(); DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode, "Year"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<YearData>(dt); } return objListToReturn; } public DataTable GetProductivity(string sort, string FromDate, string ToDate, string Employeeids, string Mode, string OutIds, string Consolidatedview, string chk) { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_Proc_productivityTracker; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_sort,sort); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_fromDate,FromDate); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_toDate,ToDate); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_Employeelist,Convert.ToString(Employeeids)); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode,Mode); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_OutType,OutIds); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_Consolidate,Consolidatedview); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_Out,chk); base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.Const_Field_Duration,""); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable FillOverall() { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProductivityTrackerReportConstants.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(ProductivityTrackerReportConstants.const_Field_Mode, "GetOverAllEmployee"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class DailyEntrysheetEmployee:VISBaseEntity { public string Employee_Name { get; set; } public string Date { get; set; } public string Entry_Type { get; set; } public string Entry_Time { get; set; } public string actualEntryTime { get; set; } public string Remarks { get; set; } public int Grace { get; set; } public Int64 Transaction_Id { get; set; } } public class DailyEntrysheetTime { public string TotalOfficeTime { get; set; } public string TotalWorkingTime { get; set; } public string TotalBreakTime { get; set; } public string TotalWorksheetHours { get; set; } } public class EmployeeMaster { public Int64 Id { get; set; } public string Employee_Name { get; set; } } public static class DailyEntrysheetConstant { public const string const_procReportPerEmp = "procReportPerEmp"; public const string const_ProcCalTotalAttendanceReport = "ProcCalTotalAttendanceReport"; public const string const_ProcCalTotalAttendanceReportAllEmployee = "ProcCalTotalAttendanceReportAllEmployee"; public const string const_procEmployee_Master_SelectAll = "procEmployee_Master_SelectAll"; public const string const_procreportRecordUpdate = "procreportRecordUpdate"; } public static class DailyEntrysheetParamaterConstant { public const string const_Mode = "mode"; public const string const_EmployeeId = "empid"; public const string const_ForWhichDate = "forWhichDate"; public const string const_LoginUserId = "LoginUserId"; public const string const_EmployeeID = "EmployeeID"; public const string const_Date = "Date"; public const string const_Time = "Time"; public const string const_actualEntryTime = "actualEntryTime"; public const string const_Remarks = "Remarks"; public const string const_grace = "grace"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Notification { public class Policy : VISBaseEntity { /// <summary> /// Policy Entity Fields. /// </summary> public string Policy_Name { get; set; } public string Description { get; set; } public bool IsNewPolicy { get; set; } } public static class PolicyConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Policy = "Policy"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Policy_Name = "Policy_Name"; public const string const_Field_Description = "Description"; public const string const_Field_IsNewPolicy = "IsNewPolicy"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procPolicy_Add = "procPolicy_Add"; public const string const_procPolicy_Update = "procPolicy_Update"; public const string const_procPolicy_ActiveInActive = "procPolicy_ActiveInActive"; public const string const_procPolicy_SelectAll = "procPolicy_SelectAll"; public const string const_procPolicy_SelectById = "procPolicy_SelectById"; public const string const_procPolicy_View = "procPolicy_View"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../app/Shared/global"); var pager_index_1 = require("../../../app/Shared/pager.index"); var router_1 = require("@angular/router"); var http_1 = require("@angular/http"); var AttendanceEntry_Service_1 = require("../../Service/UserManagement/AttendanceEntry.Service"); var AttendanceEntryComponent = (function () { function AttendanceEntryComponent(fb, _AttendanceEntryService, http, router, pagerService) { this.fb = fb; this._AttendanceEntryService = _AttendanceEntryService; this.http = http; this.router = router; this.pagerService = pagerService; this.indLoading = false; } AttendanceEntryComponent.prototype.ngOnInit = function () { var _this = this; this.modal.open(); $("#rdbpunchout").prop("disabled", true); $("#rdbLunchout").prop("disabled", true); $("#rdbLunchin").prop("disabled", true); $("#rdbotherout").prop("disabled", true); $("#rdbotherin").prop("disabled", true); $("#rdbmeetingout").prop("disabled", true); $("#rdbmeetingin").prop("disabled", true); $("#rdbOffworkout").prop("disabled", true); $("#rdbOffworkin").prop("disabled", true); this.GetEmployeeName(); this.CheckIsPunchOutOnNextDay(); setInterval(function () { _this.Datetime = new Date(); }, 1000); this.Datetime = new Date(); var month = this.Datetime.getMonth() + 1; var year = this.Datetime.getFullYear(); var date1 = this.Datetime.getDate(); this.Date = +month + '/' + this.Datetime.getDate() + '/' + this.Datetime.getFullYear(); this.forewhichdate = +month + '/' + this.Datetime.getDate() + '/' + this.Datetime.getFullYear(); this.GetTimer(); if (this.Entry_Type == 0) { this.DisableEntry_Type(); } else { this.EnableEntry_Type(); } this.AttendanceEntryFrm = this.fb.group({ Employee_Id: [''], Entry_Type: [''], Remarks: [''], Entry_Time: [''], Date: [''], actualEntryTime: [''], grace: [''], macID: [''], forWhichDate: [''], ipAddress: [''], source: [''], isApproved: [''], groupId: [''], attendancePolicy: [''], Grade: [''], ImportRemarks: [''], Days: [''], forWhichEntryType: [''] }); this.AttendanceEntryTimer = [{ TotalOfficeTime: null, TotalPunchInHours: null, TotalBreakTime: null, TotalWorkingTime: null, PunchIn: 0, InBreak: 0 }]; this.AttendanceEmployeeName = ({ Employee_Id: 0, Employee_Name: '' }); }; AttendanceEntryComponent.prototype.DisableEntry_Type = function () { var punchout = document.getElementById("rdbpunchout"); var LunchOut = document.getElementById("rdbLunchout"); var Lunchin = document.getElementById("rdbLunchin"); var Otherchout = document.getElementById("rdbotherout"); var OtherIn = document.getElementById("rdbotherin"); var MeetingOut = document.getElementById("rdbmeetingout"); var meetingIn = document.getElementById("rdbmeetingin"); var Officialworkout = document.getElementById("rdbOffworkout"); var Officialworkin = document.getElementById("rdbOffworkin"); punchout.disabled = true; LunchOut.disabled = true; Lunchin.disabled = true; Otherchout.disabled = true; OtherIn.disabled = true; MeetingOut.disabled = true; meetingIn.disabled = true; Officialworkout.disabled = true; Officialworkin.disabled = true; }; AttendanceEntryComponent.prototype.EnableEntry_Type = function () { var punchout = document.getElementById("rdbpunchout"); var LunchOut = document.getElementById("rdbLunchout"); var Lunchin = document.getElementById("rdbLunchin"); var Otherchout = document.getElementById("rdbotherout"); var OtherIn = document.getElementById("rdbotherin"); var MeetingOut = document.getElementById("rdbmeetingout"); var meetingIn = document.getElementById("rdbmeetingin"); var Officialworkout = document.getElementById("rdbOffworkout"); var Officialworkin = document.getElementById("rdbOffworkin"); punchout.disabled = false; LunchOut.disabled = false; Lunchin.disabled = false; Otherchout.disabled = false; OtherIn.disabled = false; MeetingOut.disabled = false; meetingIn.disabled = false; Officialworkout.disabled = false; Officialworkin.disabled = false; }; AttendanceEntryComponent.prototype.GetTimer = function () { var _this = this; this.indLoading = true; this._AttendanceEntryService.getTime(global_1.Global.BASE_AttendanceEntry_ENDPOINT, 21, this.Date) .subscribe(function (sucess) { _this.AttendanceEntryTimer = sucess; _this.AttendanceEntryTime = sucess; _this.indLoading = false; _this.AttendanceEntryTimer.forEach(function (sucess) { _this.PunchInHours = sucess.TotalPunchInHours; _this.WorkingTime = sucess.TotalWorkingTime; _this.BreakTime = sucess.TotalBreakTime; if (_this.PunchInHours == null) { document.getElementById("lblPunchTime").innerHTML = "00:00:00"; } else { _this.PunchInHours; } if (_this.WorkingTime == null) { document.getElementById("lblWorkTime").innerHTML = "00:00:00"; } else { _this.WorkingTime; } if (_this.BreakTime == null) { document.getElementById("lblBreakTime").innerHTML = "00:00:00"; } else { _this.BreakTime; } }); }, function (error) { alert("Error"); }); }; AttendanceEntryComponent.prototype.CheckIsPunchOutOnNextDay = function () { var _this = this; this.indLoading = true; this._AttendanceEntryService.GetPunchOutNextDay(global_1.Global.BASE_AttendanceEntry_ENDPOINT, 199, '04/01/2016') .subscribe(function (data) { _this.AttendancePunchOutonNextDay = data; _this.indLoading = false; }); }; AttendanceEntryComponent.prototype.GetEmployeeName = function () { var _this = this; this.indLoading = true; this._AttendanceEntryService.GetEmployeeName(global_1.Global.BASE_AttendanceEntry_ENDPOINT, 21) .subscribe(function (success) { _this.AttendanceEmployee = success; console.log(_this.AttendanceEmployeeName); }, function (error) { alert("error"); }); }; AttendanceEntryComponent.prototype.onsubmit = function (formData) { var _this = this; this.msg = ""; this._AttendanceEntryService.post(global_1.Global.BASE_AttendanceEntry_ENDPOINT, formData) .subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.AttendanceEntrys = data; } else { alert(data); } }, function (error) { _this.msg = error; }); }; __decorate([ core_1.ViewChild('modalAttendanceEntry'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceEntryComponent.prototype, "modal", void 0); AttendanceEntryComponent = __decorate([ core_1.Component({ providers: [AttendanceEntry_Service_1.AttendanceEntryService], templateUrl: 'app/Components/UserManagement/AttendanceEntry.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, AttendanceEntry_Service_1.AttendanceEntryService, http_1.Http, router_1.Router, pager_index_1.PagerService]) ], AttendanceEntryComponent); return AttendanceEntryComponent; }()); exports.AttendanceEntryComponent = AttendanceEntryComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class ContactMaster : VISBaseEntity { /// <summary> /// ContactMaster Entity Fields. /// </summary> public string Name { get; set; } public string Designation { get; set; } public string Email { get; set; } public string phone { get; set; } public string SkypeId { get; set; } public string MsnId { get; set; } public string GtalkId { get; set; } public string AolId { get; set; } public string Other { get; set; } public int ProspectId { get; set; } } public static class ContactMasterConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_ContactMaster = "ContactMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Name = "Name"; public const string const_Field_Designation = "Designation"; public const string const_Field_Email = "Email"; public const string const_Field_phone = "phone"; public const string const_Field_SkypeId = "SkypeId"; public const string const_Field_MsnId = "MsnId"; public const string const_Field_GtalkId = "GtalkId"; public const string const_Field_AolId = "AolId"; public const string const_Field_Other = "Other"; public const string const_Field_ProspectId = "ProspectId"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procContactMaster_Add = "procContactMaster_Add"; public const string const_procContactMaster_Update = "procContactMaster_Update"; public const string const_procContactMaster_ActiveInActive = "procContactMaster_ActiveInActive"; public const string const_procContactMaster_SelectAll = "procContactMaster_SelectAll"; public const string const_procContactMaster_SelectBaseNonBase = "procContactMaster_SelectBaseNonBase"; public const string const_procContactMaster_SelectById = "procContactMaster_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master.Configuration; namespace VIS_Repository.Reports { public class EmployeeScreenCaptureReportRepository : VISDbCommand { int intAffectedRecords; public EmployeeScreenCaptureReportRepository(string _connectionstring) : base(_connectionstring) { } public DataTable GetEmployee() { string mode = "Employee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetYear() { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeScreenCaptureReportConstant.const_procFinancialYear_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetScreenCaptureReportByEmployeeId(EmployeeScreenCaptureParamterModel entityobject) { DataTable dt = new DataTable(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeScreenCaptureReportConstant.const_procEmployee_ScreenCaptureReport; objSqlCommand.Parameters.AddWithValue(EmployeeScreenCaptureReportConstant.const_EmployeeId, entityobject.EmployeeId); objSqlCommand.Parameters.AddWithValue(EmployeeScreenCaptureReportConstant.const_FromDate,entityobject.FromDate); objSqlCommand.Parameters.AddWithValue(EmployeeScreenCaptureReportConstant.const_ToDate,entityobject.ToDate); objSqlCommand.Parameters.AddWithValue(EmployeeScreenCaptureReportConstant.const_OrderBy, entityobject.OrderBy); objSqlCommand.Parameters.AddWithValue(EmployeeScreenCaptureReportConstant.const_LoginUserId, entityobject.LoginUserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch (Exception) { } return dt; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Notification; namespace VIS_Repository.Notification { public class TicketListClosedRepository : VISDbCommand, VISIBaseRepository<TicketListClosed> { public Int32 intAffectedRecords { get; set; } public string strUserType { get; set; } public TicketListClosedRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = TicketListClosedConstants.const_procHelpTicket_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public TicketListClosed GetEntityByID(Int64 Id) { return null; } public IEnumerable<TicketListClosed> GetEntityList() { return null; ; } public string AddEntity(TicketListClosed entityObject) { return null; } public string UpdateEntity(TicketListClosed entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = TicketListClosedConstants.const_procHelpTicket_update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Remarks, entityObject.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Priority, entityObject.Priority); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); #region helpTickeMsaterLog objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = TicketListClosedConstants.const_procHelpTicketMasterLog; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.cons_Filed_HelpTicketId, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Subject, entityObject.Subject); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Remarks, entityObject.Remarks); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = TicketListClosedConstants.const_procHelpTicket_selectAll; base.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Mode, "SelectID"); base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da1 = new SqlDataAdapter(base.objSqlCommand); DataSet ds1 = new DataSet(); ds1.Clear(); da1.Fill(ds1); base.objSqlCommand.Connection.Close(); base.objSqlCommand.Parameters.Clear(); if (ds1.Tables[0].Rows.Count > 0 || ds1 != null) { Int64 EmpId = Convert.ToInt64(ds1.Tables[0].Rows[0][0]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_AssignTo, EmpId); Int64 AdId = Convert.ToInt64(ds1.Tables[0].Rows[0][1]); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_AddressToGroup, AdId); string Message = ds1.Tables[0].Rows[0]["Message"].ToString(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Message, Message); } objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Priority, entityObject.Priority); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, 21); #endregion helpTickeMsaterLog base.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<TicketListClosed> GetTicketByUserOpen(int UserId) { List<TicketListClosed> objListToReturn = new List<TicketListClosed>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = TicketListClosedConstants.const_procHelpTicketDetailByAssignToUser; if (strUserType == "admin") { base.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Mode, "allAdminClosed"); } else { base.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_Mode, "allAddressedClosed"); } base.objSqlCommand.Parameters.AddWithValue(TicketListClosedConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<TicketListClosed>(dt); } return objListToReturn; } public IEnumerable<TicketListClosed> GetViewHistory(Int64 Id) { List<TicketListClosed> objListToReturn = new List<TicketListClosed>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = TicketListClosedConstants.const_procHelpTicketHistory_History; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<TicketListClosed>(dt); } return objListToReturn; } public IEnumerable<TicketListClosed> GetTicketDetail(Int64 Id) { List<TicketListClosed> objListToReturn = new List<TicketListClosed>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = TicketListClosedConstants.const_procHelpTicket_SelectById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<TicketListClosed>(dt); } return objListToReturn; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/topromise'; import { Router } from '@angular/router'; import { Global } from '../Shared/global'; @Injectable() export class HomeService { constructor(private http: Http, private router: Router) { } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var Position_service_1 = require("../../Service/Masters/VacancyRelated/Position.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../Shared/enum"); var global_1 = require("../../Shared/global"); var pager_index_1 = require("../../Shared/pager.index"); var PositionComponent = (function () { function PositionComponent(fb, _PositionService, pagerService) { this.fb = fb; this._PositionService = _PositionService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'PositionName'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; } PositionComponent.prototype.ngOnInit = function () { this.PositionFrm = this.fb.group({ CompanyId: [''], Id: [''], PositionName: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(100)])], Remarks: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(100)])], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], EntityMessage: [''], IsActive: [''] }); this.LoadPosition(); }; PositionComponent.prototype.PositionFilterCriteriaChange = function (value) { if (value != '[object Event]') this.PositionFilter = value; }; PositionComponent.prototype.PositionSort = function (property) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; }; ; PositionComponent.prototype.LoadPosition = function () { var _this = this; this.indLoading = true; this._PositionService.get(global_1.Global.BASE_POSITION_ENDPOINT) .subscribe(function (positions) { _this.positions = positions; _this.indLoading = false; // set items to json response // initialize to page 1 _this.JumpOnPage(1); _this.pager = _this.pagerService.pager; _this.pagedItems = _this.pagerService.pagedItems; } //,error => this.msg = <any>error ); }; PositionComponent.prototype.AddPosition = function () { this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Position"; this.modalBtnTitle = "Add"; this.PositionFrm.reset(); this.modal.open(); }; PositionComponent.prototype.EditPosition = function (id) { this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Position"; this.modalBtnTitle = "Update"; this.position = this.positions.filter(function (x) { return x.Id == id; })[0]; this.PositionFrm.setValue(this.position); this.modal.open(); }; PositionComponent.prototype.DeletePosition = function (id, status) { debugger; this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.position = this.positions.filter(function (x) { return x.Id == id; })[0]; this.PositionFrm.setValue(this.position); this.modal.open(); }; PositionComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.PositionFrm.enable() : this.PositionFrm.disable(); }; PositionComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; PositionComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.positions); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; PositionComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._PositionService.post(global_1.Global.BASE_POSITION_ENDPOINT, formData._value).subscribe(function (data) { if (data == "Success") { _this.msg = "Position added successfully."; _this.LoadPosition(); } else { _this.msg = "Error has occurred while adding new Position!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._PositionService.put(global_1.Global.BASE_POSITION_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data == "Success") { _this.msg = "Position modified successfully."; _this.LoadPosition(); } else { _this.msg = "Error has occurred while modifying existing Position!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._PositionService.delete(global_1.Global.BASE_POSITION_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data == "Success") { _this.msg = "Position status changed successfully."; _this.LoadPosition(); } else { _this.msg = "Error has occurred while changing status of existing Position!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], PositionComponent.prototype, "modal", void 0); PositionComponent = __decorate([ core_1.Component({ providers: [Position_service_1.PositionService], templateUrl: 'app/Components/Masters/Position.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, Position_service_1.PositionService, pager_index_1.PagerService]) ], PositionComponent); return PositionComponent; }()); exports.PositionComponent = PositionComponent; <file_sep>export interface IMyProfiles { Mode: string; UserId: number; Employee_Name: string; LineManagerName: string; FirstName: string; MiddleName: string; LastName: string; Gender: string; PhotographFileName: string; CompanyName: string; Email: string; Designation: string; DepartmentName: string; FatherName: string; MotherName: string; PermenantAddres: string; CommunicationAddress: string; LandlineNumber: string; MobileNumber: string; BirthDate: string; BloodGroup: string; MaritalStatus: string; ClassDegree: string; SchoolInstitute: string; Medium: string; PassingYear: number; BoardUniversity: string; Percentage: string; //Employee_Id: number; }<file_sep>export interface IEmpInfoTabular { EditEmployeeid: string; Editmode: string; returnid: number; mode: string; id: number; URoleId: number; PositionId: number; DepartmentID: number; PID: number; EID: number; EducationID: number; EmployeeID: number; TechnologyID: number; technologyName: string; CompanyName: string; Employee_Name: string; Name: string; positionName: string; Department_name: string; Remarks: string; UserId: number; SalaryRangeId: number; Salary: number; salaryrangetitle: string; Value: number; Parentid: number; NonWorkingDay: string; NWID: number; IntimeMondayToFridayHH: number; IntimeMondayToFridayMM: number; IntimeSaturdayHH: number; IntimeSaturdayMM: number; OutTimeMondayToFridayHH: number; OutTimeMondayToFridayMM: number; OutTimeSaturdayHH: number; OutTimeSaturdayMM: number; CompanyId: number; strCode: string; EmployeeName: string; FirstName: string; MiddleName: string; LastName: string; Password: <PASSWORD>; Email: string; Active: boolean; UserType: string; JoiningDate: Date; RelevingDate: Date; ResignedDate: Date; TotalCL: number; TotalSl: number; AdditionalRights: number; ValidForLogin: boolean; Employeecode: string; ProbationTill: Date; ActivityId: number Gender: boolean; IsConfirmed: boolean; JoiningSalary: number; JoiningDesignation: number; PhotographFileName: string; SalaryAfterRevision: number; IsSLASigned: boolean; ConfirmationDate: Date; AppraisalDate: Date; IsAppraisalRequired: boolean; SLAYear: number; Technology: string; OtherTechnology: string; LineManagerID: number; WorkingLocation: number; WorkingLocationAddress: string; CommunicationID: string; OtherRemark: string; IsWebAccess: boolean; WorksheetThruWeb: boolean; IsSwitchUser: boolean; AllowScreenCapture: boolean; IsWorksheetFill: boolean; IsConfirmationLeave: boolean; EmployeeGradeID: number; IsResigned: boolean; isMailAlert: boolean; IsAllowMouseMovement: boolean; CreatedDateTime: Date; IsMouseTracking: boolean; IsScreenCaptureRemarks: boolean; IsHost: boolean; IsHostForEmpMaster: boolean; IsProductivityTracker: boolean; WorkFromHome: boolean; Sar: number; YearEducation: string; joingdate:string; Designation: string; SLASigned: string Department:string } export interface IPersonalInformation { EditEmployeeid: string; Editmode: string; FatherName: string; Birthdate: Date; Paddress: string; Caddress: string; Landlineno: string; Mobileno: string; Emergencyno: string; Age: number; Bloodgroup: string; Status: string; Spouse: string; Numberofchild: number; Childname: string; AnniversaryDate: Date; Grandfathername: string; Spousedob: string; MotherName: string; BrotherName: string; SisterName: string; FatherOccupation: string; MotherOccupation: string; BrotherOccupation: string; SisterOccupation: string; SpouseOccupation: string; } export interface IEducationInformation { EditEmployeeid: string; Editmode: string; Eduid: number; UserId: number; HighestEducation: boolean; ClassDegree: string; Schoolinstitute: string; Medium: string; Passingyear: number; Boarduniversity: string; Percentage: number; mode: string; } export interface IExperienceInformation { EditEmployeeid: string; Editmode: string; RoleId: number; RoleName: string; Efficiency: number; ExpRoleId: number; Expid: number; Skills: string; Totalexp: string; Org: string; Url: string; Designation: string; Joiningdate: string; Relievingdate: string; Reportingto: string; Contactno: string; Reason: string; Lastsalary: string; experiencesummary: string; skills: string; ProjectHandled: string; RelevanceExp: string; expyear: number; expmonth: number; relevanceExpYear: string; relevanceExpMonth: string; hdnProjectsToSave: string; } export interface ISalaryInformation { EditEmployeeid: string; Editmode: string; UserId: number; Salary: number; Bankname: string; Accountno: string; PFAccountNo: string; CurrentDesignation: string; ISPFApplicable: boolean; AdharNumber: number; UANNumber: number; Employee_Name: string; Type: string; } export interface IAttendanceInformation { EditEmployeeid: string; Editmode: string; UserId: number; Intime: string; Outitme: string; Intimesat: string; Outtimesat: string; Grace: number; Leaveapproveby: number; SatGrace: number; IsAlertRequired: boolean; AccessCardId: number; UpdatedBy: number; AttendancePolicy: string; Nwdday: string; NWID: number; Output: string; } export interface IJoiningInformation { EditEmployeeid: string; Editmode: string; Panno: string; Passportno: string; Placeofissue: string; Issuedate: Date; Expirydate: Date; Isrelevingletter: boolean; Isexperienceletter: boolean; Issalaryslip: boolean; IsDegreeCertificate: boolean; IsMarkSheet: boolean; IsPassport: boolean; Isdrivinglicense: boolean; Ispancard: boolean; Iscv: boolean; Isother: boolean; Other: string; RelievingLetterFileName: string; ExperienceLetterFileName: string; LastSalarySlipFileName: string; DegreeCertificateFileName: string; LastMarksheetFileName: string; PassportFileName: string; DrivingLicenseFileName: string; PANCardFileName: string; CurriculamVitaeFilName: string; OtherFileName: string; OtherFileName0: string; OtherFileName1: string; Other0: string; Other1: string; HR_Remark: string; Isother0: boolean; Isother1: boolean; } export interface IIncrementformation { EditEmployeeid: string; Editmode: string; Incrementdate: Date; Designationchange: number; Increment: number; Salarychange: number; Isfirst: boolean; Incrementid: number; AppraisalDate: Date; SalaryRangeId: number; } export interface IOfficialInformation { EditEmployeeid: string; Editmode: string; Verveemail: string; Vervepassword: string; Gmail: string; Gmailpassword: string; Yahoo: string; Yahoopassword: string; Skype: string; Skypepassword: string; Othersitename: string; Otherid: string; Otherpassword: string; } export interface IProjectInfoFrm { EditEmployeeid: string; Editmode: string; FromDate: string; ToDate: string; UserId: number; } export interface ILeaveInfoFrm { EditEmployeeid: string; Editmode: string; Leavetype: string; Balance: number; Transactiontype: string; Isadjusted: boolean; AdjustedValue: number; Lastyear: string; UUPLBalance: number; Leavedate: Date; Createddate: Date; Remarks: string; Leavename: string; Isaupl: boolean; leavestartdate: string; leaveenddate: string; } export interface IMySkillFrm { EditEmployeeid: string; Editmode: string; Name: string; lookupSkilId: number; SkillName: string; id: number; } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var MacIdConfigurationFilterPipe = (function () { function MacIdConfigurationFilterPipe() { } MacIdConfigurationFilterPipe.prototype.transform = function (value, filter) { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter(function (app) { return app.MacID != null && app.MacID.toLocaleLowerCase().indexOf(filter) != -1 || app.IPAddress != null && app.IPAddress.toLocaleLowerCase().indexOf(filter) != -1 || app.Version != null && app.Version.toLocaleLowerCase().indexOf(filter) != -1; }) : value; }; MacIdConfigurationFilterPipe = __decorate([ core_1.Pipe({ name: 'macidconfigurationFilter' }) ], MacIdConfigurationFilterPipe); return MacIdConfigurationFilterPipe; }()); exports.MacIdConfigurationFilterPipe = MacIdConfigurationFilterPipe; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class SalaryBreakupType : VISBaseEntity { /// <summary> /// SalaryBreakupType Entity Fields. /// </summary> /// public string Name { get; set; } public string Type { get; set; } public string FullName { get; set; } } public static class SalaryBreakupTypeConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_SalaryBreakupType_Table = "SalaryBreakupType"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Name = "Name"; public const string const_Type = "Type"; public const string const_FullName = "FullName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procSalaryBreakupType_Add = "procSalaryBreakupType_Add"; public const string const_procSalaryBreakupType_Update = "procSalaryBreakupType_Update"; public const string const_procSalaryBreakupType_ActiveInActive = "procSalaryBreakupType_ActiveInActive"; public const string const_procSalaryBreakupType_SelectAll = "procSalaryBreakupType_SelectAll"; public const string const_procSalaryBreakupType_SelectById = "procSalaryBreakupType_SelectById"; } } <file_sep>export interface IEventCountDown { Id: number; EventName: string; CountDownText: string; CountDownDate: string; CountDownTime: string; CountDownDateTime: string; NoOfDay: number; Active: boolean; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; CompanyId: number; EntityMessage: string; }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { ISalaryBreakupType } from '../../../Model/Masters/CompanyRelated/SalaryBreakupType'; @Pipe ({ name: 'SalaryBreakupTypeFilter' }) export class SalaryBreakupTypeFilterPipe implements PipeTransform { transform(value: ISalaryBreakupType[], filter: string): ISalaryBreakupType[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: ISalaryBreakupType) => app.Name != null && app.Name.toLocaleLowerCase().indexOf(filter) != -1 || app.FullName != null && app.FullName.toLocaleLowerCase().indexOf(filter) != -1 || app.Type != null && app.Type.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/topromise'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Router } from '@angular/router'; import { Global } from '../../../app/Shared/global'; @Injectable() export class LoginService { public token: string; // This is where your methods and properties go, for example: constructor(private http: Http, private router: Router) { } /** * // Encodes the parameters. * * @param params The parameters to be encoded * @return The encoded parameters */ //private encodeParams(params: any): string { // let body: string = ""; // for (let key in params) { // if (body.length) { // body += "&"; // } // body += key + "="; // body += encodeURIComponent(params[key]); // } // return body; //} public doLogin(loginObj: any): Observable<any> { let urltohit = Global.BASE_VISUSER_ENDPOINT + 'PostUserByUserIdPassword'; let body = JSON.stringify(loginObj); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(urltohit, body, options) .map((response: Response) => <any>response.json()) } public GetActivateImagePath(): Observable<any> { let urltohit = Global.BASE_VISUSER_ENDPOINT + 'GetActivateLoginImage'; return this.http.get(urltohit).map((response: Response) => <any>response.json()) } public ForgotPassword(loginObj: any, model: any): Observable<any> { let urltohit = Global.BASE_FORGOTPASSWORD_ENDPOINT + 'GetForgotPassword?Email=' + model.VISUsername ; let body = JSON.stringify(loginObj); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.get(urltohit) .map((response: Response) => <any>response.json()) } logout(): void { // clear token remove user from local storage to log user out this.token = null; sessionStorage.clear(); } }<file_sep>import { DatePipe } from '@angular/common'; import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { ManualPointEntryService } from '../../../service/Masters/EmployeeLevels/ManualPointEntry.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IManualPointEntry,IEmployeeTag } from '../../../Model/Masters/EmployeeLevels/ManualPointEntry'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { IMultiSelectOption } from 'angular-2-dropdown-multiselect'; @Component({ //selector: 'ss-multiselect-dropdown', providers: [ManualPointEntryService], templateUrl: 'app/Components/Masters/EmployeeLevels/ManualPointEntry.component.html', //styleUrls: ['./dropdown.component.css'], }) export class ManualPointEntryComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; ManualPointEntrys: IManualPointEntry[]; ListCriteria: IManualPointEntry[]; ListCategory: IManualPointEntry[]; DataOnCriteria: IManualPointEntry; public ManualPointEntry: IManualPointEntry; EmployeeTag: IEmployeeTag[]; msg: string; indLoading: boolean = false; ManualPointEntryFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; ManualPointEntryFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strsearchEmpName: string; strsearchCriteria: string; strsearchRemarks: string; strSearchManualPointEntryDetails: string; //////////////////////////////// optionsModel: number[]; myOptions: IMultiSelectOption[]; //myOptions: IMultiSelectOption[]; IMultiSelectOption: IEmployeeTag[]; //////////////////////////////// constructor(private fb: FormBuilder, private _ManualPointEntryService: ManualPointEntryService, private pagerService: PagerService) { } ngOnInit(): void { this.ManualPointEntry ={ Id: 0, GroupID: 0, EmpName: "", Criteria: "", Points: 0, Point:0, Month: null, Remarks: "", Category: "", Type: "", ForDate: null, CriteriaId: 0, IsPerformanceBadge: false, CategoryId: 0, CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, EntityMessage: "" }; this.TestMultidll() this.LoadManualPointEntrys() this.LoadCriteria() this.LoadCategory() this.LoadEmployee() } LoadEmployee(): void { debugger; this._ManualPointEntryService.GetEmployeeList(Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(DATA => { this.IMultiSelectOption = DATA; debugger; } //,error => this.msg = <any>error ); } TestMultidll(): void { debugger; this.myOptions = [ { id: 6, name: 'Option 1'}, { id: 7, name: 'Option 2' }, { id: 8, name: 'Option 3' } ]; } onChange() { console.log(this.optionsModel); } LoadCriteria(): void { this._ManualPointEntryService.getCriteria(Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(DATA => { this.ListCriteria = DATA; } //,error => this.msg = <any>error ); } LoadCategory(): void { this._ManualPointEntryService.getCategory(Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(DATA => { this.ListCategory = DATA; } //,error => this.msg = <any>error ); } ManualPointEntryFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.ManualPointEntryFilter = value; } ManualPointEntrySort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadManualPointEntrys(): void { this.indLoading = true; this._ManualPointEntryService.get(Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(ManualPointEntrys => { this.ManualPointEntrys = ManualPointEntrys; //Logic for searching - start if (this.ShowHideSearch) { this.strsearchEmpName = (<HTMLInputElement>document.getElementById("searchEmpName")).value; if (this.strsearchEmpName != '') { this.strsearchEmpName = this.strsearchEmpName.toLocaleLowerCase(); this.ManualPointEntrys = this.ManualPointEntrys.filter( x => x.EmpName != null && x.EmpName.toLocaleLowerCase().indexOf(this.strsearchEmpName) != -1); } } if (this.ShowHideSearch) { this.strsearchCriteria = (<HTMLInputElement>document.getElementById("searchCriteria")).value; if (this.strsearchCriteria != '') { this.strsearchCriteria = this.strsearchCriteria.toLocaleLowerCase(); this.ManualPointEntrys = this.ManualPointEntrys.filter( x => x.Criteria != null && x.Criteria.toLocaleLowerCase().indexOf(this.strsearchCriteria) != -1); } } if (this.ShowHideSearch) { this.strsearchRemarks = (<HTMLInputElement>document.getElementById("searchRemarks")).value; if (this.strsearchRemarks != '') { this.strsearchRemarks = this.strsearchRemarks.toLocaleLowerCase(); this.ManualPointEntrys = this.ManualPointEntrys.filter( x => x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(this.strsearchRemarks) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addManualPointEntry() { this.dbops = DBOperation.create; // this.SetControlsState(true); this.modalTitle = "Add New ManualPointEntry"; this.modalBtnTitle = "Add"; //this.ManualPointEntryFrm.reset(); this.modal.open(); } editManualPointEntry(id: number) { this.dbops = DBOperation.update; // this.SetControlsState(true); this.modalTitle = "Edit ManualPointEntry"; this.modalBtnTitle = "Update"; this.ManualPointEntry = this.ManualPointEntrys.filter(x => x.Id == id)[0]; // this.ManualPointEntryFrm.setValue(this.ManualPointEntry); this.modal.open(); } deleteManualPointEntry(id: number, status: boolean) { this.dbops = DBOperation.delete; //this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.ManualPointEntry = this.ManualPointEntrys.filter(x => x.Id == id)[0]; // this.ManualPointEntryFrm.setValue(this.ManualPointEntry); this.modal.open(); } //SetControlsState(isEnable: boolean) { // isEnable ? this.ManualPointEntryFrm.enable() : this.ManualPointEntryFrm.disable(); //} ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ChangeCriteria(CriteriaId: number) { this._ManualPointEntryService.GetDataOnChange(Global.BASE_ManualPointEntry_ENDPOINT,CriteriaId) .subscribe(DATA => { this.DataOnCriteria = DATA; // this.ManualPointEntry = this.DataOnCriteria; if (this.DataOnCriteria.IsPerformanceBadge == false) { this.ManualPointEntry.Type = "Manual"; } else { this.ManualPointEntry.Type = "Performance Badges"; } this.ManualPointEntry.Points = this.DataOnCriteria.Point; this.ManualPointEntry.CategoryId = this.DataOnCriteria.CategoryId } //,error => this.msg = <any>error ); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.ManualPointEntrys); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { debugger; this.msg = ""; switch (this.dbops) { case DBOperation.create: debugger; formData.EmpName = formData.EmpName.toString(); this._ManualPointEntryService.post(Global.BASE_ManualPointEntry_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadManualPointEntrys(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._ManualPointEntryService.put(Global.BASE_ManualPointEntry_ENDPOINT, formData._value.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadManualPointEntrys(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._ManualPointEntryService.delete(Global.BASE_ManualPointEntry_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "ManualPointEntry status changed successfully."; this.LoadManualPointEntrys(); } else { this.msg = "Error has occurred while changing status of existing ManualPointEntry!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.UserManagement; using VIS_Repository; using VIS_Repository.UserManagement; namespace VIS_App.Controllers.UserManagement { public class AttendanceEntryApiController : BaseAPIController { AttendanceEntryRepository objAttendanceEntryRepository = new AttendanceEntryRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); [Route("api/AttendanceEntryApi/AddAttendanceEntryDetails")] [HttpPost] public HttpResponseMessage AddAttendanceEntryDetails(AttendanceEntry objAttendance) { return ToJson(objAttendanceEntryRepository.AddEntity(objAttendance).AsEnumerable()); } [Route("api/AttendanceEntryApi/GetTime")] [HttpGet] public HttpResponseMessage GetTime(int Id, string Date) { return ToJson(objAttendanceEntryRepository.GetTimeDetails(Id, Date)); } [Route("api/AttendanceEntryApi/GetPunchOutNextDayDetails")] [HttpGet] public HttpResponseMessage GetPunchOutNextDayDetails(int Id, string Date) { return ToJson(objAttendanceEntryRepository.GetPunchOutonNextday(Id, Date)); } [Route("api/AttendanceEntryApi/GetEmployeeName")] [HttpGet] public HttpResponseMessage GetEmployeeName(int Id) { return ToJson(objAttendanceEntryRepository.GetEmployeeName(Id)); } } } <file_sep>export interface IDepartment { Id: number; Department_Name: string; } export interface IEmployee { Id: number; Employee_Name: string; } export interface ICompany { Id: number; CompanyName: string; } export interface IYear { CurrentYear: string; } export interface ILateEarlyReport { Id: number; Employees_Name: string; LateComing: number; EarlyLeaving: number; LessTime: number; } export interface ParameterModel { Id: number; Fromdate: Date; Todate: Date; MonthWise: boolean; FromMonth: string; FromYear: string; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.VacancyRelated; using VIS_Repository; using VIS_Repository.Masters; namespace VIS_App.Controllers.Masters.VacancyRelated { public class SkillGroupAPIController : BaseAPIController { VISIBaseRepository<SkillGroup> SkillGroupRepository; List<SkillGroup> EntityList = new List<SkillGroup>(); public SkillGroupAPIController(VISIBaseRepository<SkillGroup> _SkillGroupRepository) { SkillGroupRepository = _SkillGroupRepository; } public HttpResponseMessage Get() { return ToJson(SkillGroupRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]SkillGroup value) { return ToJson(SkillGroupRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]SkillGroup value) { return ToJson(SkillGroupRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(SkillGroupRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.UI.WebControls; using VIS_Domain; using VIS_Domain.GeneralHelper; using VIS_Domain.Master.EmployeeManualPointEntry; using VIS_Domain.RFQ; namespace VIS_Repository.RFQ { public class RFQRepository : VISDbCommand { public RFQRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<RFQList> GetEntityList(long EmpId, string Mode) { List<RFQList> objListToReturn = new List<RFQList>(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_RFQEstimateList; base.objSqlCommand.Parameters.AddWithValue(RFQConstants.const_Field_EmpId, EmpId); base.objSqlCommand.Parameters.AddWithValue(RFQConstants.const_Field_Mode, Mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQList>(dt); } } catch (Exception ex) { } return objListToReturn; } public IEnumerable<RFQInitial> FillBusinessHead() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_FillBusinessHead; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> FillBusinessManager(long EmpId) { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetBusinessManager; base.objSqlCommand.Parameters.AddWithValue(RFQConstants.const_Field_EmpId, EmpId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetBusinessType() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetBusinessType; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetProjectType() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetProjectType; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetIndustries() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetIndustries; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetSolution() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetSolution; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetServiceOffering() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetServiceOffering; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetFileType() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetFileType; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetAuthor() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetAuthor; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetTechnology() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_Technology; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetEmployee() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetEmployee; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public IEnumerable<RFQInitial> GetRFQStatus() { List<RFQInitial> objListToReturn = new List<RFQInitial>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetRFQStatus; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RFQInitial>(dt); } return objListToReturn; } public Boolean RFQInitial(RFQInitial mainRFQ) { try { InsertOpportunity(mainRFQ); RFQInitialBase RFQBase = new RFQInitialBase(); RFQInitial rfqInitial = new RFQInitial(); DateTime DateGet; RFQBase.CreatedBy = 0; //Convert.ToInt32(Session["EmpId"].ToString()); // RFQBase.CreatedOn = DateTime.Parse(DateTime.Now.ToString()); RFQBase.IsActive = true; RFQBase.OpportunityID = Convert.ToInt32(GetMaxOpportunity()); DateTime.TryParseExact(mainRFQ.ResponseRequiredBy.ToString().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateGet); //saurabh RFQBase.SubmittedOn = DateGet; RFQBase.SubmittedOn = DateTime.Now; //if (CheckListBox(cbWatchBy) == true) // RFQBase.WatchBy = GetListBoxID(cbWatchBy).ToString(); RFQBase.ResponseRequired = "1"; if (mainRFQ.UserIdList != null) { RFQBase.WatchBy = GetUser(mainRFQ.UserIdList); } if (rfqInitial.Source != null && rfqInitial.Title != "") // Add source ddl data RFQBase.Source = Convert.ToInt32(ddlSource.SelectedItem.Value); //if (CheckListBox(cbResReq) == true) // RFQBase.ResReq = GetListBoxID(cbResReq).ToString(); RFQBase.ResponseRequired = "1"; if (rfqInitial.StatusId != 0) RFQBase.Status = rfqInitial.StatusId; InsertRFQInitail(RFQBase); return true; } catch (Exception ex) { return false; } } public void RFQDoc(List<RFQDoc> rfqDoc, SessionData session) { RFQHelperRepository objHelper = new RFQHelperRepository(base.DatabaseConnection.ConnectionString); RFQDoc objDoc = new RFQDoc(); foreach (var rfq in rfqDoc) { objDoc.ReferenceID = Convert.ToInt64(objHelper.GetMaxRFQInitialId()); objDoc.FileTypeID = Convert.ToInt64(objHelper.GetFileType(rfq.FileType)); objDoc.AuthorId = Convert.ToInt64(objHelper.GetAuther(rfq.Author)); objDoc.OriginalFileName = null; objDoc.IsResponse = false; objDoc.FileName = rfq.FileName; objDoc.Remark = rfq.RemarkDoc; objDoc.CreatedBy = session.SessionId; objDoc.CreatedOn = DateTime.Now; objDoc.IsActive = true; InsertRFQDoc(objDoc); } } public void InsertRFQDoc(RFQDoc entityObject) { try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } int intAffectedRecords; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RFQConstants.const_Field_procRFQDocument_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQDocConstant.const_Field_ReferenceID, entityObject.ReferenceID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQDocConstant.const_Field_OriginalFileName, entityObject.OriginalFileName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQDocConstant.const_Field_FileName, entityObject.FileName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQDocConstant.const_Field_FileTypeID, entityObject.FileTypeID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQDocConstant.const_Field_AuthorId, entityObject.AuthorId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQDocConstant.const_Field_Remark, entityObject.Remark); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQDocConstant.const_Field_IsResponse, entityObject.IsResponse); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (objVISDbCommand.objSqlCommand.Connection.State == ConnectionState.Closed) { objVISDbCommand.objSqlCommand.Connection.Open(); } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } catch (Exception ex) { } } public void RFQLink(List<RFQLink> RFQLink, SessionData session) { RFQLink objLink = new RFQLink(); foreach (var rfq in RFQLink) { RFQHelperRepository objHelper = new RFQHelperRepository(base.DatabaseConnection.ConnectionString); objLink.ReferenceID = Convert.ToInt64(objHelper.GetMaxRFQInitialId()); objLink.URL = rfq.URL; objLink.UserId = rfq.UserId; objLink.Password = <PASSWORD>; objLink.Remark = rfq.RemarkLink; objLink.CreatedBy = session.SessionId; objLink.IsResponse = false; InsertRFQLink(objLink); } } public void InsertRFQLink(RFQLink entityObject) { try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } int intAffectedRecords; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RFQLinkConstant.const_Field_RFQLink_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQLinkConstant.const_Field_ReferenceID, entityObject.ReferenceID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQLinkConstant.const_Field_URL, entityObject.URL); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQLinkConstant.const_Field_UserId, entityObject.UserId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQLinkConstant.const_Field_Password, entityObject.Password); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQLinkConstant.const_Field_Remark, entityObject.Remark); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQLinkConstant.const_Field_IsResponse, entityObject.IsResponse); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (objVISDbCommand.objSqlCommand.Connection.State == ConnectionState.Closed) { objVISDbCommand.objSqlCommand.Connection.Open(); } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } catch (Exception ex) { } } /// <summary> /// helper /// </summary> /// public void InsertRFQInitail(RFQInitialBase entityObject) { try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } int intAffectedRecords; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RFQInitialBaseConstant.const_Field_RFQInitial_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQInitialBaseConstant.const_Field_OpportunityID, entityObject.OpportunityID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQInitialBaseConstant.const_Field_SubmittedOn, entityObject.SubmittedOn); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQInitialBaseConstant.const_Field_WatchBy, entityObject.WatchBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQInitialBaseConstant.const_Field_ResReq, entityObject.ResponseRequired); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQInitialBaseConstant.const_Field_Source, entityObject.Source); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQInitialBaseConstant.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (objVISDbCommand.objSqlCommand.Connection.State == ConnectionState.Closed) { objVISDbCommand.objSqlCommand.Connection.Open(); } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } catch (Exception ex) { } } public void InsertOpportunity(RFQInitial rfqInitial) { RFQOpportunity RFQop = new RFQOpportunity(); RFQInitial RFQ = new RFQInitial(); if (rfqInitial.BusinessHeadId == 0) RFQop.BDHead = 0; else RFQop.BDHead = Convert.ToInt64(rfqInitial.BusinessHeadId); if (rfqInitial.BusinessManagerId == 0) RFQop.BDManager = 0; else RFQop.BDManager = Convert.ToInt64(rfqInitial.BusinessManagerId); DateTime DateGet; //DateTime.TryParseExact(txtInitialDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateGet); RFQop.DateOfInitiation = DateTime.Now; if (!string.IsNullOrEmpty(rfqInitial.ProspectClient)) { RFQop.ProspectId = Convert.ToInt32(GetCompanyId(rfqInitial.ProspectClient.Trim())); RFQop.BillingClient = RFQop.ProspectId; } else { RFQop.ProspectId = 0; RFQop.BillingClient = 0; } if (rfqInitial.BusinessTypeId == 0) RFQop.BussinessType = 0; else RFQop.BussinessType = Convert.ToInt32(rfqInitial.BusinessTypeId); RFQop.BussTechArea = 0; if (rfqInitial.Title == "") RFQop.OpportunityName = " "; else RFQop.OpportunityName = rfqInitial.Title; if (rfqInitial.ProjectTypeId == 0) RFQop.ProjectType = 0; else RFQop.ProjectType = Convert.ToInt32(rfqInitial.ProjectTypeId); if (rfqInitial.IndustryId == 0) RFQop.Industry = 0; else RFQop.Industry = Convert.ToInt32(rfqInitial.IndustryId); if (rfqInitial.ServiceOfferingId == 0) RFQop.serviceOffering = 0; else RFQop.serviceOffering = Convert.ToInt32(rfqInitial.ServiceOfferingId); if (rfqInitial.SolutionId == 0) RFQop.Solution = 0; else RFQop.Solution = Convert.ToInt32(rfqInitial.SolutionId); RFQop.TechBody = 0; if (rfqInitial.ResponseRequiredFrom == 0) RFQop.EstimationDoneBy = 0; else RFQop.EstimationDoneBy = Convert.ToInt32(rfqInitial.ResponseRequiredFrom); // RFQop.ExactTech = GetListBoxID(cbTechnology).ToString(); RFQop.ExactTech = GetTechnology(rfqInitial.TechnologyIdList); RFQop.NextCallDate = Convert.ToDateTime("01/01/1900"); RFQop.TentativeOppClosureDate = Convert.ToDateTime("01/01/1900"); /*RFQop.TentativeStartDate = DateTime.ParseExact(rfqInitial.ExpectedClosureDate.ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);*/ //Convert.ToDateTime("01/01/1900"); RFQop.TentativeStartDate = rfqInitial.ExpectedClosureDate; RFQop.TentativeEndDate = Convert.ToDateTime("01/01/1900"); RFQop.ExpectedNoResource = 0; RFQop.Duration = "/0"; RFQop.TotalProjectHrs = 0; RFQop.Currency = 0; RFQop.Rate = Convert.ToDouble(0); RFQop.TotalValue = 0; RFQop.TimeTakenEstimate = "/0"; if (rfqInitial.ConfidenceLevel == 0) RFQop.Confidence = "0"; else RFQop.Confidence = (rfqInitial.ConfidenceLevel).ToString(); RFQop.IsProject = false; // RFQop.Status = ddlStatus.SelectedItem.Text.Trim(); RFQop.Status = rfqInitial.StatusId.ToString(); RFQop.PlaningPriority = Convert.ToDouble(0.50); DateTime.TryParseExact(rfqInitial.ExpectedClosureDate.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateGet); RFQop.ClosureDate = DateTime.Now; if (rfqInitial.Remark == null) { RFQop.OtherComments = ""; } else { RFQop.OtherComments = rfqInitial.Remark.Trim(); } RFQop.CreatedName = 0; RFQop.CreatedOn = DateTime.Now; RFQop.IsDeleted = false; SaveOpportunity(RFQop); } public string GetMaxOpportunity() { try { string objEntityToReturn = string.Empty; using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQInitialBaseConstant.const_Field_GetMaxOpportunityId; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); dt.Clear(); da.Fill(dt); objEntityToReturn = dt.Rows[0][0].ToString(); } return objEntityToReturn; } catch (Exception exc) { return ""; } } public string GetTechnology(List<long> tech) { string ReturnObj = string.Empty; foreach (var item in tech) { if (item != 0) { ReturnObj = ReturnObj + item.ToString() + ','; } } return ReturnObj; } public string GetUser(List<long> user) { string ReturnObj = string.Empty; foreach (var item in user) { if (item != 0) { ReturnObj = ReturnObj + item.ToString() + ','; } } return ReturnObj; } public string SaveOpportunity(RFQOpportunity entityObject) { try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } int intAffectedRecords; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RFQOpportunityConstant.const_Field_SaveOpportunity; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_Solution, entityObject.Solution); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_BDHead, entityObject.BDHead); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_BDManager, entityObject.BDManager); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_DateOfInitiation, entityObject.DateOfInitiation); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_ProspectId, entityObject.ProspectId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_BillingClient, entityObject.BillingClient); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_BussinessType, entityObject.BussinessType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_BussTechArea, entityObject.BussTechArea); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_OpportunityName, entityObject.OpportunityName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_ProjectType, entityObject.ProjectType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_Industry, entityObject.Industry); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_serviceOffering, entityObject.serviceOffering); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_TechBody, entityObject.TechBody); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_EstimationDoneBy, entityObject.EstimationDoneBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_ExactTech, entityObject.ExactTech); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_NextCallDate, entityObject.NextCallDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_TentativeOppClosureDate, entityObject.TentativeOppClosureDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_TentativeStartDate, entityObject.TentativeStartDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_TentativeEndDate, entityObject.TentativeEndDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_ExpectedNoResource, entityObject.ExpectedNoResource); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_Duration, entityObject.Duration); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_TotalProjectHrs, entityObject.TotalProjectHrs); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_Currency, entityObject.Currency); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_Rate, entityObject.Rate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_TotalValue, entityObject.TotalValue); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_TimeTakenEstimate, entityObject.TimeTakenEstimate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_Confidence, entityObject.Confidence); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_Status, entityObject.Status); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_PlaningPriority, entityObject.PlaningPriority); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_ClosureDate, entityObject.ClosureDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_OtherComments, entityObject.OtherComments); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_IsProject, entityObject.IsProject); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_ProjectId, entityObject.ProjectId); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQOpportunityConstant.const_Field_IsDeleted, entityObject.IsDeleted); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); //if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) //{ // objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); //} if (objVISDbCommand.objSqlCommand.Connection.State == ConnectionState.Closed) { objVISDbCommand.objSqlCommand.Connection.Open(); } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } catch (Exception ex) { } return ""; } public string GetCompanyId(string Comapny) { try { string objEntityToReturn = string.Empty; using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQConstants.const_Field_GetCompanyByClientProspect; base.objSqlCommand.Parameters.AddWithValue(RFQConstants.const_Field_Company, Comapny); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); dt.Clear(); da.Fill(dt); objEntityToReturn = dt.Rows[0][0].ToString(); } return objEntityToReturn; } catch (Exception exc) { return ""; } } public List<ProspectClient> GetProspectClient(ProspectClient prospectClient, SessionValues entityObject) { try { List<ProspectClient> objListToReturn = new List<ProspectClient>(); if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ProspectClientConstant.const_Field_GetProspectClientPopUp; base.objSqlCommand.Parameters.AddWithValue(SessionValuesConstant.const_Field_UserType, entityObject.UserType); base.objSqlCommand.Parameters.AddWithValue(ProspectClientConstant.const_Field_FilterRadioButton, prospectClient.FilterRadioButton); base.objSqlCommand.Parameters.AddWithValue(SessionValuesConstant.const_Field_UserId, entityObject.UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ProspectClient>(dt); } return objListToReturn; } catch (Exception ex) { throw; } } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var EmployeeDashboardHeartBeat_service_1 = require("../../../Service/Report/Attendance/EmployeeDashboardHeartBeat.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var EmployeeDashboardHeartBeatReportComponent = (function () { function EmployeeDashboardHeartBeatReportComponent(fb, _EmployeeDashboardHeartBeatReportService, pagerService, _CommonHelperService) { this.fb = fb; this._EmployeeDashboardHeartBeatReportService = _EmployeeDashboardHeartBeatReportService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.pager = {}; this.CurrentRecordsPerPage = 10; this.frommonth = new Date().getMonth() + 1; this.fromyear = new Date().getFullYear(); this.tomonth = new Date().getMonth() + 1; this.toyear = new Date().getFullYear(); } EmployeeDashboardHeartBeatReportComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.ParameterModel = ({ EmployeeId: 0, FromDate: '', LoginUserId: 0, OrderBy: '', ToDate: '', FromMonth: '', FromYear: '', ToMonth: '', ConsolidateBy: '', ViewBy: '', ToYear: '', MonthWise: false }); this.Year = [({ CurrentYear: '' })]; this.GetEmployee(); this.GetYear(); }; EmployeeDashboardHeartBeatReportComponent.prototype.HideShowPanel = function () { if ($("#rbtdate").prop("checked")) { $("#paneldatewise").show(); $("#panelmonthwise").hide(); $("#panelmonthwise2").hide(); $("#panelmonthwise3").hide(); $("#panelmonthwise4").hide(); } else { $("#paneldatewise").hide(); $("#panelmonthwise").show(); $("#panelmonthwise2").show(); $("#panelmonthwise3").show(); $("#panelmonthwise4").show(); } if ($("#rbtconsolidated").prop("checked")) { $("#panelconsolidate").show(); } else { $("#panelconsolidate").hide(); } }; EmployeeDashboardHeartBeatReportComponent.prototype.ToogleMyProfile = function () { $("#alltypeoutreportdata").slideToggle(300); }; EmployeeDashboardHeartBeatReportComponent.prototype.CloseWidgetProfile = function () { $("#alltypeoutreport").hide(300); }; EmployeeDashboardHeartBeatReportComponent.prototype.GetEmployee = function () { var _this = this; this._EmployeeDashboardHeartBeatReportService.getemployee(global_1.Global.BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT). subscribe(function (employee) { _this.Employee = employee; }); }; EmployeeDashboardHeartBeatReportComponent.prototype.GetYear = function () { var _this = this; this._EmployeeDashboardHeartBeatReportService.getyear(global_1.Global.BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT). subscribe(function (year) { _this.Year = year; }); }; EmployeeDashboardHeartBeatReportComponent.prototype.onSubmit = function (ParameterModel) { var _this = this; if ($("#rbtconsolidated").prop("checked")) { $("#headerouttype").hide(); $("#headerstarttime").hide(); $(".inputcentetext").hide(); } else { $("#headerouttype").show(); $("#headerstarttime").show(); $(".inputcentetext").show(); } if ($("#rbtdate").prop("checked")) { ParameterModel.MonthWise = false; } else { ParameterModel.MonthWise = true; } if ($("#rbtdeatil").prop("checked")) { ParameterModel.ViewBy = 'detail'; } else { ParameterModel.ViewBy = ''; if ($("#rbtnone").prop("checked")) { ParameterModel.ConsolidateBy = 'None'; } else if ($("#rbtname").prop("checked")) { ParameterModel.ConsolidateBy = 'Name'; } else { ParameterModel.ConsolidateBy = 'Date'; } } if ($("#rbtsortdate").prop("checked")) { ParameterModel.OrderBy = 'Date'; } else { ParameterModel.OrderBy = 'Name'; } ParameterModel.LoginUserId = 158; this.InLoading = true; this._EmployeeDashboardHeartBeatReportService.getemployeedashboardheartbeatreport(global_1.Global.BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT, ParameterModel). subscribe(function (empdashboardheartbeat) { _this.EmployeeDashboardHeartBeats = empdashboardheartbeat; _this.JumpOnPage(1); $("html, body").animate({ scrollTop: 500 }, 150); _this.InLoading = false; }); }; EmployeeDashboardHeartBeatReportComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeDashboardHeartBeats); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; EmployeeDashboardHeartBeatReportComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], EmployeeDashboardHeartBeatReportComponent.prototype, "modal", void 0); EmployeeDashboardHeartBeatReportComponent = __decorate([ core_1.Component({ providers: [EmployeeDashboardHeartBeat_service_1.EmployeeDashboardHeartBeatReportService], templateUrl: 'app/Components/Report/Attendance/EmployeeDashboardHeartBeatReport.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, EmployeeDashboardHeartBeat_service_1.EmployeeDashboardHeartBeatReportService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], EmployeeDashboardHeartBeatReportComponent); return EmployeeDashboardHeartBeatReportComponent; }()); exports.EmployeeDashboardHeartBeatReportComponent = EmployeeDashboardHeartBeatReportComponent; <file_sep>import { Component, OnInit } from "@angular/core"; import { Global } from './Shared/global'; import { SharedContents } from './Shared/sharedcontents'; import { Subscription } from 'rxjs/Subscription'; import { Router } from '@angular/router'; import { LoginComponent } from './Components/UserManagement/login.component'; import { AttendanceEntryComponent } from './Components/UserManagement/AttendanceEntry.component'; import { LoginData } from './Model/UserManagement/login'; @Component({ selector: "vis-app", templateUrl: "app/app.component.html", }) export class AppComponent implements OnInit { AttendanceEntryComponent: AttendanceEntryComponent; ShowDashboard: boolean; VISUsername: string; subscription: Subscription; PageWrapper: string; Employee_Name: string=''; strDocmentTemplateHeader: string; displayLoader = 'none'; objLoginData : LoginData; Logout() { sessionStorage.clear(); this.ExitDashboard(); this.router.navigate(['/login']); } AttendanceEntry() { this.router.navigate(['/AttendanceEntry']); } ngOnInit() { this.VISUsername = sessionStorage.getItem('VISUsername'); this.Employee_Name = sessionStorage.getItem('UserFullName'); this.GetDynamicMenuLinkText(); } constructor(private router: Router, private service: SharedContents) { this.subscription = service.pageWrapper$.subscribe(pWrapper => { this.PageWrapper = pWrapper; }); this.subscription = service.showDashboard$.subscribe(showDashboard => { this.ShowDashboard = showDashboard; }); } buttonClick() { var vProp; var vStyleOfElement = document.getElementById("VISNavigationBar"); var vNewVisNavBarWidth = "300px"; var vMainContentLeftMargin = "305px"; var vCurrentStyleInAnchor = "labeldisplayblock"; var vChangeStyleInAnchor = "labeldisplaynone"; var vCurrentArrowClass = "arrow"; var vChangeInArrowClass = "arrownone"; if (vStyleOfElement.style.width == "300px") { vNewVisNavBarWidth = "50px"; vMainContentLeftMargin = "55px"; } else { vNewVisNavBarWidth = "300px"; vMainContentLeftMargin = "305px"; vCurrentStyleInAnchor = "labeldisplaynone"; vChangeStyleInAnchor = "labeldisplayblock"; vCurrentArrowClass = "arrownone"; vChangeInArrowClass = "arrow"; } var vArrayOfAnchorTag = document.getElementsByClassName(vCurrentStyleInAnchor); while (vArrayOfAnchorTag.length > 0) { vArrayOfAnchorTag[0].setAttribute('class', vChangeStyleInAnchor); } var vArrayOfArrowClass = document.getElementsByClassName(vCurrentArrowClass); while (vArrayOfArrowClass.length > 0) { vArrayOfArrowClass[0].setAttribute('class', vChangeInArrowClass); } var vArrayOfMainContentDivTag = document.getElementById("MainDivToLoadChild"); vArrayOfMainContentDivTag.style.marginLeft = vMainContentLeftMargin; vStyleOfElement.style.width = vNewVisNavBarWidth; } ExitDashboard() { this.ShowDashboard = false; var vMainContentLeftMargin = "55px"; var vArrayOfMainContentDivTag = document.getElementById("MainDivToLoadChild"); vArrayOfMainContentDivTag.style.marginLeft = vMainContentLeftMargin; } GetDynamicMenuLinkText() { if (sessionStorage.length > 0) { if (JSON.parse(sessionStorage.getItem('IsAdmin')) || JSON.parse(sessionStorage.getItem('IsLineManager'))) { this.strDocmentTemplateHeader = 'Document Template' } else { this.strDocmentTemplateHeader = 'My Suggestion'; } } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { SecurityKeyService } from '../../../service/Masters/Configuration/SecurityKey.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ISecurityKey } from '../../../Model/Masters/Configuration/SecurityKey'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [SecurityKeyService], templateUrl: 'app/Components/Masters/Configuration/SecurityKey.component.html' }) export class SecurityKeyComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; securitykeys: ISecurityKey[]; securitykey: ISecurityKey; msg: string; indLoading: boolean = false; SecurityKeyFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; SecurityKeyFilter: string; isDesc: boolean = false; column: any = 'Key1'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchKey1: string; strSearchKey2: string; strSearchKey3: string; strSearchKey4: string; strSearchKey5: string; //Variables for UniqueKey UniqueKey: string; constructor(private fb: FormBuilder, private _SecurityKeyService: SecurityKeyService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.securitykey = ({ Id: 0, Key1:'', Key2: '', Key3: '', Key4: '', Key5: '', UniqueKey:'', Active: false, IsActive: false, CreatedOn: null, UpdatedOn: null, CreatedBy: '', UpdatedBy: '', }); this.LoadSecurityKey(); this.InputNavigator(); } CancelModel() { this.modal.dismiss(); this.securitykey = ({ Id: 0, Key1: '', Key2: '', Key3: '', Key4: '', Key5: '', UniqueKey: '', Active: false, IsActive: false, CreatedOn: null, UpdatedOn: null, CreatedBy: '', UpdatedBy: '', }); } InputNavigator():void { $(function () { $("#Key1").keyup(function () { if ($("#Key1").val().length == 4) { $("#Key2").focus(); } }); $("#Key2").keyup(function () { if ($("#Key2").val().length == 4) { $("#Key3").focus(); } }); $("#Key3").keyup(function () { if ($("#Key3").val().length == 4) { $("#Key4").focus(); } }); $("#Key4").keyup(function () { if ($("#Key4").val().length == 4) { $("#Key5").focus(); } }); }); } SecurityKeyFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.SecurityKeyFilter = value; } SecurityKeySort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; GenrateUniqueKey(formData: ISecurityKey) { if (formData.Key1.length == 4 && formData.Key2.length == 4 && formData.Key3.length == 4 && formData.Key4.length == 4 && formData.Key5.length == 4) { this._SecurityKeyService.GenrateSecurityKey(Global.BASE_SECURITYKEY_ENDPOINT, formData).subscribe( securitykeyunique => { this.securitykey.UniqueKey = securitykeyunique; }, error => { this.msg = error; } ); } } LoadSecurityKey(): void { this.indLoading = true; this._SecurityKeyService.get(Global.BASE_SECURITYKEY_ENDPOINT) .subscribe(securitykeys => { this.securitykeys = securitykeys; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchKey1 = (<HTMLInputElement>document.getElementById("searchKey1")).value; if (this.strSearchKey1 != '') { this.strSearchKey1 = this.strSearchKey1.toLocaleLowerCase(); this.securitykeys = this.securitykeys.filter ( x => x.Key1 != null && x.Key1.toLocaleLowerCase().indexOf(this.strSearchKey1) != -1); } this.strSearchKey2 = (<HTMLInputElement>document.getElementById("searchKey2")).value; if (this.strSearchKey2 != '') { this.strSearchKey2 = this.strSearchKey2.toLocaleLowerCase(); this.securitykeys = this.securitykeys.filter ( x => x.Key2 != null && x.Key2.toLocaleLowerCase().indexOf(this.strSearchKey2) != -1); } this.strSearchKey3 = (<HTMLInputElement>document.getElementById("searchKey3")).value; if (this.strSearchKey3 != '') { this.strSearchKey3 = this.strSearchKey3.toLocaleLowerCase(); this.securitykeys = this.securitykeys.filter ( x => x.Key3 != null && x.Key3.toLocaleLowerCase().indexOf(this.strSearchKey3) != -1); } this.strSearchKey4 = (<HTMLInputElement>document.getElementById("searchKey4")).value; if (this.strSearchKey4 != '') { this.strSearchKey4 = this.strSearchKey4.toLocaleLowerCase(); this.securitykeys = this.securitykeys.filter ( x => x.Key4 != null && x.Key4.toLocaleLowerCase().indexOf(this.strSearchKey4) != -1); } this.strSearchKey5 = (<HTMLInputElement>document.getElementById("searchKey5")).value; if (this.strSearchKey5 != '') { this.strSearchKey5 = this.strSearchKey5.toLocaleLowerCase(); this.securitykeys = this.securitykeys.filter ( x => x.Key5 != null && x.Key5.toLocaleLowerCase().indexOf(this.strSearchKey5) != -1); } } //Logic for searching - End this.indLoading = false; this.JumpOnPage(1); } //,error => this.msg = <any>error ); } AddSecurityKey() { this.dbops = DBOperation.create; //this.SetControlsState(true); this.modalTitle = "Add New SecurityKey"; this.modalBtnTitle = "Add"; //this.SecurityKeyFrm.reset(); this.modal.open(); } EditSecurityKey(id: number) { this.dbops = DBOperation.update; //this.SetControlsState(true); this.modalTitle = "Edit SecurityKey"; this.modalBtnTitle = "Update"; this.securitykey = this.securitykeys.filter(x => x.Id == id)[0]; this.modal.open(); } DeleteSecurityKey(id: number, status: boolean) { this.dbops = DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.securitykey = this.securitykeys.filter(x => x.Id == id)[0]; //this.SecurityKeyFrm.setValue(this.securitykey); this.modal.open(); } SetControlsState() { } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.securitykeys); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData:ISecurityKey) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._SecurityKeyService.post(Global.BASE_SECURITYKEY_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.CancelModel(); this.msg = data; this.LoadSecurityKey(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._SecurityKeyService.put(Global.BASE_SECURITYKEY_ENDPOINT,formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.CancelModel(); this.msg = data; this.LoadSecurityKey(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._SecurityKeyService.delete(Global.BASE_SECURITYKEY_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.CancelModel(); this.msg = "SecurityKey status changed successfully."; this.LoadSecurityKey(); } else { this.msg = "Error has occurred while changing status of existing SecurityKey!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var Observable_1 = require("rxjs/Observable"); require("rxjs/add/operator/map"); require("rxjs/add/operator/do"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var AttendanceReportNewService = (function () { function AttendanceReportNewService(_http) { this._http = _http; } AttendanceReportNewService.prototype.FillDepartMent = function (url) { return this._http.get(url + 'FillDepartMent') .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.FillEmployee = function (url, UserId, UserType) { return this._http.get(url + 'FillEmployee?UserId=' + UserId + '&UserType=' + UserType) .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.FillYear = function (url) { return this._http.get(url + 'FillYear') .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.FillCompany = function (url, Allow) { return this._http.get(url + 'FillCompany?Allow=' + Allow) .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.FillAllLineManager = function (url, Allow, UserId) { return this._http.get(url + 'FillAllLineManager?Allow=' + Allow + '&UserId=' + UserId) .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.FillUserType = function (url) { return this._http.get(url + 'FillUserType') .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.FillAllEmployee = function (url, Allow, UserId) { return this._http.get(url + 'FillAllEmployee?Allow=' + Allow + '&UserId=' + UserId) .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.GetSystemDateTime = function (url) { return this._http.get(url + 'GetSystemDateTime') .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.GetAllAttendanceReport = function (url, Mode, ModeId, StartDate, EndDate, SortBy, IsAdmin) { return this._http.get(url + 'GetAllAttendanceReport?Mode=' + Mode + '&ModeId=' + ModeId + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&SortBy=' + SortBy + '&IsAdmin=' + IsAdmin) .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.GetAllAttendanceData = function (url, Mode, ModeId, StartDate, EndDate, SortBy, IsAdmin) { return this._http.get(url + 'GetAllAttendanceData?Mode=' + Mode + '&ModeId=' + ModeId + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&SortBy=' + SortBy + '&IsAdmin=' + IsAdmin) .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.get = function (url) { return this._http.get(url) .map(function (response) { return response.json(); }); }; AttendanceReportNewService.prototype.put = function (url, id, model) { var body = JSON.stringify(model); var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity/' + id, body, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; AttendanceReportNewService.prototype.delete = function (url, id) { var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; AttendanceReportNewService.prototype.handleError = function (error) { console.error(error); return Observable_1.Observable.throw(error.json().error || 'Server error'); }; AttendanceReportNewService = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [http_1.Http]) ], AttendanceReportNewService); return AttendanceReportNewService; }()); exports.AttendanceReportNewService = AttendanceReportNewService; <file_sep>import { LoginService } from '../service/UserManagement/login.Service'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/debounceTime'; import 'rxjs/add/operator/distinctUntilChanged'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/toPromise'; import { Injectable } from '@angular/core'; import { Global } from '../Shared/global'; import { SharedContents } from './sharedcontents' import { Injector } from '@angular/core'; @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (sessionStorage.getItem('VISUsername')) { return true; // logged in so return true } // not logged in so redirect to login page this.router.navigate(['/login']); return false; } } <file_sep>export interface IContactMaster { Id: number; Name: string; Designation: string; Email: string; phone: string; SkypeId: string; MsnId: string; GtalkId: string; AolId: string; Other: string; ProspectId: number; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { PolicyService } from '../../service/Notification/Policy.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IPolicy } from '../../Model/Notification/Policy'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; @Component({ providers: [PolicyService], templateUrl: 'app/Components/Notification/Policy.component.html' }) export class PolicyComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('modal1') modal1: ModalComponent; Policys: IPolicy[]; Policy: IPolicy; ViewIPolicy: IPolicy[]; msg: string; indLoading: boolean = false; PolicyFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; PolicyFilter: string; isDesc: boolean = false; column: any = 'Policy_Name'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchPolicy_Name: string; strSearchDescription: string; constructor(private fb: FormBuilder, private _PolicyService: PolicyService, private pagerService: PagerService) { } ngOnInit(): void { this.PolicyFrm = this.fb.group({ CompanyId: [''], Id: [''], Policy_Name: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], Description: ['', Validators.required], IsNewPolicy: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); this.LoadPolicys() } PolicyFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.PolicyFilter = value; } PolicySort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } LoadPolicys(): void { this.indLoading = true; this._PolicyService.get(Global.BASE_POLICY_ENDPOINT) .subscribe(Policys => { this.Policys = Policys; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchPolicy_Name = (<HTMLInputElement>document.getElementById("searchPolicy_Name")).value; if (this.strSearchPolicy_Name != '') { this.strSearchPolicy_Name = this.strSearchPolicy_Name.toLocaleLowerCase(); this.Policys = this.Policys.filter( x => x.Policy_Name != null && x.Policy_Name.toLocaleLowerCase().indexOf(this.strSearchPolicy_Name) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addPolicy() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Policy"; this.modalBtnTitle = "Add"; this.PolicyFrm.reset(); this.modal.open(); } editPolicy(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Policy"; this.modalBtnTitle = "Update"; this.Policy = this.Policys.filter(x => x.Id == id)[0]; this.PolicyFrm.setValue(this.Policy); this.modal.open(); } deletePolicy(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.Policy = this.Policys.filter(x => x.Id == id)[0]; this.PolicyFrm.setValue(this.Policy); this.modal.open(); } ViewPolicy(id: number) { this.dbops = DBOperation.View; this.SetControlsState(false); this.modalTitle = "View Policy"; this.modalBtnTitle = "Back"; this.Policy = this.Policys.filter(x => x.Id == id)[0]; this.PolicyFrm.setValue(this.Policy); this.modal1.open(); this.LoadViewPolicy(id); } LoadViewPolicy(id: number): void { this.indLoading = true; this._PolicyService.getViewPolicy(Global.BASE_POLICY_ENDPOINT, id) .subscribe(DATADP => { this.ViewIPolicy = DATADP; } ); } SetControlsState(isEnable: boolean) { isEnable ? this.PolicyFrm.enable() : this.PolicyFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.Policys); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._PolicyService.post(Global.BASE_POLICY_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadPolicys(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._PolicyService.put(Global.BASE_POLICY_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadPolicys(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._PolicyService.delete(Global.BASE_POLICY_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Policy status changed successfully."; this.LoadPolicys(); } else { this.msg = "Error has occurred while changing status of existing Policy!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class AddEmployeeRecordService { constructor(private _http: Http) { } FillEmployee(url: string): Observable<any> { return this._http.get(url + 'FillEmployee') .map((response: Response) => <any>response.json()); } BindEmployeeDetails(url: string, EmpId: number, Date: string, LoginUserId: number): Observable<any> { return this._http.get(url + 'BindEmployeeDetails?EmpId=' + EmpId + '&Date=' + Date + '&LoginUserId=' + LoginUserId) .map((response: Response) => <any>response.json()); } BindEmployeeAttendance(url: string, EmployeeID: number, Date:string): Observable<any> { return this._http.get(url + 'BindEmployeeAttendance?EmployeeID=' + EmployeeID + '&Date=' + Date) .map((response: Response) => <any>response.json()); } BindHRAttendanceDetails(url: string, EmployeeId: number, forWhichDate:string): Observable<any> { return this._http.get(url + 'BindHRAttendanceDetails?EmployeeId=' + EmployeeId + '&forWhichDate=' + forWhichDate) .map((response: Response) => <any>response.json()); } GetAttendanceTransaction(url: string, EmployeeId: number, Date: string, EntryType: number): Observable<any> { return this._http.get(url + 'GetAttendanceTransaction?EmployeeId=' + EmployeeId + '&Date=' + Date + '&EntryType=' + EntryType) .map((response: Response) => <any>response.json()); } AddEmployee(url: string, EmployeeId: number, EntryType: number, Remarks: string, EntryTime: string, Date: string, Time: string, Grace: number): Observable<any> { return this._http.get(url + 'AddEmployee?EmployeeId=' + EmployeeId + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&EntryTime=' + EntryTime + '&Date=' + Date + '&Time=' + Time + '&Grace=' + Grace) .map((response: Response) => <any>response.json()); } get(url: string): Observable<any> { return this._http.get(url) .map((response: Response) => <any>response.json()); } GetUpdateEmployeeAttendance(url: string, id: number, EmployeeId: number, EntryType: number, Remarks: string, EntryTime: string, Date: string, Grace: number, LoginId: number,ActualEntryTime:string): Observable<any> { return this._http.get(url + 'GetUpdateEmployeeAttendance?id=' + id + '&EmployeeId=' + EmployeeId + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&EntryTime=' + EntryTime + '&Date=' + Date + '&Grace=' + Grace + '&LoginId=' + LoginId + '&ActualEntryTime=' + ActualEntryTime) .map((response: Response) => <any>response.json()) .catch(this.handleError); } put(url: string, id: number, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity/' + id, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } delete(url: string, id: number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep>import { Component, OnInit, Pipe, Input, ViewContainerRef, ViewChild } from '@angular/core'; import { LoginService } from '../../Service/UserManagement/login.service'; import { FormsModule, FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms'; import { HttpModule, Http, Headers } from '@angular/http'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { routing } from '../../app.routing'; import { AppComponent } from '../../app.component'; import { SharedContents } from '../../Shared/sharedcontents'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { LoginData } from '../../Model/UserManagement/login'; import { Global } from '../../../app/Shared/global'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; @Component({ selector: 'login-page', templateUrl: 'app/Components/UserManagement/login.component.html', providers: [LoginService] }) export class LoginComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; msg: string; public UserData: LoginData; public LoginObj: LoginData; public LoginForm: FormGroup; submitted = false; Empls: any; aValue: any; valAdm: any; logged: boolean = false; RandomImagePath: string; constructor(public LoginService: LoginService, private _fb: FormBuilder, public http: Http, private router: Router, private AppComponent: AppComponent, private service: SharedContents) { this.LoginObj = new LoginData(); this.service.setData('page-wrapper', false); } GetRandomImagePath() { this.LoginService.GetActivateImagePath().subscribe( data => { this.RandomImagePath = '../../../Upload/HomePageImage/' + data; } ); } DynamicHomePageStyle() { let styles = { 'background': 'url(' + this.RandomImagePath + ')', 'background-size': 'cover', 'width': 'auto', 'height': 'auto', 'position': 'fixed', 'top': '0', 'right': '0', 'bottom': '0', 'left': '0', 'margin': '0', 'background-repeat' : 'no-repeat' }; return styles; } Login() { if (this.LoginObj.VISUsername == null || this.LoginObj.VISPassword == null) { //this.toasterService.pop('info', 'Please Input User Id', 'Please Input Password') } else { this.UserData = null; this.LoginService.doLogin(this.LoginObj).subscribe( data => { this.UserData = data; if (this.UserData.Id > 0) { this.UserData.ArrayUserType = this.UserData.UserRoleTypeName.split(','); var tempDepartmentId = this.UserData.DepartmentId.split(','); this.UserData.ArrayDepartmentId = []; for (let item of tempDepartmentId) { this.UserData.ArrayDepartmentId.push(Number(item)); } this.service.setData('page-wrapper', true); sessionStorage.setItem('VISUsername', this.UserData.VISUsername); sessionStorage.setItem('VISPassword', <PASSWORD>.VISPassword); sessionStorage.setItem('UserFullName', this.UserData.UserFullName); sessionStorage.setItem('LastName', this.UserData.LastName); sessionStorage.setItem('Id', this.UserData.Id.toString()); sessionStorage.setItem('Email', this.UserData.Email); sessionStorage.setItem('UserType', this.UserData.UserType); sessionStorage.setItem('UserRoleTypeName', this.UserData.UserRoleTypeName); sessionStorage.setItem('IsAdmin', JSON.stringify(this.UserData.IsAdmin)); sessionStorage.setItem('IsLineManager', JSON.stringify(this.UserData.IsLineManager)); sessionStorage.setItem('DepartmentId', this.UserData.DepartmentId.toString()); sessionStorage.setItem('IsOnStypend', JSON.stringify(this.UserData.IsOnStypend)); sessionStorage.setItem('IsFormerEmployee', JSON.stringify(this.UserData.IsFormerEmployee)); sessionStorage.setItem('IsWebAccess', JSON.stringify(this.UserData.IsWebAccess)); sessionStorage.setItem('validForLogin', JSON.stringify(this.UserData.validForLogin)); sessionStorage.setItem('WebAccessURL', this.UserData.WebAccessURL); sessionStorage.setItem('ArrayUserType', JSON.stringify(this.UserData.ArrayUserType)); sessionStorage.setItem('ArrayDepartmentId', JSON.stringify(this.UserData.ArrayDepartmentId)); this.AppComponent.objLoginData = this.UserData; this.AppComponent.ngOnInit(); this.router.navigate(['/dashboard']); } else { alert('Authentication failed.'); } }); } } ngOnInit() { this.GetRandomImagePath(); this.UserData = null; this.LoginForm = this._fb.group({ VISUsername: ['', Validators.required], VISPassword: ['', Validators.required], }); } ForgotPassword(name: any) { this.modal.open(); } onSubmit(formData: any) { this.LoginService.ForgotPassword(Global.BASE_FORGOTPASSWORD_ENDPOINT, formData._value).subscribe( data => { //this.UserData = data; //formData._value.VISUsername == "sa"; this.msg = data; }, error => { this.msg = error; } ); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { // model For Bind Data public class EmployeeScreenCaptureReport : VISBaseEntity { public string EmployeeName { get; set; } public string AllowScreenCapture { get; set; } public string AttendanceStatus { get; set; } public int Counts { get; set; } public DateTime Date { get; set; } public string PunchIn { get; set; } public string PunchOut { get; set; } public string Timming { get; set; } } // model For Send Parameter public class EmployeeScreenCaptureParamterModel { public int EmployeeId { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } public string OrderBy { get; set; } public int LoginUserId { get; set; } public string FromMonth { get; set; } public string FromYear { get; set; } public string ToMonth { get; set; } public string ToYear { get; set; } public bool MonthWise { get; set; } } public static class EmployeeScreenCaptureReportConstant { // Constance For Parameter public const string const_EmployeeId = "employeeId"; public const string const_FromDate = "fromDate"; public const string const_ToDate = "toDate"; public const string const_OrderBy = "orderBy"; public const string const_LoginUserId = "LoginUserId"; // Constance For Store Procedure public const string const_procEmployee_ScreenCaptureReport = "procEmployee_ScreenCaptureReport"; public const string const_procFinancialYear_SelectAll = "procGetYear"; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Reports.Attendance; namespace VIS_Repository.Reports.Attendance { public class AttendanceReportNewRepository : VISDbCommand { public AttendanceReportNewRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<FillDepartment> FillDepartMent() { List<FillDepartment> objListToReturn = new List<FillDepartment>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_procAttendanceReportNew_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, "FillDP"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillDepartment>(dt); } return objListToReturn; } public IEnumerable<FillEmployee> FillEmployee(Int64 UserId, string UserType) { List<FillEmployee> objListToReturn = new List<FillEmployee>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_Proc_EmployeeDetail; if (UserType == "DHEmpDetail") { base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, "DHEmpDetail"); } else { base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, "EmpDetail"); } base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Id, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillEmployee>(dt); } return objListToReturn; } public IEnumerable<FillEmployee> FillAllEmployee(Boolean Allow, Int64 UserId) { List<FillEmployee> objListToReturn = new List<FillEmployee>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_procAttendanceReportNew_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, "chkInActiveEmployee"); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Allow, Allow); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillEmployee>(dt); } return objListToReturn; } public IEnumerable<FillCompany> FillCompany(Boolean Allow) { List<FillCompany> objListToReturn = new List<FillCompany>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_procAttendanceReportNew_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, "FillCompany"); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Allow, Allow); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillCompany>(dt); } return objListToReturn; } public IEnumerable<FillLineManager> FillAllLineManager(Boolean Allow, Int64 UserId) { List<FillLineManager> objListToReturn = new List<FillLineManager>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_procAttendanceReportNew_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, "FillAllLineManager"); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Allow, Allow); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillLineManager>(dt); } return objListToReturn; } public IEnumerable<FillUserType> FillUserType() { List<FillUserType> objListToReturn = new List<FillUserType>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_procAttendanceReportNew_SelectAll; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, "FillUserType"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<FillUserType>(dt); } return objListToReturn; } public DataTable FillYear() { ArrayList list = new ArrayList(); int currentyear = DateTime.Now.Year; for (int i = 2009; i <= currentyear; i++) { list.Add(i); } DataTable dt = new DataTable(); DataColumn dc = new DataColumn(); dc = dt.Columns.Add("Id", typeof(Int64)); dc.AutoIncrement = true; dc.AutoIncrementSeed = 1; dc.AutoIncrementStep = 1; dc = dt.Columns.Add("Year", typeof(Int64)); foreach (int item in list) { DataRow row = dt.NewRow(); row["Year"] = item; dt.Rows.Add(row); } return dt; } public string GetSystemDateTime() { string CurrentDate = System.DateTime.Now.ToString(); return CurrentDate; } public DataTable GetAllAttendanceReport(string Mode, Int64 ModeId, string StartDate, string EndDate, string SortBy, Boolean IsAdmin) { DataTable dt = new DataTable(); try { int longLeave = Convert.ToInt32(ConfigurationManager.AppSettings["LongLeave"]); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_Proc_AttendanceReport; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode, Mode); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_modeId, ModeId); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_fromDate, StartDate); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_toDate, EndDate); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_SortBy, SortBy); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_isAdmin, IsAdmin); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_LongLeaveValue, longLeave); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch(Exception ex) { } return dt; } public DataTable GetAllAttendanceData(string Mode, Int64 ModeId, string StartDate, string EndDate, string SortBy, Boolean IsAdmin) { DataTable dt = new DataTable(); try { int longLeave = Convert.ToInt32(ConfigurationManager.AppSettings["LongLeave"]); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceReportNewConstatnts.const_ProcAttendanceReport_rdlc; base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_Mode,Mode); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_modeId,ModeId); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_fromDate,StartDate); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_toDate,EndDate); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_SortBy,SortBy); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_isAdmin,IsAdmin); base.objSqlCommand.Parameters.AddWithValue(AttendanceReportNewConstatnts.const_Field_LongLeaveValue, longLeave); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch(Exception ex) { } return dt; } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using VIS_Domain; using VIS_Domain.GeneralHelper; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Domain.RFQ; using VIS_Repository; using VIS_Repository.GeneralHelper; using VIS_Repository.Masters; using VIS_Repository.RFQ; namespace VIS_App.Controllers.RFQ { public class RFQAPIController : BaseAPIController { VISIBaseRepository<RFQList> RFQRepository; HelperRepository HelperObj = null; List<RFQList> EntityList = new List<RFQList>(); RFQRepository obj = null; public RFQAPIController() { obj = new RFQRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); HelperObj = new HelperRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [HttpGet] [Route("api/RFQAPI/GetMyRFQ")] public HttpResponseMessage GetMyRFQ(string CommunicationId) { string Mode = "myrfq"; long emp = Convert.ToInt64(HelperObj.GetEmpIdByCommunicationId(CommunicationId)); return ToJson(obj.GetEntityList(emp, Mode).AsEnumerable()); } [HttpGet] [Route("api/RFQAPI/GetAllRFQ")] public HttpResponseMessage GetAllRFQ(string CommunicationId) { string Mode = "allrfq"; long emp = Convert.ToInt64(HelperObj.GetEmpIdByCommunicationId(CommunicationId)); return ToJson(obj.GetEntityList(emp, Mode).AsEnumerable()); } // [HttpGet] [Route("api/RFQAPI/GetResponceRequestedRFQ")] public HttpResponseMessage GetResponceRequestedRFQ(string CommunicationId) { IEnumerable<RFQList> lstRFQ = new List<RFQList>(); string Mode = "estimateby"; long emp = Convert.ToInt64(HelperObj.GetEmpIdByCommunicationId(CommunicationId)); lstRFQ = obj.GetEntityList(emp, Mode); lstRFQ = lstRFQ.Where(x => x.rfqStatus.ToLower().Contains("in process")).ToList(); return ToJson(lstRFQ.AsEnumerable()); } [HttpGet] [Route("api/RFQAPI/GetMyActionRFQ")] public HttpResponseMessage GetMyActionRFQ(string CommunicationId) { IEnumerable<RFQList> lstRFQ = new List<RFQList>(); string Mode = "myaction"; long emp = Convert.ToInt64(HelperObj.GetEmpIdByCommunicationId(CommunicationId)); lstRFQ = obj.GetEntityList(emp, Mode); lstRFQ = lstRFQ.Where(x => x.rfqStatus.ToLower().Contains("in process")).ToList(); return ToJson(lstRFQ.AsEnumerable()); } // [HttpGet] [Route("api/RFQAPI/GetMyWatchListRFQ")] public HttpResponseMessage GetMyWatchListRFQ(string CommunicationId) { IEnumerable<RFQList> lstRFQ = new List<RFQList>(); string Mode = "mywatch"; long emp = Convert.ToInt64(HelperObj.GetEmpIdByCommunicationId(CommunicationId)); lstRFQ = obj.GetEntityList(emp, Mode); lstRFQ = lstRFQ.Where(x => x.rfqStatus.ToLower().Contains("in process")).ToList(); return ToJson(lstRFQ.AsEnumerable()); } public HttpResponseMessage Post([FromBody]MainRFQInitial value) { bool CheckSave = obj.RFQInitial(value.RFQInitial); if (CheckSave == true) { obj.RFQDoc(value.RFQDoc, value.SessionData); obj.RFQLink(value.RFQLink, value.SessionData); return ToJson("Success:"); } else { return ToJson("Failed:"); } } //[HttpPost] //[Route("api/RFQAPI/Post")] //public void Post([FromBody]MainRFQInitial MainRFQInitial) //{ //} [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]RFQList value) { return ToJson(RFQRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(RFQRepository.DeleteEntity(Id)); } [HttpGet] [Route("api/RFQAPI/FillBusinessHead")] public HttpResponseMessage FillBusinessHead() { return ToJson(obj.FillBusinessHead()); } [HttpGet] [Route("api/RFQAPI/GetBusinessManager")] public HttpResponseMessage GetBusinessManager(string UserId) { long emp = Convert.ToInt64(HelperObj.GetEmpIdByCommunicationId(UserId)); return ToJson(obj.FillBusinessManager(emp)); } [HttpGet] [Route("api/RFQAPI/GetBusinessType")] public HttpResponseMessage GetBusinessType() { return ToJson(obj.GetBusinessType()); } [HttpGet] [Route("api/RFQAPI/GetProjectType")] public HttpResponseMessage GetProjectType() { return ToJson(obj.GetProjectType()); } [HttpGet] [Route("api/RFQAPI/GetIndustries")] public HttpResponseMessage GetIndustries() { return ToJson(obj.GetIndustries()); } [HttpGet] [Route("api/RFQAPI/GetSolution")] public HttpResponseMessage GetSolution() { return ToJson(obj.GetSolution()); } [HttpGet] [Route("api/RFQAPI/GetServiceOffering")] public HttpResponseMessage GetServiceOffering() { return ToJson(obj.GetServiceOffering()); } [HttpGet] [Route("api/RFQAPI/GetFileType")] public HttpResponseMessage GetFileType() { return ToJson(obj.GetFileType()); } [HttpGet] [Route("api/RFQAPI/GetAuthor")] public HttpResponseMessage GetAuthor() { return ToJson(obj.GetAuthor()); } [HttpGet] [Route("api/RFQAPI/GetTechnology")] public HttpResponseMessage GetTechnology() { return ToJson(obj.GetTechnology()); } [HttpGet] [Route("api/RFQAPI/GetEmployee")] public HttpResponseMessage GetEmployee() { return ToJson(obj.GetEmployee()); } [HttpGet] [Route("api/RFQAPI/GetRFQStatus")] public HttpResponseMessage GetRFQStatus() { return ToJson(obj.GetRFQStatus()); } [HttpPost] [Route("api/RFQAPI/UploadRFQDoc")] public HttpResponseMessage UploadRFQDoc() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/Upload/RFQ/Document/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } [HttpPost] [Route("api/RFQAPI/GetProspectClient")] public HttpResponseMessage GetProspectClient(SuperProspectClient superProspectClient) { return ToJson(obj.GetProspectClient(superProspectClient.ProspectClient, superProspectClient.SessionValues)); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var AttendanceReport_Service_1 = require("../../../Service/Report/Attendance/AttendanceReport.Service"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var router_1 = require("@angular/router"); var http_1 = require("@angular/http"); //import { AttendanceReportFilterPipe } from '../../../Filter/Report/Attendance/Attendance_Report'; var AttendanceReportComponent = (function () { function AttendanceReportComponent(fb, _AttendanceReportService, http, router, pagerService) { this.fb = fb; this._AttendanceReportService = _AttendanceReportService; this.http = http; this.router = router; this.pagerService = pagerService; this.indLoading = false; this.CurrentRecordsPerPage = 10; this.pager = {}; } AttendanceReportComponent.prototype.ngOnInit = function () { $("#depart").hide(); $("#companydata").hide(); $("#LM").hide(); $("#emp").show(); $("#empAll").show(); $("#Employee").prop("checked", true); $("#datedata").hide(); $("#rdbmonth").prop("checked", true); $("#rdbDate").prop("checked", false); $("#RdbSortName").prop("checked", true); $('#ddlmonth option:eq(' + (new Date).getMonth() + ')').prop('selected', true); this.Yearval = new Date().getFullYear(); this.AttendanceDepart = [ ({ Id: 0, Department_Name: '', mode: '' }) ]; this.AttendanceEmployee = [({ Id: 0, Employee_Name: '', mode: '' })]; this.AttendanceCompany = [({ Id: 0, CompanyName: '', mode: '' })]; this.AttendanceLineManager = [({ Id: 0, LineManager: '', mode: '' })]; this.AttendancebindData = [({ Employee_Id: 0, EmployeeCode: '', Employee_Name: '', Date: '', MMDDYYYY_DateFormat: '', Days: '', ImportRemarks: '', HoverImportRemarks: '', InId: 0, In_Time: null, OutId: 0, Out_Time: null, LunchOutId: 0, LunchOut_Time: null, LunchInId: 0, LunchIn_Time: null, OtherId: 0, Other_Time: null, TotalWorksheet_Hr: 0, status: '', Total_W_Hr: '', Total_Hrs: '', diff: '', TotalId: '', ActualEntryTime: '', Grace: 0, EntryType: '' })]; this.AttendanceYear = [({ Id: 0, Month: '', Year: '' })]; this.LoadDepartment(); this.LoadCompany(); this.LoadLineManager(); this.LoadYear(); this.LoadEmployee(); }; AttendanceReportComponent.prototype.HideEMCOLM = function () { $("#emp").hide(-300); $("#empAll").hide(-300); $("#companydata").hide(-300); $("#LM").hide(-300); $("#depart").show(-300); }; AttendanceReportComponent.prototype.HideCOLMDP = function () { $("#depart").hide(-300); $("#companydata").hide(-300); $("#LM").hide(-300); $("#emp").show(-300); $("#empAll").show(-300); }; AttendanceReportComponent.prototype.HideLMDPEM = function () { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#LM").hide(-300); $("#companydata").show(-300); }; AttendanceReportComponent.prototype.HideDPEMCO = function () { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#companydata").hide(-300); $("#LM").show(-300); }; AttendanceReportComponent.prototype.HideMonth = function () { $("#monthData").hide(-300); $("#datedata").show(-300); }; AttendanceReportComponent.prototype.HideDate = function () { $("#monthData").show(-300); $("#datedata").hide(-300); }; AttendanceReportComponent.prototype.btnAttendanceApprovePunchIn = function (data) { this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.Employee_Id = data.Employee_Id; this.Grace = data.Grace; this.EntryHr = data.In_Time; this.EntryMin = data.In_Time; var HH_EIN = this.EntryHr.slice(8, 10).trim(); this.EntryHr = HH_EIN; var MIN_EIN = this.EntryMin.slice(11, 13).trim(); this.EntryMin = MIN_EIN; this.DrpEntryIn = data.In_Time; var DrpIn = this.DrpEntryIn.slice(17, 19).trim(); this.InId = data.InId; this.DrpEntryIn = DrpIn; this.ActualHr = data.ActualEntryTime; var HH_AIN = this.ActualHr.slice(0, 2).trim(); this.ActualHr = HH_AIN; this.ActualMin = data.ActualEntryTime; var MIN_AIN = this.ActualMin.slice(3, 5).trim(); this.ActualMin = MIN_AIN; this.modalAttendanceApprovalPunchIn.open(); }; AttendanceReportComponent.prototype.btnAttendanceApprovePunchOut = function (data) { this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.Employee_Id = data.Employee_Id; this.Grace = data.Grace; this.EntryHr = data.Out_Time; this.EntryMin = data.Out_Time; var HH_EOUT = this.EntryHr.slice(8, 10).trim(); this.EntryHr = HH_EOUT; var MIN_EOUT = this.EntryMin.slice(11, 13).trim(); this.EntryMin = MIN_EOUT; this.DrpEntryIn = data.Out_Time; var DrpOut = this.DrpEntryIn.slice(17, 19).trim(); this.DrpEntryIn = DrpOut; this.ActualHr = data.ActualEntryTime; var HH_AOUT = this.ActualHr.slice(0, 2).trim(); this.ActualHr = HH_AOUT; this.ActualMin = data.ActualEntryTime; var MIN_AOUT = this.ActualMin.slice(3, 5).trim(); this.ActualMin = MIN_AOUT; this.OutId = data.OutId; this.modalAttendanceApprovalPunchOut.open(); }; AttendanceReportComponent.prototype.btnAttendanceApproveLunchOut = function (data) { this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.Employee_Id = data.Employee_Id; this.LunchOutId = data.LunchOutId; this.modalAttendanceApprovalLunchOut.open(); }; AttendanceReportComponent.prototype.btnAttendanceApproveLunchIn = function (data) { this.LunchInId = data.LunchInId; this.Employee_Id = data.Employee_Id; this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.modalAttendanceApprovalLunchIn.open(); }; AttendanceReportComponent.prototype.btnAttendanceApproveOtherwork = function (data) { this.OtherId = data.OtherId; this.Employee_Id = data.Employee_Id; this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.modalAttendanceApprovalWorkIn.open(); }; //----Punch-In Attendance Approve AttendanceReportComponent.prototype.ApproveAttendancePunchIn = function () { var _this = this; this.EntryHr = $("#EntryHour").val(); this.EntryMin = $("#EntryMinute").val(); this.DRPAM_PM = $("#ddlIn").val(); this.HODRemarks = $("#HODRemarks").val(); this.Grace = $("#Grace").val(); this.ActualHr = $("#ActualHour").val(); this.ActualMin = $("#ActualMinute").val(); this.DrpActualIn = $("#ddlAIn").val(); if ((parseInt(this.EntryHr.toString()) < 24) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; this.EntryType = 1; if (this.InId.toString().length > 0) { if (this.EntryType < 3) { if (this.DrpActualIn == "PM") { if (parseInt(this.ActualHr) <= 12) { } else { this.ActualHr += 12; } this.ActualHr; } else { this.ActualHr; } this.ActualHr = this.ActualHr + ":" + this.ActualMin; } this.indLoading = true; this._AttendanceReportService.AttendanceApproval(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.InId, 1, this.HODRemarks, this.strDate, this.Temp, this.Grace, this.ActualHr) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } else { this._AttendanceReportService.GetDailyEntryTime(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(function (data) { _this.indLoading = false; _this.EmployeeDailyTime = data; var Datetime = new Date(_this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { var Time_1 = ""; _this.EmployeeDailyTime = data; if (_this.EntryType == 1) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_1 = data.In_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_1 = data.In_Mon_Fri; }); } } else if (_this.EntryType = 2) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_1 = data.Out_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_1 = data.Out_Mon_Fri; }); } } else { Time_1 = ""; } _this.strDate = _this.AttendanceDate; _this.strarrdate = _this.strDate.split("/"); _this.Temp = _this.strarrdate[2] + _this.strarrdate[1] + _this.strarrdate[0] + " " + _this.EntryHr + ":" + _this.EntryMin + ":00" + " " + _this.DRPAM_PM; _this.EntryType = 1; _this._AttendanceReportService.AddEmployeeAttendance(global_1.Global.BASE_AttendanceReport_ENDPOINT, 0, _this.Employee_Id, _this.EntryType, _this.HODRemarks, _this.Temp, _this.strDate, Time_1, _this.Grace) .subscribe(function (success) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } } }; AttendanceReportComponent.prototype.AttendanceRejectPunchIn = function () { var _this = this; this.EntryType = 1; this.HODRemarks = $("#HODRemarks").val(); this._AttendanceReportService.AttendanceRejectPunchIn(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Id, this.EntryType, this.AttendanceDate, this.HODRemarks, this.InId) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; AttendanceReportComponent.prototype.ApproveAttendanceOkPunchIn = function () { var _this = this; var Remarks = $("#RemarksQuickApprove").val(); this._AttendanceReportService.ApproveAttendanceOkIn(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.InId, Remarks) .subscribe(function (data) { _this.indLoading = true; }, function (error) { _this.msg = error; }); }; //----Punch-Out Attendance Approve AttendanceReportComponent.prototype.ApproveAttendancePunchOut = function () { var _this = this; this.EntryHr = $("#EntryHrPunchout").val(); this.EntryMin = $("#EntryMinPunchOut").val(); this.DRPAM_PM = $("#ddlout").val(); this.HODRemarks = $("#HODRemarksPunchOut").val(); this.Grace = $("#GracePunchOut").val(); this.ActualHr = $("#ActualHourPunchOut").val(); this.ActualMin = $("#ActualMinute").val(); this.DrpActualOut = $("#ddlout").val(); this.EntryType = 2; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.OutId.toString().length > 0) { if (this.EntryType < 3) { if (this.DrpActualOut == "PM") { if (parseInt(this.ActualHr) <= 12) { } else { this.ActualHr += 12; } this.ActualHr; } else { this.ActualHr; } this.ActualHr = this.ActualHr + ":" + this.ActualMin; } this._AttendanceReportService.ApproveAttendancePunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.OutId, this.EntryType, this.HODRemarks, this.strDate, this.Temp, this.Grace, this.ActualHr) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } else { this._AttendanceReportService.GetDailyEntryTime(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(function (data) { _this.indLoading = false; _this.EmployeeDailyTime = data; var Datetime = new Date(_this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { var Time_2 = ""; _this.EmployeeDailyTime = data; if (_this.EntryType == 1) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_2 = data.In_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_2 = data.In_Mon_Fri; }); } } else if (_this.EntryType = 2) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_2 = data.Out_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_2 = data.Out_Mon_Fri; }); } } else { Time_2 = ""; } _this.strDate = _this.AttendanceDate; _this.strarrdate = _this.strDate.split("/"); _this.Temp = _this.strarrdate[2] + _this.strarrdate[1] + _this.strarrdate[0] + " " + _this.EntryHr + ":" + _this.EntryMin + ":00" + " " + _this.DRPAM_PM; _this.EntryType = 2; _this._AttendanceReportService.AddEmployeeAttendancePunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, _this.Employee_Id, _this.EntryType, _this.HODRemarks, _this.Temp, _this.strDate, _this.ActualHr, _this.Grace) .subscribe(function (success) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } } }; AttendanceReportComponent.prototype.AttendanceRejectPunchOut = function () { var _this = this; this.EntryType = 2; this.HODRemarks = $("#HODRemarksPunchOut").val(); this._AttendanceReportService.AttendanceRejectPunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Id, this.EntryType, this.AttendanceDate, this.HODRemarks, this.OutId) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; AttendanceReportComponent.prototype.ApproveAttendanceOkPunchOut = function () { var _this = this; var Remarks = $("#ApprovalRemarksOut").val(); this._AttendanceReportService.ApproveAttendanceOkPunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.OutId, Remarks) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; //----Lunch-Out Attendance Approve AttendanceReportComponent.prototype.ApproveAttendanceLunchOut = function () { var _this = this; this.EntryHr = $("#EntryHrLunchOut").val(); this.EntryMin = $("#EntryMinuteLunchOut").val(); this.DRPAM_PM = $("#ddlLunchOut").val(); this.HODRemarks = $("#RemarksLunchOut").val(); this.EntryType = 3; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.LunchOutId.toString().length > 0) { this._AttendanceReportService.ApproveAttendanceLunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.LunchOutId, this.HODRemarks, this.Temp) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } else { this.strDate = this.AttendanceDate; this._AttendanceReportService.GetDailyEntryTime(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(function (data) { _this.indLoading = false; _this.EmployeeDailyTime = data; var Datetime = new Date(_this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { var Time_3 = ""; _this.EmployeeDailyTime = data; if (_this.EntryType == 1) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_3 = data.In_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_3 = data.In_Mon_Fri; }); } } else if (_this.EntryType = 2) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_3 = data.Out_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_3 = data.Out_Mon_Fri; }); } } else { Time_3 = ""; } _this.strDate = _this.AttendanceDate; _this.strarrdate = _this.strDate.split("/"); _this.Temp = _this.strarrdate[2] + _this.strarrdate[1] + _this.strarrdate[0] + " " + _this.EntryHr + ":" + _this.EntryMin + ":00" + " " + _this.DRPAM_PM; _this.EntryType = 3; _this._AttendanceReportService.AddEmployeeAttendanceLunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, _this.Employee_Id, _this.EntryType, _this.HODRemarks, _this.Temp, _this.strDate, Time_3) .subscribe(function (success) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } } }; AttendanceReportComponent.prototype.AttendanceRejectLunchOut = function () { var _this = this; this.EntryType = 3; this.strDate = this.AttendanceDate; this.HODRemarks = $("#RemarksLunchOut").val(); this._AttendanceReportService.AttendanceRejectLunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.LunchOutId, this.Employee_Id, this.EntryType, this.strDate, this.HODRemarks) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; AttendanceReportComponent.prototype.ApproveAttendanceOkLunchOut = function () { var _this = this; var Remarks = $("#ApprovalRemarksLunchOut").val(); this._AttendanceReportService.ApproveAttendanceOkLunchOut(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.LunchOutId, Remarks) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; //----Lunch-In Attendance Approve AttendanceReportComponent.prototype.ApproveAttendanceLunchIn = function () { var _this = this; this.EntryHr = $("#EntryHourLunchIn").val(); this.EntryMin = $("#EntryMinuteLunchIn").val(); this.HODRemarks = $("#RemarksLunchIn").val(); this.DRPAM_PM = $("#ddlLunchIn").val(); this.EntryType = 4; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.LunchInId.toString().length > 0) { this._AttendanceReportService.ApproveAttendanceLunchIn(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.LunchInId, this.HODRemarks, this.Temp) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } else { this.strDate = this.AttendanceDate; this._AttendanceReportService.GetDailyEntryTime(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(function (data) { _this.indLoading = false; _this.EmployeeDailyTime = data; var Datetime = new Date(_this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { var Time_4 = ""; _this.EmployeeDailyTime = data; if (_this.EntryType == 1) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_4 = data.In_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_4 = data.In_Mon_Fri; }); } } else if (_this.EntryType = 2) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_4 = data.Out_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_4 = data.Out_Mon_Fri; }); } } else { Time_4 = ""; } _this.strDate = _this.AttendanceDate; _this.strarrdate = _this.strDate.split("/"); _this.Temp = _this.strarrdate[2] + _this.strarrdate[1] + _this.strarrdate[0] + " " + _this.EntryHr + ":" + _this.EntryMin + ":00" + " " + _this.DRPAM_PM; _this.EntryType = 4; _this._AttendanceReportService.AddEmployeeAttendanceLunchIn(global_1.Global.BASE_AttendanceReport_ENDPOINT, _this.Employee_Id, _this.EntryType, _this.HODRemarks, _this.Temp, _this.strDate, Time_4) .subscribe(function (success) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } } }; AttendanceReportComponent.prototype.AttendanceRejectLunchIn = function () { var _this = this; this.EntryType = 4; this.HODRemarks = $("#RemarksLunchIn").val(); this._AttendanceReportService.AttendanceRejectLunchIn(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.LunchInId, this.EntryType, this.AttendanceDate, this.HODRemarks) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; AttendanceReportComponent.prototype.ApproveAttendanceOkLunchIn = function () { var _this = this; var Remarks = $("#approvalRemarkslunchin").val(); this._AttendanceReportService.ApproveAttendanceOkLunchIn(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.LunchInId, Remarks) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; //-----Other In Attendance Approve AttendanceReportComponent.prototype.ApproveAttendanceOther = function () { var _this = this; this.EntryHr = $("#EntryHrother").val(); this.EntryMin = $("#EntryMinother").val(); this.DRPAM_PM = $("#ddlotherin").val(); this.HODRemarks = $("#Remarksother").val(); this.EntryType = 6; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.OtherId.toString().length > 0) { this._AttendanceReportService.ApproveAttendanceOther(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.OtherId, this.HODRemarks, this.Temp) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } else { this._AttendanceReportService.GetEmployeeIsNotHostEmployee(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id) .subscribe(function (data) { _this.indLoading = false; _this.EmployeeDailyTime = data; var Datetime = new Date(_this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { var Time_5 = ""; _this.EmployeeDailyTime = data; if (_this.EntryType == 1) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_5 = data.In_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_5 = data.In_Mon_Fri; }); } } else if (_this.EntryType = 2) { if (weekday == "Saturday") { _this.EmployeeDailyTime.forEach(function (data) { Time_5 = data.Out_Sat; }); } else { _this.EmployeeDailyTime.forEach(function (data) { Time_5 = data.Out_Mon_Fri; }); } } else { Time_5 = ""; } _this.strDate = _this.AttendanceDate; _this.strarrdate = _this.strDate.split("/"); _this.Temp = _this.strarrdate[2] + _this.strarrdate[1] + _this.strarrdate[0] + " " + _this.EntryHr + ":" + _this.EntryMin + ":00" + " " + _this.DRPAM_PM; _this.EntryType = 6; _this._AttendanceReportService.AddEmployeeAttendanceOtherwork(global_1.Global.BASE_AttendanceReport_ENDPOINT, _this.Employee_Id, _this.EntryType, _this.HODRemarks, _this.Temp, _this.strDate, Time_5) .subscribe(function (success) { _this.indLoading = false; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } } }; AttendanceReportComponent.prototype.AttendanceRejectOther = function () { var _this = this; this.EntryType = 6; this.HODRemarks = $("#Remarksother").val(); this._AttendanceReportService.AttendanceRejectOtherWork(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.OtherId, this.EntryType, this.AttendanceDate, this.HODRemarks) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; AttendanceReportComponent.prototype.ApproveAttendanceOkOtherWork = function () { var _this = this; var Remarks = $("#approvalRemarksother").val(); this._AttendanceReportService.ApproveAttendanceOkOtherWorkIn(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.OtherId, Remarks) .subscribe(function (data) { _this.indLoading = false; }, function (error) { _this.msg = error; }); }; //-------Change Event--------// AttendanceReportComponent.prototype.ChangeDepartData = function (event) { this.Id = event.target.value; }; AttendanceReportComponent.prototype.ChangeEmpData = function (event) { this.Id = event.target.value; var empid = event.target.value; }; AttendanceReportComponent.prototype.ChangeCompData = function (event) { this.Id = event.target.value; }; AttendanceReportComponent.prototype.ChangeLMData = function (event) { this.Id = event.target.value; }; //-------end drop-down----------// AttendanceReportComponent.prototype.LoadEmployee = function () { var _this = this; this.indLoading = true; this._AttendanceReportService.GetEmployee(global_1.Global.BASE_AttendanceReport_ENDPOINT) .subscribe(function (data) { _this.AttendanceEmployee = data; _this.indLoading = false; }); }; AttendanceReportComponent.prototype.LoadAllEmployee = function (event) { var _this = this; this.indLoading = true; this._AttendanceReportService.GetAllEmployee(global_1.Global.BASE_AttendanceReport_ENDPOINT) .subscribe(function (data) { _this.AttendanceEmployee = data; _this.indLoading = false; }); }; AttendanceReportComponent.prototype.LoadDepartment = function () { var _this = this; this.indLoading = true; this._AttendanceReportService.GetDepartment(global_1.Global.BASE_AttendanceReport_ENDPOINT) .subscribe(function (data) { _this.AttendanceDepart = data; _this.indLoading = false; }); }; AttendanceReportComponent.prototype.LoadCompany = function () { var _this = this; this.indLoading = true; this._AttendanceReportService.GetCompany(global_1.Global.BASE_AttendanceReport_ENDPOINT) .subscribe(function (data) { _this.AttendanceCompany = data; _this.indLoading = false; }); }; AttendanceReportComponent.prototype.LoadLineManager = function () { var _this = this; this.indLoading = true; this._AttendanceReportService.GetLineManager(global_1.Global.BASE_AttendanceReport_ENDPOINT) .subscribe(function (data) { _this.AttendanceLineManager = data; _this.indLoading = false; }); }; AttendanceReportComponent.prototype.LoadYear = function () { var _this = this; this.indLoading = true; this._AttendanceReportService.GetYear(global_1.Global.BASE_AttendanceReport_ENDPOINT) .subscribe(function (data) { _this.AttendanceYear = data; _this.indLoading = false; }); }; AttendanceReportComponent.prototype.RedirectToAddEmpRecord = function (data) { var d1 = data.Date.split('/'); var datval = d1[1] + '/' + d1[0] + '/' + d1[2]; this.router.navigate(['/AddEmployeeRecord'], { queryParams: { EmployeeId: data.Employee_Id, EmployeeName: data.Employee_Name, Date: datval, EntryTime: data.In_Time, Remarks: data.ImportRemarks } }); }; AttendanceReportComponent.prototype.RedirectToRecordPerEmp = function (data) { this.router.navigate(['/DailyEntryReport'], { queryParams: { EmployeeId: data.Employee_Id, EmployeeName: data.Employee_Name, Date: data.Date, EntryTime: data.In_Time, Remarks: data.ImportRemarks } }); }; AttendanceReportComponent.prototype.Getselectedmon = function (event) { this.Rdbmonth = $("#ddlmonth").val(); }; AttendanceReportComponent.prototype.Getselectedyear = function (event) { this.year = parseInt($("#ddlyear option:selected").text()); }; AttendanceReportComponent.prototype.ToogleMyProfile = function () { $("#AttendanceReport").slideToggle(300); }; AttendanceReportComponent.prototype.CloseWidgetProfile = function () { $("#AttendanceReport").hide(300); }; AttendanceReportComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.AttendancebindData); this.pager = this.pagerService.pager; this.pagedItems = null; this.pagedItems = this.pagerService.pagedItems; }; AttendanceReportComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; AttendanceReportComponent.prototype.ColorChange = function (data) { if (data.Total_W_Hr < data.TotalWorksheet_Hr) { //if ((data.TotalWorksheet_Hr - data.Total_W_Hr) ) //{ //} } }; AttendanceReportComponent.prototype.onSubmit = function (formData) { var _this = this; if ($("#LineManager").prop("checked")) { this.DRPData = $("#ddllm").val(); this.name = "LineManager"; } if ($("#Employee").prop("checked")) { this.DRPData = $("#ddlemp").val(); this.name = "Employee"; } if ($("#Department").prop("checked")) { this.name = "DepartMent"; this.DRPData = 0; } if ($("#Company").prop("checked")) { this.DRPData = $("#ddlcompany").val(); this.name = "Company"; } if ($("#rdbDate").prop("checked")) { this.strDate = $("#txtfromdate").val(); this.ToDate = $("#txttodate").val(); this.RDBDate = "checkedDate"; this.month = 0; this.year = 0; this.Rdbmonth = ""; } if ($("#rdbmonth").prop("checked")) { this.Rdbmonth = "Month"; this.RDBDate = ""; this.month = parseInt($("#ddlmonth").val()); this.year = parseInt($("#ddlyear option:selected").text()); this.strDate = ""; this.ToDate = ""; } var fromdate; var todate; if (this.RDBDate == 'checkedDate') { fromdate = this.strDate; todate = this.ToDate; } if (this.Rdbmonth == 'Month') { if (this.month.toString().length == 1) { fromdate = (this.year).toString().concat('0').toString().concat(this.month.toString()).concat('01').toString(); todate = (this.year).toString().concat('0').toString().concat(this.month.toString()).concat('30').toString(); } else { fromdate = (this.year).toString().concat(this.month.toString()).concat('01').toString(); todate = (this.year).toString().concat(this.month.toString()).concat('30').toString(); } } if (formData.cbMissingEntry == true) { var strEmployeeids = ''; if (this.name == "DepartMent") { this._AttendanceReportService.SelectDepartment(global_1.Global.BASE_AttendanceReport_ENDPOINT, formData.ddldept) .subscribe(function (data) { _this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); _this._AttendanceReportService.GetMissingEntry(global_1.Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(function (data) { _this.indLoading = false; _this.AttendancebindData = data; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } else if (this.name == "Company") { this._AttendanceReportService.SelectCompany(global_1.Global.BASE_AttendanceReport_ENDPOINT, formData.ddlcompany) .subscribe(function (data) { _this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); _this._AttendanceReportService.GetMissingEntry(global_1.Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(function (data) { _this.indLoading = false; _this.AttendancebindData = data; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } else if (this.name == "LineManager") { this._AttendanceReportService.SelectLineManager(global_1.Global.BASE_AttendanceReport_ENDPOINT, formData.ddllm) .subscribe(function (data) { _this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); _this._AttendanceReportService.GetMissingEntry(global_1.Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(function (data) { _this.indLoading = false; _this.AttendancebindData = data; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } } else if (formData.cbDeduction == true) { var strEmployeeids = ''; if (this.name == "DepartMent") { this._AttendanceReportService.SelectDepartment(global_1.Global.BASE_AttendanceReport_ENDPOINT, formData.ddldept) .subscribe(function (data) { _this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); _this._AttendanceReportService.GetDeductionDetails(global_1.Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(function (data) { _this.indLoading = false; _this.AttendancebindData = data; }, function (error) { _this.msg = error; }); } }); } else if (this.name == "Company") { this._AttendanceReportService.SelectCompany(global_1.Global.BASE_AttendanceReport_ENDPOINT, formData.ddlcompany) .subscribe(function (data) { _this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); _this._AttendanceReportService.GetDeductionDetails(global_1.Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(function (data) { _this.indLoading = false; _this.AttendancebindData = data; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } else if (this.name == "LineManager") { this._AttendanceReportService.SelectLineManager(global_1.Global.BASE_AttendanceReport_ENDPOINT, formData.ddllm) .subscribe(function (data) { _this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); _this._AttendanceReportService.GetDeductionDetails(global_1.Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(function (data) { _this.indLoading = false; _this.AttendancebindData = data; }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } } else { this._AttendanceReportService.GetBindAttendanceData(global_1.Global.BASE_AttendanceReport_ENDPOINT, this.Id, this.strDate, this.ToDate, this.name, this.DRPData, this.RDBDate, this.Rdbmonth, this.month, this.year) .subscribe(function (success) { _this.AttendancebindData = success; _this.JumpOnPage(1); }, function (error) { _this.msg = error; }); } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportComponent.prototype, "modal", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalPunchIn'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportComponent.prototype, "modalAttendanceApprovalPunchIn", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalPunchOut'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportComponent.prototype, "modalAttendanceApprovalPunchOut", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalLunchOut'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportComponent.prototype, "modalAttendanceApprovalLunchOut", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalLunchIn'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportComponent.prototype, "modalAttendanceApprovalLunchIn", void 0); __decorate([ core_1.ViewChild('modalAttendanceApprovalWorkIn'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceReportComponent.prototype, "modalAttendanceApprovalWorkIn", void 0); AttendanceReportComponent = __decorate([ core_1.Component({ providers: [AttendanceReport_Service_1.AttendanceReportService], templateUrl: 'app/Components/Report/Attendance/AttendanceReport.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, AttendanceReport_Service_1.AttendanceReportService, http_1.Http, router_1.Router, pager_index_1.PagerService]) ], AttendanceReportComponent); return AttendanceReportComponent; }()); exports.AttendanceReportComponent = AttendanceReportComponent; <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.RFQ; using VIS_Repository; using VIS_Repository.GeneralHelper; using VIS_Repository.RFQ; namespace VIS_App.Controllers.RFQ { public class RFQResponseAPIController : BaseAPIController { RFQResponseRepository obj = null; RFQHelperRepository objHelper = null; RFQRepository objDL = null; public RFQResponseAPIController() { obj = new RFQResponseRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objDL = new RFQRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); objHelper = new RFQHelperRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [HttpGet] [Route("api/RFQResponseAPI/GetActionTaken")] public HttpResponseMessage GetActionTaken(long UserId, bool Access) { string UserID = UserId.ToString(); return ToJson(obj.GetActionTaken(UserID, Access)); } [HttpGet] [Route("api/RFQResponseAPI/GetOnLoadData")] public HttpResponseMessage GetOnLoadData(long UserId, long RFQId) { string UserID = UserId.ToString(); return ToJson(obj.GetOnLoadData(UserID, RFQId)); } public HttpResponseMessage Post([FromBody]MainAddResponse value) { obj.SaveAddResponse(value.RFQResponse, value.SessionData, value.RFQId); objDL.RFQDoc(value.RFQDoc, value.SessionData); objDL.RFQLink(value.RFQLink, value.SessionData); return ToJson("Success:"); } [HttpGet] [Route("api/RFQResponseAPI/GetRFQDocument")] public HttpResponseMessage GetRFQDocument() { return ToJson(objHelper.GetRFQDocument()); } [HttpGet] [Route("api/RFQResponseAPI/GetRFQLink")] public HttpResponseMessage GetRFQLink() { return ToJson(objHelper.GetRFQLink()); } [HttpGet] [Route("api/RFQResponseAPI/GetViewRFQResponseById")] public HttpResponseMessage GetViewRFQResponseById(long Id) { return ToJson(obj.GetViewRFQResponseById(Id)); } } } <file_sep>export interface IAddRFQResponse { RFQ_InitialID: number; IsEstimateReady: boolean; IsChangeToAction: boolean; Hours: number; Timeline: number; Timeline_Unit: string; Leadtime: number; Leadtime_Unit: string; Technology: string; TechnologyIdList: number; Description: string; ActionRequestedBy: number; ActionByDate: Date; CurruntDate: Date; hdnEmployee: string; EmployeeName: string; hdnEmployeeId: number; EmpId : number } export interface IActionTakenBy { EmpId: number; Employee_Name: string; } export interface IHiddenValue { hdnEmployeeId : number; hdnEmployee : string; } export interface IForRFQId { RFQId: number; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Master.CurrencyRelated; namespace VIS_Domain.Master.CompanyRelated { public class Bank : Currency { /// <summary> /// Bank Entity Fields. /// </summary> public string BankAlias { get; set; } public string BankName { get; set; } public string BranchName { get; set; } public string BankAddress { get; set; } public string BankDetail { get; set; } public string AccountNumber { get; set; } public Int64 CurrencyId { get; set; } } public static class BankConstsants { /// <summary> /// Database table name constant. /// </summary> public const string const_BankMaster_Table = "BankMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_BankAlias = "BankAlias"; public const string const_BankName = "BankName"; public const string const_BranchName = "BranchName"; public const string const_BankAddress = "BankAddress"; public const string const_BankDetail = "BankDetail"; public const string const_AccountNumber = "AccountNumber"; public const string const_CurrencyId = "CurrencyId"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_Proc_BankMaster_Add = "BankMaster_Add"; public const string const_Proc_BankMaster_Update = "BankMaster_Update"; public const string const_Proc_BankMaster_Delete = "BankMaster_Delete"; public const string const_Proc_BankMaster_GetAll = "BankMaster_GetAll"; } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { SkillService } from '../../../service/Masters/VacancyRelated/Skill.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ISkill } from '../../../Model/Masters/VacancyRelated/Skill'; import { ISkillGroup } from '../../../Model/Masters/VacancyRelated/SkillGroup'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component ({ providers: [SkillService], templateUrl: 'app/Components/Masters/VacancyRelated/Skill.component.html' }) export class SkillComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; skills: ISkill[]; skill: ISkill; skillgroups: ISkillGroup[]; skillgroup: ISkillGroup; msg: string; indLoading: boolean = false; SkillFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; SkillFilter: string; isDesc: boolean = false; column: any = 'SkillName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; constructor(private fb: FormBuilder, private _SkillService: SkillService, private pagerService: PagerService) { } someFunction(data: any) { alert(data); } ngOnInit(): void { this.SkillFrm = this.fb.group ({ CompanyId: [''], Id: [''], SkillName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], Description: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], SkillGroupID: [''], SkillGroupName: [''], RatingGroup: [''], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], EntityMessage: [''] }); this.LoadSkill(); this.LoadSkillGroup(); } SkillFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.SkillFilter = value; } SkillSort(property: any) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; }; LoadSkill(): void { this.indLoading = true; this._SkillService.get(Global.BASE_SKILL_ENDPOINT) .subscribe(skills => { this.skills = skills; this.indLoading = false; console.log(skills); // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); this.indLoading = true; this._SkillService.get(Global.BASE_SKILLGROUP_ENDPOINT) .subscribe(skillgroups => { this.skillgroups = skillgroups; this.indLoading = false; } //,error => this.msg = <any>error ); } AddSkill() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Skill"; this.modalBtnTitle = "Add"; this.SkillFrm.reset(); this.modal.open(); } EditSkill(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Skill"; this.modalBtnTitle = "Update"; this.skill = this.skills.filter(x => x.Id == id)[0]; this.SkillFrm.setValue(this.skill); this.modal.open(); } DeleteSkill(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.skill = this.skills.filter(x => x.Id == id)[0]; this.SkillFrm.setValue(this.skill); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.SkillFrm.enable() : this.SkillFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.skills); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } LoadSkillGroup() { this.indLoading = true; this._SkillService.get(Global.BASE_SKILLGROUP_ENDPOINT) .subscribe(skillgroups => { this.skillgroups = skillgroups; this.indLoading = false; // set items to json response // initialize to page 1 this.JumpOnPage(1); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } //,error => this.msg = <any>error ); } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._SkillService.post(Global.BASE_SKILL_ENDPOINT, formData._value).subscribe( data => { if (data == "Success") //Success { this.msg = "Skill added successfully."; this.LoadSkill(); } else { this.msg = "Error has occurred while adding new Skill!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.update: this._SkillService.put(Global.BASE_SKILL_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data == "Success") //Success { this.msg = "Skill modified successfully."; this.LoadSkill(); } else { this.msg = "Error has occurred while modifying existing Skill!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.delete: this._SkillService.delete(Global.BASE_SKILL_ENDPOINT, formData._value.Id).subscribe( data => { if (data == "Success") //Success { this.msg = "Skill status changed successfully."; this.LoadSkill(); } else { this.msg = "Error has occurred while changing status of existing Skill!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep> import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { FinancialYearService } from '../../../service/Masters/CompanyRelated/FinancialYear.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IFinancialYear } from '../../../Model/Masters/CompanyRelated/FinancialYear'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component({ providers: [FinancialYearService], templateUrl: 'app/Components/Masters/CompanyRelated/FinancialYear.component.html' }) export class FinancialYearComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; FinancialYears: IFinancialYear[]; public FinancialYear: IFinancialYear; msg: string; indLoading: boolean = false; FinancialYearFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; FinancialYearFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strSearchFromMonth: string; strSearchToMonth: string; strSearchCurrentYear: string; strSearchNextyear: string; ArrayYear: number[] = new Array(); CurrentYear: number; constructor(private fb: FormBuilder, private _FinancialYearService: FinancialYearService, private pagerService: PagerService) { } ngOnInit(): void { this.FinancialYear = ({ Id: 0, FromMonth:'', ToMonth: '', CurrentYear:'', Nextyear: '', FinancialYear: '', CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, EntityMessage: '' }); this.LoadFinancialYearsCM(); this.LoadFinancialYears(); } LoadFinancialYearsCM(): void { } GetNextYear(): void { this.ArrayYear = []; var displayDate = (new Date()).getFullYear(); var EndDate = displayDate + 1; var j: number = 10; for (var i = 0; i < j; i++) { this.ArrayYear.push(EndDate); EndDate = EndDate - 1; } } FinancialYearFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.FinancialYearFilter = value; } FinancialYearSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ResetInputControls(): void { this.FinancialYear.FinancialYear = null; this.FinancialYear.FromMonth = null; this.FinancialYear.Nextyear = null; this.FinancialYear.ToMonth = null; } LoadFinancialYears(): void { this.indLoading = true; this._FinancialYearService.get(Global.BASE_FINANCIALYEAR_ENDPOINT) .subscribe(FinancialYears => { this.FinancialYears = FinancialYears; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchFromMonth = (<HTMLInputElement>document.getElementById("searchFromMonth")).value; if (this.strSearchFromMonth != '') { this.strSearchFromMonth = this.strSearchFromMonth.toLocaleLowerCase(); this.FinancialYears = this.FinancialYears.filter( x => x.FromMonth != null && x.FromMonth.toLocaleLowerCase().indexOf(this.strSearchFromMonth) != -1); } this.strSearchToMonth = (<HTMLInputElement>document.getElementById("searchToMonth")).value; if (this.strSearchToMonth != '') { this.strSearchToMonth = this.strSearchToMonth.toLocaleLowerCase(); this.FinancialYears = this.FinancialYears.filter( x => x.ToMonth != null && x.ToMonth.toLocaleLowerCase().indexOf(this.strSearchToMonth) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addFinancialYear() { // this.ResetInputControls(); $(function () { var year = $("#lblYear").val((new Date()).getFullYear()); }); this.GetNextYear(); this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Financial Year"; this.modalBtnTitle = "Add"; //this.FinancialYearFrm.reset(); this.modal.open(); } editFinancialYear(id: number) { this.GetNextYear(); this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Financial Year"; this.modalBtnTitle = "Update"; this.FinancialYear = this.FinancialYears.filter(x => x.Id == id)[0]; //this.FinancialYearFrm.setValue(this.FinancialYear); this.modal.open(); } deleteFinancialYear(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.FinancialYear = this.FinancialYears.filter(x => x.Id == id)[0]; //this.FinancialYearFrm.setValue(this.FinancialYear); this.modal.open(); } SetControlsState(isEnable: boolean) { // isEnable ? this.FinancialYearFrm.enable() : this.FinancialYearFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.FinancialYears); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._FinancialYearService.post(Global.BASE_FINANCIALYEAR_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadFinancialYears(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._FinancialYearService.put(Global.BASE_FINANCIALYEAR_ENDPOINT, formData.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadFinancialYears(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._FinancialYearService.delete(Global.BASE_FINANCIALYEAR_ENDPOINT, formData.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Financial Year status changed successfully."; this.LoadFinancialYears(); } else { this.msg = "Error has occurred while changing status of existing FinancialYear!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { SkillGroupService } from '../../../service/Masters/VacancyRelated/SkillGroup.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ISkillGroup } from '../../../Model/Masters/VacancyRelated/SkillGroup'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component ({ providers: [SkillGroupService], templateUrl: 'app/Components/Masters/VacancyRelated/SkillGroup.component.html' }) export class SkillGroupComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; skillgroups: ISkillGroup[]; skillgroup: ISkillGroup; msg: string; indLoading: boolean = false; SkillGroupFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; SkillGroupFilter: string; isDesc: boolean = false; column: any = 'SkillGroupName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; constructor(private fb: FormBuilder, private _SkillGroupService: SkillGroupService, private pagerService: PagerService) { } ngOnInit(): void { this.SkillGroupFrm = this.fb.group ({ CompanyId: [''], Id:[''], SkillGroupID: [''], SkillGroupName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], RatingGroup: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], EntityMessage: [''] }); this.LoadSkillGroup(); } SkillGroupFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.SkillGroupFilter = value; } SkillGroupSort(property: any) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; }; LoadSkillGroup(): void { this.indLoading = true; this._SkillGroupService.get(Global.BASE_SKILLGROUP_ENDPOINT) .subscribe(skillgroups => { this.skillgroups = skillgroups; this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } AddSkillGroup() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New SkillGroup"; this.modalBtnTitle = "Add"; this.SkillGroupFrm.reset(); this.modal.open(); } EditSkillGroup(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit SkillGroup"; this.modalBtnTitle = "Update"; this.skillgroup = this.skillgroups.filter(x => x.SkillGroupID == id)[0]; this.SkillGroupFrm.setValue(this.skillgroup); this.modal.open(); } DeleteSkillGroup(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.skillgroup = this.skillgroups.filter(x => x.SkillGroupID == id)[0]; this.SkillGroupFrm.setValue(this.skillgroup); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.SkillGroupFrm.enable() : this.SkillGroupFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.skillgroups); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._SkillGroupService.post(Global.BASE_SKILLGROUP_ENDPOINT, formData._value).subscribe( data => { if (data == "Success") //Success { this.msg = "SkillGroup added successfully."; this.LoadSkillGroup(); } else { this.msg = "Error has occurred while adding new SkillGroup!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.update: this._SkillGroupService.put(Global.BASE_SKILLGROUP_ENDPOINT, formData._value.SkillGroupID, formData._value).subscribe( data => { if (data == "Success") //Success { this.msg = "SkillGroup modified successfully."; this.LoadSkillGroup(); } else { this.msg = "Error has occurred while modifying existing SkillGroup!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.delete: this._SkillGroupService.delete(Global.BASE_SKILLGROUP_ENDPOINT, formData._value.SkillGroupID).subscribe( data => { if (data == "Success") //Success { this.msg = "SkillGroup status changed successfully."; this.LoadSkillGroup(); } else { this.msg = "Error has occurred while changing status of existing SkillGroup!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.VacancyRelated; using VIS_Repository; using VIS_Repository.Masters; using VIS_Repository.Masters.VacancyRelated; namespace VIS_App.Controllers.Masters.VacancyRelated { public class SkillAPIController : BaseAPIController { SkillRepository objSkillRepository=null; public SkillAPIController() { objSkillRepository = new SkillRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(objSkillRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]Skill value) { return ToJson(objSkillRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]Skill value) { return ToJson(objSkillRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(objSkillRepository.DeleteEntity(Id)); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var MyTeam_service_1 = require("../../../Service/HumanResource/Attendance/MyTeam.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var MyTeamComponent = (function () { function MyTeamComponent(fb, _MyTeamService, pagerService) { this.fb = fb; this._MyTeamService = _MyTeamService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'SkillName'; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; //Variables for Filter this.ShowHideSearch = false; this.ShowHideSearchNew = false; } MyTeamComponent.prototype.ngOnInit = function () { this.MyTeamFrm = this.fb.group({ CompanyId: [''], mode: [''], UserID: [''], Name: [''], NumberOfSkill: [''], NumberToBeApproved: [''], SkillName: [''], SkillGroup: [''], leavel: [''], SkillID: [''], id: [''], IsApproved: [''], Status: [''], }); this.LoadMyTeams(21); }; MyTeamComponent.prototype.MyTeamFilterCriteriaChange = function (value) { if (value != '[object Event]') this.MyTeamFilter = value; }; MyTeamComponent.prototype.MyTeamSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; MyTeamComponent.prototype.MyTeamSortNew = function (property) { if (!this.ShowHideSearchNew) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; MyTeamComponent.prototype.MouseHover = function (id) { var _this = this; //this.LoadhoverPopup(event.target.value); this.indLoading = true; this._MyTeamService.GetHoverPopup(global_1.Global.BASE_MyTeam_ENDPOINT, id) .subscribe(function (data) { _this.HoverList = data; console.log(data); //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; MyTeamComponent.prototype.LoadMyTeams = function (UserId) { var _this = this; this.indLoading = true; this._MyTeamService.GetMyTeam(global_1.Global.BASE_MyTeam_ENDPOINT, UserId) .subscribe(function (MyTeams) { _this.MyTeams = MyTeams; console.log(MyTeams); //Logic for searching - start if (_this.ShowHideSearch) { _this.searchName = document.getElementById("searchName").value; if (_this.searchName != '') { _this.searchName = _this.searchName.toLocaleLowerCase(); _this.MyTeams = _this.MyTeams.filter(function (x) { return x.Name != null && x.Name.toLocaleLowerCase().indexOf(_this.searchName) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; MyTeamComponent.prototype.addMyTeam = function () { this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New MyTeam"; this.modalBtnTitle = "Add"; this.MyTeamFrm.reset(); this.modal.open(); }; MyTeamComponent.prototype.editMyTeam = function (id) { var _this = this; debugger; this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit MyTeam"; this.modalBtnTitle = "Update"; this.indLoading = true; this._MyTeamService.GetLinemanager(global_1.Global.BASE_MyTeam_ENDPOINT, id) .subscribe(function (Linemangers) { _this.Linemangers = Linemangers; //Logic for searching - start if (_this.ShowHideSearchNew) { _this.searchSkillName = document.getElementById("searchSkillName").value; if (_this.searchSkillName != '') { _this.searchSkillName = _this.searchSkillName.toLocaleLowerCase(); _this.Linemangers = _this.Linemangers.filter(function (x) { return x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(_this.searchName) != -1; }); } _this.searchSkillGroup = document.getElementById("searchSkillGroup").value; if (_this.searchSkillGroup != '') { _this.searchSkillGroup = _this.searchSkillGroup.toLocaleLowerCase(); _this.Linemangers = _this.Linemangers.filter(function (x) { return x.SkillGroup != null && x.SkillGroup.toLocaleLowerCase().indexOf(_this.searchSkillGroup) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 } //,error => this.msg = <any>error ); this.modal.open(); }; MyTeamComponent.prototype.GetSkillOrderLeavel = function (SkillId) { var _this = this; if (SkillId != null) { this._MyTeamService.GetSkill(global_1.Global.BASE_MyTeam_ENDPOINT, SkillId) .subscribe(function (Skillleavels) { _this.Skillleavels = Skillleavels; //Logic for searching - End _this.indLoading = false; // initialize to page 1 } //,error => this.msg = <any>error ); } else { alert(SkillId); } }; MyTeamComponent.prototype.deleteMyTeam = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.MyTeamFrm.setValue(this.MyTeam); this.modal.open(); }; MyTeamComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.MyTeamFrm.enable() : this.MyTeamFrm.disable(); }; MyTeamComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; MyTeamComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.MyTeams); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; MyTeamComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; MyTeamComponent.prototype.ShowHideSearchControlsNew = function () { this.ShowHideSearchNew = !this.ShowHideSearchNew; }; MyTeamComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._MyTeamService.post(global_1.Global.BASE_MyTeam_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadMyTeams(21); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._MyTeamService.put(global_1.Global.BASE_MyTeam_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadMyTeams(21); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._MyTeamService.delete(global_1.Global.BASE_MyTeam_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadMyTeams(21); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], MyTeamComponent.prototype, "modal", void 0); MyTeamComponent = __decorate([ core_1.Component({ providers: [MyTeam_service_1.MyTeamService], templateUrl: 'app/Components/HumanResource/Attendance/MyTeam.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, MyTeam_service_1.MyTeamService, pager_index_1.PagerService]) ], MyTeamComponent); return MyTeamComponent; }()); exports.MyTeamComponent = MyTeamComponent; <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.Grievance; using VIS_Repository.HumanResource.Grievance; namespace VIS_App.Controllers.HumanResource.Grievance { public class SalaryGrievanceAPIController : BaseAPIController { SalaryGrievanceRepository objSalaryGrievanceRepository = null; public SalaryGrievanceAPIController() { objSalaryGrievanceRepository = new SalaryGrievanceRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/SalaryGrievanceAPI/GetGrievance")] [HttpGet] public HttpResponseMessage GetGrievance(Int64 UserId, string mode) { return ToJson(objSalaryGrievanceRepository.GetGrievance(UserId, mode)); } [Route("api/SalaryGrievanceAPI/FillDeductionDate")] [HttpGet] public HttpResponseMessage FillDeductionDate(Int64 UserId, string mode) { return ToJson(objSalaryGrievanceRepository.FillDeductionDate(UserId, mode)); } [Route("api/SalaryGrievanceAPI/LoadEmployeeDailyEntry")] [HttpGet] public HttpResponseMessage LoadEmployeeDailyEntry(Int64 EmployeeId, string Date) { return ToJson(objSalaryGrievanceRepository.LoadEmployeeDailyEntry(EmployeeId, Date)); } [Route("api/SalaryGrievanceAPI/LoadEmployeeAttendance")] [HttpGet] public HttpResponseMessage LoadEmployeeAttendance(Int64 EmployeeId, string Date) { return ToJson(objSalaryGrievanceRepository.LoadEmployeeAttendance(EmployeeId, Date)); } [Route("api/SalaryGrievanceAPI/AddGrievance")] [HttpGet] public HttpResponseMessage AddGrievance(Int64 EmployeeId, string Date, string PaycutAmt, string GrievanceRemark) { return ToJson(objSalaryGrievanceRepository.AddGrievance(EmployeeId, Date, PaycutAmt, GrievanceRemark)); } [Route("api/SalaryGrievanceAPI/UpdateEntity")] [HttpPut] public HttpResponseMessage UpdateEntity(Int64 UpdatedBy, SalaryGrievance Value) { return ToJson(objSalaryGrievanceRepository.UpdateEntity(Value)); } [Route("api/SalaryGrievanceAPI/GetGrievanceData")] [HttpGet] public HttpResponseMessage GetGrievanceData(Int64 Id) { return ToJson(objSalaryGrievanceRepository.GetGrievanceData(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Registration { public class VISUser : VISBaseEntity { /// <summary> /// User Entity Fields. /// </summary> public String VISUsername { get; set; } public String VISPassword { get; set; } } public static class VISUserConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_VISUser = "VISUser"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_VISUsername = "VISUsername"; public const string const_Field_VISPassword = "<PASSWORD>"; public const string const_Field_VISEmail = "Email"; public const string const_Field_FirstName = "FirstName"; public const string const_Field_LastName = "LastName"; public const string const_Field_Email = "Email"; public const string const_Field_UserType = "UserType"; public const string const_Field_IsAdmin = "IsAdmin"; public const string const_Field_IsLineManager = "IsLineManager"; public const string const_Field_DepartmentId = "DepartmentId"; public const string const_Field_IsOnStypend = "IsOnStypend"; public const string const_Field_IsFormerEmployee = "IsFormerEmployee"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procVISUser_Add = "procVISUser_Add"; public const string const_procVISUser_Update = "procVISUser_Update"; public const string const_procVISUser_ActiveInActive = "procVISUser_ActiveInActive"; public const string const_procVISUser_SelectAll = "procVISUser_SelectAll"; public const string const_procVISUser_SelectBaseNonBase = "procVISUser_SelectBaseNonBase"; public const string const_procVISUser_SelectById = "procVISUser_SelectById"; public const string const_procGetActivateImages = "procGetActivateImages"; public const string const_procVISUser_SelectByUserIdPassword = "<PASSWORD>"; public const string const_procVISUser_ForgotPassword = "<PASSWORD>"; } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Repository { public class VISDbCommand : VISDbConnection { public string CommandName { get; set; } public Int32 Timeout { get; set; } public SqlCommand objSqlCommand { get; set; } public VISDbCommand(string _connectionstring) : base(_connectionstring) { objSqlCommand = new SqlCommand(); objSqlCommand.Connection = base.DatabaseConnection; objSqlCommand.Connection.ConnectionString = _connectionstring; objSqlCommand.CommandTimeout = 24000; } public SqlParameter AddEntityMessageParameter() { SqlParameter objSqlEntityMessageParameter = new SqlParameter(); objSqlEntityMessageParameter.SqlDbType = System.Data.SqlDbType.VarChar; objSqlEntityMessageParameter.Size = 1000; objSqlEntityMessageParameter.Direction = System.Data.ParameterDirection.Output; objSqlEntityMessageParameter.ParameterName = VISBaseEntityConstants.const_Field_EntityMessage; objSqlEntityMessageParameter.Value = String.Empty; return objSqlEntityMessageParameter; } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { MySkillService } from '../../../Service/HumanResource/Attendance/MySkill.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IMySkill } from '../../../Model/HumanResource/Attendance/MySkill'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; @Component({ providers: [MySkillService], templateUrl: 'app/Components/HumanResource/Attendance/MySkill.component.html' }) export class MySkillComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; MySkills: IMySkill[]; MySkill: IMySkill; Childdata: IMySkill[]; SecondData: IMySkill[]; msg: string; indLoading: boolean = false; MySkillFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; MySkillFilter: string; isDesc: boolean = false; column: any = 'SkillName'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; searchSkillName: string; searchSkillGroupName: string; constructor(private fb: FormBuilder, private _MySkillService: MySkillService, private pagerService: PagerService) { } ngOnInit(): void { this.MySkillFrm = this.fb.group({ CompanyId: [''], mode: [''], UserID: [''], SkillName: [''], SkillGroup: [''], Skilltext: [''], SkillID: [''], lookupSkilId:[''], Name: [''], status: [''], IsApproved: [''], id :[''], }); this.LoadMySkills(21); } MySkillFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.MySkillFilter = value; } MySkillSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } deleteNewSkill(SkillID: number, UserId: number,) { this.indLoading = true; this._MySkillService.DeleteSkill(Global.BASE_MySkill_ENDPOINT, SkillID,21) .subscribe(data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadMySkills(21); } else { alert(data); } this.indLoading = false; // initialize to page 1 //this.JumpOnPageNewSkill(1); } //,error => this.msg = <any>error ); } LoadChildgrop() { this.indLoading = true; this._MySkillService.GetPopupChildSkill(Global.BASE_MySkill_ENDPOINT) .subscribe(data => { this.Childdata = data this.indLoading = false; } ); } LoadSkillName(event) { this.indLoading = true; this._MySkillService.GetPopupSecondSkill(Global.BASE_MySkill_ENDPOINT, event.target.value) .subscribe(data => { this.SecondData = data; this.indLoading = false; } ); } LoadMySkills(UserId: number): void { this.indLoading = true; this._MySkillService.GetMySkill(Global.BASE_MySkill_ENDPOINT, UserId) .subscribe(MySkills => { this.MySkills = MySkills; console.log(MySkills) //Logic for searching - start if (this.ShowHideSearch) { this.searchSkillName = (<HTMLInputElement>document.getElementById("searchSkillName")).value; if (this.searchSkillName != '') { this.searchSkillName = this.searchSkillName.toLocaleLowerCase(); this.MySkills = this.MySkills.filter( x => x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(this.searchSkillName) != -1); } } if (this.ShowHideSearch) { this.searchSkillGroupName = (<HTMLInputElement>document.getElementById("searchSkillGroupName")).value; if (this.searchSkillGroupName != '') { this.searchSkillGroupName = this.searchSkillGroupName.toLocaleLowerCase(); this.MySkills = this.MySkills.filter( x => x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(this.searchSkillGroupName) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addMySkill() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New MySkill"; this.modalBtnTitle = "Add"; this.MySkillFrm.reset(); this.modal.open(); this.LoadChildgrop(); } editMySkill(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit MySkill"; this.modalBtnTitle = "Update"; this.MySkillFrm.setValue(this.MySkill); this.modal.open(); } deleteMySkill(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.MySkillFrm.setValue(this.MySkill); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.MySkillFrm.enable() : this.MySkillFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.MySkills); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._MySkillService.post(Global.BASE_MySkill_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadMySkills(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._MySkillService.put(Global.BASE_MySkill_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data == "Success") //Success { this.msg = "MySkill modified successfully."; } else { this.msg = "Error has occurred while modifying existing MySkill!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.delete: this._MySkillService.DeleteSkill(Global.BASE_MySkill_ENDPOINT, formData._value.UserId, formData._value.SkillID).subscribe( data => { if (data == "Success") //Success { this.msg = "MySkill status changed successfully."; } else { this.msg = "Error has occurred while changing status of existing MySkill!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.VacancyRelated; using VIS_Repository.Masters; namespace VIS_Repository.Masters.VacancyRelated { public class RatingTypeRepository : VISDbCommand, VISIBaseRepository<RatingType> { public Int32 intAffectedRecords { get; set; } public RatingTypeRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RatingTypeConstant.const_procRatingType_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public RatingType GetEntityByID(Int64 entityId) { RatingType objEntityToReturn = new RatingType(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RatingTypeConstant.const_procRatingType_SelectById; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<RatingType>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<RatingType> GetEntityList() { List<RatingType> objListToReturn = new List<RatingType>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RatingTypeConstant.const_procRatingType_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<RatingType>(dt); } return objListToReturn; } public string AddEntity(RatingType entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RatingTypeConstant.const_procRatingType_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RatingTypeConstant.const_TypeName, entityObject.TypeName); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(RatingType entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RatingTypeConstant.const_procRatingType_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RatingTypeConstant.const_TypeName, entityObject.TypeName); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository; using VIS_Repository.Masters; using VIS_Repository.Masters.CompanyRelated; namespace VIS_App.Controllers.Masters.CompanyRelated { public class BankMasterAPIController : BaseAPIController { BankMasterRepositiory objBankBankRepository = null; public BankMasterAPIController() { objBankBankRepository = new BankMasterRepositiory(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/BankMasterAPI/Get")] public HttpResponseMessage Get() { return ToJson(objBankBankRepository.GetEntityList().AsEnumerable()); } [Route("api/BankMasterAPI/Post")] public HttpResponseMessage Post([FromBody]BankMaster value) { return ToJson(objBankBankRepository.AddEntity(value)); } [Route("api/BankMasterAPI/UpdateEntity")] [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, BankMaster value) { return ToJson(objBankBankRepository.UpdateEntity(value)); } [Route("api/BankMasterAPI/DeleteEntity")] [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(objBankBankRepository.DeleteEntity(Id)); } [Route("api/BankMasterAPI/GetCompany")] [HttpGet] public HttpResponseMessage GetCompany() { return ToJson(objBankBankRepository.GetCompany()); } [Route("api/BankMasterAPI/GetCurrency")] [HttpGet] public HttpResponseMessage GetCurrency() { return ToJson(objBankBankRepository.GetCurrency()); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.VacancyRelated; using VIS_Repository.Masters; namespace VIS_Repository.Masters.VacancyRelated { public class SkillRepository : VISDbCommand { public Int32 intAffectedRecords { get; set; } public SkillRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = SkillConstant.const_procSkillMaster_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public SkillViewModel GetEntityByID(Int64 Id) { SkillViewModel objEntityToReturn = new SkillViewModel(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SkillConstant.const_procSkillMaster_SelectById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<SkillViewModel>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<SkillViewModel> GetEntityList() { List<SkillViewModel> objListToReturn = new List<SkillViewModel>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SkillConstant.const_procSkillMaster_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<SkillViewModel>(dt); } return objListToReturn; } public string AddEntity(Skill entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = SkillConstant.const_procSkillMaster_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillName, entityObject.SkillName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_Description, entityObject.Description); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillGroupId, entityObject.SkillGroupID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_Status, entityObject.Status); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); if(intAffectedRecords > 0) { int counter = 0; foreach (var item in entityObject.Level) { AddSkilllevel(0,item.ToString(), counter); counter++; } } objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(Skill entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = SkillConstant.const_procSkillMaster_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillName, entityObject.SkillName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_Description, entityObject.Description); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillGroupId, entityObject.SkillGroupID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_Status, entityObject.Status); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); DeleteSkilllevel(entityObject.Id); int counter = 0; foreach (var item in entityObject.Level) { AddSkilllevel(entityObject.Id, item.ToString(), counter); counter++; } string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public void AddSkilllevel(Int64 SkillId,string SkillLevelText, int SkillLevelOrder) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = SkillConstant.const_procSkillMasterLevel_Add; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillLevelText, SkillLevelText); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillLevelOrder, SkillLevelOrder); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillId, SkillId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { } } public void DeleteSkilllevel(Int64 SkillId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = SkillConstant.const_procSkillMasterLevel_Delete; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(SkillConstant.const_SkillId, SkillId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.EmployeeLevels; using VIS_Repository; using VIS_Repository.Masters; namespace VIS_App.Controllers.Masters.EmployeeLevels { public class LevelsAPIController : BaseAPIController { VISIBaseRepository<Levels> LevelsRepository; List<Levels> EntityList = new List<Levels>(); public LevelsAPIController(VISIBaseRepository<Levels> _levelsRepository) { LevelsRepository = _levelsRepository; } public HttpResponseMessage Get() { return ToJson(LevelsRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]Levels value) { return ToJson(LevelsRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 id, [FromBody]Levels value) { return ToJson(LevelsRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(LevelsRepository.DeleteEntity(Id)); } } } <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IMyLeaveDetails = (function () { function IMyLeaveDetails() { } return IMyLeaveDetails; }()); exports.IMyLeaveDetails = IMyLeaveDetails; var INwdHistory = (function () { function INwdHistory() { } return INwdHistory; }()); exports.INwdHistory = INwdHistory; var ICalTotalAttendance = (function () { function ICalTotalAttendance() { } return ICalTotalAttendance; }()); exports.ICalTotalAttendance = ICalTotalAttendance; var IActualEntryTimeAndGraceForPunchInId = (function () { function IActualEntryTimeAndGraceForPunchInId() { } return IActualEntryTimeAndGraceForPunchInId; }()); exports.IActualEntryTimeAndGraceForPunchInId = IActualEntryTimeAndGraceForPunchInId; var IEmpLeaveLedgerForDate = (function () { function IEmpLeaveLedgerForDate() { } return IEmpLeaveLedgerForDate; }()); exports.IEmpLeaveLedgerForDate = IEmpLeaveLedgerForDate; var ILeaveDetailsByDate = (function () { function ILeaveDetailsByDate() { } return ILeaveDetailsByDate; }()); exports.ILeaveDetailsByDate = ILeaveDetailsByDate; var IEmpHolidayListForDate = (function () { function IEmpHolidayListForDate() { } return IEmpHolidayListForDate; }()); exports.IEmpHolidayListForDate = IEmpHolidayListForDate; var IHolidayForDate = (function () { function IHolidayForDate() { } return IHolidayForDate; }()); exports.IHolidayForDate = IHolidayForDate; var IMyCalender = (function () { function IMyCalender() { this.myDatePickeroption = { todaybtnTxt: 'Today', dateFormat: 'yyyy-mm-dd', firstdayofweek: 'mo', sunHighlights: true, height: '150px', width: '300px', background: '#3BAFDA', ShowTextBox: false, }; this.SelectedDate = ''; } return IMyCalender; }()); exports.IMyCalender = IMyCalender; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.EmployeeLevels { public class Reports_EmployeeLevelsRepository : VISDbCommand { private static Reports_EmployeeLevelsRepository instance = new Reports_EmployeeLevelsRepository(string.Empty); private Reports_EmployeeLevelsRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_EmployeeLevelsRepository getInstance() { return instance; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters; namespace VIS_Repository.Masters.Configuration { public class MacIdConfigurationRepository : VISDbCommand, VISIBaseRepository<MacIdConfiguration> { public Int32 intAffectedRecords { get; set; } public MacIdConfigurationRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<MacIdConfiguration> GetAllEmployees() { List<MacIdConfiguration> objListToReturn = new List<MacIdConfiguration>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MacIdConfigurationConstant.const_procEmployee_Master_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MacIdConfiguration>(dt); } return objListToReturn; } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MacIdConfigurationConstant.const_procEmployee_MacRegisteration_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public MacIdConfiguration GetEntityByID(Int64 Id) { MacIdConfiguration objEntityToReturn = new MacIdConfiguration(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MacIdConfigurationConstant.const_procEmployee_MACRegister_SelectById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<MacIdConfiguration>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<MacIdConfiguration> GetEntityList() { List<MacIdConfiguration> objListToReturn = new List<MacIdConfiguration>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MacIdConfigurationConstant.const_procEmployee_MACRegister_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MacIdConfiguration>(dt); } return objListToReturn; } public string AddEntity(MacIdConfiguration entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MacIdConfigurationConstant.const_procEmployee_MacRegisteration_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_EmployeeId,entityObject.EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_MacID, entityObject.MacID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_IPAddress, entityObject.IPAddress); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_Version, entityObject.Version); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_ApprovedBy,Convert.ToInt64(entityObject.ApprovedBy)); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(MacIdConfiguration entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MacIdConfigurationConstant.const_procEmployee_MacRegisteration_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_EmployeeId, entityObject.EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_MacID, entityObject.MacID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_IPAddress, entityObject.IPAddress); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_Version, entityObject.Version); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MacIdConfigurationConstant.const_ApprovedBy, Convert.ToInt64(entityObject.ApprovedBy)); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string ActivateDeactivateStatus(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MacIdConfigurationConstant.const_procEmployee_MacRegisteration_ActivateDeactivate; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue; } catch (Exception ex) { return ex.ToString(); } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.EmployeeManagement; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.HumanResource.EmployeeManagement; using VIS_Repository.Masters.CompanyRelated; namespace VIS_App.Controllers.HumanResource.EmployeeManagement { public class UserRoleAPIController : BaseAPIController { UserRoleRepository ObjUserRoleRepository = null; public UserRoleAPIController() { ObjUserRoleRepository = new UserRoleRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjUserRoleRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]UserRole value) { return ToJson(ObjUserRoleRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]UserRole value) { return ToJson(ObjUserRoleRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 id) { return ToJson(ObjUserRoleRepository.DeleteEntity(id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class CommonConfiguration : VISBaseEntity { /// <summary> /// CommonConfiguration Entity Fields. /// </summary> /// public string URLLocal { get; set; } public string URLLive { get; set; } public int MinimumLunchBreak { get; set; } public int MinimumOtherBreak { get; set; } public int MouseMinutes { get; set; } public int PlusMouseMinutes { get; set; } public int MouseTracking { get; set; } public int ProductivityTracker { get; set; } public int WorksheetPrompt { get; set; } public int MinimumPunchoutInterval { get; set; } public int InTimeMondayToFridayHH { get; set; } public int InTimeMondayToFridayMM { get; set; } public int OutTimeMondayToFridayHH { get; set; } public int OutTimeMondayToFridayMM { get; set; } public int InTimeSaturdayHH { get; set; } public int InTimeSaturdayMM { get; set; } public int OutTimeSaturdayHH { get; set; } public int OutTimeSaturdayMM { get; set; } public int ShiftDurationHH { get; set; } public int ShiftDurationMM { get; set; } public string TDSMenuHideOrShow { get; set; } public string RoleMenu { get; set; } } public static class CommonConfigurationConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_CommonConfiguration_Table = "CommonConfiguration"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_URLLocal = "URLLocal"; public const string const_URLLive = "URLLive"; public const string const_MinimumLunchBreak = "MinimumLunchBreak"; public const string const_MinimumOtherBreak = "MinimumOtherBreak"; public const string const_MouseMinutes = "MouseMinutes"; public const string const_PlusMouseMinutes = "PlusMouseMinutes"; public const string const_MouseTracking = "MouseTracking"; public const string const_ProductivityTracker = "ProductivityTracker"; public const string const_WorksheetPrompt = "WorksheetPrompt"; public const string const_MinimumPunchoutInterval = "MinimumPunchoutInterval"; public const string const_InTimeMondayToFridayHH = "InTimeMondayToFridayHH"; public const string const_InTimeMondayToFridayMM = "InTimeMondayToFridayMM"; public const string const_OutTimeMondayToFridayHH = "OutTimeMondayToFridayHH"; public const string const_OutTimeMondayToFridayMM = "OutTimeMondayToFridayMM"; public const string const_InTimeSaturdayHH = "InTimeSaturdayHH"; public const string const_InTimeSaturdayMM = "InTimeSaturdayMM"; public const string const_OutTimeSaturdayHH = "OutTimeSaturdayHH"; public const string const_OutTimeSaturdayMM = "OutTimeSaturdayMM"; public const string const_ShiftDurationHH = "ShiftDurationHH"; public const string const_ShiftDurationMM = "ShiftDurationMM"; public const string const_TDSMenuHideOrShow = "TDSMenuHideOrShow"; public const string const_RoleMenu = "RoleMenu"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_procCommonConfiguration_Add = "procCommonConfiguration_Add"; public const string const_procCommonConfiguration_Update = "procCommonConfiguration_Update"; public const string const_procCommonConfiguration_SelectAll = "procCommonConfiguration_SelectAll"; public const string const_procCommonConfiguration_SelectById = "procCommonConfiguration_SelectById"; public const string const_procCommonConfiguration_ActiveInActive = "procCommonConfiguration_ActiveInActive"; } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Reports; using VIS_Repository; using VIS_Repository.Reports; using VIS_Domain.Reports.Attendance; using VIS_Repository.Reports.Attendance; namespace VIS_App.Controllers.Report.Attendance { public class ProductivityTrackerReportAPIController : BaseAPIController { ProductivityTrackerReportRepository objProductivityTrackerReportRepository = null; public ProductivityTrackerReportAPIController() { objProductivityTrackerReportRepository = new ProductivityTrackerReportRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/ProductivityTrackerReportAPI/FillDepartment")] [HttpGet] public HttpResponseMessage FillDepartment() { return ToJson(objProductivityTrackerReportRepository.FillDepartment()); } [Route("api/ProductivityTrackerReportAPI/FillEmployee")] [HttpGet] public HttpResponseMessage FillEmployee(Int64 UserId,Boolean InActive) { return ToJson(objProductivityTrackerReportRepository.FillEmployee(UserId,InActive)); } [Route("api/ProductivityTrackerReportAPI/FillAllEmployees")] [HttpGet] public HttpResponseMessage FillAllEmployees(Int64 UserId, Boolean Allow) { return ToJson(objProductivityTrackerReportRepository.FillAllEmployees(UserId, Allow)); } [Route("api/ProductivityTrackerReportAPI/FillLineManager")] [HttpGet] public HttpResponseMessage FillLineManager(Int64 UserId, Boolean Allow) { return ToJson(objProductivityTrackerReportRepository.FillLineManager(UserId, Allow)); } [Route("api/ProductivityTrackerReportAPI/FillOverall")] [HttpGet] public HttpResponseMessage FillOverall() { return ToJson(objProductivityTrackerReportRepository.FillOverall()); } [Route("api/ProductivityTrackerReportAPI/FillLookup")] [HttpGet] public HttpResponseMessage FillLookup() { return ToJson(objProductivityTrackerReportRepository.FillLookup()); } [Route("api/ProductivityTrackerReportAPI/FillYear")] [HttpGet] public HttpResponseMessage FillYear() { return ToJson(objProductivityTrackerReportRepository.FillYear()); } [Route("api/ProductivityTrackerReportAPI/GetProductivity")] [HttpGet] public HttpResponseMessage GetProductivity(string sort, string FromDate, string ToDate, string Employeeids, string Mode, string OutIds, string Consolidatedview, string chk) { return ToJson(objProductivityTrackerReportRepository.GetProductivity(sort, FromDate,ToDate,Employeeids,Mode, OutIds, Consolidatedview,chk)); } } } <file_sep> import { PipeTransform, Pipe } from '@angular/core'; import { IMyProfiles } from '../../../Model/HumanResource/ProfileAttendance/MyProfiles'; @Pipe ({ name: 'MyProfilesFilter' }) export class MyProfilesFilterPipe implements PipeTransform { transform(value: IMyProfiles[], filter: string): IMyProfiles[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IMyProfiles) => app.CompanyName != null && app.CompanyName.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.UI.WebControls; using System.Web.UI; using VIS_Domain.HumanResource.Attendance; using System.Net; using System.Web; using System.Text.RegularExpressions; using VIS_Domain; namespace VIS_Repository.HumanResource.Attendace { public class WorkSheetRepository : VISDbCommand { public Int32 intAffectedRecords { get; set; } public WorkSheetRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { return null; } public WorkSheet GetEntityByID(Int64 Id) { return null; } public IEnumerable<WorkSheet> GetEntityList() { return null; ; } public string AddEntity(WorkSheet entityObject) { return null; } //public string AddWorkSheet(WorkSheet entityObject) //{ // try // { // VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); // objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // objVISDbCommand.objSqlCommand.CommandText = WorkSheetConstants.const_InsertUpdateWorkSheetMaster; // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "Insert"); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.ProjectID); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_SubActivityId, 12); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Description, entityObject.Description); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_FillDate, "2017-09-25 00:00:00.000"); // int totalminutes = 0; // int totalhours = 0; // //for (int i = 0; i < 7; i++) // //{ // double temphour; // if (entityObject.Hours != "") // { // temphour = Convert.ToDouble(entityObject.Hours); // string[] split = entityObject.Hours.Split('.'); // totalminutes += (Int32.Parse(split[0]) * 60) + (Int32.Parse(split[1])); // } // // } // totalhours = totalminutes / 60; // totalminutes = totalminutes % 60; // string finalhours = totalhours.ToString() + "." + totalminutes.ToString(); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Hours, finalhours); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, 21); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_TaskId, entityObject.TaskId); // objVISDbCommand.objSqlCommand.Connection.Open(); // intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // objSqlCommand.Connection.Close(); // } // catch (Exception ex) // { // return ex.Message + Environment.NewLine + ex.StackTrace; // } // return ""; //} //public string AddEntity(WorkSheet entityObject) //{ // try // { // VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); // objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // objVISDbCommand.objSqlCommand.CommandText = WorkSheetConstants.const_InsertUpdateWorkSheetMaster; // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "Insert"); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.ProjectID); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_SubActivityId, 12); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Description, entityObject.Description); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_FillDate, "2017-09-25 00:00:00.000"); // int totalminutes = 0; // int totalhours = 0; // //for (int i = 0; i < 7; i++) // //{ // double temphour; // if (entityObject.Hours != "") // { // temphour = Convert.ToDouble(entityObject.Hours); // string[] split = entityObject.Hours.Split('.'); // totalminutes += (Int32.Parse(split[0]) * 60) + (Int32.Parse(split[1])); // } // // } // totalhours = totalminutes / 60; // totalminutes = totalminutes % 60; // string finalhours = totalhours.ToString() + "." + totalminutes.ToString(); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Hours, finalhours); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, 21); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_TaskId, entityObject.TaskId); // objVISDbCommand.objSqlCommand.Connection.Open(); // intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // objSqlCommand.Connection.Close(); // return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; // } // catch (Exception ex) // { // return ex.Message + Environment.NewLine + ex.StackTrace; // } // //try // //{ // // int wbs_flag = 0; // // VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); // // objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // // objVISDbCommand.objSqlCommand.CommandText = WorkSheetConstants.const_InsertUpdateWorkSheetMaster; // // objVISDbCommand.objSqlCommand.Connection.Open(); // // DayOfWeek today = DateTime.Now.DayOfWeek; // // DateTime firstDate = DateTime.Now.AddDays(-(int)today); // // DataTable dt = new DataTable(); // // dt.Columns.Add("date", Type.GetType("System.String")); // // for (int i = 0; i < 7; i++) // // { // // DataRow dr = dt.NewRow(); // // dr["date"] = firstDate.AddDays(i + 1).ToShortDateString(); // // dt.Rows.Add(dr); // // } // // for (int outer = 0; outer < dt.Rows.Count; outer++) // // { // // int totalminutes = 0; // // int totalhours = 0; // // //for (int i = 0; i < 7; i++) // // //{ // // double temphour; // // if (entityObject.Hours != "") // // { // // temphour = Convert.ToDouble(entityObject.Hours); // // string[] split = entityObject.Hours.Split('.'); // // totalminutes += (Int32.Parse(split[0]) * 60) + (Int32.Parse(split[1])); // // } // // // } // // totalhours = totalminutes / 60; // // totalminutes = totalminutes % 60; // // string finalhours = totalhours.ToString() + "." + totalminutes.ToString(); // // if (Convert.ToDouble(finalhours) > 24) // // { // // // System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "AddMessage", " alert('Worksheet hours must be less than 24 hours')", true); // // } // // else // // { // // for (int inner = 0; inner < 7; inner++) // // { // // if ((entityObject.ProjectID != 0) && (!String.IsNullOrEmpty(entityObject.Description)) && (!String.IsNullOrEmpty(entityObject.Hours))) // // { // // using (base.objSqlCommand.Connection) // // { // // base.objSqlCommand.Parameters.Clear(); // // base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // // base.objSqlCommand.CommandText = WorkSheetConstants.const_ProcGetWorkSheetTaskName; // // base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "FollowWBS"); // // base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.ProjectID); // // if (base.objSqlCommand.Connection.State != ConnectionState.Open) // // { // // base.objSqlCommand.Connection.Open(); // // } // // SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); // // DataSet dt1 = new DataSet(); // // da.Fill(dt1); // // base.objSqlCommand.Connection.Close(); // // bool iswbs = (Convert.ToBoolean(dt1.Tables[0].Rows[0]["IsFollowWBS"])==true); // // if (entityObject.WorkSheetID == 0) // // { // // try // // { // // if (iswbs) // // { // // wbs_flag = 1; // // base.objSqlCommand.Parameters.Clear(); // // base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // // base.objSqlCommand.CommandText = WorkSheetConstants.const_ProcGetWorkSheetTaskName; // // base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "FollowWBS"); // // base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.TaskId); // // if (base.objSqlCommand.Connection.State != ConnectionState.Open) // // { // // base.objSqlCommand.Connection.Open(); // // } // // SqlDataAdapter daCode = new SqlDataAdapter(base.objSqlCommand); // // DataSet dtCode = new DataSet(); // // daCode.Fill(dtCode); // // base.objSqlCommand.Connection.Close(); // // string activitycode = dtCode.Tables[0].Rows[0]["activitycode"].ToString(); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "Insert"); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.ProjectID); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_SubActivityId, activitycode); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Description, entityObject.Description); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Hours, finalhours); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, entityObject.UserId); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_TaskId, entityObject.TaskId); // // objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // // base.objSqlCommand.Parameters.Clear(); // // base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // // base.objSqlCommand.CommandText = WorkSheetConstants.const_ProcGetWorkSheetTaskName; // // base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "TaskIdGet"); // // base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_TaskId, entityObject.TaskId); // // if (base.objSqlCommand.Connection.State != ConnectionState.Open) // // { // // base.objSqlCommand.Connection.Open(); // // } // // SqlDataAdapter datask = new SqlDataAdapter(base.objSqlCommand); // // DataSet dstask = new DataSet(); // // datask.Fill(dstask); // // base.objSqlCommand.Connection.Close(); // // bool value = Convert.ToBoolean(dtCode.Tables[0].Rows[0]["IsSignedOff"].ToString()); // // if (!value) // // { // // objVISDbCommand.objSqlCommand.Connection.Open(); // // intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // // if (intAffectedRecords == -1) // // { // // } // // } // // else // // { // // // ScriptManager.RegisterStartupScript(this, this.GetType(), "AddMessage", " alert('SignedOff Task can not be inserted/updated')", true); // // value = false; // // } // // } // // else // // { // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "Insert"); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.ProjectID); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_SubActivityId, 12); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Description, entityObject.Description); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_FillDate, "2015-04-14 00:00:00.000"); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Hours, finalhours); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, 21); // // intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // // if (intAffectedRecords == -1) // // { // // // ScriptManager.RegisterStartupScript(this, this.GetType(), "AddMessage", " alert('Please Contact Your Line Manager/Project Manager To Update Your Worksheet. ')", true); // // } // // } // // } // // catch (Exception ex) // // { // // // System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "AddMessage", " alert('" + ex.Message.ToString() + "')", true); // // } // // } // // else // // { // // try // // { // // if (iswbs) // // { // // wbs_flag = 1; // // objVISDbCommand.objSqlCommand.Parameters.Clear(); // // objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // // objVISDbCommand.objSqlCommand.CommandText = WorkSheetConstants.const_UpdateWorkSheetMaster; // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.TaskId); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.ProjectID); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_SubActivityId, 12); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Description, entityObject.Description); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Hours, finalhours); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, entityObject.UserId); // // intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // // if (intAffectedRecords == -1) // // { // // ///ScriptManager.RegisterStartupScript(this, this.GetType(), "AddMessage", " alert('Please Contact Your Line Manager/Project Manager To Update Your Worksheet. ')", true); // // } // // } // // else // // { // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, entityObject.ProjectID); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_SubActivityId, entityObject.SubActivityId); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Description, entityObject.Description); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Hours, finalhours); // // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, entityObject.UserId); // // intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // // if (intAffectedRecords == -1) // // { // // //ScriptManager.RegisterStartupScript(this, this.GetType(), "AddMessage", " alert('Please Contact Your Line Manager/Project Manager To Update Your Worksheet. ')", true); // // } // // } // // } // // catch (Exception ex) // // { // // // ScriptManager.RegisterStartupScript(this, this.GetType(), "AddMessage", " alert('" + ex.Message.ToString() + "')", true); // // } // // } // // } // // } // // } // // } // // break; // // } // // objSqlCommand.Connection.Close(); // // return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; // //} // //catch (Exception ex) // //{ // // return ex.Message + Environment.NewLine + ex.StackTrace; // //} //} public string SaveWorksheet(List<WorkSheet> entityObject) { try { foreach (WorkSheet WorkSheet in entityObject) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = WorkSheetConstants.const_InsertUpdateWorkSheetMaster; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "Insert"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, WorkSheet.ProjectID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_SubActivityId, 12); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Description, WorkSheet.Description); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_FillDate, "2017-09-25 00:00:00.000"); int totalminutes = 0; int totalhours = 0; //for (int i = 0; i < 7; i++) //{ double temphour; if (WorkSheet.Hours != "") { temphour = Convert.ToDouble(WorkSheet.Hours); string[] split = WorkSheet.Hours.Split('.'); totalminutes += (Int32.Parse(split[0]) * 60) + (Int32.Parse(split[1])); } // } totalhours = totalminutes / 60; totalminutes = totalminutes % 60; string finalhours = totalhours.ToString() + "." + totalminutes.ToString(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Hours, finalhours); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, 21); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_TaskId, WorkSheet.TaskId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } finally { base.objSqlCommand.Connection.Close(); } return "WorkSheet Successfully Saved...."; } public string UpdateEntity(WorkSheet entityObject) { return null; } public IEnumerable<WorkSheet> GetDefaultConfigure() { List<WorkSheet> objListToReturn = new List<WorkSheet>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = WorkSheetConstants.const_ProcGetAllActivity; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); DataSet Activity = new DataSet(); Activity.Clear(); da.Fill(Activity); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = WorkSheetConstants.const_procGetAllSubActivity; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da1 = new SqlDataAdapter(base.objSqlCommand); DataTable dt1 = new DataTable(); DataSet SubActivity = new DataSet(); SubActivity.Clear(); da.Fill(SubActivity); DataColumn dcA = new DataColumn("SubActivityId"); DataColumn dcA1 = new DataColumn("SubActivityName"); DataTable dtActivty = new DataTable(); dtActivty.Columns.Add(dcA); dtActivty.Columns.Add(dcA1); for (int Act = 0; Act < Activity.Tables[0].Rows.Count; Act++) { DataRow NewRow = dtActivty.NewRow(); NewRow["SubActivityId"] = 0; NewRow["SubActivityName"] = Activity.Tables[0].Rows[Act]["ActivityName"].ToString() + " ...."; dtActivty.Rows.Add(NewRow); DataRow[] dr = SubActivity.Tables[0].Select("activityid = " + Activity.Tables[0].Rows[Act]["Activityid"]); for (int innerRow = 0; innerRow < dr.Length; innerRow++) { NewRow = dtActivty.NewRow(); NewRow["SubActivityId"] = dr[innerRow]["SubActivityId"]; NewRow["SubActivityName"] = SpaceDDL(3) + dr[innerRow]["SubActivityName"]; dtActivty.Rows.Add(NewRow); } } objListToReturn = (from DataRow row in dtActivty.Rows select new WorkSheet() { SubActivityId = (Convert.ToInt64(row["SubActivityId"])), SubActivityName = row["SubActivityName"].ToString() }).ToList(); } return objListToReturn; } public IEnumerable<WorkSheet> GetDate() { List<WorkSheet> objListToDate = new List<WorkSheet>(); DayOfWeek today = DateTime.Now.DayOfWeek; DateTime firstDate = DateTime.Now.AddDays(-(int)today); DataTable dt = new DataTable(); dt.Columns.Add("date", Type.GetType("System.String")); for (int i = 0; i < 7; i++) { DataRow dr = dt.NewRow(); dr["date"] = firstDate.AddDays(i + 1).ToShortDateString(); dt.Rows.Add(dr); } objListToDate = (from DataRow row in dt.Rows select new WorkSheet() { Date = row["Date"].ToString() }).ToList(); return objListToDate; // DataSet WorkSheetData = SelectWorkSheetByDate(Convert.ToDateTime(lblDate.Text), Convert.ToInt32(Session["EmpId"].ToString())); } public IEnumerable<WorkSheet> GetProjectList(long UserId, string Date) { List<WorkSheet> objListToReturn = new List<WorkSheet>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = WorkSheetConstants.const_procGetProjectsByUserId; base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Date, Date); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<WorkSheet>(dt); } return objListToReturn; } public IEnumerable<WorkSheet> GetTaskDropDownFill(long ProjectId, long UserId, string Date) { List<WorkSheet> objListToReturn = new List<WorkSheet>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = WorkSheetConstants.const_ProcGetWorkSheetTaskName; base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_mode, "GetTaskName"); base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_ProjectID, ProjectId); base.objSqlCommand.Parameters.AddWithValue(WorkSheetConstants.const_Field_Date, Date); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<WorkSheet>(dt); } return objListToReturn; } private string SpaceDDL(int numberOfSpaces) { string Spaces = ""; for (int i = 0; i <= numberOfSpaces; i++) { Spaces += "&nbsp;"; } return System.Net.WebUtility.HtmlDecode(Spaces); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } //void IDisposable.Dispose() //{ // throw new NotImplementedException(); //} //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Web; using System.Web.Http; using VIS_Domain.Notification; using VIS_Repository; using VIS_Repository.Notification; namespace VIS_App.Controllers.Notification { public class MyTicketAPIController : BaseAPIController { //VISIBaseRepository<MyTicket> MyTicketRepository; //List<MyTicket> EntityList = new List<MyTicket>(); MyTicketRepository ObjMyTicketRepository = null; public MyTicketAPIController() { // MyTicketRepository = _MyTicketRepository; ObjMyTicketRepository = new MyTicketRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjMyTicketRepository.GetEntityList().AsEnumerable()); } [Route("api/MyTicketapi/GetDepatmentDll")] [HttpGet] public HttpResponseMessage GetDepatmentDll() { return ToJson(ObjMyTicketRepository.GetDepartmentOrganization().AsEnumerable()); } [Route("api/MyTicketapi/GetChildGroupData")] [HttpGet] public HttpResponseMessage GetChildGroupData(int CreatedId) { return ToJson(ObjMyTicketRepository.GetTicketByUser(CreatedId)); } [Route("api/MyTicketapi/GetViewHistoryTicket")] [HttpGet] public HttpResponseMessage GetViewHistoryTicket(int id) { return ToJson(ObjMyTicketRepository.GetViewHistory(id)); } [Route("api/MyTicketapi/GetDetailTicket")] [HttpGet] public HttpResponseMessage GetDetailTicket(int id) { return ToJson(ObjMyTicketRepository.GetTicketDetail(id)); } public HttpResponseMessage Post([FromBody]MyTicket value) { return ToJson(ObjMyTicketRepository.AddEntity(value)); } [HttpPost] [Route("api/MyTicketapi/UploadJsonFile")] public HttpResponseMessage UploadJsonFile() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/Upload/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]MyTicket value) { return ToJson(ObjMyTicketRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjMyTicketRepository.DeleteEntity(Id)); } } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IEmployeeList } from '../../../Model/HumanResource/EmployeeManagement/EmployeeList'; @Pipe ({ name: 'EmployeeListFilter' }) export class EmployeeListFilterPipe implements PipeTransform { transform(value: IEmployeeList[], filter: string): IEmployeeList[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IEmployeeList) => app.EmployeeCode != null && app.EmployeeCode.toLocaleLowerCase().indexOf(filter) != -1 || app.CompanyName != null && app.CompanyName.toLocaleLowerCase().indexOf(filter) != -1 || app.Employee_Name != null && app.Employee_Name.toLocaleLowerCase().indexOf(filter) != -1 || app.Email != null && app.Email.toLocaleLowerCase().indexOf(filter) != -1 || app.Department != null && app.Department.toLocaleLowerCase().indexOf(filter) != -1 || app.TotalExp != null && app.TotalExp.toLocaleLowerCase().indexOf(filter) != -1 || app.SL_CL != null && app.SL_CL.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class GroupName : VISBaseEntity { /// <summary> /// GroupName Entity Fields. /// </summary> /// public string GroupNames { get; set; } } public static class GroupNameConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_GroupName_Table = "GroupName"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_GroupNames = "GroupNames"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procGroupName_Add = "procGroupName_Add"; public const string const_procGroupName_Update = "procGroupName_Update"; public const string const_procGroupName_ActiveInActive = "procGroupName_ActiveInActive"; public const string const_procGroupName_SelectAll = "procGroupName_SelectAll"; public const string const_procGroupName_SelectById = "procGroupName_SelectById"; } } <file_sep>import { Component, OnInit, ViewChild} from '@angular/core'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { AddEmployeeRecordService } from '../../../Service/Report/Attendance/AddEmployeeRecord.service'; import { IEmployee, IBindEmployeeDetails, IBindEmployeeAttendance, IHRAttendance, IAttendance } from '../../../Model/Report/Attendance/AddEmployeeRecord'; @Component({ providers: [AddEmployeeRecordService], templateUrl: 'app/Components/Report/Attendance/AddEmployeeRecord.component.html' }) export class AddEmployeeRecordcomponent implements OnInit { AddEmployeeRecordFrm: FormGroup; Employees: IEmployee[]; EmployeeDailyEntrySheet: IBindEmployeeDetails[]; EmployeeEntrySheet: IBindEmployeeDetails; EmployeeAttendance: IBindEmployeeAttendance; HRAttendance: IHRAttendance[]; Attendance: IAttendance[]; indLoading: boolean = false; CurrentRecordsPerPage: number = 10; PagerInformation: string; pagedItems: any[]; pager: any = {}; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; msg: string; Grace: number; Grade: string; Mode: string; InTime: string; OutTime: string; AMPM_Data: string; TransactionId: number; EntryTime: string; EmpId: number; Date: string; HR: string; MIN: string; EntryType: number; constructor(private fb: FormBuilder, public _AddEmployeeRecordService: AddEmployeeRecordService, private router: Router, private pagerService: PagerService, private route: ActivatedRoute) { } ngOnInit(): void { this.FillEmployee(); this.EmpId = this.route.snapshot.queryParams["EmployeeId"]; this.Date = this.route.snapshot.queryParams["Date"]; if (this.EmpId != 0 && this.Date != null) { $("#Id").prop("disabled", true); $("#txtDate").prop("disabled", true); } this.BindEmployeeDetails(); this.BindEmployeeAttendance(); this.BindHRAttendanceDetails(); } FillEmployee(): void { this._AddEmployeeRecordService.FillEmployee(Global.BASE_AddEmployeeRecord_ENDPOINT) .subscribe(data => { this.indLoading = false; this.Employees = data; }, error => { this.msg = error; }); } BindEmployeeDetails(): void { this._AddEmployeeRecordService.BindEmployeeDetails(Global.BASE_AddEmployeeRecord_ENDPOINT, this.EmpId, this.Date, 21) .subscribe(data => { this.indLoading = false; this.EmployeeDailyEntrySheet = data; this.JumpOnPage(1); }, error => { this.msg = error; }); } BindEmployeeAttendance(): void { this._AddEmployeeRecordService.BindEmployeeAttendance(Global.BASE_AddEmployeeRecord_ENDPOINT, this.EmpId, this.Date) .subscribe(data => { this.indLoading = false; this.EmployeeAttendance = data; }, error => { this.msg = error; }); } BindHRAttendanceDetails(): void { this._AddEmployeeRecordService.BindHRAttendanceDetails(Global.BASE_AddEmployeeRecord_ENDPOINT, this.EmpId, this.Date) .subscribe(data => { this.indLoading = false; if (data != '') { this.HRAttendance = data; this.HRAttendance.forEach(data => { this.Grade = data.Grade; this.Grace = data.Grace; this.InTime = data.HRInTime; this.OutTime = data.HROutTime; if (this.Grade == "A1" || this.Grade == "A2") { this.Mode = "Flexible"; } else { this.Mode = "Non-Flexible"; } }); } }, error => { this.msg = error; }); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeDailyEntrySheet); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ClearFields(): void { $("#ddltype").empty(); $("#txtHr").val(''); $("#txtMinute").val(''); $("#Remarks").val('<NAME>' + ':'); // Session Storage Login User Name $("#grace").val(''); } EditReport(EmployeeEntrySheet: any): void { this.EmployeeEntrySheet = EmployeeEntrySheet; let HH = this.EmployeeEntrySheet.Entry_Time; let MM = this.EmployeeEntrySheet.Entry_Time; let AMPM = this.EmployeeEntrySheet.Entry_Time; if (this.EmployeeEntrySheet.Entry_Type == "In Time") { this.EntryType = 1; } else if (this.EmployeeEntrySheet.Entry_Type == "Out Time") { this.EntryType = 2; } else if (this.EmployeeEntrySheet.Entry_Type == "Lunch Out Time") { this.EntryType = 3; } else if (this.EmployeeEntrySheet.Entry_Type == "Lunch In Time") { this.EntryType = 4; } else if (this.EmployeeEntrySheet.Entry_Type == "Other Out Time") { this.EntryType = 5; } else if (this.EmployeeEntrySheet.Entry_Type == "Other In Time") { this.EntryType = 6; } else if (this.EmployeeEntrySheet.Entry_Type == "Meeting Out Time") { this.EntryType = 7; } else if (this.EmployeeEntrySheet.Entry_Type == "Meeting In Time") { this.EntryType = 8; } else if (this.EmployeeEntrySheet.Entry_Type == "Official Work Out Time (Approved)") { this.EntryType = 9; } else if (this.EmployeeEntrySheet.Entry_Type == "Official Work In Time (Approved)") { this.EntryType = 10; } if (HH.length <= 10) { HH.split(':'); this.HR = HH[0]; } else { HH.split(':'); this.HR = HH[0] + HH[1]; } if (MM.length <= 10) { MM.split(':'); this.MIN = MM[2] + MM[3]; } else { MM.split(':'); this.MIN = MM[3] + MM[4]; } if (AMPM.length <= 10) { AMPM.split(" "); this.AMPM_Data = AMPM[8] + AMPM[9]; } else { AMPM.split(" "); this.AMPM_Data = AMPM[9] + AMPM[10]; } } ReBindAllDetails(): void { this.BindEmployeeDetails(); this.ClearFields(); this.BindEmployeeAttendance(); this.TransactionId = null; } onSubmit(formData: any) { if (formData.EmployeeId > 0) { if (formData.EntryType > 0) { let Hr = $("#txtHr").val(); let Minute = $("#txtMinute").val(); let Remarks = $("#Remarks").val(); let Grace = $("#grace").val(); if ((parseInt($("#txtHr").val()) < 13) && (parseInt($("#txtMinute").val())) < 60) { this._AddEmployeeRecordService.BindEmployeeDetails(Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.Date,21) .subscribe(data => { this.indLoading = false; let StrEntryType; if (formData.EntryType == 1) { StrEntryType = "In Time"; } else if (formData.EntryType == 2) { StrEntryType = "Out Time"; } else if (formData.EntryType == 3) { StrEntryType = "Lunch Out Time"; } else if (formData.EntryType == 4) { StrEntryType = "Lunch In Time"; } this.EmployeeDailyEntrySheet = data; var first; var firstdata var EntryType this.EmployeeDailyEntrySheet.forEach(data => { first = function (element) { return !!element } firstdata = this.EmployeeDailyEntrySheet.find(first); EntryType = firstdata.Entry_Type; StrEntryType == EntryType }); let IsExist = false; if (StrEntryType == EntryType) { first = function (element) { return !!element } firstdata = this.EmployeeDailyEntrySheet.find(first); } else { IsExist = true; } if (IsExist) { this._AddEmployeeRecordService.GetAttendanceTransaction(Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.Date, formData.EntryType) .subscribe(success => { this.indLoading = false; this.Attendance = success; var date = $("#txtEntryDate").val(); var strDate = date.toString().split('-'); var stDate = strDate[0] + strDate[1] + strDate[2]; this.EntryTime = stDate + " " + $("#txtHr").val() + ":" + $("#txtMinute").val() + ":00" + " "; var strActualEntry = ""; if (success != '') { let id; let actualEntryTime; this.Attendance.forEach(success => { id = this.TransactionId != null ? this.TransactionId : parseInt(success.Id.toString()); actualEntryTime = success.actualEntryTime; }); if (formData.EntryType < 3) { var ActualHr = actualEntryTime.trim().toString(); ActualHr.split(':'); var A_HR = ActualHr[0] + ActualHr[1]; var A_MIN = ActualHr[3] + ActualHr[4]; if (this.AMPM_Data == "PM") { if (A_HR <= 12) { } else { A_HR += 12; } strActualEntry = A_HR.toString(); } else { strActualEntry = A_HR; } strActualEntry = strActualEntry + ":" + A_MIN; } this._AddEmployeeRecordService.GetUpdateEmployeeAttendance(Global.BASE_AddEmployeeRecord_ENDPOINT, id, formData.EmployeeId, formData.EntryType, Remarks, this.EntryTime, formData.Date, Grace, 21, strActualEntry) .subscribe(AddEmployee => { this.indLoading = false; this.ReBindAllDetails(); alert("Record Updated"); }, error => { this.msg = error; }); } else if (this.TransactionId != null) { let id; let actualEntryTime; this.Attendance.forEach(success => { id = this.TransactionId != null ? this.TransactionId : parseInt(success.Id.toString()); actualEntryTime = success.actualEntryTime; }); if (formData.EntryType < 3) { if (this.AMPM_Data == "PM") { var ActualHr = actualEntryTime.trim().toString(); ActualHr.split(':'); var A_HR = ActualHr[0] + ActualHr[1]; var A_MIN = ActualHr[3] + ActualHr[4]; if (A_HR <= 12) { } else { A_HR += 12; } strActualEntry = A_HR.toString(); } else { strActualEntry = A_HR; } strActualEntry = strActualEntry + ":" + A_MIN; } this._AddEmployeeRecordService.GetUpdateEmployeeAttendance(Global.BASE_AddEmployeeRecord_ENDPOINT, id, formData.EmployeeId, formData.EntryType, Remarks, this.EntryTime, formData.Date, Grace, 21, strActualEntry) .subscribe(AddEmployee => { this.indLoading = false; this.ReBindAllDetails(); alert("Record Updated"); }, error => { this.msg = error; }); } else { this._AddEmployeeRecordService.BindHRAttendanceDetails(Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.Date) .subscribe(HRAttendance => { this.indLoading = false; this.HRAttendance = HRAttendance; var Time = ""; if (formData.EntryType == 1) { this.HRAttendance.forEach((HRAttendance) => { Time = HRAttendance.HRInTime.toString(); }); } else if (formData.EntryType == 2) { this.HRAttendance.forEach((HRAttendance) => { Time = HRAttendance.HROutTime.toString(); }); } else { Time = ""; } this._AddEmployeeRecordService.AddEmployee(Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.EntryType, Remarks, this.EntryTime, formData.Date, Time, Grace) .subscribe(Add => { this.indLoading = false; this.ReBindAllDetails(); alert("Record Saved"); }, error => { this.msg = error; }); }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } else { this.ReBindAllDetails(); alert("Record Exist"); } }, error => { this.msg = error; }); } else { alert("Invalid Time Information !") } } else { alert("Select Type !") } } else { alert("Select Employee !"); } } }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { ISecurityKey } from '../../../Model/Masters/Configuration/SecurityKey'; @Pipe ({ name: 'securitykeyFilter' }) export class SecurityKeyFilterPipe implements PipeTransform { transform(value: ISecurityKey[], filter: string): ISecurityKey[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: ISecurityKey) => app.Key1 != null && app.Key1.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; using VIS_Repository.Reports.Attendance; using VIS_Repository.Dashboard; using VIS_Repository.Reports; namespace VIS_App.Controllers.Masters.Configuration { public class EmployeeScreenCaptureReportAPIController : BaseAPIController { EmployeeScreenCaptureReportRepository objEmployeeScreenCaptureReportRepository = null; public EmployeeScreenCaptureReportAPIController() { objEmployeeScreenCaptureReportRepository = new EmployeeScreenCaptureReportRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/EmployeeScreenCaptureReportAPI/GetEmployee")] [HttpGet] public HttpResponseMessage GetEmployee() { return ToJson(objEmployeeScreenCaptureReportRepository.GetEmployee()); } [Route("api/EmployeeScreenCaptureReportAPI/GetYear")] [HttpGet] public HttpResponseMessage GetYear() { return ToJson(objEmployeeScreenCaptureReportRepository.GetYear()); } [Route("api/EmployeeScreenCaptureReportAPI/GetReportByEmployeeId")] [HttpPost] public HttpResponseMessage GetReportByEmployeeId(EmployeeScreenCaptureParamterModel entityobject) { if(entityobject.MonthWise==true) { entityobject.FromDate = new DateTime(Convert.ToInt32(entityobject.FromYear), Convert.ToInt32(entityobject.FromMonth), 01); entityobject.ToDate = new DateTime(Convert.ToInt32(entityobject.ToYear), Convert.ToInt32(entityobject.ToMonth), DateTime.DaysInMonth(Convert.ToInt32(entityobject.ToYear), Convert.ToInt32(entityobject.ToMonth))); } return ToJson(objEmployeeScreenCaptureReportRepository.GetScreenCaptureReportByEmployeeId(entityobject)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class EducationType : VISBaseEntity { /// <summary> /// EducationType Entity Fields. /// </summary> /// public string Name { get; set; } public string Type { get; set; } public string FullName { get; set; } } public static class EducationTypeConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_EducationType_Table = "EducationType"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Name = "Name"; public const string const_Type = "Type"; public const string const_FullName = "FullName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procEducationType_Add = "procEducationType_Add"; public const string const_procEducationType_Update = "procEducationType_Update"; public const string const_procEducationType_ActiveInActive = "procEducationType_ActiveInActive"; public const string const_procEducationType_SelectAll = "procEducationType_SelectAll"; public const string const_procEducationType_SelectById = "procEducationType_SelectById"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var HelpTicketAdd_service_1 = require("../../service/Notification/HelpTicketAdd.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var http_1 = require("@angular/http"); var enum_1 = require("../../Shared/enum"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); var pager_index_1 = require("../../Shared/pager.index"); var HelpTicketAddComponent = (function () { function HelpTicketAddComponent(fb, _HelpAddTicketService, pagerService, http) { this.fb = fb; this._HelpAddTicketService = _HelpAddTicketService; this.pagerService = pagerService; this.http = http; this.indLoading = false; this.isDesc = false; this.column = 'Subject'; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; //Variables for Filter this.ShowHideSearch = false; } HelpTicketAddComponent.prototype.ngOnInit = function () { this.HelpAddTicketFrm = this.fb.group({ CompanyId: [''], Id: [''], Subject: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(50)])], Message: ['', forms_1.Validators.required], Remarks: [''], AssignTo: [''], AddressToGroup: [''], Priority: [''], Status: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], FileName: [''], FileName1: [''], FileName2: [''], EntityMessage: [''] }); // this.LoadHelpAddTickets() this.LoadDp(); }; //file upload event HelpTicketAddComponent.prototype.fileChange1 = function (event) { this.fileList1 = event.target.files; }; HelpTicketAddComponent.prototype.fileChange2 = function (event) { this.fileList2 = event.target.files; }; HelpTicketAddComponent.prototype.fileChange3 = function (event) { this.fileList3 = event.target.files; }; HelpTicketAddComponent.prototype.HelpAddTicketFilterCriteriaChange = function (value) { if (value != '[object Event]') this.HelpAddTicketFilter = value; }; HelpTicketAddComponent.prototype.HelpAddTicketSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; HelpTicketAddComponent.prototype.LoadDp = function () { var _this = this; this.indLoading = true; this._HelpAddTicketService.getDp(global_1.Global.BASE_HelpTicketAdd_ENDPOINT) .subscribe(function (DATADP) { _this.Oraganization = DATADP; } //,error => this.msg = <any>error ); }; HelpTicketAddComponent.prototype.LoadHelpAddTickets = function () { var _this = this; this.indLoading = true; this._HelpAddTicketService.get(global_1.Global.BASE_HelpTicketAdd_ENDPOINT) .subscribe(function (HelpAddTickets) { _this.HelpAddTickets = HelpAddTickets; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchHelpAddTicket_Name = document.getElementById("searchMessage").value; if (_this.strSearchHelpAddTicket_Name != '') { _this.strSearchHelpAddTicket_Name = _this.strSearchHelpAddTicket_Name.toLocaleLowerCase(); _this.HelpAddTickets = _this.HelpAddTickets.filter(function (x) { return x.Message != null && x.Message.toLocaleLowerCase().indexOf(_this.strSearchHelpAddTicket_Name) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; HelpTicketAddComponent.prototype.addHelpAddTicket = function () { this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New HelpAddTicket"; this.modalBtnTitle = "Add"; this.HelpAddTicketFrm.reset(); this.modal.open(); }; HelpTicketAddComponent.prototype.editHelpAddTicket = function (id) { this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit HelpAddTicket"; this.modalBtnTitle = "Update"; this.HelpAddTicket = this.HelpAddTickets.filter(function (x) { return x.Id == id; })[0]; this.HelpAddTicketFrm.setValue(this.HelpAddTicket); this.modal.open(); }; HelpTicketAddComponent.prototype.deleteHelpAddTicket = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.HelpAddTicket = this.HelpAddTickets.filter(function (x) { return x.Id == id; })[0]; this.HelpAddTicketFrm.setValue(this.HelpAddTicket); this.modal.open(); }; HelpTicketAddComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.HelpAddTicketFrm.enable() : this.HelpAddTicketFrm.disable(); }; HelpTicketAddComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; HelpTicketAddComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.HelpAddTickets); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; HelpTicketAddComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; //onSubmit(formData: IHelpAddTicket) { // this.msg = ""; // console.log(formData); // this._HelpAddTicketService.put(Global.BASE_HelpTicketAdd_ENDPOINT, formData.Id, formData).subscribe( // data => { // if data.startsWith("Success: "){ // this.msg = "Common Configuration Save successfully."; // this.LoadHelpAddTickets(); // } // else { // this.msg = "Error has occurred while modifying existing Common Configuration!" // } // }, // error => { // this.msg = error; // } // ); //} HelpTicketAddComponent.prototype.onSubmit = function (formData) { var _this = this; console.log(formData); this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: if (this.fileList1 != null) { formData._value.FileName = this.fileList1.item(0).name; } else { formData._value.FileName = null; } if (this.fileList2 != null) { formData._value.FileName1 = this.fileList2.item(0).name; } else { formData._value.FileName1 = null; } if (this.fileList3 != null) { formData._value.FileName2 = this.fileList3.item(0).name; } else { formData._value.FileName2 = null; } this._HelpAddTicketService.post(global_1.Global.BASE_HelpTicketAdd_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { if (_this.fileList1 != null) { if (_this.fileList1.length > 0) { _this.fileList1.item(0).name; var file = _this.fileList1[0]; var formData_1 = new FormData(); formData_1.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; _this.http.post(apiUrl1, formData_1, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); } } else { formData._value.FileName = null; } if (_this.fileList2 != null) { if (_this.fileList2.length > 0) { _this.fileList2.item(0).name; var file = _this.fileList2[0]; var formData_2 = new FormData(); formData_2.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; _this.http.post(apiUrl1, formData_2, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); } } else { formData._value.FileName2 = null; } if (_this.fileList3 != null) { if (_this.fileList3.length > 0) { _this.fileList3.item(0).name; var file = _this.fileList3[0]; var formData_3 = new FormData(); formData_3.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; _this.http.post(apiUrl1, formData_3, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); } } else { formData._value.FileName3 = null; } _this.msg = data; _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._HelpAddTicketService.put(global_1.Global.BASE_HelpTicketAdd_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadHelpAddTickets(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._HelpAddTicketService.delete(global_1.Global.BASE_HelpTicketAdd_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "HelpAddTicket status changed successfully."; _this.LoadHelpAddTickets(); } else { _this.msg = "Error has occurred while changing status of existing HelpAddTicket!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], HelpTicketAddComponent.prototype, "modal", void 0); HelpTicketAddComponent = __decorate([ core_1.Component({ providers: [HelpTicketAdd_service_1.HelpTicketAddService], templateUrl: 'app/Components/Notification/HelpTicketAdd.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, HelpTicketAdd_service_1.HelpTicketAddService, pager_index_1.PagerService, http_1.Http]) ], HelpTicketAddComponent); return HelpTicketAddComponent; }()); exports.HelpTicketAddComponent = HelpTicketAddComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository; using VIS_Repository.Masters; namespace VIS_App.Controllers.Masters.CompanyRelated { public class LookupAPIController : BaseAPIController { VISIBaseRepository<Lookup> LookupRepository; List<Lookup> EntityList = new List<Lookup>(); public LookupAPIController(VISIBaseRepository<Lookup> _LookupRepositiory) { LookupRepository = _LookupRepositiory; } public HttpResponseMessage Get() { return ToJson(LookupRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]Lookup value) { return ToJson(LookupRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]Lookup value) { return ToJson(LookupRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(LookupRepository.DeleteEntity(Id)); } } } <file_sep>export interface ICompanyMaster { Id: number; CompanyName: string; City: string; ZipCode: string; State: string; Country: string; CountryName: string; ContactNo: string; E_mail: string; Fax: string; CompanyURL: string; Address: string; CompanyLogo: string; CompanyLogoUpload : string; AccountHead: string; Designation: string; Signature: string; SignatureUpload: string; CompanyShortCode: string; Address2: string; StartSeries: string; FinancialYear: number; AccountHeadOther: string; DesignationOther: string; SignatureOther: string; SignatureOtherUpload: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; PositionName: string; Employee_Name: string; FinancialYeardll: string; }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.HumanResource.EmployeeManagement; namespace VIS_Repository.HumanResource.EmployeeManagement { public class EmployeeListRepository : VISDbCommand, VISIBaseRepository<EmployeeList> { public Int32 intAffectedRecords { get; set; } public EmployeeListRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { return null; } public string deleteEmployeeid(Int64 Id) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.Connection.Open(); base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeListConstants.const_procSelectListDeleteEmployeelist; base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Suggestionselect"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daSuggestion = new SqlDataAdapter(base.objSqlCommand); DataSet dsSuggestion = new DataSet(); dsSuggestion.Clear(); daSuggestion.Fill(dsSuggestion); base.objSqlCommand.Connection.Close(); if ((dsSuggestion.Tables[0].Rows.Count > 0 && dsSuggestion != null) || (dsSuggestion.Tables[1].Rows.Count > 0 && dsSuggestion != null)) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Suggestionselect"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Leave"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daleave = new SqlDataAdapter(base.objSqlCommand); DataSet dsleave = new DataSet(); dsleave.Clear(); daleave.Fill(dsleave); base.objSqlCommand.Connection.Close(); if (dsleave.Tables[0].Rows.Count > 0 && dsleave != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Leave"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Email"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daEmail = new SqlDataAdapter(base.objSqlCommand); DataSet dsEmail = new DataSet(); dsEmail.Clear(); daEmail.Fill(dsEmail); base.objSqlCommand.Connection.Close(); if (dsEmail.Tables[0].Rows.Count > 0 && dsEmail != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Email"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"CoFFEmployee"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daCoff = new SqlDataAdapter(base.objSqlCommand); DataSet dsCoff = new DataSet(); dsCoff.Clear(); daCoff.Fill(dsCoff); base.objSqlCommand.Connection.Close(); if (dsCoff.Tables[0].Rows.Count > 0 && dsCoff != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"CoFFEmployee"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"CurrentSalary"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daCurrentSalary = new SqlDataAdapter(base.objSqlCommand); DataSet dsCurrentSalary = new DataSet(); dsCurrentSalary.Clear(); daCurrentSalary.Fill(dsCurrentSalary); base.objSqlCommand.Connection.Close(); if (dsCurrentSalary.Tables[0].Rows.Count > 0 && dsCurrentSalary != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"CurrentSalary"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Education"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daEducation = new SqlDataAdapter(base.objSqlCommand); DataSet dsEducation = new DataSet(); dsEducation.Clear(); daEducation.Fill(dsEducation); base.objSqlCommand.Connection.Close(); if (dsEducation.Tables[0].Rows.Count > 0 && dsEducation != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Education"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"ExperienceInformation"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daExperienceInformation = new SqlDataAdapter(base.objSqlCommand); DataSet dsExperienceInformation = new DataSet(); dsExperienceInformation.Clear(); daExperienceInformation.Fill(dsExperienceInformation); base.objSqlCommand.Connection.Close(); if (dsExperienceInformation.Tables[0].Rows.Count > 0 && dsExperienceInformation != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"ExperienceInformation"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Experience"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daExperienceMaster = new SqlDataAdapter(base.objSqlCommand); DataSet dsExperienceMaster = new DataSet(); dsExperienceMaster.Clear(); daExperienceMaster.Fill(dsExperienceMaster); base.objSqlCommand.Connection.Close(); if (dsExperienceMaster.Tables[0].Rows.Count > 0 && dsExperienceMaster != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Experience"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"IncrementHistory"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daIncrementHistoryMaster = new SqlDataAdapter(base.objSqlCommand); DataSet dsIncrementHistoryMaster = new DataSet(); dsIncrementHistoryMaster.Clear(); daIncrementHistoryMaster.Fill(dsIncrementHistoryMaster); if (dsIncrementHistoryMaster.Tables[0].Rows.Count > 0 && dsIncrementHistoryMaster != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"IncrementHistory"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"JoiningDocument"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daJoiningDocument = new SqlDataAdapter(base.objSqlCommand); DataSet dsJoiningDocument = new DataSet(); dsJoiningDocument.Clear(); daJoiningDocument.Fill(dsJoiningDocument); base.objSqlCommand.Connection.Close(); if (dsJoiningDocument.Tables[0].Rows.Count > 0 && dsJoiningDocument != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"JoiningDocument"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"OfficialDetail"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daOfficialDetail = new SqlDataAdapter(base.objSqlCommand); DataSet dsOfficialDetail = new DataSet(); dsOfficialDetail.Clear(); daOfficialDetail.Fill(dsOfficialDetail); base.objSqlCommand.Connection.Close(); if (dsOfficialDetail.Tables[0].Rows.Count > 0 && dsOfficialDetail != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"OfficialDetail"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Organization"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daOrganization = new SqlDataAdapter(base.objSqlCommand); DataSet dsOrganization = new DataSet(); dsOrganization.Clear(); daOrganization.Fill(dsOrganization); base.objSqlCommand.Connection.Close(); if (dsOrganization.Tables[0].Rows.Count > 0 && dsOrganization != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Organization"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"PersonalInformation"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daPersonalInformation = new SqlDataAdapter(base.objSqlCommand); DataSet dsPersonalInformation = new DataSet(); dsPersonalInformation.Clear(); daPersonalInformation.Fill(dsPersonalInformation); base.objSqlCommand.Connection.Close(); if (dsPersonalInformation.Tables[0].Rows.Count > 0 && dsPersonalInformation != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"PersonalInformation"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"RelevingInformation"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daRelevingInformation = new SqlDataAdapter(base.objSqlCommand); DataSet dsRelevingInformation = new DataSet(); dsRelevingInformation.Clear(); daRelevingInformation.Fill(dsRelevingInformation); base.objSqlCommand.Connection.Close(); if (dsRelevingInformation.Tables[0].Rows.Count > 0 && dsRelevingInformation != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"RelevingInformation"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"carryTbl"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter dacarryTbl = new SqlDataAdapter(base.objSqlCommand); DataSet dscarryTbl = new DataSet(); dscarryTbl.Clear(); dacarryTbl.Fill(dscarryTbl); base.objSqlCommand.Connection.Close(); if (dscarryTbl.Tables[0].Rows.Count > 0 && dsSuggestion != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"carryTbl"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"NwdHistory"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daNwdHistory = new SqlDataAdapter(base.objSqlCommand); DataSet dsNwdHistory = new DataSet(); dsNwdHistory.Clear(); daNwdHistory.Fill(dsNwdHistory); base.objSqlCommand.Connection.Close(); if (dsNwdHistory.Tables[0].Rows.Count > 0 && dsNwdHistory != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"NwdHistory"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Employee_ModuleAccess"); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter daModuleAccess = new SqlDataAdapter(base.objSqlCommand); DataSet dsModuleAccess = new DataSet(); dsModuleAccess.Clear(); daModuleAccess.Fill(dsModuleAccess); base.objSqlCommand.Connection.Close(); if (dsModuleAccess.Tables[0].Rows.Count > 0 && dsModuleAccess != null) { objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Employee_ModuleAccess"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); } objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = EmployeeListConstants.const_procDeleteEmployeelist; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_mode,"Employee"); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId,Id); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } public EmployeeList GetEntityByID(Int64 entityId) { return null; } public IEnumerable<EmployeeList> GetEntityList() { return null; } public string AddEntity(EmployeeList entityObject) { try { return null; //VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); //objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; //objVISDbCommand.objSqlCommand.CommandText =EmployeeListConstants.const_procSkillUser_Add; //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId, 21); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_SkillID, entityObject.id); //if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) //{ // objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); //} //objVISDbCommand.objSqlCommand.Connection.Open(); //intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); //objSqlCommand.Connection.Close(); ////return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; //string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(EmployeeList entityObject) { return null; } public IEnumerable<EmployeeList> GetEmployeeListActive(string Usertype, long UserId, string EmployeeCode) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeListConstants.const_procgetEmployeeRecordActive; base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_Usertype, Usertype); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_EmployeeCode, EmployeeCode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public IEnumerable<EmployeeList> GetEmployeeListAll(string Usertype, long UserId, string EmployeeCode) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeListConstants.const_procgetEmployeeRecordAll; base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_Usertype, Usertype); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_EmployeeCode, EmployeeCode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public IEnumerable<EmployeeList> GetEmployeeListInActive(string Usertype, long UserId, string EmployeeCode) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeListConstants.const_procgetEmployeeRecorInActive; base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_Usertype, Usertype); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_EmployeeCode, EmployeeCode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public IEnumerable<EmployeeList> GetEmployeeModeAll(string Usertype, long UserId) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeListConstants.const_procEmployeemodeAll; base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_Usertype, Usertype); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public IEnumerable<EmployeeList> GetEmployeeModeActive(string Usertype, long UserId) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeListConstants.const_procEmployeemodeActive; base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_Usertype, Usertype); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public IEnumerable<EmployeeList> GetEmployeeModeInActive(string Usertype, long UserId) { List<EmployeeList> objListToReturn = new List<EmployeeList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeListConstants.const_procEmployeemodeInActive; base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_Usertype, Usertype); base.objSqlCommand.Parameters.AddWithValue(EmployeeListConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<EmployeeList>(dt); } return objListToReturn; } public string Delete() { try { return null; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~EmployeeListRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.Payroll { public class Reports_PayrollRepository : VISDbCommand { private static Reports_PayrollRepository instance = new Reports_PayrollRepository(string.Empty); private Reports_PayrollRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_PayrollRepository getInstance() { return instance; } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { DailyEntrysheetService } from '../../../Service/Report/Attendance/DailyEntrysheet.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IDailyEntrysheetEmployee } from '../../../Model/Report/Attendance/DailyEntrysheet'; import { IDailyEntrysheetTime, IBindAttendanceReportEmp } from '../../../Model/Report/Attendance/DailyEntrysheet'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { IEmployees } from '../../../Model/Report/Attendance/DailyEntrysheet'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { DatePipe } from '@angular/common'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [DailyEntrysheetService], templateUrl: 'app/Components/Report/Attendance/DailyEntrysheet.component.html' }) export class DailyEntrysheetComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; MM: number = new Date().getMonth() + 1 ; DD: number = new Date().getDate(); YYYY: number = new Date().getFullYear(); todaydate: string = this.MM + '/' + this.DD + '/' + this.YYYY ; employees: IEmployees[]; dailyentrytimes: IDailyEntrysheetTime[]; dailyentrytime: IDailyEntrysheetTime; dailyentryemployees: IDailyEntrysheetEmployee[]; dailyentryemployee: IDailyEntrysheetEmployee; AttendanceReportEmp: IBindAttendanceReportEmp; msg: string; msgtimevalidation: string; indLoading: boolean = false; DailyEntrysheetFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; DailyEntryFilter: string; isDesc: boolean = false; column: any = 'EventName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; nums: number[]; fulldate: string; newdate: string; newmonth: string; newyear: string; Transaction_Id: number; Date: string; formbackup: IDailyEntrysheetEmployee; InLoading: boolean; EmployeeId: number; Dateval: Date; TempDD: string; TempMM: string; TempYYYY: string; CombineDate: string; constructor(private fb: FormBuilder, private _DailyEntrysheetService: DailyEntrysheetService, private pagerService: PagerService, private route: ActivatedRoute, private _CommonHelperService: CommonHelperService ) { } ngOnInit() { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.BindEmployeeDropdownlist(); this.LoadDailyEntryData(); this.EmployeeId = this.route.snapshot.queryParams["EmployeeId"]; let EmployeeName = this.route.snapshot.queryParams["EmployeeName"]; this.Dateval = this.route.snapshot.queryParams["Date"]; let EntryTime = this.route.snapshot.queryParams["EntryTime"]; let Remarks = this.route.snapshot.queryParams["Remarks"]; this.DailyEntrysheetFrm = this.fb.group ({ Id: [''], Date: new Date() }); this.dailyentryemployee = ({ Date: null, Employee_Name: '', Entry_Time: '', Entry_Type: '', Grace: 0, Id: 0, Remarks: '', TotalBreakTime: '', TotalOfficeTime: '', TotalWorkingTime: '', TotalWorksheetHours: '', Transaction_Id: 0, actualEntryTime: '' }) if (this.EmployeeId == undefined && this.Dateval == undefined) { this.EmployeeId = 0; this.Dateval = new Date(); } } LoadDailyEntryData() { debugger; this.indLoading = true; this._DailyEntrysheetService.getalldailyentryreport(Global.BASE_DailyEntrysheet_ENDPOINT, Number(sessionStorage.getItem('Id')), this.todaydate) .subscribe(reportdata => { this.dailyentryemployees = reportdata; this.indLoading = false; this.JumpOnPage(1); } ); this.indLoading = true; this._DailyEntrysheetService.getalldailyentryreporttime(Global.BASE_DailyEntrysheet_ENDPOINT, Number(sessionStorage.getItem('Id')), this.todaydate) .subscribe(reportdatatime => { this.dailyentrytime = reportdatatime; this.indLoading = false; } ); } onSubmit(formData: any) { this.formbackup = formData; if (formData._value.Id == '0' && formData._value.Date != '') { debugger; this.msg = ''; this.InLoading = true; this._DailyEntrysheetService.getalldailyentryreportallemp(Global.BASE_DailyEntrysheet_ENDPOINT, formData._value.Date) .subscribe(reportdata => { this.dailyentryemployees = reportdata; this.dailyentrytime = null; this.JumpOnPage(1); $("html, body").animate({ scrollTop: 230 }, 150); this.InLoading = false; } ); } else { this.msg = ''; if (formData._value.Id != '' && formData._value.Date != '') { debugger; this.InLoading = true; this._DailyEntrysheetService.getalldailyentryreport(Global.BASE_DailyEntrysheet_ENDPOINT, formData._value.Id, formData._value.Date) .subscribe(reportdata => { this.dailyentryemployees = reportdata; this.JumpOnPage(1); } ); this.dailyentryemployees = null; this.indLoading = true; this._DailyEntrysheetService.getalldailyentryreporttime(Global.BASE_DailyEntrysheet_ENDPOINT, formData._value.Id, formData._value.Date) .subscribe(reportdatatime => { this.dailyentrytime = reportdatatime; this.InLoading = false; } ); } else { this.msg = "Please Select Date and Employee"; } } } ToogleMyProfile() { $("#myprofiledata").slideToggle(300); } CloseWidgetProfile() { $("#adminProfile").hide(300); } BindEmployeeDropdownlist() { this.indLoading = true; this._DailyEntrysheetService.getemployee(Global.BASE_DailyEntrysheet_ENDPOINT) .subscribe(employeedata => { this.employees = employeedata; this.indLoading = false; } //,error => this.msg = <any>error ); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.dailyentryemployees); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } SelectDate() { this.msg = ''; } EditReport(Transaction_Id: number) { this.dbops = DBOperation.update; this.modalTitle = 'Edit Record'; this.modalBtnTitle = 'Update'; this.dailyentryemployee = this.dailyentryemployees.filter(asd => asd.Transaction_Id == Transaction_Id)[0]; this.modal.open(); } UpdateReport(formDataUpdate: IDailyEntrysheetEmployee) { this.msgtimevalidation = ""; formDataUpdate.actualEntryTime = $("#actualEntryTimeHH").val() + ':' + $("#actualEntryTimeMM").val(); formDataUpdate.Entry_Time = $("#Entry_TimeHH").val() + ':' + $("#Entry_TimeMM").val() + ':' + '00' + ' ' + $("#Entry_TimeAM").val(); this._DailyEntrysheetService.updatereportdetail(Global.BASE_DailyEntrysheet_ENDPOINT, formDataUpdate).subscribe( data => { if (data != null) { if (this.formbackup!=null) { this.onSubmit(this.formbackup); } else { this.LoadDailyEntryData(); } this.modal.dismiss(); this.msg = "Data Saved Successfully...."; } else { this.msg = "Error has occurred while modifying existing Data!" } }, error => { this.msg = error; } ); } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.Attendance; using VIS_Repository.HumanResource.Attendace; namespace VIS_App.Controllers.HumanResource.Attendance { public class EmployeeFeedbackAPIController : BaseAPIController { EmployeeFeedbackRepository ObjEmployeeFeedbackRepository = null; public EmployeeFeedbackAPIController() { ObjEmployeeFeedbackRepository = new EmployeeFeedbackRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/EmployeeFeedbackAPI/UpdateFeedback")] [HttpPut] public HttpResponseMessage UpdateFeedback(Int64 Id) { return ToJson(ObjEmployeeFeedbackRepository.UpdateFeedback(Id)); } [Route("api/EmployeeFeedbackAPI/RejectFeedback")] [HttpPut] public HttpResponseMessage RejectFeedback(Int64 Id) { return ToJson(ObjEmployeeFeedbackRepository.RejectFeedback(Id)); } [Route("api/EmployeeFeedbackAPI/GetEmployeeList")] [HttpGet] public HttpResponseMessage GetEmployeeList(long UserId) { return ToJson(ObjEmployeeFeedbackRepository.GetEmployeeList(UserId)); } [Route("api/EmployeeFeedbackAPI/GetEmployeeFeedback")] [HttpGet] public HttpResponseMessage GetEmployeeFeedback(long UserId) { return ToJson(ObjEmployeeFeedbackRepository.GetEmployeeFeedbackList(UserId)); } [Route("api/EmployeeFeedbackAPI/GetPendingListEmployee")] [HttpGet] public HttpResponseMessage GetPendingListEmployee(long UserId) { return ToJson(ObjEmployeeFeedbackRepository.GetPendingListEmployee(UserId)); } [Route("api/EmployeeFeedbackAPI/GetMyTeam")] [HttpGet] public HttpResponseMessage GetMyTeam(long UserId) { return ToJson(ObjEmployeeFeedbackRepository.GetMyTeam(UserId)); } [Route("api/EmployeeFeedbackAPI/GetEmployeewiseSelect")] [HttpGet] public HttpResponseMessage GetEmployeewiseSelect(long TeamEmployeeId, long UserId) { return ToJson(ObjEmployeeFeedbackRepository.GetEmployeewiseSelect(TeamEmployeeId, UserId)); } public HttpResponseMessage Get() { return ToJson(ObjEmployeeFeedbackRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]EmployeeFeedback value) { return ToJson(ObjEmployeeFeedbackRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]EmployeeFeedback value) { return ToJson(ObjEmployeeFeedbackRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjEmployeeFeedbackRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.ProjectManagement { public class Reports_ProjectManagementRepository : VISDbCommand { private static Reports_ProjectManagementRepository instance = new Reports_ProjectManagementRepository(string.Empty); private Reports_ProjectManagementRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_ProjectManagementRepository getInstance() { return instance; } } } <file_sep>export interface IChangePassword { Id: number; VISUsername: string; VISPassword: string; NewPassword: string; ConfirmNewPassword: string; }<file_sep>import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'search-list', template: `<div class="form-inline" style="float:right;clear:both"> <div class="form-group"> <label><h3>{{title}}</h3></label> </div> <div class="form-group"> <div class="col-lg-12"> <input class="form-control" placeholder="Enter any text to filter" (paste)="getPasteData($event)" (keyup)="getEachChar($event.target.value)" type="text" [(ngModel)]="listFilter" /><img src="../../images/cross.png" class="cross-btn" (click)="clearFilter()" *ngIf="listFilter"/> </div> </div> <div class="form-group"> <div *ngIf='listFilter'> </div> </div> </div> ` }) export class SearchComponent { listFilter: string; @Input() title: string; @Output() change: EventEmitter<string> = new EventEmitter<string>(); getEachChar(value: any) { this.change.emit(value); } clearFilter() { this.listFilter = null; this.change.emit(null); } getPasteData(value: any) { let pastedVal = value.clipboardData.getData('text/plain'); this.change.emit(pastedVal); value.preventDefault(); } } /* 1. In first line we are importing Input, Output interfaces and EventEmitter class. Input and Output interfaces are self-explanatory, to take the input parameter from CurrencyComponent (in our case the search string from user), Output is to send the value back from SearchComponent but it is little interesting, the output is sent back through event using EventEmitter class. This will get more clear in the further steps. 2. In next line, we are providing the Component metadata, i.e. selector (tag name through which we will use SearchComponent in CurrencyComponent e.g. <search-list></search-list>). template is the HTML part of component. You can also put it in separate HTML file and specify the templateUrl property instead but since this is quite slim, I would prefer to have it in the same file. 3. In SearchComponent class, we are declaring one local variable listFilter that is search string we will use to display here <div class="h3 text-muted">Filter by: {{listFilter}}</div>. That is only for cosmetic purpose to show what we are searching. 4. Second variable title is with @Input decorator, we will send search textbox title from CurrencyComponent. Third variable change is with @Output decorator and of EventEmitter type. This is how we send data back to parent component. change EventEmitter<string> means change is an event that parent component needs to subscribe and will get string argument type. We will explicitly call emit function (i.e. change.emit(“test”)) to send the value back to the parent component. 5. getEachChar(value: any): this function will be called for every character user will enter in search textbox. We are only calling this.change.emit(value); that is sending that character to parent component where it is being sent to the CurrencyFilterPipe pipe to be filtered from Currency list. Just for revision, in CurrencyPipeFilter we are comparing that character with and returning only those records where this character(s) exist. So as long the user would be entering characters in Search textbox, data would be filtering on runtime. 6. clearFilter(): Will clear the filter to reset the Currency list to default without any filtering. 7. getPasteData(value: any): This is little interesting function that will take care if user would copy search string from somewhere and paste it in search textbox to filter the Currencys list. Through value.clipboardData.getData('text/plain') we are getting the pasted data and sending it through change.emit(value) function to parent component. 8. Now, we got some idea about these function, if you jump back to SearchComponent template (HTML). We are calling getEachChar on keyup event that will trigger every time user would type in Search textbox, getPasteData is being called on paste event that will occur when user would paste value in Search textbox, clearFilter function would be called on clicking the cross image that would only be visible if search textbox would have at least one character. */<file_sep>export interface IEmployee { Id: number; Employee_Name: string; } export interface IYear { CurrentYear: string; } export interface IEmployeeScreenCapture { EmployeeName: string; AllowScreenCapture: string; AttendanceStatus: string; Counts: number; Date: Date; PunchIn: string; PunchOut: string; Timming: string; } export interface IParameterModel { EmployeeId: number; FromDate: string; ToDate: string; OrderBy: string; LoginUserId: number; FromMonth: string; FromYear: string; ToMonth: string; ToYear: string; MonthWise: boolean; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Reports.Attendance { public class AddEmployeeRecord :VISBaseEntity { } public class EmployeeMaster { public Int64 Id { get; set; } public string Employee_Name { get; set; } } public class BindEmployeeDetails { public Int64 Id { get; set; } public string Employee_Name { get; set; } public Int64 Transaction_Id { get; set; } public string Entry_Type { get; set; } public string Remarks { get; set; } public string Entry_Time { get; set; } public string forWhichDate { get; set; } public string actualEntryTime { get; set; } public Int64 grace { get; set; } } public class BindHRAttendanceDetails { public string HRInTime { get; set; } public string HROutTime { get; set; } public string Grace { get; set; } public string Grade { get; set; } } public static class AddEmployeeRecordConstant { //--- Constant For Parameter public const string const_Mode = "mode"; public const string const_empId = "empId"; public const string const_forWhichDate = "forWhichDate"; public const string const_LoginUserId = "LoginUserId"; public const string const_EmployeeID = "EmployeeID"; public const string const_Date = "Date"; public const string const_EntryType = "EntryType"; public const string const_Remarks = "Remarks"; public const string const_Entry_Time = "Entry_Time"; public const string const_actualEntryTime = "actualEntryTime"; public const string const_grace = "grace"; public const string const_createdBy = "createdBy"; public const string const_Id = "Id"; public const string const_StrDate = "StrDate"; public const string const_Employee_Id = "Employee_Id"; public const string const_Entry_Type = "Entry_Type"; //--- Constant For Store Procedure public const string const_procGeneralSP = "Proc_GeneralSP"; public const string const_procReportPerEmp = "procReportPerEmp"; public const string const_ProcCalTotalAttendanceReport = "ProcCalTotalAttendanceReport"; public const string const_Proc_HRAttendanceDetail = "Proc_HRAttendanceDetail"; public const string const_Proc_updateTransaction = "Proc_updateTransaction"; public const string const_Procattendance_transaction = "Procattendance_transaction"; } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { TechnologyMasterService } from '../../../service/Masters/VacancyRelated/TechnologyMaster.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ITechnologyMaster } from '../../../Model/Masters/VacancyRelated/TechnologyMaster'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component({ providers: [TechnologyMasterService], templateUrl: 'app/Components/Masters/VacancyRelated/TechnologyMaster.component.html' }) export class TechnologyMasterComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; TechnologyMasters: ITechnologyMaster[]; TechnologyMaster: ITechnologyMaster; msg: string; indLoading: boolean = false; TechnologyMasterFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; TechnologyMasterFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; //Variables for Filter ShowHideSearch: boolean = false; strSearchTechnologyName: string; strSearchRemarks: string; strSearchMajor: string; // paged items pagedItems: any[]; constructor(private fb: FormBuilder, private _TechnologyMasterService: TechnologyMasterService, private pagerService: PagerService) { } ngOnInit(): void { this.TechnologyMasterFrm = this.fb.group({ CompanyId: [''], Id: [''], TechnologyName: ['', Validators.required], Remarks: ['', Validators.required], Major: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); this.LoadTechnologyMasters() } TechnologyMasterFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.TechnologyMasterFilter = value; } TechnologyMasterSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadTechnologyMasters(): void { this.indLoading = true; this._TechnologyMasterService.get(Global.BASE_TECHNOLOGYMASTER_ENDPOINT) .subscribe(TechnologyMasters => { this.TechnologyMasters = TechnologyMasters; this.indLoading = false; // set items to json response //Logic for searching - start if (this.ShowHideSearch) { this.strSearchTechnologyName = (<HTMLInputElement>document.getElementById("searchTechnologyName")).value; if (this.strSearchTechnologyName != '') { this.strSearchTechnologyName = this.strSearchTechnologyName.toLocaleLowerCase(); this.TechnologyMasters = this.TechnologyMasters.filter( x => x.TechnologyName != null && x.TechnologyName.toLocaleLowerCase().indexOf(this.strSearchTechnologyName) != -1); } this.strSearchRemarks = (<HTMLInputElement>document.getElementById("searchRemarks")).value; if (this.strSearchRemarks != '') { this.strSearchRemarks = this.strSearchRemarks.toLocaleLowerCase(); this.TechnologyMasters = this.TechnologyMasters.filter( x => x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(this.strSearchRemarks) != -1); } //this.strSearchMajor = (<HTMLInputElement>document.getElementById("searchSub_Unit")).value; //if (this.strSearchMajor != '') { // this.strSearchMajor = this.strSearchMajor.toLocaleLowerCase(); // this.TechnologyMasters = this.TechnologyMasters.filter( // x => x.Major != null && x.Major.toLocaleLowerCase().indexOf(this.strSearchMajor) != -1); //} } //Logic for searching - End // initialize to page 1 this.JumpOnPage(1); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } //,error => this.msg = <any>error ); } addTechnologyMaster() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New TechnologyMaster"; this.modalBtnTitle = "Add"; this.TechnologyMasterFrm.reset(); this.modal.open(); } editTechnologyMaster(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit TechnologyMaster"; this.modalBtnTitle = "Update"; this.TechnologyMaster = this.TechnologyMasters.filter(x => x.Id == id)[0]; this.TechnologyMasterFrm.setValue(this.TechnologyMaster); this.modal.open(); } deleteTechnologyMaster(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.TechnologyMaster = this.TechnologyMasters.filter(x => x.Id == id)[0]; this.TechnologyMasterFrm.setValue(this.TechnologyMaster); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.TechnologyMasterFrm.enable() : this.TechnologyMasterFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.TechnologyMasters); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._TechnologyMasterService.post(Global.BASE_TECHNOLOGYMASTER_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadTechnologyMasters(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._TechnologyMasterService.put(Global.BASE_TECHNOLOGYMASTER_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadTechnologyMasters(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._TechnologyMasterService.delete(Global.BASE_TECHNOLOGYMASTER_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "TechnologyMaster status changed successfully."; this.LoadTechnologyMasters(); } else { this.msg = "Error has occurred while changing status of existing TechnologyMaster!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class SharedContents { private PageWrapper = new Subject<string>(); private ShowDashboard = new Subject<boolean>(); private loader = new Subject<string>(); pageWrapper$ = this.PageWrapper.asObservable(); showDashboard$ = this.ShowDashboard.asObservable(); loader$ = this.loader.asObservable(); setData(pWrapper: string, showDashboard: boolean) { this.PageWrapper.next(pWrapper); this.ShowDashboard.next(showDashboard); } setLoader(loader: string) { this.loader.next(loader); } }<file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; @Injectable() export class EmpInfoTabularService { constructor(private _http: Http) { } get(url: string): Observable<any> { return this._http.get(url) .map((response: Response) => <any>response.json()); } GetRoleAdd(url: string): Observable<any> { return this._http.get(url + 'GetRoleAdd') .map((response: Response) => <any>response.json()); } GetRole(url: string): Observable<any> { return this._http.get(url + 'GetRole') .map((response: Response) => <any>response.json()); } GetTechnology(url: string): Observable<any> { return this._http.get(url + 'GetTechnology') .map((response: Response) => <any>response.json()); } GetCompany(url: string): Observable<any> { return this._http.get(url + 'GetCompany') .map((response: Response) => <any>response.json()); } GetWorking(url: string): Observable<any> { return this._http.get(url + 'GetWorking') .map((response: Response) => <any>response.json()); } GetJoiningDesignation(url: string): Observable<any> { return this._http.get(url + 'GetJoiningDesignation') .map((response: Response) => <any>response.json()); } GetDepartmentname(url: string): Observable<any> { return this._http.get(url + 'GetDepartmentname') .map((response: Response) => <any>response.json()); } GetPositionName(url: string): Observable<any> { return this._http.get(url + 'GetPositionName' ) .map((response: Response) => <any>response.json()); } GetEmployeeGrade(url: string): Observable<any> { return this._http.get(url + 'GetEmployeeGrade' ) .map((response: Response) => <any>response.json()); } GetUserRole(url: string): Observable<any> { return this._http.get(url + 'GetUserRole' ) .map((response: Response) => <any>response.json()); } GetLinemanager(url: string, Usertype: string, UserId: number): Observable<any> { return this._http.get(url + 'GetLinemanager?Usertype=' + Usertype + '&&UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetEducationType(url: string): Observable<any> { return this._http.get(url + 'GetEducationType') .map((response: Response) => <any>response.json()); } GetSalaryRangeDropDown(url: string, Salary: number): Observable<any> { return this._http.get(url + 'GetSalaryRangeDropDown?Salary=' + Salary) .map((response: Response) => <any>response.json()); } GetSalaryBrakup(url: string, SalaryRangeId: number): Observable<any> { return this._http.get(url + 'GetSalaryBrakup?SalaryRangeId=' + SalaryRangeId) .map((response: Response) => <any>response.json()); } FillEmployee(url: string): Observable<any> { return this._http.get(url + 'FillEmployee') .map((response: Response) => <any>response.json()); } GetOfferdeatils(url: string, UserId:number): Observable<any> { return this._http.get(url + 'GetOfferdeatils?UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetAdustmentleave(url: string, UserId: number): Observable<any> { return this._http.get(url + 'GetAdustmentleave?UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetEmployeeDeatils(url: string, UserId: string): Observable<any> { return this._http.get(url + 'GetEmployeeDeatils?UserId=' + UserId) .map((response: Response) => <any>response.json()); } FillLeaveDeatil(url: string): Observable<any> { debugger; return this._http.get(url + 'FillLeaveDeatil') .map((response: Response) => <any>response.json()); } GetPendingList(url: string, UserId: string): Observable<any> { return this._http.get(url + 'GetPendingList?UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetFeedbackList(url: string, UserId: string): Observable<any> { return this._http.get(url + 'GetFeedbackList?UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetNonWorking(url: string): Observable<any> { return this._http.get(url + 'GetNonWorking') .map((response: Response) => <any>response.json()); } GetInTimeOutTimeSelected(url: string): Observable<any> { return this._http.get(url + 'GetInTimeOutTimeSelected') .map((response: Response) => <any>response.json()); } GetEmployeeTime(url: string, CompanyId: number): Observable<any> { return this._http.get(url + 'GetEmployeeTime?CompanyId=' + CompanyId) .map((response: Response) => <any>response.json()); } FillPassingYear(url: string, EditEmployeeid: string, Editmode:string): Observable<any> { return this._http.get(url + 'FillPassingYear?EditEmployeeid=' + EditEmployeeid + '&&Editmode=' + Editmode) .map((response: Response) => <any>response.json()); } GetIncrementType(url: string): Observable<any> { return this._http.get(url + 'GetIncrementType') .map((response: Response) => <any>response.json()); } GetLeaveType(url: string): Observable<any> { return this._http.get(url + 'GetLeaveType') .map((response: Response) => <any>response.json()); } GetSkill(url: string): Observable<any> { return this._http.get(url + 'GetSkill') .map((response: Response) => <any>response.json()); } GetPopupSkill(url: string, lookupSkilId:number): Observable<any> { return this._http.get(url + 'GetPopupSkill?lookupSkilId=' + lookupSkilId) .map((response: Response) => <any>response.json()); } GetGridViewList(url: string, UserId: number): Observable<any> { return this._http.get(url + 'GetGridViewList?UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetAttendanceDetail(url: string, AccessCardId: number, UserId: number): Observable<any> { debugger; return this._http.get(url + 'GetAttendanceDetail?AccessCardId=' + AccessCardId + '&&UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetIncrementList(url: string): Observable<any> { return this._http.get(url + 'GetIncrementList') .map((response: Response) => <any>response.json()); } GetAccountNo(url: string, AccountNumber: string, UserId: string): Observable<any> { return this._http.get(url + 'GetAccountNo?AccountNumber=' + AccountNumber + '&&UserId=' + UserId) .map((response: Response) => <any>response.json()); } FillProjectDetail(url: string, FromDate: string, ToDate: string, UserId:number): Observable<any> { return this._http.get(url + 'FillProjectDetail?FromDate=' + FromDate + '&&ToDate=' + ToDate + '&&UserId=' + UserId) .map((response: Response) => <any>response.json()); } FillProjectDetailWbs(url: string, FromDate: string, ToDate: string, UserId:number): Observable<any> { return this._http.get(url + 'FillProjectDetailWbs?FromDate=' + FromDate + '&&ToDate=' + ToDate + '&&UserId=' + UserId) .map((response: Response) => <any>response.json()); } SaveMain(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveMain/', body, options) .map((response: Response) => <any>response.json()); } SavePersonal(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SavePersonal/', body, options) .map((response: Response) => <any>response.json()); } SaveEducation(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveEducation/', body, options) .map((response: Response) => <any>response.json()); } SaveSalary(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveSalary/', body, options) .map((response: Response) => <any>response.json()); } SaveAttendance(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveAttendance/', body, options) .map((response: Response) => <any>response.json()); } SaveNwdDay(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveNwdDay/', body, options) .map((response: Response) => <any>response.json()); } SaveJoining(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveJoining/', body, options) .map((response: Response) => <any>response.json()); } SaveIncrement(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveIncrement/', body, options) .map((response: Response) => <any>response.json()); } SaveOfficial(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'SaveOfficial/', body, options) .map((response: Response) => <any>response.json()); } btnAddExp(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'btnAddExp/', body, options) .map((response: Response) => <any>response.json()); } AddLeave(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'AddLeave/', body, options) .map((response: Response) => <any>response.json()); } Saveskill(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'Saveskill/', body, options) .map((response: Response) => <any>response.json()); } AddRole(url: any, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'AddRole/', body, options) .map((response: Response) => <any>response.json()); } post(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } put(url: string, id: number, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity/' + id, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } delete(url: string, id: number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } //DeleteRole(url: string, ExpRoleId: number): Observable<any> { // debugger; // let headers = new Headers({ 'Content-Type': 'application/json' }); // let options = new RequestOptions({ headers: headers }); // return this._http.delete(url + 'DeleteRole/' + ExpRoleId, options) // .map((response: Response) => <any>response.json()) // .catch(this.handleError); //} private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.Attendance { public class MyTeam : VISBaseEntity { public Int64 id { get; set; } public string mode { get; set; } public Int64 UserId { get; set; } public string Name { get; set; } public Int64 NumberOfSkill { get; set; } public Int64 NumberToBeApproved { get; set; } public string SkillName { get; set; } public string SkillGroup { get; set; } public string SkillText { get; set; } public string leavel { get; set; } public Int64 SkillID { get; set; } public string LevelText { get; set; } public int Levelorder { get; set; } public bool IsApproved { get; set; } public string Status { get; set; } } public static class MyTeamConstants { public const string const_Table_MyTeam = "MyTeam"; public const string const_Field_id = "id"; public const string const_Field_mode = "mode"; public const string const_Field_UserId = "UserId"; public const string const_Field_Name = "Name"; public const string const_Field_NumberOfSkill = "NumberOfSkill"; public const string const_Field_NumberToBeApproved = "NumberToBeApproved"; public const string const_Field_SkillName = "SkillName"; public const string const_Field_SkillGroup = "SkillGroup"; public const string const_Field_SkillText = "SkillText"; public const string const_Field_leavel = "leavel"; public const string const_Field_SkillID = "SkillID"; public const string const_Field_LevelText = "LevelText"; public const string const_Field_Levelorder = "Levelorder"; public const string const_Field_IsApproved = "IsApproved"; public const string const_Field_Status = "Status"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_procGetMyTeam_List = "procGetMyTeam_List"; public const string const_procgetLinemanager = "procgetLinemanager"; public const string const_procSkillLeavel = "procSkillLeavel"; } } <file_sep>export interface IHelpAddTicket { CompanyId: number; Id: number; Subject: string; Message: string; Remarks: string; AssignTo: number; AddressToGroup: number; Priority: string Status: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IMySkill } from '../../../Model/HumanResource/Attendance/MySkill'; @Pipe ({ name: 'MySkillFilter' }) export class MySkillFilterPipe implements PipeTransform { transform(value: IMySkill[], filter: string): IMySkill[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IMySkill) => app.SkillName != null && app.SkillName.toLocaleLowerCase().indexOf(filter) != -1 || app.SkillGroup != null && app.SkillGroup.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>import {IChangePassword } from '../ProfileAttendance/ChangePassword'; export class IHumanResource { ChangePasswordData: IChangePassword; }<file_sep>using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository { public class VISDbConnection { protected SqlConnection DatabaseConnection { get; set; } public VISDbConnection(String _connectionstring) { try { DatabaseConnection = new SqlConnection(_connectionstring); } catch { throw; } } //~VISDbConnection() //{ // SqlConnection.ClearPool(DatabaseConnection); //} } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.EmployeeManualPointEntry; using VIS_Domain.Masters.EmployeeLevelCriteriaSetup; using VIS_Domain.Masters.EmployeeLevels; namespace VIS_Repository.Masters.EmployeeLevels { public class ManualPointEntryRepository : VISDbCommand, VISIBaseRepository<ManualPointEntry> { public Int32 intAffectedRecords { get; set; } public ManualPointEntryRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public ManualPointEntry GetEntityByID(Int64 entityId) { ManualPointEntry objEntityToReturn = new ManualPointEntry(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_SelectById; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<ManualPointEntry>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<ManualPointEntry> GetEntityList() { List<ManualPointEntry> objListToReturn = new List<ManualPointEntry>(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ManualPointEntry>(dt); } return objListToReturn; } catch (Exception ex) { return objListToReturn; } } public DataTable GetEmployeeList() { //List<ManualPointEntry> objListToReturn = new List<ManualPointEntry>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_SelectEmployee; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); //objListToReturn = VISAutoMapper.ConvertDataTable<ManualPointEntry>(dt); return dt; } } public string AddEntity(ManualPointEntry entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_Add; //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_EndPoint, entityObject.EndPoint); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_LevelIcon, entityObject.LevelIcon); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_LevelName, entityObject.LevelName); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_LevelNumber, entityObject.LevelNumber); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_StartPoint, entityObject.StartPoint); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(ManualPointEntry entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_EndPoint, entityObject.EndPoint); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_LevelIcon, entityObject.LevelIcon); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_LevelName, entityObject.LevelName); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_LevelNumber, entityObject.LevelNumber); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_StartPoint, entityObject.StartPoint); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<ManualPointEntry> GetCriteria() { List<ManualPointEntry> objListToReturn = new List<ManualPointEntry>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_GetCriteria; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ManualPointEntry>(dt); } return objListToReturn; } //GetDataByCriteriaId public ManualPointEntry GetDataByCriteriaId(int CriteriaId) { ManualPointEntry objEntityToReturn = new ManualPointEntry(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_GetDataByCriteriaId; base.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_CriteriaId, CriteriaId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<ManualPointEntry>(dt.Rows[0]); } return objEntityToReturn; } public ManualPointEntry GetEmployeeById(int Id) { ManualPointEntry objEntityToReturn = new ManualPointEntry(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_GetEmployeeById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<ManualPointEntry>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<ManualPointEntry> GetCategory() { List<ManualPointEntry> objListToReturn = new List<ManualPointEntry>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_GetCategory; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ManualPointEntry>(dt); } return objListToReturn; } public string SaveLevelsPointLog(LevelsPointLog entityObject) { try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ManualPointEntryConstants.const_procSaveLevelsPointLog; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_EmployeeID, entityObject.EmployeeID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_SetupID, entityObject.SetupID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_Date, entityObject.Date); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_Points, entityObject.Points); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_GroupID, entityObject.GroupID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_Remarks, entityObject.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_Count, entityObject.Count); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsPointLogConstants.const_Field_IsActive, entityObject.IsActive); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string GetMaxGroupId() { string max; using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (SqlCommand cmd = new SqlCommand(ManualPointEntryConstants.const_procGetMaxGroupId, base.objSqlCommand.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@max", SqlDbType.VarChar, 30); cmd.Parameters["@max"].Direction = ParameterDirection.Output; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } cmd.ExecuteNonQuery(); max = cmd.Parameters["@Max"].Value.ToString(); } //base.objSqlCommand.Parameters.Clear(); //base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; //base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procGetMaxGroupId; //if (!base.objSqlCommand.Parameters.Contains(ManualPointEntryConstants.const_Field_Max)) //{ // base.objSqlCommand.Parameters.Add(AddEntityMaxParameter()); //} //if (base.objSqlCommand.Connection.State != ConnectionState.Open) //{ // base.objSqlCommand.Connection.Open(); //} //SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); //max = (string)objSqlCommand.ExecuteScalar(); } return max; } public string GetCriteriaFromSetupId(long iSetupId) { string AliasName; using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (SqlCommand cmd = new SqlCommand(ManualPointEntryConstants.const_GetCriteriaFromSetupId, base.objSqlCommand.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@AliasName", SqlDbType.VarChar, 30); cmd.Parameters["@AliasName"].Direction = ParameterDirection.Output; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } cmd.ExecuteNonQuery(); AliasName = cmd.Parameters["@AliasName"].Value.ToString(); } } return AliasName; } public EmployeeData GetEmployeeByIdForMail(long Id) { EmployeeData objEntityToReturn = new EmployeeData(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_GetEmployeeById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<EmployeeData>(dt.Rows[0]); } return objEntityToReturn; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~ManualPointEntryRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using System.Configuration; using VIS_Domain.Registration; using VIS_Domain.UserManagement; using VIS_Domain.Master.Configuration; namespace VIS_Repository.Registration { public class VISUserRepository : VISDbCommand, VISIBaseRepository<VISUser> { public Int32 intAffectedRecords { get; set; } public VISUserRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = VISUserConstants.const_procVISUser_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public VISUser GetEntityByID(Int64 entityId) { VISUser objEntityToReturn = new VISUser(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = VISUserConstants.const_procVISUser_SelectById; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<VISUser>(dt.Rows[0]); } return objEntityToReturn; } public LoginData PostUserByUserIdPassword(string VISUserName, string VISPassword) { LoginData objLoginData = new LoginData(); string strEntityMessage = string.Empty; using (base.objSqlCommand) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = VISUserConstants.const_procVISUser_SelectByUserIdPassword; base.objSqlCommand.Parameters.AddWithValue(VISUserConstants.const_Field_VISUsername, VISUserName); base.objSqlCommand.Parameters.AddWithValue(VISUserConstants.const_Field_VISPassword, VISPassword); base.objSqlCommand.Parameters.Add(base.AddEntityMessageParameter()); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if(dt.Rows.Count>0) { objLoginData = VISAutoMapper.ConvertDataRow<LoginData>(dt.Rows[0]); } } return objLoginData; } public IEnumerable<VISUser> GetEntityList() { List<VISUser> objListToReturn = new List<VISUser>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = VISUserConstants.const_procVISUser_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<VISUser>(dt); } return objListToReturn; } public string AddEntity(VISUser entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = VISUserConstants.const_procVISUser_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISUserConstants.const_Field_VISUsername, entityObject.VISUsername); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISUserConstants.const_Field_VISPassword, entityObject.VISPassword); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(VISUser entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = VISUserConstants.const_procVISUser_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISUserConstants.const_Field_VISUsername, entityObject.VISUsername); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISUserConstants.const_Field_VISPassword, entityObject.VISPassword); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string GetActivateLoginImage() { string ImagePath=""; List<HomePageImage> ListImagePath = new List<HomePageImage>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = VISUserConstants.const_procGetActivateImages; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if(dt.Rows.Count > 0) { ListImagePath = VISAutoMapper.ConvertDataTable<HomePageImage>(dt); } if(ListImagePath.Count>0) { ImagePath = ListImagePath[new Random().Next(ListImagePath.Count)].ImagePath; } } return ImagePath; } public string ForgotPassword(string Email) { string strEntityMessage = string.Empty; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = VISUserConstants.const_procVISUser_ForgotPassword; base.objSqlCommand.Parameters.AddWithValue(VISUserConstants.const_Field_VISEmail, Email); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { strEntityMessage = Convert.ToString(objSqlCommand.ExecuteScalar()); } else { strEntityMessage = "Please Enter valid Email"; } // return dt; base.objSqlCommand.Connection.Close(); } return strEntityMessage; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } public void Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~VISUserRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>export interface INews { CompanyId: number; Id: number; News_Name: string; Description: string; IsNew: boolean; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using VIS_Domain.Master.EmployeeLevels; using VIS_Domain.Masters.EmployeeLevels; using VIS_Repository; using VIS_Repository.Masters.EmployeeLevels; namespace VIS_App.Controllers.Masters.EmployeeLevels { public class Levels_AchievementAPIController : BaseAPIController { Levels_AchievementRepository objLevels_AchievementRepository = null; List<Levels_Achievement> EntityList = new List<Levels_Achievement>(); public Levels_AchievementAPIController() { objLevels_AchievementRepository = new Levels_AchievementRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(objLevels_AchievementRepository.GetEntityList().AsEnumerable()); } [HttpGet] [Route("api/Levels_AchievementAPI/GetIsCriteria")] public HttpResponseMessage GetIsCriteria(int value) { return ToJson(objLevels_AchievementRepository.GetIsCriteriaDDL(value).AsEnumerable()); } public HttpResponseMessage Post([FromBody]Levels_Achievement value) { return ToJson(objLevels_AchievementRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 id, [FromBody]Levels_Achievement value) { return ToJson(objLevels_AchievementRepository.UpdateEntity(value)); } [HttpGet] [Route("api/Levels_AchievementAPI/GetDataOnEdit")] public HttpResponseMessage GetDataOnEdit(int Id) { return ToJson(objLevels_AchievementRepository.GetEditData(Id)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(objLevels_AchievementRepository.DeleteEntity(Id)); } [HttpPost] [Route("api/Levels_AchievementAPI/UploadJsonFile")] public HttpResponseMessage UploadJsonFile() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/Upload/EmployeeLevels/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.VacancyRelated; using VIS_Repository; using VIS_Repository.Masters; namespace VIS_App.Controllers.Masters.VacancyRelated { public class RatingTypeAPIController : BaseAPIController { VISIBaseRepository<RatingType> RatingTypeRepository; List<RatingType> EntityList = new List<RatingType>(); public RatingTypeAPIController(VISIBaseRepository<RatingType>_RatingTypeRepository) { RatingTypeRepository = _RatingTypeRepository; } public HttpResponseMessage Get() { return ToJson(RatingTypeRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]RatingType value) { return ToJson(RatingTypeRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]RatingType value) { return ToJson(RatingTypeRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(RatingTypeRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.Grievance { public class SalaryGrievancePE { } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class OutReportService { constructor(private _http: Http) { } getemployee(url: any): Observable<any> { return this._http.get(url + 'GetEmployee') .map((response: Response) => <any>response.json()); } getallemployee(url: any): Observable<any> { return this._http.get(url + 'GetAllEmployee') .map((response: Response) => <any>response.json()); } getdepartment(url: any): Observable<any> { return this._http.get(url + 'GetDepartment') .map((response: Response) => <any>response.json()); } getcompany(url: any): Observable<any> { return this._http.get(url + 'GetCompany') .map((response: Response) => <any>response.json()); } getlinemanager(url: any): Observable<any> { return this._http.get(url + 'GetLineManager') .map((response: Response) => <any>response.json()); } getoutreportdata(url: any,model:any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + 'GetReportByEmployeeId/', body, options) .map((response: Response) => <any>response.json()); } getemployeeidbylm(url: any, LineManagerId:number): Observable<any> { return this._http.get(url + 'GetEmployeeIdByLM?LineManagerId=' + LineManagerId) .map((response: Response) => <any>response.json()); } getemployeeidbycompany(url: any, CompanyId: number): Observable<any> { return this._http.get(url + 'GetEmployeeIdByCompany?CompanyId=' + CompanyId) .map((response: Response) => <any>response.json()); } getemployeeidbydepartment(url: any, ParentId: number): Observable<any> { return this._http.get(url + 'GetEmployeeIdByDepartment?ParentId=' + ParentId) .map((response: Response) => <any>response.json()); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep> import { Component, OnInit, ViewChild } from '@angular/core'; import { TicketListOpenService } from '../../service/Notification/TicketListOpen.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ITicketListOpen } from '../../Model/Notification/TicketListOpen'; import { IOraganization } from '../../Model/Notification/Organization'; import { FileDropDirective, FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-upload'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { DatePipe } from '@angular/common'; @Component({ providers: [TicketListOpenService], templateUrl: 'app/Components/Notification/TicketListOpen.component.html' }) export class TicketListOpenComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('modal1') modal1: ModalComponent; TicketListOpens: ITicketListOpen[]; TicketListOpen: ITicketListOpen; ViewHistory: ITicketListOpen[]; GetDetail: ITicketListOpen[]; GetDetails: ITicketListOpen; OpenTicketCount: number; UnderReviewTicketCount: number; ResolvedTicketCount: number; SuspendedTicketCount: number; msg: string; indLoading: boolean = false; TicketListOpenFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; TicketListOpenFilter: string; isDesc: boolean = false; column: any = 'Subject'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchSubject: string; strSearchMessage: string; strSearchAddressToGroup: string; strSearchAssignTo: string; strSearchPriority: string; strSearchUpdatebyName: string; strSearchStatus: string; Count: number; constructor(private fb: FormBuilder, private _TicketListOpenService: TicketListOpenService, private pagerService: PagerService) { } ngOnInit(): void { this.TicketListOpenFrm = this.fb.group({ CompanyId: [''], Id: 0, Subject: [''], Message: [''], Remarks: [''], AddressToGroup: [''], AssignTo: [''], CreatedByName: [''], UpdatedByName: [''], Priority: [''], Status: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], Mode:[''], HelpTicketId: [''], FileName: [''], UserType: [''], RoleType: [''], EntityMessage: [''] }); this.LoadGetTicketDetailUser(21); } TicketListOpenFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.TicketListOpenFilter = value; } TicketListOpenSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } loadcount() { this.OpenTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "open").length; this.UnderReviewTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "underReview").length; this.SuspendedTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "suspended").length; this.ResolvedTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "resolved").length; } FilterByStatus(event) { if (event.target.value == 'TicketAddressedToMe') { this.LoadGetTicketDetailUser(21); } else if (event.target.value == 'AllTicket') { this.LoadGetTicketDetailAdminAllTicket(); } } LoadGetTicketDetailUser(UserId: number): void { this.indLoading = true; this._TicketListOpenService.getTicketuser(Global.BASE_MyTicketListOpen_ENDPOINT, UserId) .subscribe(data => { // console.log(data) this.TicketListOpens = data; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchSubject = (<HTMLInputElement>document.getElementById("searchSubject")).value; if (this.strSearchSubject != '') { this.strSearchSubject = this.strSearchSubject.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(this.strSearchSubject) != -1); } } if (this.ShowHideSearch) { this.strSearchAddressToGroup = (<HTMLInputElement>document.getElementById("searchAddressToGroup")).value; if (this.strSearchAddressToGroup != '') { this.strSearchAddressToGroup = this.strSearchAddressToGroup.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.AddressToGroup != null && x.AddressToGroup.toLocaleLowerCase().indexOf(this.strSearchAddressToGroup) != -1); } } if (this.ShowHideSearch) { this.strSearchAssignTo = (<HTMLInputElement>document.getElementById("searchAssignTo")).value; if (this.strSearchAssignTo != '') { this.strSearchAssignTo = this.strSearchAssignTo.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.AssignTo != null && x.AssignTo.toLocaleLowerCase().indexOf(this.strSearchAssignTo) != -1); } if (this.ShowHideSearch) { this.strSearchPriority = (<HTMLInputElement>document.getElementById("searchPriority")).value; if (this.strSearchPriority != '') { this.strSearchPriority = this.strSearchPriority.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(this.strSearchPriority) != -1); } } if (this.ShowHideSearch) { this.strSearchStatus = (<HTMLInputElement>document.getElementById("searchStatus")).value; if (this.strSearchStatus != '') { this.strSearchStatus = this.strSearchStatus.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.Status != null && x.Status.toLocaleLowerCase().indexOf(this.strSearchStatus) != -1); } } } //Logic for searching - End this.OpenTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "open").length; this.UnderReviewTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "underReview").length; this.SuspendedTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "suspended").length; this.ResolvedTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "resolved").length; this.indLoading = false; this.JumpOnPage(1); } ); } LoadGetTicketDetail(id: number): void { this.indLoading = true; this._TicketListOpenService.getTicketDetail(Global.BASE_MyTicketListOpen_ENDPOINT, id) .subscribe(DATADP => { this.GetDetail = DATADP; } ); } LoadGetTicketDetailAdminAllTicket(): void { this.indLoading = true; this._TicketListOpenService.getTicketAdmin(Global.BASE_MyTicketListOpen_ENDPOINT) .subscribe(data => { // console.log(data) this.TicketListOpens = data; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchSubject = (<HTMLInputElement>document.getElementById("searchSubject")).value; if (this.strSearchSubject != '') { this.strSearchSubject = this.strSearchSubject.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(this.strSearchSubject) != -1); } } if (this.ShowHideSearch) { this.strSearchAddressToGroup = (<HTMLInputElement>document.getElementById("searchAddressToGroup")).value; if (this.strSearchAddressToGroup != '') { this.strSearchAddressToGroup = this.strSearchAddressToGroup.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.AddressToGroup != null && x.AddressToGroup.toLocaleLowerCase().indexOf(this.strSearchAddressToGroup) != -1); } } if (this.ShowHideSearch) { this.strSearchAssignTo = (<HTMLInputElement>document.getElementById("searchAssignTo")).value; if (this.strSearchAssignTo != '') { this.strSearchAssignTo = this.strSearchAssignTo.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.AssignTo != null && x.AssignTo.toLocaleLowerCase().indexOf(this.strSearchAssignTo) != -1); } if (this.ShowHideSearch) { this.strSearchPriority = (<HTMLInputElement>document.getElementById("searchPriority")).value; if (this.strSearchPriority != '') { this.strSearchPriority = this.strSearchPriority.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(this.strSearchPriority) != -1); } } if (this.ShowHideSearch) { this.strSearchStatus = (<HTMLInputElement>document.getElementById("searchStatus")).value; if (this.strSearchStatus != '') { this.strSearchStatus = this.strSearchStatus.toLocaleLowerCase(); this.TicketListOpens = this.TicketListOpens.filter( x => x.Status != null && x.Status.toLocaleLowerCase().indexOf(this.strSearchStatus) != -1); } } } //Logic for searching - End this.OpenTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "open").length; this.UnderReviewTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "underReview").length; this.SuspendedTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "suspended").length; this.ResolvedTicketCount = this.TicketListOpens.filter(x => x.Status.toLowerCase() == "resolved").length; this.indLoading = false; this.JumpOnPage(1); } ); } addTicketListOpen() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New News"; this.modalBtnTitle = "Add"; this.TicketListOpenFrm.reset(); this.modal.open(); } editTicketListOpen(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit News"; this.modalBtnTitle = "Update"; this.TicketListOpen = this.TicketListOpens.filter(x => x.Id == id)[0]; this.TicketListOpenFrm.setValue(this.TicketListOpen); this.modal.open(); this.LoadGetTicketDetail(id); } ViewTicketListOpen(id: number) { this.dbops = DBOperation.View; this.SetControlsState(true); this.modalTitle = "Conversation Ticket"; this.TicketListOpen = this.TicketListOpens.filter(x => x.Id == id)[0]; this.TicketListOpenFrm.setValue(this.TicketListOpen); this.LoadViwHistory(id); this.modal1.open(); this.modal.dismiss(); } deleteTicketListOpen(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.TicketListOpen = this.TicketListOpens.filter(x => x.Id == id)[0]; this.TicketListOpenFrm.setValue(this.TicketListOpen); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.TicketListOpenFrm.enable() : this.TicketListOpenFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.TicketListOpens); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } LoadViwHistory(id: number): void { this.indLoading = true; this._TicketListOpenService.getViewHistory(Global.BASE_MyTicket_ENDPOINT, id) .subscribe(DATADP => { this.ViewHistory = DATADP; } ); } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._TicketListOpenService.post(Global.BASE_MyTicketListOpen_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadGetTicketDetailUser(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._TicketListOpenService.put(Global.BASE_MyTicketListOpen_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadGetTicketDetailUser(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._TicketListOpenService.delete(Global.BASE_MyTicketListOpen_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "TicketListOpen status changed successfully."; this.LoadGetTicketDetailUser(21); } else { this.msg = "Error has occurred while changing status of existing TicketListOpen!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Masters.EmployeeLevels; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.Masters; using VIS_Domain; using System.Configuration; using VIS_Domain.RFQ; namespace VIS_Repository.GeneralHelper { public class HelperRepository : VISDbCommand { public Int32 intAffectedRecords { get; set; } public HelperRepository(string _connectionstring) : base(_connectionstring) { } public string GetEmpIdByCommunicationId(string CommunicationId) { string objEntityToReturn = string.Empty; try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } objSqlCommand.Parameters.Clear(); objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objSqlCommand.CommandText = RFQConstants.const_Field_GetEmployeeIdByCommunicationId; objSqlCommand.Parameters.AddWithValue(RFQConstants.const_Field_CommunicationId, CommunicationId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } string objListToReturn; SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); dt.Clear(); da.Fill(dt); objListToReturn = dt.Rows[0][0].ToString(); objSqlCommand.Connection.Close(); return objListToReturn; } catch (Exception ex) { } return objEntityToReturn; } } } <file_sep>//Saurabh import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { RFQResponseService } from '../../Service/RFQ/RFQResponse.service'; import { RFQService } from '../../Service/RFQ/RFQ.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IAddRFQResponse, IActionTakenBy, IHiddenValue, IForRFQId } from '../../Model/RFQ/RFQResponse'; import { ITechMultiCheckBox, ITechnology, IRFQDocEntity, IRFQLink, IRFQDoc, IRFQLinkEntity } from '../../Model/RFQ/GeneralRFQ'; import { IRFQInitial } from '../../Model/RFQ/RFQEstimateListing'; import { ForSessionData } from '../../Model/RFQ/RFQEstimateListing'; import { DBOperation } from '../../Shared/enum'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; @Component({ providers: [RFQResponseService, RFQService], templateUrl: 'app/Components/RFQ/ViewResponse.component.html' }) export class ViewRFQResponsecomponent implements OnInit { @ViewChild('modal') modal: ModalComponent; hiddenValue: IHiddenValue; addRFQResponse: IAddRFQResponse; actionTakenByList: IActionTakenBy[]; actionTakenBy: IActionTakenBy; msg: string; indLoading: boolean = false; RFQFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; RFQFilter: string; isDesc: boolean = false; direction: number; forSessionData: ForSessionData; myOptions: ITechMultiCheckBox[]; myOptionsEmp: ITechMultiCheckBox[]; MultiTechnologys: ITechMultiCheckBox; Technology: ITechnology[] = []; FileTypeDDL: IRFQInitial; AuthorDDL: IRFQDoc; Access: boolean = true; forRFQId: IForRFQId; RFQDocList: IRFQDoc[] = []; RFQDoc: IRFQDoc; RFQDocEntity: IRFQDocEntity; RFQDocEntityList: IRFQDocEntity[] = []; RFQLinkList: IRFQLink[] = []; RFQLink: IRFQLink; RFQLinkEntityList: IRFQLink[] = []; RFQLinkEntity: IRFQLink; fileList: FileList; i: number; fileListForAPI: FileList[] = []; constructor(private fb: FormBuilder, private _RFQResponseService: RFQResponseService, private _RFQService: RFQService, private router: Router, private pagerService: PagerService, private route: ActivatedRoute, private http: Http) { } ngOnInit(): void { this.addRFQResponse = ({ RFQ_InitialID: 0, IsEstimateReady: false, IsChangeToAction: false, Hours: 0, Timeline: 0, Timeline_Unit: '', Leadtime: 0, Leadtime_Unit: '', Technology: '', TechnologyIdList: 0, Description: '', ActionRequestedBy: 0, ActionByDate: null, EmployeeName: '', hdnEmployee: '', CurruntDate: null, hdnEmployeeId: 0, EmpId: 0 }); this.forRFQId = ({ RFQId: 0 }); this.forSessionData = ({ SessionId: 0 }); this.actionTakenBy = ({ EmpId: 0, Employee_Name: '' }); this.RFQDoc = ({ FileTypeID: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQDocEntity = ({ FileTypeId: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQLink = ({ RemarkLink: '', UserId: '', Password: '', URL: '' }) this.forSessionData.SessionId = +sessionStorage.getItem('Id'); this.LoadActionTaken(); this.GetTechnology(); this.LoadData(); this.GetRFQLink(); this.GetRFQDocument(); } GetRFQLink() { this._RFQResponseService.GetRFQLink(Global.BASE_RFQResponse_ENDPOINT) .subscribe(RFQs => { this.RFQLink = RFQs; }); } GetRFQDocument() { this._RFQResponseService.GetRFQDocument(Global.BASE_RFQResponse_ENDPOINT) .subscribe(RFQs => { this.RFQDoc = RFQs; }); } LoadActionTaken(): void { this.indLoading = true; this._RFQResponseService.GetActionTaken(Global.BASE_RFQResponse_ENDPOINT, this.forSessionData.SessionId, this.Access) .subscribe(RFQs => { this.actionTakenByList = RFQs; } //,error => this.msg = <any>error ); } LoadData(): void { this._RFQResponseService.GetViewRFQResponseById(Global.BASE_RFQResponse_ENDPOINT, 68)//68==rfqid .subscribe(RFQs => { this.addRFQResponse = RFQs; debugger; if (this.addRFQResponse.Timeline_Unit = 'D') { this.addRFQResponse.Timeline_Unit = 'Days'; } else if (this.addRFQResponse.Timeline_Unit = 'W') { this.addRFQResponse.Timeline_Unit = 'Week'; } else if (this.addRFQResponse.Timeline_Unit = 'M') { this.addRFQResponse.Timeline_Unit = 'Month'; } else { this.addRFQResponse.Timeline_Unit = 'Year'; } if (this.addRFQResponse.Leadtime_Unit = 'D') { this.addRFQResponse.Leadtime_Unit = 'Days'; } else if (this.addRFQResponse.Leadtime_Unit = 'W') { this.addRFQResponse.Leadtime_Unit = 'Week'; } else if (this.addRFQResponse.Leadtime_Unit = 'M') { this.addRFQResponse.Leadtime_Unit = 'Month'; } else { this.addRFQResponse.Timeline_Unit = 'Year'; } debugger; } //,error => this.msg = <any>error ); } GetTechnology(): void { this.indLoading = true; this._RFQResponseService.GetTechnology(Global.BASE_RFQ_ENDPOINT) .subscribe(Technology => { this.Technology = Technology; this.myOptions = []; for (let item of this.Technology) { this.myOptions.push({ id: item.TechnologyId, name: item.TechnologyName }); } this.indLoading = false; }); } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.ProfileAttendance; using VIS_Repository; using VIS_Repository.HumanResource.ProfileAttendace; namespace VIS_App.Controllers.HumanResource.ProfileAttendance { public class ProfileAttendanceAPIController : BaseAPIController { ProfileAttendanceRepository ObjProfileAttendanceRepository = null; //VISIBaseRepository<ProfileAttend> ProfileAttendanceRepository; List<ProfileAttend> EntityList = new List<ProfileAttend>(); public ProfileAttendanceAPIController() { ObjProfileAttendanceRepository= new ProfileAttendanceRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [HttpPost] [Route("api/ProfileAttendanceAPI/GetChangePassword")] public HttpResponseMessage GetChangePassword(int Id, ProfileAttend Profile) { return ToJson(ObjProfileAttendanceRepository.userchangepsw(Id, Profile)); } //[HttpPut] //[Route("api/ProfileAttendanceAPI/GetChangePassword")] //public HttpResponseMessage GetChangePassword(Int64 Id, [FromBody]ProfileAttend value) //{ // return ToJson(ProfileAttendanceRepository.UpdateEntity(value)); //} } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.Masters; namespace VIS_Repository.Masters.CompanyRelated { public class CompanyMasterRepository : VISDbCommand, VISIBaseRepository<CompanyMaster> { public Int32 intAffectedRecords { get; set; } public CompanyMasterRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public CompanyMaster GetEntityByID(Int64 entityId) { CompanyMaster objEntityToReturn = new CompanyMaster(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_SelectById; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<CompanyMaster>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<CompanyMaster> GetEntityList() { List<CompanyMaster> objListToReturn = new List<CompanyMaster>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<CompanyMaster>(dt); } return objListToReturn; } public string AddEntity(CompanyMaster entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyName, entityObject.CompanyName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_City, entityObject.City); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_ZipCode, entityObject.ZipCode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_State, entityObject.State); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Country, entityObject.Country); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_ContactNo, entityObject.ContactNo); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_E_mail, entityObject.E_mail); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Fax, entityObject.Fax); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyURL, entityObject.CompanyURL); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Address, entityObject.Address); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyLogo, entityObject.CompanyLogo); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_AccountHead, entityObject.AccountHead); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Designation, entityObject.Designation); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Signature, entityObject.Signature); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyShortCode, entityObject.CompanyShortCode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Address2, entityObject.Address2); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_StartSeries, entityObject.StartSeries); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_FinancialYear, entityObject.FinancialYear); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_AccountHeadOther, entityObject.AccountHeadOther); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_DesignationOther, entityObject.DesignationOther); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_SignatureOther, entityObject.SignatureOther); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } if (objVISDbCommand.objSqlCommand.Connection.State==ConnectionState.Closed) { objVISDbCommand.objSqlCommand.Connection.Open(); } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(CompanyMaster entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyName, entityObject.CompanyName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_City, entityObject.City); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_ZipCode, entityObject.ZipCode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_State, entityObject.State); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Country, entityObject.Country); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_ContactNo, entityObject.ContactNo); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_E_mail, entityObject.E_mail); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Fax, entityObject.Fax); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyURL, entityObject.CompanyURL); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Address, entityObject.Address); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyLogo, entityObject.CompanyLogo); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_AccountHead, entityObject.AccountHead); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Designation, entityObject.Designation); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Signature, entityObject.Signature); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_CompanyShortCode, entityObject.CompanyShortCode); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_Address2, entityObject.Address2); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_StartSeries, entityObject.StartSeries); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_FinancialYear, entityObject.FinancialYear); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_AccountHeadOther, entityObject.AccountHeadOther); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_DesignationOther, entityObject.DesignationOther); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CompanyMasterConstants.const_Field_SignatureOther, entityObject.SignatureOther); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<CompanyMaster> GetDesignation() { List<CompanyMaster> objListToReturn = new List<CompanyMaster>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_ForPositiondll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<CompanyMaster>(dt); } return objListToReturn; } public IEnumerable<CompanyMaster> GetCountry() { List<CompanyMaster> objListToReturn = new List<CompanyMaster>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_ForCountrydll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<CompanyMaster>(dt); } return objListToReturn; } public IEnumerable<CompanyMaster> GetFinancialYear() { List<CompanyMaster> objListToReturn = new List<CompanyMaster>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_ForFinancialYeardll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<CompanyMaster>(dt); } return objListToReturn; } public IEnumerable<CompanyMaster> GetHeaddll() { List<CompanyMaster> objListToReturn = new List<CompanyMaster>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CompanyMasterConstants.const_procCompanyMaster_ForSelectHeaddll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<CompanyMaster>(dt); } return objListToReturn; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CompanyMasterRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Notification { public class TicketListClosed : VISBaseEntity { public string Mode { get; set; } public string Subject { get; set; } public string Message { get; set; } public string Remarks { get; set; } public string AddressToGroup { get; set; } public string AssignTo { get; set; } public string Priority { get; set; } public string Status { get; set; } public string CreatedByName { get; set; } public string UpdatedByName { get; set; } public Int64 HelpTicketId { get; set; } public string FileName { get; set; } public string RoleType { get; set; } } public static class TicketListClosedConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_HelpTicket_Master = "HelpTicketMaster"; /// <summary> /// Database table field Name Constants. /// </summary> /// public const string const_Field_Mode = "Mode"; public const string const_Field_Subject = "Subject"; public const string const_Field_Message = "Message"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_AddressToGroup = "AddressToGroup"; public const string const_Field_AssignTo = "AssignTo"; public const string const_Field_CreatedByName = "CreatedByName"; public const string const_Field_UpdatedByName = "UpdatedByName"; public const string const_Field_Priority = "Priority"; public const string const_Field_Status = "Status"; public const string const_Field_UserId = "UserID"; public const string cons_Filed_HelpTicketId = "HelpTicketId"; public const string cons_Filed_FileName = "FileName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procHelpTicketDetailByAssignToUser = "procHelpTicketDetailByAssignToUser"; public const string const_procHelpTicketHistory_History = "ProcHelpTicket_History"; public const string const_procHelpTicket_update = "procHelpTicket_Update"; public const string const_procHelpTicketMasterLog = "procHelpTicketMasterLog"; public const string const_procHelpTicket_selectAll = "procHelpTicketMaster_SelectAll"; public const string const_procHelpTicket_SelectById = "procHelpTickeMster_SelectById"; public const string const_procHelpTicket_ActiveInActive = "procHelpTicaket_ActiveInActive"; } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class DailyEntrysheetService { constructor(private _http: Http) { } getemployee(url: any): Observable<any> { return this._http.get(url + 'GetAllEmployee') .map((response: Response) => <any>response.json()); } getalldailyentryreport(url:any,Id:number,Date:string): Observable<any> { return this._http.get(url + 'GetDailyEntryRecord?Id=' + Id + '&&Date=' + Date) .map((response: Response) => <any>response.json()); } getalldailyentryreportallemp(url: any,Date:string): Observable<any> { return this._http.get(url + 'GetDailyEntryTimeAllEmp?Date='+Date) .map((response: Response) => <any>response.json()); } getalldailyentryreporttime(url: any, Id: number, Date: string): Observable<any> { return this._http.get(url + 'GetDailyEntryTime?Id=' + Id + '&&Date=' + Date) .map((response: Response) => <any>response.json()); } updatereportdetail(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateReportDeatil/' , body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LoginData = (function () { function LoginData() { } return LoginData; }()); exports.LoginData = LoginData; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { PositionService } from '../../../service/Masters/VacancyRelated/Position.service'; import { SkillService } from '../../../service/Masters/VacancyRelated/Skill.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IPosition } from '../../../Model/Masters/VacancyRelated/Position'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; import { IMultiSelectOption } from 'angular-2-dropdown-multiselect'; import { ISkillList } from '../../../Model/Masters/VacancyRelated/Skill'; import { ISkillListViewModel } from '../../../Model/Masters/VacancyRelated/Position'; @Component ({ providers: [PositionService, SkillService], templateUrl: 'app/Components/Masters/VacancyRelated/Position.component.html' }) export class PositionComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; positions: IPosition[]; position: IPosition; msg: string; indLoading: boolean = false; PositionFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; PositionFilter: string; isDesc: boolean = false; column: any = 'PositionName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strSearchPositionName: string; strSearchRemarks: string; optionsModel: number[]; myOptions: IMultiSelectOption[]; IMultiSelectOption: ISkillList[]; objISkillListViewModel: ISkillListViewModel[]; TempSkillId: string[]; constructor(private fb: FormBuilder, private _PositionService: PositionService, private pagerService: PagerService, private _SkillService: SkillService, private _CommonHelperService: CommonHelperService) { } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.LoadPosition(); this.LoadSkills(); this.ModelReset(); } ModelReset() : void { this.position = { SkillsId:"", SkillName: "", CreatedBy: "", CreatedOn: null, Id: 0, IsActive: false, Status: false, PositionName: "", Remarks: "", UpdatedBy: "", UpdatedOn: null, SkillId: null } } TestMultidll(): void { this.myOptions = [ { id: 6, name: 'Option 1' }, { id: 7, name: 'Option 2' }, { id: 8, name: 'Option 3' } ]; } LoadSkills() { this._PositionService.getskills(Global.BASE_POSITION_ENDPOINT) .subscribe(skilllist => { this.IMultiSelectOption = skilllist; }); } PositionFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.PositionFilter = value; } PositionSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadPosition(): void { this.indLoading = true; this._PositionService.get(Global.BASE_POSITION_ENDPOINT) .subscribe(positions => { this.positions = positions; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchPositionName = (<HTMLInputElement>document.getElementById("searchPositionName")).value; if (this.strSearchPositionName != '') { this.strSearchPositionName = this.strSearchPositionName.toLocaleLowerCase(); this.positions = this.positions.filter ( x => x.PositionName != null && x.PositionName.toLocaleLowerCase().indexOf(this.strSearchPositionName) != -1); } this.strSearchRemarks = (<HTMLInputElement>document.getElementById("searchRemarks")).value; if (this.strSearchRemarks != '') { this.strSearchRemarks = this.strSearchRemarks.toLocaleLowerCase(); this.positions = this.positions.filter ( x => x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(this.strSearchRemarks) != -1); } } //Logic for searching - End this.indLoading = false; // set items to json response // initialize to page 1 this.JumpOnPage(1); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } //,error => this.msg = <any>error ); } AddPosition() { this.dbops = DBOperation.create; this.modalTitle = "Add New Position"; this.modalBtnTitle = "Add"; this.ModelReset(); this.modal.open(); } EditPosition(id: number) { this.dbops = DBOperation.update; this.modalTitle = "Edit Position"; this.modalBtnTitle = "Update"; this.position = this.positions.filter(x => x.Id == id)[0]; this.TempSkillId = this.position.SkillsId.split(','); this.position.SkillId = []; for (let item of this.TempSkillId) { this.position.SkillId.push(Number(item)); } this.modal.open(); } DeletePosition(id: number, status: boolean) { this.dbops = DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.position = this.positions.filter(x => x.Id == id)[0]; this.TempSkillId = this.position.SkillsId.split(','); this.position.SkillId = []; for (let item of this.TempSkillId) { this.position.SkillId.push(Number(item)); } this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.PositionFrm.enable() : this.PositionFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.positions); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: IPosition) { this.msg = ""; if (formData.SkillId == null) { formData.SkillId=[0]; } switch (this.dbops) { case DBOperation.create: this._PositionService.post(Global.BASE_POSITION_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadPosition(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._PositionService.put(Global.BASE_POSITION_ENDPOINT, formData.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadPosition(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._PositionService.delete(Global.BASE_POSITION_ENDPOINT, formData.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Position status changed successfully."; this.LoadPosition(); } else { this.msg = "Error has occurred while changing status of existing Position!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep> import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; @Injectable() export class SalaryGrievanceService { constructor(private _http: Http) { } get(url: string): Observable<any> { return this._http.get(url) .map((response: Response) => <any>response.json()); } post(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } put(url: string, UpdatedBy: number,model:any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity?UpdatedBy=' + UpdatedBy, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } delete(url: string, id: number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } GetGrievance(url: string,UserId:number,mode:string): Observable<any> { return this._http.get(url + 'GetGrievance?UserId=' + UserId + '&mode=' + mode) .map((response: Response) => <any>response.json()); } FillDeductionDate(url: string, UserId: number, mode: string): Observable<any> { return this._http.get(url + 'FillDeductionDate?UserId=' + UserId + '&mode=' + mode) .map((response: Response) => <any>response.json()); } LoadEmployeeAttendance(url: string, EmployeeId: number, Date: string): Observable<any> { return this._http.get(url + 'LoadEmployeeAttendance?EmployeeId=' + EmployeeId + '&Date=' + Date) .map((response: Response) => <any>response.json()); } LoadEmployeeDailyEntry(url: string, EmployeeId: number, Date: string): Observable<any> { return this._http.get(url + 'LoadEmployeeDailyEntry?EmployeeId=' + EmployeeId + '&Date=' + Date) .map((response: Response) => <any>response.json()); } AddGrievance(url: string,EmployeeId:number,Date:string,PaycutAmt:string,GrievanceRemark:string): Observable<any> { return this._http.get(url + 'AddGrievance?EmployeeId=' + EmployeeId + '&Date=' + Date + '&PaycutAmt=' + PaycutAmt + '&GrievanceRemark=' + GrievanceRemark) .map((response: Response) => <any>response.json()); } GetGrievanceData(url: string,id:number): Observable<any> { return this._http.get(url + 'GetGrievanceData?Id=' + id) .map((response: Response) => <any>response.json()); } }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IEventCountDown } from '../../../Model/Masters/Configuration/EventCountDown'; @Pipe ({ name: 'eventcountdownFilter' }) export class EventCountDownFilterPipe implements PipeTransform { transform(value: IEventCountDown[], filter: string): IEventCountDown[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IEventCountDown) => app.EventName != null && app.EventName.toLocaleLowerCase().indexOf(filter) != -1 || app.CountDownText != null && app.CountDownText.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; using VIS_Repository; using System.Configuration; using VIS_Repository.Masters; using VIS_Domain.Registration; using VIS_Domain.Master; using VIS_Repository.Registration; using VIS_Domain.Master.CurrencyRelated; using VIS_Domain.Master.EmployeeLevels; using VIS_Domain.Master.CompanyRelated; using VIS_Domain.Master.VacancyRelated; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.CurrencyRelated; using VIS_Repository.Masters.EmployeeLevels; using VIS_Repository.Masters.CompanyRelated; using VIS_Repository.Masters.VacancyRelated; using VIS_Repository.Masters.Configuration; using VIS_Domain.Masters.EmployeeLevels; using VIS_Domain.Notification; using VIS_Repository.Notification; using VIS_Domain.Masters.EmployeeLevelCriteriaSetup; using VIS_Domain.Master.VacancyRelated; using VIS_Domain.UserManagement; using VIS_Repository.UserManagement; using VIS_Domain.Master.EmployeeManualPointEntry; using VIS_Repository.RFQ; using VIS_Domain.RFQ; [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(VIS_App.App_Start.NinjectWebCommon), "Start")] [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(VIS_App.App_Start.NinjectWebCommon), "Stop")] namespace VIS_App.App_Start { public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } catch { kernel.Dispose(); throw; } } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind(typeof(VISIBaseRepository<Currency>)).To<CurrencyRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<VISUser>)).To<VISUserRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<Levels>)).To<LevelsRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<ContactMaster>)).To<ContactMasterRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<BankMaster>)).To<BankMasterRepositiory>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<LookupType>)).To<LookupTypeRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<RatingType>)).To<RatingTypeRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<Lookup>)).To<LookupRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<SkillGroup>)).To<SkillGroupRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<Skill>)).To<SkillRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<Position>)).To<PositionRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<TechnologyMaster>)).To<TechnologyMasterRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<CompanyMaster>)).To<CompanyMasterRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<MacIdConfiguration>)).To<MacIdConfigurationRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<SecurityKey>)).To<SecurityKeyRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<FinancialYear>)).To<FinancialYearRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<>)).To<FinancialYearRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<EventCountDown>)).To<EventCountDownRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<CommonConfiguration>)).To<CommonConfigurationRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<LevelConfiguration>)).To<LevelConfigurationRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<Policy>)).To<PolicyRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<ConfigureWorksheet>)).To<ConfigureWorksheetRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<News>)).To<NewsRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<MyTicket>)).To<MyTicketRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<TicketListOpen>)).To<TicketListOpenRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<TicketListClosed>)).To<TicketListClosedRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<LevelCriteriaSetup>)).To<LevelCriteriaSetupRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<ConfigureTicket>)).To<ConfigureTicketRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<HomePageImage>)).To<HomePageImageRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<LeaveType>)).To<LeaveTypeRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<GroupName>)).To<GroupNameRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<Levels_Achievement>)).To<Levels_AchievementRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<AttendanceEntry>)).To<AttendanceEntryRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<UserRole>)).To<UserRoleRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<EducationType>)).To<EducationTypeRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<ManualPointEntry>)).To<ManualPointEntryRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<SalaryBreakupType>)).To<SalaryBreakupTypeRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<RFQList>)).To<RFQRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); kernel.Bind(typeof(VISIBaseRepository<RFQResponse>)).To<RFQResponseRepository>().WithConstructorArgument("_connectionstring", ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } } } <file_sep>export interface ILookup { Id: number; Name: string; Type:string; Value: string; FullName: string; ColorCode: string; Country: string; CreatedOn: string; CreatedBy: string; UpdatedOn: string; UpdatedBy: string; IsActive: string; CompanyId:number; EntityMessage: string; }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var WorkSheet_service_1 = require("../../../Service/HumanResource/Attendance/WorkSheet.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var router_1 = require("@angular/router"); var http_1 = require("@angular/http"); var WorkSheetComponent = (function () { function WorkSheetComponent(fb, _WorkSheetService, http, router, pagerService) { this.fb = fb; this._WorkSheetService = _WorkSheetService; this.http = http; this.router = router; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.CurrentRecordsPerPage = 10; this.tempUserId = 158; this.tempDate = '20150525'; // pager object this.pager = {}; this.toStr = JSON.stringify; } WorkSheetComponent.prototype.ngOnInit = function () { debugger; this.WorkSheetFrm = this.fb.group({ ActivityId: [''], ActivityName: [''], SubActivityId: [''], SubActivityName: [''], Date: [''], UserId: [''], ProjectID: [''], ProjectName: [''], TaskId: [''], Description: [''], Hours: [''], FillDate: [''], WorkSheetID: [''], }); //this.WorkSheet = // ({ // ActivityId:0, // ActivityName: '', // SubActivityId:0, // SubActivityName: '', // Date: '', // UserId: 0, // ProjectID:0, // ProjectName: '', // TaskId: 0, // Description: '', // Hours: '', // FillDate: '', // WorkSheetID: 0, // TaskName:'' // }); this.LoadDeafultConfigure(); this.LoadDate(); this.LoadProjectList(this.tempUserId, this.tempDate); }; WorkSheetComponent.prototype.OpenSave = function () { this.SetControlsState(true); this.modalTitle = "Task List For Date ()"; this.modalBtnTitle = "Save"; this.modal.open(); }; WorkSheetComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.WorkSheetFrm.enable() : this.WorkSheetFrm.disable(); }; WorkSheetComponent.prototype.GetDate = function (event) { debugger; this.objValue1 = event.target.Date; }; WorkSheetComponent.prototype.ToogleMyProfile = function () { $("#myprofiledata").slideToggle(300); }; WorkSheetComponent.prototype.CloseWidgetProfile = function () { $("#adminProfile").hide(300); }; WorkSheetComponent.prototype.createRange = function (number) { var items = []; for (var i = 1; i <= number; i++) { items.push(i); } return items; }; WorkSheetComponent.prototype.LoadDeafultConfigure = function () { var _this = this; this.indLoading = true; this._WorkSheetService.GetDropDownList(global_1.Global.BASE_WorkSheet_ENDPOINT) .subscribe(function (data) { _this.DefaulConfigure = data; _this.indLoading = false; }); }; WorkSheetComponent.prototype.LoadProjectList = function (UserId, Date) { var _this = this; debugger; this.indLoading = true; this._WorkSheetService.GetProjectList(global_1.Global.BASE_WorkSheet_ENDPOINT, UserId, Date) .subscribe(function (data) { _this.ProjectList = data; console.log(data); _this.indLoading = false; }); }; WorkSheetComponent.prototype.LoadChildTaskDroDown = function (event, UserId, Date) { var _this = this; debugger; if (event == 0) { $("#taskid").prop("disabled", true); } else { $("#taskid").prop("disabled", false); } this.indLoading = true; this._WorkSheetService.GetChildTaskDropdown(global_1.Global.BASE_WorkSheet_ENDPOINT, event.target.value, this.tempUserId, this.tempDate) .subscribe(function (data) { _this.ChildDropDown = data; _this.indLoading = false; }); }; WorkSheetComponent.prototype.LoadDate = function () { var _this = this; debugger; this.indLoading = true; this._WorkSheetService.GetDate(global_1.Global.BASE_WorkSheet_ENDPOINT) .subscribe(function (data) { _this.Date = data; _this.indLoading = false; _this.printValues(); }); }; WorkSheetComponent.prototype.printValues = function () { console.log('objValue1', this.Date[0]); console.log('objValue2', this.Date[1]); console.log('objValue3', this.Date[2]); console.log('objValue4', this.Date[3]); }; WorkSheetComponent.prototype.onSubmit = function (formData) { var _this = this; debugger; console.log(formData); this._WorkSheetService.Savepost(global_1.Global.BASE_WorkSheet_ENDPOINT, formData._value).subscribe(function (data) { if (data == "Success") { _this.msg = "Worksheet Save successfully."; } else { _this.msg = "Worksheet has occurred while modifying existing Ticket Configuration!"; } }, function (error) { _this.msg = error; }); //this._WorkSheetService.Savepost(Global.BASE_WorkSheet_ENDPOINT, formData._value).subscribe( // data => { // if (data == "Success") { // this.msg = "Worksheet Save successfully."; // } // else { // this.msg = "Worksheet has occurred while modifying existing Ticket Configuration!" // } // }, // error => { // this.msg = error; // } //); // this.No++; ///} }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], WorkSheetComponent.prototype, "modal", void 0); WorkSheetComponent = __decorate([ core_1.Component({ providers: [WorkSheet_service_1.WorkSheetService], templateUrl: 'app/Components/HumanResource/Attendance/WorkSheet.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, WorkSheet_service_1.WorkSheetService, http_1.Http, router_1.Router, pager_index_1.PagerService]) ], WorkSheetComponent); return WorkSheetComponent; }()); exports.WorkSheetComponent = WorkSheetComponent; <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IHumanResource = (function () { function IHumanResource() { } return IHumanResource; }()); exports.IHumanResource = IHumanResource; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.HumanResource.Grievance { public class SalaryGrievancePERepository { } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Masters.EmployeeLevelCriteriaSetup; using VIS_Domain.Masters.EmployeeLevels; using VIS_Repository; using VIS_Repository.Masters.EmployeeLevels; namespace VIS_App.Controllers.Masters.EmployeeLevels { public class LevelCriteriaSetupAPIController : BaseAPIController { LevelCriteriaSetupRepository objLevelCriteriaSetupRepository = null; VISIBaseRepository<LevelCriteriaSetup> LevelCriteriaSetupRepository; List<LevelCriteriaSetup> EntityList = new List<LevelCriteriaSetup>(); public LevelCriteriaSetupAPIController(VISIBaseRepository<LevelCriteriaSetup> _levelsRepository) { LevelCriteriaSetupRepository = _levelsRepository; objLevelCriteriaSetupRepository = new LevelCriteriaSetupRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [HttpGet] [Route("api/LevelCriteriaSetupAPI/GetCriteriadll")] public HttpResponseMessage GetCriteriadll() { return ToJson(objLevelCriteriaSetupRepository.GetCriteria().AsEnumerable()); } [HttpGet] [Route("api/LevelCriteriaSetupAPI/GetCalculatedOndll")] public HttpResponseMessage GetCalculatedOndll() { return ToJson(objLevelCriteriaSetupRepository.GetCalculatedOn().AsEnumerable()); } [HttpGet] [Route("api/LevelCriteriaSetupAPI/GetCategorydll")] public HttpResponseMessage GetCategorydll() { return ToJson(objLevelCriteriaSetupRepository.GetCategory().AsEnumerable()); } [Route("api/LevelCriteriaSetupAPI/getLevelSetupId")] public HttpResponseMessage getLevelSetupId(int CriteriaId) { return ToJson(objLevelCriteriaSetupRepository.GetSetupIdForAchievement(CriteriaId)); } public HttpResponseMessage Get() { return ToJson(LevelCriteriaSetupRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]LevelCriteriaSetup value) { DefineLevelCriteriaObject(ref value); return ToJson(LevelCriteriaSetupRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 id, [FromBody]LevelCriteriaSetup value) { DefineLevelCriteriaObject(ref value); return ToJson(LevelCriteriaSetupRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(LevelCriteriaSetupRepository.DeleteEntity(Id)); } private void DefineLevelCriteriaObject(ref LevelCriteriaSetup levelcriteriasetup) { if (levelcriteriasetup.ArbCriteriaType == "Automatic") { levelcriteriasetup.IsAutomatic = true; if (levelcriteriasetup.ArbSubType == "Range") { levelcriteriasetup.IsRange = true; } if (levelcriteriasetup.ArbSubType == "Repeated") { levelcriteriasetup.IsRepeated = true; levelcriteriasetup.Units = levelcriteriasetup.Units; } if (levelcriteriasetup.ArbSubType == "Once") { levelcriteriasetup.IsOnce = true; } } if (levelcriteriasetup.ArbCriteriaType == "Manual") { levelcriteriasetup.IsAutomatic = false; levelcriteriasetup.AliasName = levelcriteriasetup.Name; levelcriteriasetup.CategoryID = Convert.ToInt32(levelcriteriasetup.CategoryID); levelcriteriasetup.IsAutomatic = false; if (levelcriteriasetup.ArbManualType == "PerformanceBased") { levelcriteriasetup.IsPerformanceBased = true; } } // start: for edit part //if (lblFromPercent.Visible && lblToPercent.Visible) //{ // criteriaSetup.IsPercentage = true; //}rbtnProgressiveYes.Checked if (levelcriteriasetup.ArbIsProgressive=="Yes") { levelcriteriasetup.IsProgressive = true; } else { levelcriteriasetup.IsProgressive = false; levelcriteriasetup.ProgressiveDays = 0; levelcriteriasetup.ProgressivePoints = 0; } if (levelcriteriasetup.ArbCascading == "Yes") { LevelCriteriaSetup CascadingLogEntry = new LevelCriteriaSetup(); CascadingLogEntry.dtFromDate = DateTime.Now.Date; CascadingLogEntry.dtToDate = DateTime.Now.Date; CascadingLogEntry.bFromYes = false; CascadingLogEntry.bToYes = false; CascadingLogEntry.bBothYes = false; CascadingLogEntry.bBothNo = false; CascadingLogEntry.Point = levelcriteriasetup.Point; CascadingLogEntry.CriteriaID = levelcriteriasetup.CriteriaID; if (levelcriteriasetup.dtFromDate != null) { CascadingLogEntry.dtFromDate = levelcriteriasetup.dtFromDate; } if (levelcriteriasetup.dtToDate != null) { CascadingLogEntry.dtFromDate = levelcriteriasetup.dtToDate; } if (levelcriteriasetup.dtFromDate != null && levelcriteriasetup.dtToDate != null) { CascadingLogEntry.bBothYes = true; } else if (levelcriteriasetup.dtFromDate == null && levelcriteriasetup.dtToDate != null) { CascadingLogEntry.bToYes = true; } else if (levelcriteriasetup.dtFromDate != null && levelcriteriasetup.dtToDate == null) { CascadingLogEntry.bFromYes = true; } else { CascadingLogEntry.bBothNo = true; } //levelsBAL.CascadingEffect(); objLevelCriteriaSetupRepository.LevelsPointLogEntry(CascadingLogEntry); } //End : For Edit part } } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; @Injectable() export class DocumentTemplateService { constructor(private _http: Http) { } // step1 related services getapprovedrecord(url: string, EmployeeId: number, EmployeeRole: string, ApprovedStatus:string): any { return this._http.get(url + 'GetAllApprovedRecord?EmployeeId=' + EmployeeId + '&EmployeeRole=' + EmployeeRole + '&ApprovedStatus=' + ApprovedStatus +'').map((response: Response) => response.json()); } getallmodule(url: string): any { return this._http.get(url + 'GetAllModule').map((response: Response) => response.json()); } getbyid(url: string,id:number): any { return this._http.get(url + 'GetById?Id='+ id).map((response: Response) => response.json()); } addnewdocument(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + "AddNewDocumentTemplate", body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } updatedocument(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + "UpdateDocumentTemplate", body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } deletedocument(url: string, id: number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + "DeleteDocumentTemplate?Id=" + id, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } // step2 related services addnewdocumentfield(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + "AddDocumentField", body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } updatedocumentfield(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + "UpdateDocumentField", body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } deletedocumentfield(url: string, Id: number,UpdatedBy:number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteDocumentField?Id=' + Id + '&UpdatedBy=' + UpdatedBy + '', options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } getbydoctempid(url: string, id: number): any { return this._http.get(url + 'GetAllDocumenetFieldByDocId?DocTempId=' + id).map((response: Response) => response.json()); } getalldocumentfieldbyid(url: string, id: number): any { return this._http.get(url + 'GetAllDocumenetFieldById?Id=' + id).map((response: Response) => response.json()); } getmaxid(url: string): any { return this._http.get(url + 'GetDocTemplateMaxId').map((response: Response) => response.json()); } bindtablefielddropdown(url: string,TableName:string): any { return this._http.get(url + 'BindTableFieldDropDown?TableName=' + TableName).map((response: Response) => response.json()); } bindcustomfielddropdown(url: string,DocTempId:number): any { return this._http.get(url + 'BindCustomFieldDropDown?DocTempId=' + DocTempId).map((response: Response) => response.json()); } // step 3 Service AddDocumentMasterField(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + "AddDocumentMasterField", body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } AddDocumentContainerField(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url + "AddDocumentContainerField", body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } GetDocumentContainer(url: string, id: number): any { return this._http.get(url + 'BindDocumentContainer?DocTempId=' + id).map((response: Response) => response.json()); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.Attendance; using VIS_Repository.HumanResource.Attendace; namespace VIS_App.Controllers.HumanResource.Attendance { public class MyTeamAPIController : BaseAPIController { MyTeamRepository ObjMyTeamRepository = null; public MyTeamAPIController() { ObjMyTeamRepository = new MyTeamRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/MyTeamAPI/GetMyTeam")] [HttpGet] public HttpResponseMessage GetMyTeam(long UserId) { return ToJson(ObjMyTeamRepository.GetMyTeamList(UserId)); } [Route("api/MyTeamAPI/GetHoverPopup")] [HttpGet] public HttpResponseMessage GetHoverPopup(long UserId) { return ToJson(ObjMyTeamRepository.GetHoverPopup(UserId)); } [Route("api/MyTeamAPI/GetLinemanager")] [HttpGet] public HttpResponseMessage GetLinemanager(Int64 id) { return ToJson(ObjMyTeamRepository.GetLinemanager(id)); } [Route("api/MyTeamAPI/GetSkill")] [HttpGet] public HttpResponseMessage GetSkill(Int64 SkillID) { return ToJson(ObjMyTeamRepository.GetSkill(SkillID)); } public HttpResponseMessage Get() { return ToJson(ObjMyTeamRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]MyTeam value) { return ToJson(ObjMyTeamRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]MyTeam value) { return ToJson(ObjMyTeamRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjMyTeamRepository.DeleteEntity(Id)); } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { UserRoleService } from '../../../service/Masters/CompanyRelated/UserRole.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IUserRole } from '../../../Model/Masters/CompanyRelated/UserRole'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component ({ providers: [UserRoleService], templateUrl: 'app/Components/Masters/CompanyRelated/UserRole.component.html' }) export class UserRoleComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; UserRoles: IUserRole[]; UserRole: IUserRole; msg: string; indLoading: boolean = false; UserRoleFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; UserRoleFilter: string; isDesc: boolean = false; column: any = 'Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; ShowHideSearch: boolean = false; strsearchName: string; strsearchType: string; strsearchFileName: string; constructor(private fb: FormBuilder, private _UserRoleService: UserRoleService, private pagerService: PagerService) { } ngOnInit(): void { this.UserRoleFrm = this.fb.group ({ CompanyId: [''], Id: [''], Name: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], Type: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], FullName: [''], IsActive: 0, CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], EntityMessage: [''], }); this.LoadUserRole(); } UserRoleFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.UserRoleFilter = value; } UserRoleSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadUserRole(): void { this.indLoading = true; this._UserRoleService.get(Global.BASE_UserRole_ENDPOINT) .subscribe(UserRoles => { this.UserRoles = UserRoles; debugger; //Logic for searching - start if (this.ShowHideSearch) { this.strsearchName = (<HTMLInputElement>document.getElementById("searchName")).value; if (this.strsearchName != '') { this.strsearchName = this.strsearchName.toLocaleLowerCase(); this.UserRoles = this.UserRoles.filter ( x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strsearchName) != -1); } } if (this.ShowHideSearch) { this.strsearchType = (<HTMLInputElement>document.getElementById("searchType")).value; if (this.strsearchType != '') { this.strsearchType = this.strsearchType.toLocaleLowerCase(); this.UserRoles = this.UserRoles.filter ( x => x.Type != null && x.Type.toLocaleLowerCase().indexOf(this.strsearchType) != -1); } } if (this.ShowHideSearch) { this.strsearchFileName = (<HTMLInputElement>document.getElementById("searchFileName")).value; if (this.strsearchFileName!= '') { this.strsearchFileName = this.strsearchFileName.toLocaleLowerCase(); this.UserRoles = this.UserRoles.filter ( x => x.FullName != null && x.FullName.toLocaleLowerCase().indexOf(this.strsearchFileName) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } AddUserRole() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New UserRole"; this.modalBtnTitle = "Add"; this.UserRoleFrm.reset(); this.modal.open(); } EditUserRole(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit UserRole"; this.modalBtnTitle = "Update"; this.UserRole = this.UserRoles.filter(x => x.Id == id)[0]; this.UserRoleFrm.setValue(this.UserRole); this.modal.open(); } DeleteUserRole(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.UserRole = this.UserRoles.filter(x => x.Id == id)[0]; this.UserRoleFrm.setValue(this.UserRole); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.UserRoleFrm.enable() : this.UserRoleFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.UserRoles); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { debugger; this.msg = ""; switch (this.dbops) { case DBOperation.create: this._UserRoleService.post(Global.BASE_UserRole_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data this.LoadUserRole(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._UserRoleService.put(Global.BASE_UserRole_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data this.LoadUserRole(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._UserRoleService.delete(Global.BASE_UserRole_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "UserRole status changed successfully."; this.LoadUserRole(); } else { this.msg = "Error has occurred while changing status of existing UserRole!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class CommonHelperService { constructor(private _http: Http) { } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } UploadImageToServer(url: string, formData: any): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, formData, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } public ToogleMenu(): void { var vProp; var vStyleOfElement = document.getElementById("VISNavigationBar"); var vNewVisNavBarWidth = "300px"; var vMainContentLeftMargin = "305px"; var vCurrentStyleInAnchor = "labeldisplayblock"; var vChangeStyleInAnchor = "labeldisplaynone"; var vCurrentArrowClass = "arrow"; var vChangeInArrowClass = "arrownone"; if (vStyleOfElement.style.width == "300px") { vNewVisNavBarWidth = "50px"; vMainContentLeftMargin = "55px"; } else { vNewVisNavBarWidth = "300px"; vMainContentLeftMargin = "305px"; vCurrentStyleInAnchor = "labeldisplaynone"; vChangeStyleInAnchor = "labeldisplayblock"; vCurrentArrowClass = "arrownone"; vChangeInArrowClass = "arrow"; } var vArrayOfAnchorTag = document.getElementsByClassName(vCurrentStyleInAnchor); while (vArrayOfAnchorTag.length > 0) { vArrayOfAnchorTag[0].setAttribute('class', vChangeStyleInAnchor); } var vArrayOfArrowClass = document.getElementsByClassName(vCurrentArrowClass); while (vArrayOfArrowClass.length > 0) { vArrayOfArrowClass[0].setAttribute('class', vChangeInArrowClass); } var vArrayOfMainContentDivTag = document.getElementById("MainDivToLoadChild"); vArrayOfMainContentDivTag.style.marginLeft = vMainContentLeftMargin; vStyleOfElement.style.width = vNewVisNavBarWidth; $(".navbar-collapse in").addClass("navbar-collapse"); $(".navbar-collapse in").toggleClass("collapsed"); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { // model For Bind Data public class AttendanceAccessCardComparisionReport : VISBaseEntity { public string EmployeeCode { get; set; } public string Employee_Name { get; set; } public DateTime Date { get; set; } public string LineManager { get; set; } public int Grace { get; set; } public string Grade { get; set; } public string Status { get; set; } public DateTime PunchInVIS { get; set; } public DateTime PunchInAC { get; set; } public DateTime PunchOutVIS { get; set; } public DateTime PunchOutAC { get; set; } public string MAC { get; set; } public string IP { get; set; } public string TimeofFirstScreenShot { get; set; } public string TimeofLastScreenShot { get; set; } public string PunchInIssue { get; set; } public string PunchOutIssue { get; set; } } // model For Send Parameter public class AttendanceAccessCardComparisionReportParameterModel { public int EmployeeId { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } public string IssueOnly { get; set; } public string Search { get; set; } public int LoginUserId { get; set; } public string FromMonth { get; set; } public string FromYear { get; set; } public string ToMonth { get; set; } public string ToYear { get; set; } public bool MonthWise { get; set; } } public static class AttendanceAccessCardComparisionReportConstant { // Constance For Parameter public const string const_EmployeeId = "empId"; public const string const_FromDate = "fromDate"; public const string const_ToDate = "toDate"; public const string const_IssueOnly = "issueOnly"; public const string const_Search = "search"; public const string const_LoginUserId = "LoginUserId"; // Constance For Store Procedure public const string const_procAccessCardEntry_Report = "procAccessCardEntry_Report"; public const string const_ProcAttendanceReportBindDropdown = "ProcAttendanceReportBindDropdown"; public const string const_procFinancialYear_SelectAll = "procGetYear"; } } <file_sep>export interface IEmployeeList { mode: string; UserId: number; Usertype: string; Id: number; EmployeeCode: string; CompanyName: string; Employee_Name: string; Email: string; Department:string; TotalExp: string; JoiningDate: Date; RelevingDate:Date; Grace: number; SL_CL: string; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.VacancyRelated { public class SkillGroup : VISBaseEntity { /// <summary> /// SkillGroup Entity Fields. /// </summary> /// public Int64 SkillGroupID { get; set; } public string SkillGroupName { get; set; } public string RatingGroup { get; set; } } public static class SkillGroupConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_SkillGroup_Table = "SkillGroup"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_SkillGroupID = "SkillGroupID"; public const string const_SkillGroupName = "SkillGroupName"; public const string const_RatingGroup = "RatingGroup"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procSkillGroup_Add = "procSkillGroup_Add"; public const string const_procSkillGroup_Update = "procSkillGroup_Update"; public const string const_procSkillGroup_ActiveInActive = "procSkillGroup_ActiveInActive"; public const string const_procSkillGroup_SelectAll = "procSkillGroup_SelectAll"; public const string const_procSkillGroup_SelectById = "procSkillGroup_SelectById"; } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { RatingTypeService } from '../../../service/Masters/VacancyRelated/RatingType.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IRatingType } from '../../../Model/Masters/VacancyRelated/RatingType'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component ({ providers: [RatingTypeService], templateUrl: 'app/Components/Masters/VacancyRelated/RatingType.component.html' }) export class RatingTypeComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; RatingTypes: IRatingType[]; RatingType: IRatingType; msg: string; indLoading: boolean = false; RatingTypeFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; RatingTypeFilter: string; isDesc: boolean = false; column: any = 'TypeName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; ShowHideSearch: boolean = false; strSearchTypeName: string; constructor(private fb: FormBuilder, private _RatingTypeService: RatingTypeService, private pagerService: PagerService) { } ngOnInit(): void { this.RatingTypeFrm = this.fb.group ({ CompanyId: [''], Id: [''], TypeName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], EntityMessage: [''], }); this.LoadRatingType(); } LookupTypeFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.RatingTypeFilter = value; } RatingTypeSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadRatingType(): void { this.indLoading = true; this._RatingTypeService.get(Global.BASE_RATINGTYPE_ENDPOINT) .subscribe(lookuptypes => { this.RatingTypes = lookuptypes; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchTypeName = (<HTMLInputElement>document.getElementById("searchTypeName")).value; if (this.strSearchTypeName != '') { this.strSearchTypeName = this.strSearchTypeName.toLocaleLowerCase(); this.RatingTypes = this.RatingTypes.filter ( x => x.TypeName != null && x.TypeName.toLocaleLowerCase().indexOf(this.strSearchTypeName) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } AddRatingType() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New RatingType"; this.modalBtnTitle = "Add"; this.RatingTypeFrm.reset(); this.modal.open(); } EditRatingType(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit RatingType"; this.modalBtnTitle = "Update"; this.RatingType = this.RatingTypes.filter(x => x.Id == id)[0]; this.RatingTypeFrm.setValue(this.RatingType); this.modal.open(); } DeleteRatingType(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.RatingType = this.RatingTypes.filter(x => x.Id == id)[0]; this.RatingTypeFrm.setValue(this.RatingType); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.RatingTypeFrm.enable() : this.RatingTypeFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.RatingTypes); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { debugger; this.msg = ""; switch (this.dbops) { case DBOperation.create: this._RatingTypeService.post(Global.BASE_RATINGTYPE_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data this.LoadRatingType(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._RatingTypeService.put(Global.BASE_RATINGTYPE_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data this.LoadRatingType(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._RatingTypeService.delete(Global.BASE_RATINGTYPE_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "RatingType status changed successfully."; this.LoadRatingType(); } else { this.msg = "Error has occurred while changing status of existing RatingType!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain { public class VISBaseEntity { /// <summary> /// Base entity fields. /// </summary> public Int64 Id { get; set; } public Int64 CompanyId { get; set; } public DateTime CreatedOn { get; set; } public DateTime UpdatedOn { get; set; } public Int64 CreatedBy { get; set; } public Int64 UpdatedBy { get; set; } public bool IsActive { get; set; } public bool EntityMessage { get; set; } } public static class VISBaseEntityConstants { /// <summary> /// Base Entity Constants. /// </summary> public const string const_Field_Id = "Id"; public const string const_Field_IsActive = "IsActive"; public const string const_Field_CreatedOn = "CreatedOn"; public const string const_Field_UpdatedOn = "UpdatedOn"; public const string const_Field_CompanyId = "CompanyId"; public const string const_Field_CreatedBy = "CreatedBy"; public const string const_Field_UpdatedBy = "UpdatedBy"; public const string const_Field_EntityMessage = "EntityMessage"; public const string const_Result_Success = "Success: "; public const string const_Result_Failure = "Failure: "; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Notification { public class MyTicket : VISBaseEntity { public string Subject { get; set; } public string Message { get; set; } public string Remarks { get; set; } public string AddressToGroup { get; set; } public string AssignTo { get; set; } public string Priority { get; set; } public string Status { get; set; } public string CreatedByName { get; set; } public string UpdatedByName { get; set; } public Int64 CreatedId { get; set; } public string RecordCreatedBy { get; set; } public DateTime RecordCreatedOn {get;set;} public Int64 HelpTicketId { get; set; } public string FileName { get; set; } public string FileName1 { get; set; } public string FileName2 { get; set; } public string RoleType { get; set; } // for dropdown in add company master public string DepartmentHelpTicketDll { get; set; } public string SuggestionAlie { get; set; } public Int64 SuggestionId { get; set; } } public static class MyTicketConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_HelpTicket_Master = "HelpTicketMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Subject = "Subject"; public const string const_Field_Message = "Message"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_AddressToGroup = "AddressToGroup"; public const string const_Field_AssignTo = "AssignTo"; public const string const_Field_CreatedByName = "CreatedByName"; public const string const_Field_UpdatedByName = "UpdatedByName"; public const string const_Field_Priority = "Priority"; public const string const_Field_Status = "Status"; public const string const_Field_CreatedId = "CreatedId"; public const string const_Field_SuggestionAlie = "SuggestionAlie"; public const string const_Field_SuggestionId = "SuggestionId"; public const string const_Field_Mode = "Mode"; public const string const_Field_Employee_Id = "Employee_Id"; public const string cons_Filed_Organization_id = "Organization_Id"; public const string const_Field_RecordCreatedBy = "RecordCreatedBy"; public const string cons_Filed_RecordCreatedOn = "RecordCreatedOn"; public const string cons_Filed_HelpTicketId = "HelpTicketId"; public const string cons_Filed_FileName = "FileName"; public const string cons_Filed_FileName1 = "FileName"; public const string cons_Filed_FileName2 = "FileName"; public const string cons_Filed_OriginalFileName = "OriginalFileName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procHelpTicketDetailByUser = "procHelpTicketDetailByUser"; public const string const_procHelpTicket_Add = "procHelpTicketMaster_Add"; public const string const_procHelpTicket_update = "procHelpTicket_Update"; public const string const_procHelpTicket_selectAll = "procHelpTicketMaster_SelectAll"; public const string const_procHelpTicket_ActiveInActive = "procHelpTicaket_ActiveInActive"; public const string const_procHelpTicket_StatusOpenUserAssignTo = "procHelpTicketDetailByAssignToOpen"; public const string const_procHelpTicket_ProcHelpTicketAssignToFind = "ProcHelpTicketAssignTo"; /// <summary> /// drop down bind /// </summary> public const string const_procHelpTicketMaster_DepartmentHelpTicketDll = "procSelectDepartmentHelpTicket"; public const string const_procHelpTicketHistory_History= "ProcHelpTicket_History"; public const string const_procHelpTicketAttachement = "procHelpTicketAttachement_Add"; public const string const_procHelpTicketAttachementUpdate = "procHelpTicketAttachement_Update"; public const string const_procHelpTicketMasterLog = "procHelpTicketMasterLog"; public const string const_procHelpTicket_SelectById = "procHelpTickeMster_SelectById"; } } <file_sep>export interface IWorkSheet { ActivityId: number; ActivityName: string; SubActivityId: number; SubActivityName: string; Date: string; FillDate: string; UserId: number; ProjectID: number; ProjectName: string; TaskName: string; TaskId: number; Description: string; Hours: string; WorkSheetID: number; } export interface IProject { Date: string; UserId: number; ProjectID: number; ProjectName: string; }<file_sep>export interface IPoints { EventName: String; Type: boolean; CalculatedOn: String; PointsGained: number; Date: String; }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IConfigureTicket } from '../../../Model/Masters/Configuration/ConfigureTicket'; @Pipe ({ name: 'configureticketFilter' }) export class ConfigureTicketFilterPipe implements PipeTransform { transform(value: IConfigureTicket[], filter: string): IConfigureTicket[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IConfigureTicket) => app.Department_Name != null && app.Department_Name.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Reports.Attendance { public class LateEarlyReport { } public static class LateEarlyReportConstant { // Constance For Parameter public const string const_Employee_Id = "Employee_Id"; public const string const_Id = "Id"; public const string const_mode = "mode"; public const string const_FromDate = "FromDate"; public const string const_ToDate = "ToDate"; public const string const_Date = "Date"; public const string const_Field_EntityMessage = "EntityMessage"; // Constance For Store Procedure public const string const_ProcAttendanceReportBindDropdown = "ProcAttendanceReportBindDropdown"; public const string const_procFinancialYear_SelectAll = "procGetYear"; public const string const_procGetEmployeeId = "procGetEmployeeId"; public const string const_ProcLevels_GetAttendance = "ProcLevels_GetAttendance"; public const string const_ProcLevels_GetAttendanceForLateComing = "ProcLevels_GetAttendanceForLateComing"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class CompanyMaster : VISBaseEntity { /// <summary> /// CompanyMaster Entity Fields. /// </summary> public string CompanyName { get; set; } public string City { get; set; } public string ZipCode { get; set; } public string State { get; set; } public string Country { get; set; } public string CountryName { get; set; } public string ContactNo { get; set; } public string E_mail { get; set; } public string Fax { get; set; } public string CompanyURL { get; set; } public string Address { get; set; } public string CompanyLogo { get; set; } public string AccountHead { get; set; } public string Designation { get; set; } public string Signature { get; set; } public string CompanyShortCode { get; set; } public string Address2 { get; set; } public string StartSeries { get; set; } public int FinancialYear { get; set; } public string DesignationOther { get; set; } public string AccountHeadOther { get; set; } public string SignatureOther { get; set; } // for dropdown in add company master public string FinancialYeardll { get; set; } public string Employee_Name { get; set; } } public static class CompanyMasterConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_CompanyMaster = "CompanyMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_CompanyName = "CompanyName"; public const string const_Field_City = "City"; public const string const_Field_ZipCode = "ZipCode"; public const string const_Field_State = "State"; public const string const_Field_Country = "Country"; public const string const_Field_ContactNo = "ContactNo"; public const string const_Field_E_mail = "E_mail"; public const string const_Field_Fax = "Fax"; public const string const_Field_CompanyURL = "CompanyURL"; public const string const_Field_Address = "Address"; public const string const_Field_CompanyLogo = "CompanyLogo"; public const string const_Field_AccountHead = "AccountHead"; public const string const_Field_Designation = "Designation"; public const string const_Field_Signature = "Signature"; public const string const_Field_CompanyShortCode = "CompanyShortCode"; public const string const_Field_Address2 = "Address2"; public const string const_Field_StartSeries = "StartSeries"; public const string const_Field_FinancialYear = "FinancialYear"; public const string const_Field_AccountHeadOther = "AccountHeadOther"; public const string const_Field_SignatureOther = "SignatureOther"; public const string const_Field_DesignationOther = "DesignationOther"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procCompanyMaster_Add = "procCompanyMaster_Add"; public const string const_procCompanyMaster_Update = "procCompanyMaster_Update"; public const string const_procCompanyMaster_ActiveInActive = "procCompanyMaster_ActiveInActive"; public const string const_procCompanyMaster_SelectAll = "procCompanyMaster_SelectAll"; public const string const_procCompanyMaster_SelectBaseNonBase = "procCompanyMaster_SelectBaseNonBase"; public const string const_procCompanyMaster_SelectById = "procCompanyMaster_SelectById"; public const string const_procCompanyMaster_ForCountrydll = "procSelectCountry"; public const string const_procCompanyMaster_ForFinancialYeardll = "procSelectFinancialYear"; public const string const_procCompanyMaster_ForPositiondll = "procSelectPosition"; public const string const_procCompanyMaster_ForSelectHeaddll = "procSelectHead"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var CurrencyHistory_service_1 = require("../../../service/Masters/CurrencyRelated/CurrencyHistory.service"); var currency_service_1 = require("../../../service/Masters/CurrencyRelated/currency.service"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); //import * as _ from 'underscore'; var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var CurrencyHistoryComponent = (function () { function CurrencyHistoryComponent(_CurrencyHistoryService, pagerService, _CurrencyService, _CommonHelperService) { this._CurrencyHistoryService = _CurrencyHistoryService; this.pagerService = pagerService; this._CurrencyService = _CurrencyService; this._CommonHelperService = _CommonHelperService; this.ToDayDate = new Date(); this.YearNow = this.ToDayDate.getFullYear(); this.indLoading = false; this.isDesc = false; this.column = 'Full_Name'; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; //Variables for Filter this.ShowHideSearch = false; } CurrencyHistoryComponent.prototype.ResetModel = function () { this.objICurrencyHistory = ({ CompanyId: 0, CreatedBy: '', CreatedOn: null, Currency_Id: 0, Current_Exch_Rate: 0, Date_Entered: null, Default_Exch_Rate: 0, FromDate: null, Id: 0, IsActive: false, Month_Entered: 1, ToDate: null, UpdatedBy: '', UpdatedOn: null, Year_Entered: this.YearNow }); }; CurrencyHistoryComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.ResetModel(); this.listICurrencyHistory = [({ CompanyId: 0, CreatedBy: '', CreatedOn: null, Currency_Id: 0, Current_Exch_Rate: 0, Date_Entered: null, Default_Exch_Rate: 0, FromDate: null, Id: 0, IsActive: false, Month_Entered: 0, ToDate: null, UpdatedBy: '', UpdatedOn: null, Year_Entered: 0 })]; this.LoadCurrencyHistory(); this.BindCurrencyDropdown(); this.GetYear(); }; CurrencyHistoryComponent.prototype.GetYear = function () { this.YearNow = new Date().getFullYear(); this.Year = []; for (var i = 0; i < 100; i++) { this.Year.push(this.YearNow); this.YearNow++; } }; CurrencyHistoryComponent.prototype.ChangeDefaultExchangeRateByCurrency = function (id) { var _this = this; this._CurrencyHistoryService.getbyid(global_1.Global.BASE_CurrencyHistoryAPI_ENDPOINT, id). subscribe(function (defaultexchangerate) { _this.objICurrencyHistory.Default_Exch_Rate = Number(defaultexchangerate); }); }; CurrencyHistoryComponent.prototype.CurrencyFilterCriteriaChange = function (value) { if (value != '[object Event]') this.CurrencyFilter = value; }; CurrencyHistoryComponent.prototype.CurrencySort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; CurrencyHistoryComponent.prototype.LoadCurrencyHistory = function () { var _this = this; this.indLoading = true; this._CurrencyHistoryService.get(global_1.Global.BASE_CurrencyHistoryAPI_ENDPOINT) .subscribe(function (currencyhistorylist) { _this.listICurrencyHistory = currencyhistorylist; //Logic for searching - start if (_this.ShowHideSearch) { _this.DefaultExchangeRate = document.getElementById("txtDefaultExchangeRate").value; if (_this.DefaultExchangeRate != '') { _this.DefaultExchangeRate = _this.DefaultExchangeRate.toLocaleLowerCase(); _this.listICurrencyHistory = _this.listICurrencyHistory.filter(function (x) { return x.Default_Exch_Rate != null && x.Default_Exch_Rate.toLocaleString().indexOf(_this.DefaultExchangeRate) != -1; }); } _this.CurrentExchangeRate = document.getElementById("txtCurrentExchangeRate").value; if (_this.CurrentExchangeRate != '') { _this.CurrentExchangeRate = _this.CurrentExchangeRate.toLocaleLowerCase(); _this.listICurrencyHistory = _this.listICurrencyHistory.filter(function (x) { return x.Current_Exch_Rate != null && x.Current_Exch_Rate.toLocaleString().indexOf(_this.CurrentExchangeRate) != -1; }); } _this.FromDate = document.getElementById("txtfromdate").value; if (_this.FromDate != '') { _this.FromDate = _this.FromDate.toLocaleLowerCase(); _this.listICurrencyHistory = _this.listICurrencyHistory.filter(function (x) { return x.FromDate != null && x.FromDate.toLocaleString().indexOf(_this.FromDate) != -1; }); } _this.ToDate = document.getElementById("txttodate").value; if (_this.ToDate != '') { _this.ToDate = _this.ToDate.toLocaleLowerCase(); _this.listICurrencyHistory = _this.listICurrencyHistory.filter(function (x) { return x.ToDate != null && x.ToDate.toLocaleString().indexOf(_this.ToDate) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); }); //,error => this.msg = <any>error }; CurrencyHistoryComponent.prototype.BindCurrencyDropdown = function () { var _this = this; this._CurrencyService.get(global_1.Global.BASE_CURRENCY_ENDPOINT). subscribe(function (currencylist) { _this.lstCurrency = currencylist; }); }; CurrencyHistoryComponent.prototype.addCurrencyhistory = function () { this.dbops = enum_1.DBOperation.create; this.modalTitle = "Add New Currency History"; this.modalBtnTitle = "Add"; this.objICurrencyHistory.Currency_Id = 0; this.objICurrencyHistory.Default_Exch_Rate = 0; this.objICurrencyHistory.Current_Exch_Rate = 0; this.objICurrencyHistory.Month_Entered = 1; this.YearNow = this.ToDayDate.getFullYear(); this.objICurrencyHistory.Year_Entered = this.YearNow; this.modal.open(); }; CurrencyHistoryComponent.prototype.editCurrencyhistory = function (id) { this.dbops = enum_1.DBOperation.update; this.modalTitle = "Edit Currency"; this.modalBtnTitle = "Update"; this.objICurrencyHistory = this.listICurrencyHistory.filter(function (x) { return x.Id == id; })[0]; this.YearNow = this.ToDayDate.getFullYear(); if (this.objICurrencyHistory.Year_Entered < this.YearNow) { this.objICurrencyHistory.Year_Entered = this.YearNow; } this.modal.open(); }; CurrencyHistoryComponent.prototype.deleteCurrencyhistory = function (id, status) { this.dbops = enum_1.DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.objICurrencyHistory = this.listICurrencyHistory.filter(function (x) { return x.Id == id; })[0]; this.YearNow = this.ToDayDate.getFullYear(); if (this.objICurrencyHistory.Year_Entered < this.YearNow) { this.objICurrencyHistory.Year_Entered = this.YearNow; } this.modal.open(); }; CurrencyHistoryComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.currencyFrm.enable() : this.currencyFrm.disable(); }; CurrencyHistoryComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; CurrencyHistoryComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.listICurrencyHistory); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; CurrencyHistoryComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; CurrencyHistoryComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; if (formData.Currency_Id != 0) { switch (this.dbops) { case enum_1.DBOperation.create: this._CurrencyHistoryService.post(global_1.Global.BASE_CurrencyHistoryAPI_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadCurrencyHistory(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._CurrencyHistoryService.put(global_1.Global.BASE_CurrencyHistoryAPI_ENDPOINT, formData.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadCurrencyHistory(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._CurrencyHistoryService.delete(global_1.Global.BASE_CurrencyHistoryAPI_ENDPOINT, formData.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "Currency status changed successfully."; _this.LoadCurrencyHistory(); } else { _this.msg = "Error has occurred while changing status of existing currency!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } } else { alert("Please Select Currency !"); } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], CurrencyHistoryComponent.prototype, "modal", void 0); CurrencyHistoryComponent = __decorate([ core_1.Component({ providers: [CurrencyHistory_service_1.CurrencyHistoryService, currency_service_1.CurrencyService], templateUrl: 'app/Components/Masters/CurrencyRelated/CurrencyHistory.component.html' }), __metadata("design:paramtypes", [CurrencyHistory_service_1.CurrencyHistoryService, pager_index_1.PagerService, currency_service_1.CurrencyService, CommonHelper_service_1.CommonHelperService]) ], CurrencyHistoryComponent); return CurrencyHistoryComponent; }()); exports.CurrencyHistoryComponent = CurrencyHistoryComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class HomePageImage : VISBaseEntity { /// <summary> /// HomePage Entity Fields. /// </summary> public string ImagePath { get; set; } public bool Active { get; set; } } public static class HomePageImageConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_organization_Table = "HomePage"; /// <summary> /// Table organization field Name Constants. /// </summary> public const string const_ImagePath = "ImagePath"; public const string const_Active = "Active"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procHomePage_Add = "procHomePage_Add"; public const string const_procHomePage_Update = "procHomePage_Update"; public const string const_procHomePage_ActiveInActive = "procHomePage_ActiveInActive"; public const string const_procHomePage_SelectAll = "procHomePage_SelectAll"; public const string const_procHomePage_SelectById = "procHomePage_SelectById"; public const string const_procHomePage_CountActiveImage = "procHomePage_CountActiveImage"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var ManualPointEntry_service_1 = require("../../../service/Masters/EmployeeLevels/ManualPointEntry.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var ManualPointEntryComponent = (function () { //////////////////////////////// function ManualPointEntryComponent(fb, _ManualPointEntryService, pagerService) { this.fb = fb; this._ManualPointEntryService = _ManualPointEntryService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'Full_Name'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; } ManualPointEntryComponent.prototype.ngOnInit = function () { this.ManualPointEntry = { Id: 0, GroupID: 0, EmpName: "", Criteria: "", Points: 0, Point: 0, Month: null, Remarks: "", Category: "", Type: "", ForDate: null, CriteriaId: 0, IsPerformanceBadge: false, CategoryId: 0, CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, EntityMessage: "" }; this.TestMultidll(); this.LoadManualPointEntrys(); this.LoadCriteria(); this.LoadCategory(); this.LoadEmployee(); }; ManualPointEntryComponent.prototype.LoadEmployee = function () { var _this = this; debugger; this._ManualPointEntryService.GetEmployeeList(global_1.Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(function (DATA) { _this.IMultiSelectOption = DATA; debugger; } //,error => this.msg = <any>error ); }; ManualPointEntryComponent.prototype.TestMultidll = function () { debugger; this.myOptions = [ { id: 6, name: 'Option 1' }, { id: 7, name: 'Option 2' }, { id: 8, name: 'Option 3' } ]; }; ManualPointEntryComponent.prototype.onChange = function () { console.log(this.optionsModel); }; ManualPointEntryComponent.prototype.LoadCriteria = function () { var _this = this; this._ManualPointEntryService.getCriteria(global_1.Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(function (DATA) { _this.ListCriteria = DATA; } //,error => this.msg = <any>error ); }; ManualPointEntryComponent.prototype.LoadCategory = function () { var _this = this; this._ManualPointEntryService.getCategory(global_1.Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(function (DATA) { _this.ListCategory = DATA; } //,error => this.msg = <any>error ); }; ManualPointEntryComponent.prototype.ManualPointEntryFilterCriteriaChange = function (value) { if (value != '[object Event]') this.ManualPointEntryFilter = value; }; ManualPointEntryComponent.prototype.ManualPointEntrySort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; ManualPointEntryComponent.prototype.LoadManualPointEntrys = function () { var _this = this; this.indLoading = true; this._ManualPointEntryService.get(global_1.Global.BASE_ManualPointEntry_ENDPOINT) .subscribe(function (ManualPointEntrys) { _this.ManualPointEntrys = ManualPointEntrys; //Logic for searching - start if (_this.ShowHideSearch) { _this.strsearchEmpName = document.getElementById("searchEmpName").value; if (_this.strsearchEmpName != '') { _this.strsearchEmpName = _this.strsearchEmpName.toLocaleLowerCase(); _this.ManualPointEntrys = _this.ManualPointEntrys.filter(function (x) { return x.EmpName != null && x.EmpName.toLocaleLowerCase().indexOf(_this.strsearchEmpName) != -1; }); } } if (_this.ShowHideSearch) { _this.strsearchCriteria = document.getElementById("searchCriteria").value; if (_this.strsearchCriteria != '') { _this.strsearchCriteria = _this.strsearchCriteria.toLocaleLowerCase(); _this.ManualPointEntrys = _this.ManualPointEntrys.filter(function (x) { return x.Criteria != null && x.Criteria.toLocaleLowerCase().indexOf(_this.strsearchCriteria) != -1; }); } } if (_this.ShowHideSearch) { _this.strsearchRemarks = document.getElementById("searchRemarks").value; if (_this.strsearchRemarks != '') { _this.strsearchRemarks = _this.strsearchRemarks.toLocaleLowerCase(); _this.ManualPointEntrys = _this.ManualPointEntrys.filter(function (x) { return x.Remarks != null && x.Remarks.toLocaleLowerCase().indexOf(_this.strsearchRemarks) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; ManualPointEntryComponent.prototype.addManualPointEntry = function () { this.dbops = enum_1.DBOperation.create; // this.SetControlsState(true); this.modalTitle = "Add New ManualPointEntry"; this.modalBtnTitle = "Add"; //this.ManualPointEntryFrm.reset(); this.modal.open(); }; ManualPointEntryComponent.prototype.editManualPointEntry = function (id) { this.dbops = enum_1.DBOperation.update; // this.SetControlsState(true); this.modalTitle = "Edit ManualPointEntry"; this.modalBtnTitle = "Update"; this.ManualPointEntry = this.ManualPointEntrys.filter(function (x) { return x.Id == id; })[0]; // this.ManualPointEntryFrm.setValue(this.ManualPointEntry); this.modal.open(); }; ManualPointEntryComponent.prototype.deleteManualPointEntry = function (id, status) { this.dbops = enum_1.DBOperation.delete; //this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.ManualPointEntry = this.ManualPointEntrys.filter(function (x) { return x.Id == id; })[0]; // this.ManualPointEntryFrm.setValue(this.ManualPointEntry); this.modal.open(); }; //SetControlsState(isEnable: boolean) { // isEnable ? this.ManualPointEntryFrm.enable() : this.ManualPointEntryFrm.disable(); //} ManualPointEntryComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; ManualPointEntryComponent.prototype.ChangeCriteria = function (CriteriaId) { var _this = this; this._ManualPointEntryService.GetDataOnChange(global_1.Global.BASE_ManualPointEntry_ENDPOINT, CriteriaId) .subscribe(function (DATA) { _this.DataOnCriteria = DATA; // this.ManualPointEntry = this.DataOnCriteria; if (_this.DataOnCriteria.IsPerformanceBadge == false) { _this.ManualPointEntry.Type = "Manual"; } else { _this.ManualPointEntry.Type = "Performance Badges"; } _this.ManualPointEntry.Points = _this.DataOnCriteria.Point; _this.ManualPointEntry.CategoryId = _this.DataOnCriteria.CategoryId; } //,error => this.msg = <any>error ); }; ManualPointEntryComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.ManualPointEntrys); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; ManualPointEntryComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; ManualPointEntryComponent.prototype.onSubmit = function (formData) { var _this = this; debugger; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: debugger; formData.EmpName = formData.EmpName.toString(); this._ManualPointEntryService.post(global_1.Global.BASE_ManualPointEntry_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadManualPointEntrys(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._ManualPointEntryService.put(global_1.Global.BASE_ManualPointEntry_ENDPOINT, formData._value.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadManualPointEntrys(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._ManualPointEntryService.delete(global_1.Global.BASE_ManualPointEntry_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "ManualPointEntry status changed successfully."; _this.LoadManualPointEntrys(); } else { _this.msg = "Error has occurred while changing status of existing ManualPointEntry!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], ManualPointEntryComponent.prototype, "modal", void 0); ManualPointEntryComponent = __decorate([ core_1.Component({ //selector: 'ss-multiselect-dropdown', providers: [ManualPointEntry_service_1.ManualPointEntryService], templateUrl: 'app/Components/Masters/EmployeeLevels/ManualPointEntry.component.html', }), __metadata("design:paramtypes", [forms_1.FormBuilder, ManualPointEntry_service_1.ManualPointEntryService, pager_index_1.PagerService]) ], ManualPointEntryComponent); return ManualPointEntryComponent; }()); exports.ManualPointEntryComponent = ManualPointEntryComponent; <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var HomePageImage_service_1 = require("../../../service/Masters/CompanyRelated/HomePageImage.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var http_1 = require("@angular/http"); var HomePageImageComponent = (function () { function HomePageImageComponent(fb, _HomePageImageService, pagerService, http, _CommonHelperService) { this.fb = fb; this._HomePageImageService = _HomePageImageService; this.pagerService = pagerService; this.http = http; this._CommonHelperService = _CommonHelperService; this.ShowHideSearch = false; this.indLoading = false; this.isDesc = false; this.column = 'ImagePath'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; } HomePageImageComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.homepageimage = ({ Id: 0, ImagePath: '', Active: false, IsActive: false, CreatedOn: null, UpdatedOn: null, CreatedBy: 0, UpdatedBy: 0 }); this.GetAllImage(); this.GetActiveImage(); }; HomePageImageComponent.prototype.AddHomePageImage = function () { this.dbops = enum_1.DBOperation.create; this.modalTitle = "Add New Home Page Image"; this.modalBtnTitle = "Upload Image"; //this.homepageimage.ImagePath = this.homepageimage.ImagePath; this.ngOnInit(); this.modal.open(); }; HomePageImageComponent.prototype.EditHomePageImage = function (id) { debugger; this.dbops = enum_1.DBOperation.update; this.modalTitle = "Edit Home Page Image"; this.modalBtnTitle = "Update"; this.homepageimage = this.homepageimages.filter(function (x) { return x.Id == id; })[0]; this.modal.open(); }; HomePageImageComponent.prototype.DeleteHomePageImage = function (id, status) { this.dbops = enum_1.DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.homepageimage = this.homepageimages.filter(function (x) { return x.Id == id; })[0]; this.homepageimage.ImagePath = this.homepageimage.ImagePath; this.modal.open(); }; HomePageImageComponent.prototype.GetAllImage = function () { var _this = this; this.indLoading = true; this._HomePageImageService.get(global_1.Global.BASE_HOMEPAGEIMAGE_ENDPOINT) .subscribe(function (data) { _this.homepageimages = data; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchImageName = document.getElementById("searchImageName").value; if (_this.strSearchImageName != '') { _this.strSearchImageName = _this.strSearchImageName.toLocaleLowerCase(); _this.homepageimages = _this.homepageimages.filter(function (x) { return x.ImagePath != null && x.ImagePath.toLocaleLowerCase().indexOf(_this.strSearchImageName) != -1; }); } } //Logic for searching - End _this.indLoading = false; _this.JumpOnPage(1); }); }; HomePageImageComponent.prototype.GetActiveImage = function () { var _this = this; this.indLoading = true; this._HomePageImageService.getactiveimage(global_1.Global.BASE_HOMEPAGEIMAGE_ENDPOINT) .subscribe(function (activeimages) { _this.activeimages = activeimages; _this.indLoading = false; }); }; HomePageImageComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.HomePageImageFrm.enable() : this.HomePageImageFrm.disable(); }; HomePageImageComponent.prototype.HomePageImageSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; HomePageImageComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.homepageimages); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; HomePageImageComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; HomePageImageComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: if (this.fileList1 != null) { formData.ImagePath = this.fileList1.item(0).name; this._HomePageImageService.post(global_1.Global.BASE_HOMEPAGEIMAGE_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.fileList1.item(0).name; var file = _this.fileList1[0]; var formData_1 = new FormData(); formData_1.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl = "/api/HomePageImageAPI/UploadJsonFile"; _this.http.post(apiUrl, formData_1, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); _this.msg = data; _this.GetAllImage(); _this.GetActiveImage(); _this.fileList1 = null; _this.msg2 = ''; _this.modal.dismiss(); } else { alert(data); _this.fileList1 = null; } }, function (error) { _this.msg = error; }); } else { this.msg2 = "Please Choose Image"; } break; case enum_1.DBOperation.update: this._HomePageImageService.put(global_1.Global.BASE_HOMEPAGEIMAGE_ENDPOINT, formData.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.GetAllImage(); _this.modal.dismiss(); } else { alert(data); } _this.GetActiveImage(); }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._HomePageImageService.delete(global_1.Global.BASE_HOMEPAGEIMAGE_ENDPOINT, formData.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "Home Page Image status changed successfully."; _this.GetAllImage(); } else { _this.msg = "Error has occurred while changing status of existing Home Page Image!"; } _this.modal.dismiss(); _this.GetActiveImage(); }, function (error) { _this.msg = error; }); break; } }; HomePageImageComponent.prototype.fileChange = function (event) { this.fileList1 = event.target.files; }; HomePageImageComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; HomePageImageComponent.prototype.ViewImage = function (id) { this.modalTitle = "Preview Home Page Image"; this.homepageimage = this.homepageimages.filter(function (x) { return x.Id == id; })[0]; this.imgpathshow = this.homepageimage.ImagePath; this.modal2.open(); }; HomePageImageComponent.prototype.CancelPopup = function () { this.modal.dismiss(); this.msg2 = ''; }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], HomePageImageComponent.prototype, "modal", void 0); __decorate([ core_1.ViewChild('modal2'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], HomePageImageComponent.prototype, "modal2", void 0); HomePageImageComponent = __decorate([ core_1.Component({ providers: [HomePageImage_service_1.HomePageImageService], templateUrl: 'app/Components/Masters/CompanyRelated/HomePageImage.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, HomePageImage_service_1.HomePageImageService, pager_index_1.PagerService, http_1.Http, CommonHelper_service_1.CommonHelperService]) ], HomePageImageComponent); return HomePageImageComponent; }()); exports.HomePageImageComponent = HomePageImageComponent; <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { ICommonConfiguration } from '../../../Model/Masters/Configuration/CommonConfiguration'; @Pipe ({ name: 'commonconfigurationFilter' }) export class CommonConfigurationFilterPipe implements PipeTransform { transform(value: ICommonConfiguration[], filter: string): ICommonConfiguration[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: ICommonConfiguration) => app.TDSMenuHideOrShow != null && app.TDSMenuHideOrShow.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.GeneralHelper; namespace VIS_Domain.RFQ { public class RFQList : VISBaseEntity { public long RFQInitialId { get; set; } public long OpportunityId { get; set; } public string Title { get; set; } public string InitiatedBy { get; set; } public DateTime DateOfInitiation { get; set; } public string EstimateBy { get; set; } public DateTime SubmittedOn { get; set; } public string LastResponseBy { get; set; } public Nullable<DateTime> LastResponseDate { get; set; } public string ActionRequestedBy { get; set; } public string Status { get; set; } public string rfqStatus { get; set; } public string OtherComments { get; set; } public string CommunicationId { get; set; } public string CreatedByName { get; set; } public long EmpId { get; set; } public string Mode { get; set; } public string Industries { get; set; } } public class RFQOpportunity : VISBaseEntity { public long BDHead { get; set; } public long BDManager { get; set; } public DateTime DateOfInitiation { get; set; } public int ProspectId { get; set; } public int BillingClient { get; set; } public int BussinessType { get; set; } public int BussTechArea { get; set; } public string OpportunityName { get; set; } public int ProjectType { get; set; } public int Industry { get; set; } public int serviceOffering { get; set; } public int Solution { get; set; } public int TechBody { get; set; } public int EstimationDoneBy { get; set; } public string ExactTech { get; set; } public DateTime NextCallDate { get; set; } public DateTime TentativeOppClosureDate { get; set; } public DateTime TentativeStartDate { get; set; } public DateTime TentativeEndDate { get; set; } public double ExpectedNoResource { get; set; } public string Duration { get; set; } public float TotalProjectHrs { get; set; } public int Currency { get; set; } public double Rate { get; set; } public int TotalValue { get; set; } public string TimeTakenEstimate { get; set; } public string Confidence { get; set; } public string Status { get; set; } public double PlaningPriority { get; set; } public DateTime ClosureDate { get; set; } public string OtherComments { get; set; } public Boolean IsProject { get; set; } public int CreatedName { get; set; } public int UpdatedName { get; set; } public Boolean IsDeleted { get; set; } public int ProjectId { get; set; } } public static class RFQOpportunityConstant { public const string const_Field_BDHead = "BDHead"; public const string const_Field_BDManager = "BDManager"; public const string const_Field_DateOfInitiation = "DateOfInitiation"; public const string const_Field_ProspectId = "ProspectId"; public const string const_Field_BillingClient = "BillingClient"; public const string const_Field_BussinessType = "BussinessType"; public const string const_Field_BussTechArea = "BussTechArea"; public const string const_Field_OpportunityName = "OpportunityName"; public const string const_Field_ProjectType = "ProjectType"; public const string const_Field_Industry = "Industry"; public const string const_Field_serviceOffering = "serviceOffering"; public const string const_Field_Solution = "Solution"; public const string const_Field_TechBody = "TechBody"; public const string const_Field_EstimationDoneBy = "EstimationDoneBy"; public const string const_Field_ExactTech = "ExactTech"; public const string const_Field_NextCallDate = "NextCallDate"; public const string const_Field_TentativeOppClosureDate = "TentativeOppClosureDate"; public const string const_Field_TentativeStartDate = "TentativeStartDate"; public const string const_Field_TentativeEndDate = "TentativeEndDate"; public const string const_Field_ExpectedNoResource = "ExpectedNoResource"; public const string const_Field_Duration = "Duration"; public const string const_Field_TotalProjectHrs = "TotalProjectHrs"; public const string const_Field_Currency = "Currency"; public const string const_Field_Rate = "Rate"; public const string const_Field_TotalValue = "TotalValue"; public const string const_Field_TimeTakenEstimate = "TimeTakenEstimate"; public const string const_Field_Confidence = "Confidence"; public const string const_Field_Status = "Status"; public const string const_Field_PlaningPriority = "PlaningPriority"; public const string const_Field_ClosureDate = "ClosureDate"; public const string const_Field_OtherComments = "OtherComments"; public const string const_Field_IsProject = "IsProject"; public const string const_Field_CreatedName = "CreatedName"; public const string const_Field_UpdatedName = "UpdatedName"; public const string const_Field_IsDeleted = "IsDeleted"; public const string const_Field_ProjectId = "ProjectId"; ///// ///Stored Procedure //// public const string const_Field_SaveOpportunity = "procOpportunity_Add"; } public class RFQInitial : VISBaseEntity { /// <summary> /// /RFQ initial /// </summary> /// public long BusinessManagerId { get; set; } public long BusinessHeadId { get; set; } public string Employee_Name { get; set; } public long BusinessTypeId { get; set; } public string BusinessType { get; set; } public long ProjectTypeId { get; set; } public string ProjectType { get; set; } public long ServiceOfferingId { get; set; } public string ServiceOffering { get; set; } public long SolutionId { get; set; } public string Solution { get; set; } public long FileTypeId { get; set; } public string FileType { get; set; } public long IndustryId { get; set; } public string Industries { get; set; } public long AuthorId { get; set; } public string Author { get; set; } public long TechnologyId { get; set; } public List<long> TechnologyIdList { get; set; } public string TechnologyName { get; set; } public string Remark { get; set; } public DateTime ResponseRequiredBy { get; set; } public long ResponseRequiredFrom { get; set; } public string SupportedBy { get; set; } public int ConfidenceLevel { get; set; } public string OpportunityStatus { get; set; } public long StatusId { get; set; } public string RFQStatus { get; set; } public DateTime ExpectedClosureDate { get; set; } public long UserId { get; set; } public List<long> UserIdList { get; set; } public string ProspectClient { get; set; } public int MyProperty { get; set; } public string Company { get; set; } public string Title { get; set; } public string Source { get; set; } public DateTime DateOfInitiation { get; set; } ///// ///Stored Procedure //// public const string const_Field_SaveOpportunity = "procOpportunity_Add"; } public class RFQInitialBase : VISBaseEntity { public int RFQID { get; set; } public int OpportunityID { get; set; } public DateTime SubmittedOn { get; set; } public string WatchBy { get; set; } public string ResponseRequired { get; set; } public int Source { get; set; } public long Status { get; set; } } public static class RFQInitialBaseConstant { public const string const_Field_RFQID = "RFQID"; public const string const_Field_OpportunityID = "OpportunityID"; public const string const_Field_SubmittedOn = "SubmittedOn"; public const string const_Field_WatchBy = "WatchBy"; public const string const_Field_ResReq = "ResponseRequired"; public const string const_Field_Source = "Source"; public const string const_Field_Status = "Status"; ///// ///procedure //// public const string const_Field_GetMaxOpportunityId = "GetMaxOpportunityId"; public const string const_Field_RFQInitial_Add = "procRFQInitial_Add"; } public class RFQDoc : VISBaseEntity { public long FileTypeID { get; set; } public string FileType { get; set; } public string FileName { get; set; } public long AuthorId { get; set; } public string Author { get; set; } public string RemarkDoc { get; set; } public string Remark { get; set; } public int RFQ_DocumentID { get; set; } public long ReferenceID { get; set; } public string OriginalFileName { get; set; } public string PopUp { get; set; } public Boolean IsResponse { get; set; } } public static class RFQDocConstant { /// <summary> /// Database table field Name Constants.Industries /// </summary> /// public const string const_Field_FileTypeID = "FileTypeID"; public const string const_Field_FileType = "FileType"; public const string const_Field_FileName = "FileName"; public const string const_Field_AuthorId = "AuthorId"; public const string const_Field_Author = "Author"; public const string const_Field_RemarkDoc = "RemarkDoc"; public const string const_Field_Remark = "Remark"; public const string const_Field_RFQ_DocumentID = "RFQ_DocumentID"; public const string const_Field_ReferenceID = "ReferenceID"; public const string const_Field_OriginalFileName = "OriginalFileName"; public const string const_Field_PopUp = "PopUp"; public const string const_Field_IsResponse = "IsResponse"; /// <summary> /// Procedure /// </summary> public const string const_Field_procRFQDocument_Add = "procRFQDocument_Add"; public const string const_Field_procGetRFQDocument = "procGetRFQDocument"; } public class RFQLink : VISBaseEntity { public string RemarkLink { get; set; } public string URL { get; set; } public string UserId { get; set; } public string Password { get; set; } public int RFQ_LinkID { get; set; } public long ReferenceID { get; set; } public string Remark { get; set; } public string PopUp { get; set; } public Boolean IsResponse { get; set; } } public static class RFQLinkConstant { /// <summary> /// Database table field Name Constants.Industries /// </summary> /// public const string const_Field_RemarkLink = "RemarkLink"; public const string const_Field_URL = "URL"; public const string const_Field_UserId = "UserId"; public const string const_Field_Password = "<PASSWORD>"; public const string const_Field_RFQ_LinkID = "RFQ_LinkID"; public const string const_Field_ReferenceID = "ReferenceID"; public const string const_Field_Remark = "Remark"; public const string const_Field_RFQ_DocumentID = "RFQ_DocumentID"; public const string const_Field_PopUp = "PopUp"; public const string const_Field_IsResponse = "IsResponse"; /// <summary> ///procedure /// </summary> /// public const string const_Field_RFQLink_Add = "procRFQLink_Add"; public const string const_Field_GetRFQLink = "procGetRFQLink"; } public class SessionData { public long SessionId { get; set; } } public class MainRFQInitial { public SessionData SessionData { get; set; } public RFQInitial RFQInitial { get; set; } public List<RFQDoc> RFQDoc { get; set; } public List<RFQLink> RFQLink { get; set; } } public static class RFQConstants { /// <summary> /// Database table field Name Constants.Industries /// </summary> /// public const string const_Field_Company = "Company"; public const string const_Field_RFQInitialId = "RFQInitialId"; public const string const_Field_OpportunityId = "OpportunityId"; public const string const_Field_Title = "Title"; public const string const_Field_InitiatedBy = "InitiatedBy"; public const string const_Field_DateOfInitiation = "DateOfInitiation"; public const string const_Field_EstimateBy = "EstimateBy"; public const string const_Field_SubmittedOn = "SubmittedOn"; public const string const_Field_LastResponseBy = "LastResponseBy"; public const string const_Field_LastResponseDate = "LastResponseDate"; public const string const_Field_ActionRequestedBy = "ActionRequestedBy"; public const string const_Field_Status = "Status"; public const string const_Field_rfqStatus = "rfqStatus"; public const string const_Field_OtherComments = "OtherComments"; public const string const_Field_CommunicationId = "CommunicationId"; public const string const_Field_EmpId = "EmpId"; public const string const_Field_Mode = "Mode"; public const string const_Field_BusinessManagerId = "BusinessManagerId"; public const string const_Field_BusinessHeadId = "Employee_Name"; public const string const_Field_Employee_Name = "Employee_Name"; public const string const_Field_BusinessType = "BusinessType"; public const string const_Field_ProjectType = "ProjectType"; public const string const_Field_Industries = "Industries"; public const string const_Field_FileType = "FileType"; public const string const_Field_Author = "Author"; public const string const_Field_Employee_FileName = "FileName"; public const string const_Field_RemarkDoc = "RemarkDoc"; public const string const_Field_RemarkLink = "RemarkLink"; public const string const_Field_URL = "URL"; public const string const_Field_UserId = "UserId"; public const string const_Field_Password = "<PASSWORD>"; /// <summary> /// Database Procedure and fucntion constants /// </summary> /// public const string const_Field_RFQEstimateList = "procRFQEstimateListingPerPage"; public const string const_Field_GetEmployeeIdByCommunicationId = "procGetEmployeeIdByCommunicationId"; ///// ///RFQ inital ///// public const string const_Field_FillBusinessHead = "procFillBusinessHead"; public const string const_Field_GetBusinessManager = "procGetBusinessManager"; public const string const_Field_GetBusinessType = "procGetBusinessType"; public const string const_Field_GetProjectType = "procGetProjectType"; public const string const_Field_GetIndustries = "procGetIndustries"; public const string const_Field_GetSolution = "procGetSolution"; public const string const_Field_GetServiceOffering = "procGetServiceOffering"; public const string const_Field_GetFileType = "procGetFileType"; public const string const_Field_GetAuthor = "procGetAuthor"; public const string const_Field_Technology = "procGetTechnology"; public const string const_Field_GetRFQStatus = "procGetStatus"; public const string const_Field_GetEmployee = "procGetEmployeeList"; public const string const_Field_GetCompanyByClientProspect = "procGetCompanyByClientProspect"; ///// ///RFQ Doc ///// public const string const_Field_GetAuthorIdByAuthorName = "procGetAuthorIdByAuthorName"; public const string const_Field_GetFileTypeIdByFileTypeName = "procGetFileTypeIdByFileTypeName"; public const string const_Field_GetMaxRFQInitialId = "procGetMaxRFQInitialId"; public const string const_Field_procRFQDocument_Add = "procRFQDocument_Add"; } public class ProspectClient { public long Id { get; set; } public string CompanyName { get; set; } public string Country { get; set; } public string FilterRadioButton { get; set; } } public class SuperProspectClient { public ProspectClient ProspectClient { get; set; } public SessionValues SessionValues { get; set; } } public static class ProspectClientConstant { /// <summary> /// Database table field Name Constants.Industries /// </summary> /// public const string const_Field_Id = "Id"; public const string const_Field_CountryName = "CountryName"; public const string const_Field_Country = "Country"; public const string const_Field_FilterRadioButton = "FilterRadioButton"; public const string const_Field_GetProspectClientPopUp = "procGetProspectClientPopUp"; } } <file_sep>export interface IConfigureTicket { Parent_Id: number; User_Id: number; Department_Name: string; Position_Id: number; IsActiveSuggestion: boolean; SuggestionAlie: string; Organization_Id: number; Suggestion_Dep_Emp_Id: number; Flag: boolean; Id: number; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; Employee_Name: string; Employee_Id: number; }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using VIS_Domain.Master.Configuration; using VIS_Repository.Reports.Attendance; namespace VIS_App.Controllers.Report.Attendance { public class AttendanceAccessCardComparisionReportAPIController : BaseAPIController { AttendanceAccessCardComparisionReportRepository objAttendanceAccessCardComparisionReportRepository = null; public AttendanceAccessCardComparisionReportAPIController() { objAttendanceAccessCardComparisionReportRepository = new AttendanceAccessCardComparisionReportRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/AttendanceAccessCardComparisionReportAPI/GetEmployee")] [HttpGet] public HttpResponseMessage GetEmployee() { return ToJson(objAttendanceAccessCardComparisionReportRepository.GetEmployee()); } [Route("api/AttendanceAccessCardComparisionReportAPI/GetYear")] [HttpGet] public HttpResponseMessage GetYear() { return ToJson(objAttendanceAccessCardComparisionReportRepository.GetYear()); } [Route("api/AttendanceAccessCardComparisionReportAPI/GetEmployeeAccessCardEntryComparision")] [HttpPost] public HttpResponseMessage GetEmployeeAccessCardEntryComparision(AttendanceAccessCardComparisionReportParameterModel entityobject) { if (entityobject.MonthWise == true) { entityobject.FromDate = new DateTime(Convert.ToInt32(entityobject.FromYear), Convert.ToInt32(entityobject.FromMonth), 01); entityobject.ToDate = new DateTime(Convert.ToInt32(entityobject.ToYear), Convert.ToInt32(entityobject.ToMonth), DateTime.DaysInMonth(Convert.ToInt32(entityobject.ToYear), Convert.ToInt32(entityobject.ToMonth))); } return ToJson(objAttendanceAccessCardComparisionReportRepository.GetAttendanceAccessCardEntryComparisionEmployeeId(entityobject)); } } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class LateEarlyReportService { constructor(private _http: Http) { } getemployee(url: any): Observable<any> { return this._http.get(url + 'GetEmployee') .map((response: Response) => <any>response.json()); } getallemployee(url: any): Observable<any> { return this._http.get(url + 'GetAllEmployee') .map((response: Response) => <any>response.json()); } getdepartment(url: any): Observable<any> { return this._http.get(url + 'GetDepartment') .map((response: Response) => <any>response.json()); } getcompany(url: any): Observable<any> { return this._http.get(url + 'GetCompany') .map((response: Response) => <any>response.json()); } getyear(url: any): Observable<any> { return this._http.get(url + 'GetYear') .map((response: Response) => <any>response.json()); } getemployeeidbydepartment(url: any, Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth: string, FromYear: string): Observable<any> { return this._http.get(url + 'GetIdByDepartment?Id=' + Id + '&Fromdate=' + Fromdate + '&Todate=' + Todate + "&MonthWise=" + MonthWise + "&FromMonth=" + FromMonth + "&FromYear=" + FromYear) .map((response: Response) => <any>response.json()); } getemployeeidbyemployee(url: any, Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth: string, FromYear: string): Observable<any> { return this._http.get(url + 'GetIdByEmployee?Id=' + Id + '&Fromdate=' + Fromdate + '&Todate=' + Todate + "&MonthWise=" + MonthWise + "&FromMonth=" + FromMonth + "&FromYear=" + FromYear) .map((response: Response) => <any>response.json()); } getemployeeidbycompany(url: any, Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth: string, FromYear: string): Observable<any> { return this._http.get(url + 'GetIdByCompany?Id=' + Id + '&Fromdate=' + Fromdate + '&Todate=' + Todate + "&MonthWise=" + MonthWise + "&FromMonth=" + FromMonth + "&FromYear=" + FromYear) .map((response: Response) => <any>response.json()); } getemployeeidbyselectall(url: any, Id: number, Fromdate: Date, Todate: Date, MonthWise: boolean, FromMonth: string, FromYear: string): Observable<any> { return this._http.get(url + 'GetIdBySelectAll?Id=' + Id + '&Fromdate=' + Fromdate + '&Todate=' + Todate + "&MonthWise=" + MonthWise + "&FromMonth=" + FromMonth + "&FromYear=" + FromYear) .map((response: Response) => <any>response.json()); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.EmployeeManagement { public class EmpInfoTabular : VISBaseEntity { //store procedure pass parameter public string EditEmployeeid { get; set; } public string Editmode { get; set; } public Int64 ExpRoleId { get; set; } public Int64 returnid { get; set; } public string mode { get; set; } public Int64 id { get; set; } public string Usertype { get; set; } public Int64 URoleId { get; set; } public Int64 RoleId { get; set; } public Int64 Parentid { get; set; } public Int64 PositionId { get; set; } public Int64 DepartmentID { get; set; } public Int64 PID { get; set; } public Int64 EID { get; set; } public Int64 WID { get; set; } public Int64 EducationID { get; set; } public Int64 TechnologyID { get; set; } public Int64 EmployeeID { get; set; } public string RoleName { get; set; } public string technologyName { get; set; } public string CompanyName { get; set; } public string Employee_Name { get; set; } public string Name { get; set; } public string positionName { get; set; } public string Department_name { get; set; } public string Remarks { get; set; } public Int64 Efficiency { get; set; } public string UserId { get; set; } public int SalaryRangeId { get; set; } public Int64 Salary { get; set; } public Int64 Sar { get; set; } public string salaryrangetitle { get; set; } public decimal Value { get; set; } public string NonWorkingDay { get; set; } public Int64 NWID { get; set; } public Int64 IntimeMondayToFridayHH { get; set; } public Int64 IntimeMondayToFridayMM { get; set; } public Int64 IntimeSaturdayHH { get; set; } public Int64 IntimeSaturdayMM { get; set; } public Int64 OutTimeMondayToFridayHH { get; set; } public Int64 OutTimeMondayToFridayMM { get; set; } public Int64 OutTimeSaturdayHH { get; set; } public Int64 OutTimeSaturdayMM { get; set; } public string strCode { get; set; } public string EmployeeName { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string Password { get; set; } public string Email { get; set; } public string Active { get; set; } public string UserType { get; set; } public string JoiningDate { get; set; } public string RelevingDate { get; set; } public string ResignedDate { get; set; } public string TotalCL { get; set; } public string TotalSl { get; set; } public bool AdditionalRights { get; set; } public bool ValidForLogin { get; set; } public string Employeecode { get; set; } public string ProbationTill { get; set; } public bool ActivityId { get; set; } public bool Gender { get; set; } public bool IsConfirmed { get; set; } public string JoiningSalary { get; set; } public string JoiningDesignation { get; set; } public string PhotographFileName { get; set; } public string SalaryAfterRevision { get; set; } public bool IsSLASigned { get; set; } public string ConfirmationDate { get; set; } public string AppraisalDate { get; set; } public bool IsAppraisalRequired { get; set; } public string SLAYear { get; set; } public string Technology { get; set; } public string OtherTechnology { get; set; } public string LineManagerID { get; set; } public string WorkingLocation { get; set; } public string WorkingLocationAddress { get; set; } public string CommunicationID { get; set; } public string OtherRemark { get; set; } public bool IsWebAccess { get; set; } public bool WorksheetThruWeb { get; set; } public bool IsSwitchUser { get; set; } public bool AllowScreenCapture { get; set; } public bool IsWorksheetFill { get; set; } public bool IsConfirmationLeave { get; set; } public string EmployeeGradeID { get; set; } public bool IsResigned { get; set; } public bool isMailAlert { get; set; } public bool IsAllowMouseMovement { get; set; } public string CreatedDateTime { get; set; } public bool IsMouseTracking { get; set; } public bool IsScreenCaptureRemarks { get; set; } public bool IsHost { get; set; } public bool IsHostForEmpMaster { get; set; } public bool IsProductivityTracker { get; set; } public bool WorkFromHome { get; set; } public bool IsWorksheetWeb { get; set; } public bool isInvisibleUser { get; set; } public string FatherName { get; set; } public string Birthdate { get; set; } public string Paddress { get; set; } public string Caddress { get; set; } public string Landlineno { get; set; } public string Mobileno { get; set; } public string Emergencyno { get; set; } public Int64 Age { get; set; } public string Bloodgroup { get; set; } public string Status { get; set; } public string Spouse { get; set; } public string ofchild { get; set; } public string Childname { get; set; } public DateTime AnniversaryDate { get; set; } public string Grandfathername { get; set; } public string Spousedob { get; set; } public string MotherName { get; set; } public string BrotherName { get; set; } public string SisterName { get; set; } public string FatherOccupation { get; set; } public string MotherOccupation { get; set; } public string BrotherOccupation { get; set; } public string SisterOccupation { get; set; } public string SpouseOccupation { get; set; } public string YearEducation { get; set; } public int Numberofchild { get; set; } public Int64 Education { get; set; } public Int64 Eduid { get; set; } public bool HighestEducation { get; set; } public string ClassDegree { get; set; } public string Schoolinstitute { get; set; } public string Medium { get; set; } public Int64 Passingyear { get; set; } public string Boarduniversity { get; set; } public Int64 Percentage { get; set; } public Int64 Expid { get; set; } public string Skills { get; set; } public string Totalexp { get; set; } public string Org { get; set; } public string Url { get; set; } public string Designation { get; set; } public string Joiningdate { get; set; } public string Relievingdate { get; set; } public string Reportingto { get; set; } public string Contactno { get; set; } public string Reason { get; set; } public Int64 Lastsalary { get; set; } public string Bankname { get; set; } public string Accountno { get; set; } public string PFAccountNo { get; set; } public string CurrentDesignation { get; set; } public bool ISPFApplicable { get; set; } public Int64 AdharNumber { get; set; } public Int64 UANNumber { get; set; } public string Intime { get; set; } public string Outitme { get; set; } public string Intimesat { get; set; } public string Outtimesat { get; set; } public Int64 Grace { get; set; } public Int64 Leaveapproveby { get; set; } public Int64 SatGrace { get; set; } public bool IsAlertRequired { get; set; } public int AccessCardId { get; set; } public string AttendancePolicy { get; set; } public DateTime strNow { get; set; } public DateTime strEnd { get; set; } public string strDay { get; set; } public int nwdId { get; set; } public DateTime dtFromNon { get; set; } public string strDuration { get; set; } public string Nwdday { get; set; } public string Panno { get; set; } public string Passportno { get; set; } public string Placeofissue { get; set; } public DateTime Issuedate { get; set; } public DateTime Expirydate { get; set; } public bool Isrelevingletter { get; set; } public bool Isexperienceletter { get; set; } public bool Issalaryslip { get; set; } public bool IsDegreeCertificate { get; set; } public bool IsMarkSheet { get; set; } public bool IsPassport { get; set; } public bool Isdrivinglicense { get; set; } public bool Ispancard { get; set; } public bool Iscv { get; set; } public bool Isother { get; set; } public string Other { get; set; } public string RelievingLetterFileName { get; set; } public string ExperienceLetterFileName { get; set; } public string LastSalarySlipFileName { get; set; } public string DegreeCertificateFileName { get; set; } public string LastMarksheetFileName { get; set; } public string PassportFileName { get; set; } public string DrivingLicenseFileName { get; set; } public string PANCardFileName { get; set; } public string CurriculamVitaeFilName { get; set; } public string OtherFileName { get; set; } public string OtherFileName0 { get; set; } public string OtherFileName1 { get; set; } public string Other0 { get; set; } public string Other1 { get; set; } public string HR_Remark { get; set; } public string Isother0 { get; set; } public string Isother1 { get; set; } public string Incrementdate { get; set; } public Int64 Designationchange { get; set; } public string Increment { get; set; } public Int64 Salarychange { get; set; } public bool Isfirst { get; set; } public Int64 Incrementid { get; set; } public Int64 CurrentSalaryId { get; set; } public string Verveemail { get; set; } public string Vervepassword { get; set; } public string Gmail { get; set; } public string Gmailpassword { get; set; } public string Yahoo { get; set; } public string Yahoopassword { get; set; } public string Skype { get; set; } public string Skypepassword { get; set; } public string Othersitename { get; set; } public string Otherid { get; set; } public string Otherpassword { get; set; } public string FromDate { get; set; } public string ToDate { get; set; } public string ProjectName { get; set; } public string ProJectManagerName { get; set; } public decimal Workinghrs { get; set; } public string TechnologyName { get; set; } public int TotalUser { get; set; } public string Duration { get; set; } public decimal AllocatedPer { get; set; } public decimal EstimatedHours { get; set; } public decimal PlannedHours { get; set; } public decimal ActualHours { get; set; } public int TeamSize { get; set; } public decimal AllocationWeight { get; set; } public decimal PlannedEff { get; set; } public decimal ActualEff { get; set; } public int Allocated { get; set; } public int Completed { get; set; } public int SignedOff { get; set; } public int Incomplete { get; set; } public int Extended { get; set; } public decimal AvgRating { get; set; } public string TaskName { get; set; } public string ModuleName { get; set; } public DateTime PlStartDate { get; set; } public DateTime PlEndDate { get; set; } public int PlHrs { get; set; } public DateTime AcStartDate { get; set; } public DateTime AcEndDate { get; set; } public string AcHrs { get; set; } public int PercentComplete { get; set; } public string StatusTask { get; set; } public bool IsLike { get; set; } public string Leavetype { get; set; } public float Balance { get; set; } public string Transactiontype { get; set; } public bool Isadjusted { get; set; } public float AdjustedValue { get; set; } public string Lastyear { get; set; } public float UUPLBalance { get; set; } public DateTime Leavedate { get; set; } public DateTime Createddate { get; set; } public string Leavename { get; set; } public bool Isaupl { get; set; } public Int64 LeaveTypeid { get; set; } public string LeaveTypeName { get; set; } public string CarryForwardSL { get; set; } public string CarryForwardCL { get; set; } public string OpeningSL { get; set; } public string OpeningCL { get; set; } public string AccuredUSL { get; set; } public string accuredUCL { get; set; } public string AccuredCSL { get; set; } public string AccuredCCL { get; set; } public string TotalSL { get; set; } public string AvailableSL { get; set; } public string AvailableCL { get; set; } public string AvailAUPLSL { get; set; } public string AvailAUPLCL { get; set; } public string AvailPLSL { get; set; } public string AvailPLCL { get; set; } public string AdjustmentSL { get; set; } public string AdjustmentCL { get; set; } public string ExpireLeaveSL { get; set; } public string ExpireLeaveCL { get; set; } public string BalanceCurSL { get; set; } public string BalanceCurCL { get; set; } public string ConfirmationDateJoin { get; set; } public string joingdate { get; set; } public string SalaryAfter { get; set; } public string SLASigned { get; set; } public string experiencesummary { get; set; } public string skills { get; set; } public string ProjectHandled { get; set; } public string RelevanceExp { get; set; } public int expyear { get; set; } public int expmonth { get; set; } public string relevanceExpYear { get; set; } public string relevanceExpMonth { get; set; } public string hdnProjectsToSave { get; set; } public string Type { get; set; } public string AccountNumber { get; set; } public string Output { get; set; } //skill public Int64 lookupSkilId { get; set; } public int SkillID { get; set; } public string SkillName{get;set;} } public static class EmpInfoTabularConstants { public const string const_Table_EmployeeMaster = "Employee_Master"; //store procedure pass parameter cons public const string const_Field_EditEmployeeid = "EditEmployeeid"; public const string const_Field_Editmode = "Editmode"; public const string const_Field_ExpRoleId = "ExpRoleId"; public const string const_Field_returnid = "returnid"; public const string const_Field_mode = "mode"; public const string const_Field_UserId = "UserId"; public const string const_Field_Usertype = "Usertype"; public const string const_Field_RoleId = "RoleId"; public const string const_Field_Efficiency = "Efficiency"; public const string const_Field_URoleId = "URoleId"; public const string const_Field_RoleName = "RoleName"; public const string const_Field_PositionId = "PositionId"; public const string const_Field_DepartmentID = "DepartmentID"; public const string const_Field_PID = "PID"; public const string const_Field_EID = "EID"; public const string const_Field_WID = "WID"; public const string const_Field_EmployeeID = "EmployeeID"; public const string const_Field_TechnologyID = "TechnologyID"; public const string const_Field_technologyName = "technologyName"; public const string const_Field_CompanyName = "CompanyName"; public const string const_Field_Employee_Name = "Employee_Name"; public const string const_Field_Name = "Name"; public const string const_Field_positionName = "positionName"; public const string const_Field_Department_name = "Department_name"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_SalaryRangeId = "SalaryRangeId"; public const string const_Field_Salary = "Salary"; public const string const_Field_Sar = "Sar"; public const string const_Field_salaryrangetitle = "salaryrangetitle"; public const string const_Field_Value = "Value"; public const string const_Field_Parentid = "Parentid"; public const string const_Field_NonWorkingDay = "NonWorkingDay"; public const string const_Field_IsWorksheetWeb = "IsWorksheetWeb"; public const string const_Field_NWID = "NWID"; public const string const_Field_OutTimeMondayToFridayHH = "OutTimeMondayToFridayHH"; public const string const_Field_IntimeMondayToFridayMM = "IntimeMondayToFridayMM"; public const string const_Field_IntimeSaturdayHH = "IntimeSaturdayHH"; public const string const_Field_IntimeSaturdayMM = "IntimeSaturdayMM"; public const string const_Field_IntimeMondayToFridayHH = "IntimeMondayToFridayHH"; public const string const_Field_OutTimeMondayToFridayMM = "OutTimeMondayToFridayMM"; public const string const_Field_OutTimeSaturdayHH = "OutTimeSaturdayHH"; public const string const_Field_OutTimeSaturdayMM = "OutTimeSaturdayMM"; public const string const_Field_strCode = "strCode"; public const string const_Field_EmployeeName = "EmployeeName"; public const string const_Field_FirstName = "FirstName "; public const string const_Field_MiddleName = "MiddleName"; public const string const_Field_LastName = "LastName"; public const string const_Field_Password = "<PASSWORD>"; public const string const_Field_Email = "Email"; public const string const_Field_Active = "Active"; public const string const_Field_UserType = "UserType"; public const string const_Field_JoiningDate = "JoiningDate"; public const string const_Field_RelevingDate = "RelevingDate"; public const string const_Field_ResignedDate = "ResignedDate"; public const string const_Field_TotalCL = "TotalCL"; public const string const_Field_TotalSL = "TotalSL"; public const string const_Field_AdditionalRights = "AdditionalRights"; public const string const_Field_ValidForLogin = "ValidForLogin"; public const string const_Field_Employeecode = "Employeecode"; public const string const_Field_ProbationTill = "ProbationTill"; public const string const_Field_ActivityId = "ActivityId"; public const string const_Field_Gender = "Gender"; public const string const_Field_IsConfirmed = "IsConfirmed "; public const string const_Field_JoiningSalary = "JoiningSalary"; public const string const_Field_JoiningDesignation = "JoiningDesignation"; public const string const_Field_PhotographFileName = "PhotographFileName "; public const string const_Field_SalaryAfterRevision = "SalaryAfterRevision "; public const string const_Field_IsSLASigned = "IsSLASigned"; public const string const_Field_ConfirmationDate = "ConfirmationDate"; public const string const_Field_AppraisalDate = "AppraisalDate"; public const string const_Field_IsAppraisalRequired = "IsAppraisalRequired "; public const string const_Field_SLAYear = "SLAYear"; public const string const_Field_Technology = "Technology"; public const string const_Field_OtherTechnology = "OtherTechnology"; public const string const_Field_LineManagerID = "LineManagerID"; public const string const_Field_WorkingLocation = "WorkingLocation"; public const string const_Field_WorkingLocationAddress = "WorkingLocationAddress"; public const string const_Field_CommunicationID = "CommunicationID"; public const string const_Field_OtherRemark = "OtherRemark"; public const string const_Field_IsWebAccess = "IsWebAccess "; public const string const_Field_WorksheetThruWeb = "WorksheetThruWeb"; public const string const_Field_IsSwitchUser = "IsSwitchUser"; public const string const_Field_AllowScreenCapture = "AllowScreenCapture"; public const string const_Field_IsWorksheetFill = "IsWorksheetFill"; public const string const_Field_IsConfirmationLeave = "IsConfirmationLeave"; public const string const_Field_EmployeeGradeID = "EmployeeGradeID "; public const string const_Field_IsResigned = "IsResigned "; public const string const_Field_isMailAlert = "isMailAlert"; public const string const_Field_IsAllowMouseMovement = "IsAllowMouseMovement"; public const string const_Field_CreatedDateTime = "CreatedDateTime"; public const string const_Field_IsMouseTracking = "IsMouseTracking"; public const string const_Field_IsScreenCaptureRemar = "IsScreenCaptureRemarks"; public const string const_Field_IsHost = "IsHost"; public const string const_Field_IsHostForEmpMaster = "IsHostForEmpMaster"; public const string const_Field_IsProductivityTracker = "IsProductivityTracker"; public const string const_Field_WorkFromHome = "WorkFromHome"; public const string const_Field_isInvisibleUser = "isInvisibleUser"; public const string const_Field_Numberofchild = "Numberofchild"; public const string const_Field_Education = "Education"; public const string const_Field_FatherName = "FatherName"; public const string const_Field_Birthdate = "Birthdate"; public const string const_Field_Paddress = "Paddress"; public const string const_Field_Caddress = "Caddress"; public const string const_Field_Landlineno = "Landlineno"; public const string const_Field_Mobileno = "Mobileno"; public const string const_Field_Emergencyno = "Emergencyno"; public const string const_Field_Age = "Age"; public const string const_Field_Bloodgroup = "Bloodgroup"; public const string const_Field_Status = "Status"; public const string const_Field_Spouse = "Spouse"; public const string const_Field_ofchild = "ofchild"; public const string const_Field_Childname = "Childname"; public const string const_Field_AnniversaryDate = "AnniversaryDate"; public const string const_Field_Grandfathername = "Grandfathername"; public const string const_Field_Spousedob = "Spousedob"; public const string const_Field_MotherName = "MotherName"; public const string const_Field_BrotherName = "BrotherName"; public const string const_Field_SisterName = "SisterName"; public const string const_Field_FatherOccupation = "FatherOccupation"; public const string const_Field_MotherOccupation = "MotherOccupation"; public const string const_Field_BrotherOccupation = "BrotherOccupation"; public const string const_Field_SisterOccupation = "SisterOccupation"; public const string const_Field_SpouseOccupation = "SpouseOccupation"; public const string const_Field_YearEducation = "YearEducation"; public const string const_Field_Eduid = "Eduid"; public const string const_Field_HighestEducation = "HighestEducation"; public const string const_Field_ClassDegree = "ClassDegree"; public const string const_Field_Schoolinstitute = "Schoolinstitute"; public const string const_Field_Medium = "Medium"; public const string const_Field_Passingyear = "Passingyear"; public const string const_Field_Boarduniversity = "Boarduniversity"; public const string const_Field_Percentage = "Percentage"; public const string const_Field_Expid = "Expid"; public const string const_Field_Skills = "Skills"; public const string const_Field_Totalexp = "Totalexp"; public const string const_Field_Org = "Org"; public const string const_Field_Url = "Url"; public const string const_Field_Designation = "Designation"; public const string const_Field_Joiningdate = "Joiningdate"; public const string const_Field_Relievingdate = "Relievingdate"; public const string const_Field_Reportingto = "Reportingto"; public const string const_Field_Contactno = "Contactno"; public const string const_Field_Reason = "Reason"; public const string const_Field_Lastsalary = "Lastsalary"; public const string const_Field_Bankname = "Bankname"; public const string const_Field_Accountno = "Accountno"; public const string const_Field_AccountNumber = "AccountNumber"; public const string const_Field_PFAccountNo = "PFAccountNo"; public const string const_Field_CurrentDesignation = "CurrentDesignation"; public const string const_Field_ISPFApplicable = "ISPFApplicable"; public const string const_Field_AdharNumber = "AdharNumber"; public const string const_Field_UANNumber = "UANNumber"; public const string const_Field_Intime = "Intime"; public const string const_Field_Outitme = "Outitme"; public const string const_Field_Intimesat = "Intimesat"; public const string const_Field_Outtimesat = "Outtimesat"; public const string const_Field_Grace = "Grace"; public const string const_Field_Leaveapproveby = "Leaveapproveby"; public const string const_Field_SatGrace = "SatGrace"; public const string const_Field_IsAlertRequired = "IsAlertRequired"; public const string const_Field_AccessCardId = "AccessCardId"; public const string const_Field_AttendancePolicy = "AttendancePolicy"; public const string const_Field_strNow = "strNow "; public const string const_Field_strEnd = "strEnd "; public const string const_Field_strDay = "strDay "; public const string const_Field_nwdId = "nwdId"; public const string const_Field_dtFromNon = "dtFromNon"; public const string const_Field_strDuration = "strDuration"; public const string const_Field_Panno = "Panno"; public const string const_Field_Passportno = "Passportno"; public const string const_Field_Placeofissue = "Placeofissue"; public const string const_Field_Issuedate = "Issuedate"; public const string const_Field_Expirydate = "Expirydate"; public const string const_Field_Isrelevingletter = "Isrelevingletter"; public const string const_Field_Isexperienceletter = "Isexperienceletter"; public const string const_Field_Issalaryslip = "Issalaryslip"; public const string const_Field_IsDegreeCertificate = "IsDegreeCertificate"; public const string const_Field_IsMarkSheet = "IsMarkSheet"; public const string const_Field_IsPassport = "IsPassport "; public const string const_Field_Isdrivinglicense = "Isdrivinglicense"; public const string const_Field_Ispancard = "Ispancard"; public const string const_Field_Iscv = "Iscv"; public const string const_Field_Isother = "Isother"; public const string const_Field_Other = "Other"; public const string const_Field_RelievingLetterFileName = "RelievingLetterFileName"; public const string const_Field_ExperienceLetterFileName = "ExperienceLetterFileName "; public const string const_Field_LastSalarySlipFileName = "LastSalarySlipFileName"; public const string const_Field_DegreeCertificateFileName = "DegreeCertificateFileName"; public const string const_Field_LastMarksheetFileName = "LastMarksheetFileName"; public const string const_Field_PassportFileName = "PassportFileName"; public const string const_Field_DrivingLicenseFileName = "DrivingLicenseFileName"; public const string const_Field_PANCardFileName = "PANCardFileName"; public const string const_Field_CurriculamVitaeFilName = "CurriculamVitaeFilName"; public const string const_Field_OtherFileName = "OtherFileName"; public const string const_Field_OtherFileName0 = "OtherFileName0"; public const string const_Field_OtherFileName1 = "OtherFileName1"; public const string const_Field_Other0 = "Other0"; public const string const_Field_Other1 = "Other1"; public const string const_Field_HR_Remark = "HR_Remark"; public const string const_Field_Isother0 = "Isother0"; public const string const_Field_Isother1 = " Isother1"; public const string const_Field_Incrementdate = "Incrementdate"; public const string const_Field_Designationchange = "Designationchange"; public const string const_Field_Increment = "Increment"; public const string const_Field_Salarychange = "Salarychange"; public const string const_Field_Isfirst = "Isfirst"; public const string const_Field_Incrementid = "Incrementid"; public const string const_Field_CurrentSalaryId = "CurrentSalaryId"; public const string const_Field_Verveemail = "Verveemail"; public const string const_Field_Vervepassword = "<PASSWORD> "; public const string const_Field_Gmail = "Gmail"; public const string const_Field_Gmailpassword = "<PASSWORD>"; public const string const_Field_Yahoo = "Yahoo"; public const string const_Field_Yahoopassword = "<PASSWORD>"; public const string const_Field_Skype = "Skype"; public const string const_Field_Skypepassword = "<PASSWORD>"; public const string const_Field_Othersitename = "Othersitename"; public const string const_Field_Otherid = "Otherid"; public const string const_Field_Otherpassword = "<PASSWORD>"; public const string const_Field_FromDate = "FromDate"; public const string const_Field_ToDate = "ToDate"; public const string const_Field_Leavetype = "Leavetype"; public const string const_Field_Balance = "Balance"; public const string const_Field_Transactiontype = "Transactiontype"; public const string const_Field_Isadjusted = "Isadjusted"; public const string const_Field_AdjustedValue = "AdjustedValue"; public const string const_Field_Lastyear = "Lastyear"; public const string const_Field_UUPLBalance = "UUPLBalance"; public const string const_Field_Leavedate = "Leavedate"; public const string const_Field_Createddate = "Createddate"; public const string const_Field_Leavename = "Leavename"; public const string const_Field_Isaupl = "Isaupl"; public const string const_Field_experiencesummary = "experiencesummary"; public const string const_Field_skills = "skills"; public const string const_Field_ProjectHandled = "ProjectHandled"; public const string const_Field_RelevanceExp = "RelevanceExp"; public const string const_Field_skillgroupid = "skillgroupid"; public const string const_Field_SkillID = "SkillID"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_procEmployeedropdownbind = "procEmployeedropdownbind"; public const string const_procEmployeeDropDown = "procEmployeeDropDown"; public const string const_procEmployeeEducation = "procEmployeeEducation"; public const string const_procTechnologyListboxbind = "procTechnologyListboxbind"; public const string const_procRoleBind = "procRoleBind"; public const string const_procExperienceRoleAdd = "procExperienceRoleAdd"; public const string const_procSalaryRange = "procSalaryRange"; public const string const_procSalaryBreakUpSalaryRangeWise = "procSalaryBreakUpSalaryRangeWise"; public const string const_procEmployeeListAttandancetabBind = "procEmployeeListAttandancetabBind"; public const string const_procNonWorking = "procNonWorking"; public const string const_procIntimeSelected = "procIntimeSelected"; public const string const_procGetEmployeeCodeComapanyWise = "procGetEmployeeCodeComapanyWise"; public const string const_Field_procNewEmployeeAdd = "procNewEmployeeAdd"; public const string const_Field_procPersonalInformation_Add = "procPersonalInformation_Add"; public const string const_Field_procGetEducationYear = "procGetEducationYear"; public const string const_Field_ProcEducation = "ProcEducation"; public const string const_Field_procEducationAdd = "procEducationAdd"; public const string const_Field_procExperience_Add = "procExperience_Add"; public const string const_Field_procCheckExperience = "procCheckExperience"; public const string const_Field_procCurrentSalary_Add = "procCurrentSalary_Add"; public const string const_Field_procManagesalary = "procManagesalary"; public const string const_Field_procAttendance_Add = "procAttendance_Add"; public const string const_Field_procNowworkingcheck = "procNowworkingcheck"; public const string const_Field_procFunctioncallNwd = "procFunctioncallNwd"; public const string const_Field_procJoiningDocument_Add = "procJoiningDocument_Add"; public const string const_Field_procIncrementHistoryMaster_Add = "procIncrementHistoryMaster_Add"; public const string const_Field_procIncrementtype = "procIncrementtype"; public const string const_Field_procOfficialDetail_Add = "procOfficialDetail_Add"; public const string const_Field_procprojectListGet = "procprojectListGet"; public const string const_Field_procOfferdeatils = "procOfferdeatils"; public const string const_Field_procEmployeeMasterGet = "procEmployeeMasterGet"; public const string const_Field_procPendingTask = "procPendingTask"; public const string const_Field_procEmployeeFeedback = "procEmployeeFeedback"; public const string const_Field_procAdjustedLeaveAdd = "procAdjustedLeaveAdd"; public const string const_Field_procLeaveDeatilMaster = "procLeaveDeatilMaster"; public const string const_Field_procExperienceProjectGet = "procExperienceProjectGet"; public const string const_Field_procSalarySAccountNo = "procSalarySAccountNo"; public const string const_Field_procAttencessdeatilcheck = "procAttencessdeatilcheck"; public const string const_Field_procGetMySkill = "procGetMySkill"; public const string const_Field_procSkillAddtab = "procSkillAddtab"; } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class AttendanceReportService { constructor(private _http: Http) { } GetDepartment(url: string): Observable<any> { return this._http.get(url + 'GetDepartment') .map((response: Response) => <any>response.json()); } GetEmployee(url: string): Observable<any> { return this._http.get(url + 'GetEmployee') .map((response: Response) => <any>response.json()); } GetAllEmployee(url: string): Observable<any> { return this._http.get(url + 'GetAllEmployee') .map((response: Response) => <any>response.json()); } GetCompany(url: string): Observable<any> { return this._http.get(url + 'GetCompany') .map((response: Response) => <any>response.json()); } GetLineManager(url: string): Observable<any> { return this._http.get(url + 'GetLineManager') .map((response: Response) => <any>response.json()); } //GetBindAttendanceData(url: string, Id: number, strDate: string, ToDate: string, name: string, DRPData: number, rdbDate: string, Rdbmonth: string, month: number, year: number, cbDeduction: boolean, cbMissingEntry:boolean): Observable<any> { // return this._http.get(url + 'GetBindAttendanceData?Id=' + Id + '&strDate=' + strDate + '&ToDate=' + ToDate + '&name=' + name + '&DRPData=' + DRPData + '&rdbDate=' + rdbDate + '&Rdbmonth=' + Rdbmonth + '&month=' + month + '&year=' + year + '&cbDeduction=' + cbDeduction + '&cbMissingEntry='+ cbMissingEntry) // .map((response: Response) => <any>response.json()); //} GetBindAttendanceData(url: string, Id: number, strDate: string, ToDate: string, name: string, DRPData: number, rdbDate: string, Rdbmonth: string, month: number, year: number): Observable<any> { return this._http.get(url + 'GetBindAttendanceData?Id=' + Id + '&strDate=' + strDate + '&ToDate=' + ToDate + '&name=' + name + '&DRPData=' + DRPData + '&rdbDate=' + rdbDate + '&Rdbmonth=' + Rdbmonth + '&month=' + month + '&year=' + year) .map((response: Response) => <any>response.json()); } GetMissingEntry(url: string, fromdate: string, todate: string, Employeeids:string): Observable<any> { return this._http.get(url + 'GetMissingEntry?fromdate=' + fromdate + '&todate=' + todate + '&Employeeids=' + Employeeids) .map((response: Response) => <any>response.json()); } SelectDepartment(url: string,Department:string): Observable<any> { return this._http.get(url + 'SelectDepartment?Department=' + Department) .map((response: Response) => <any>response.json()); } SelectCompany(url: string, Company: string): Observable<any> { return this._http.get(url + 'SelectCompany?Company=' + Company) .map((response: Response) => <any>response.json()); } SelectLineManager(url: string, LineManager: string): Observable<any> { return this._http.get(url + 'SelectLineManager?LineManager=' + LineManager) .map((response: Response) => <any>response.json()); } GetDepartmentEmployee(url: string, Id: number): Observable<any> { return this._http.get(url + 'GetDepartmentEmployee?Id=' + Id) .map((response: Response) => <any>response.json()); } GetDeductionDetails(url: string, fromdate: string, todate: string, Employeeids:string): Observable<any> { return this._http.get(url + 'GetDeductionDetails?fromdate=' + fromdate + '&todate=' + todate + '&Employeeids=' + Employeeids) .map((response: Response) => <any>response.json()); } GetYear(url: string): Observable<any> { return this._http.get(url + 'GetYear') .map((response: Response) => <any>response.json()); } GetCheckedData(url: string, name: string, DRPData: string): Observable<any> { return this._http.get(url + 'GetCheckedData?name=' + name + '&DRPData=' + DRPData) .map((response: Response) => <any>response.json()); } //----Attendance Approve Punch In AttendanceApproval(url: string, InId: number, EntryType: number, Remarks: string, Date: string, Time: string, Grace: number, ActualHrs: string): Observable<any> { return this._http.get(url + 'AttendanceApproval?InId=' + InId + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Date=' + Date + '&Time=' + Time + '&Grace=' + Grace + '&ActualHrs=' + ActualHrs) .map((response: Response) => <any>response.json()); } GetDailyEntryTime(url: string, Employee_Id: number, Date: string): Observable<any> { return this._http.get(url + 'GetDailyEntryTime?Employee_Id=' + Employee_Id + '&Date=' + Date) .map((response: Response) => <any>response.json()); } AddEmployeeAttendance(url: string, Id: number, Employee_Id: number, EntryType: number, HODRemarks: string, Temp: string, strDate: string, Time: string, Grace: number): Observable<any> { return this._http.get(url + 'AttendanceApproveAdd?Id=' + Id + '&Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&HODRemarks=' + HODRemarks + '&Temp=' + Temp + '&strDate=' + strDate + '&Time=' + Time + '&Grace=' + Grace) .map((response: Response) => <any>response.json()) } AttendanceRejectPunchIn(url: string, Employee_Id: number, EntryType: number, Date: string, RemarksIn: string, InId: number): Observable<any> { return this._http.get(url + 'AttendanceRejectPunchIn?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Date=' + Date + '&RemarksIn=' + RemarksIn + '&InId=' + InId) .map((response: Response) => <any>response.json()); } ApproveAttendanceOkIn(url: string, InId: number, Remarks: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceOkIn?InId=' + InId + '&Remarks=' + Remarks) .map((response: Response) => <any>response.json()); } //----Attendance Approve Punch Out ApproveAttendancePunchOut(url: string, OutId: number, EntryType: number, Remarks: string, Date: string, Time: string, Grace: number, ActualHrs: string): Observable<any> { return this._http.get(url + 'ApproveAttendancePunchOut?OutId=' + OutId + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Date=' + Date + '&Time=' + Time + '&Grace=' + Grace + '&ActualHrs=' + ActualHrs) .map((response: Response) => <any>response.json()); } AddEmployeeAttendancePunchOut(url: string, Employee_Id: number, EntryType: number, HODRemarks: string, Temp: string, strDate: string, Time: string, Grace: number): Observable<any> { return this._http.get(url + 'AddEmployeeAttendancePunchOut?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&HODRemarks=' + HODRemarks + '&Temp=' + Temp + '&strDate=' + strDate + '&Time=' + Time + '&Grace=' + Grace) .map((response: Response) => <any>response.json()) } AttendanceRejectPunchOut(url: string, Employee_Id: number, EntryType: number, Date: string, HODRemarks: string, OutId: number): Observable<any> { return this._http.get(url + 'AttendanceRejectPunchOut?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks + '&OutId=' + OutId) .map((response: Response) => <any>response.json()); } ApproveAttendanceOkPunchOut(url: string, OutId: number, Remarks: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceOkPunchOut?OutId=' + OutId + '&Remarks=' + Remarks) .map((response: Response) => <any>response.json()); } //----Attendance Approve Lunch Out ApproveAttendanceLunchOut(url: string, LunchOutId: number, Remarks: string, Time: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceLunchOut?LunchOutId=' + LunchOutId + '&Remarks=' + Remarks + '&Time=' + Time) .map((response: Response) => <any>response.json()); } AddEmployeeAttendanceLunchOut(url: string, Employee_Id: number, EntryType: number, Remarks: string, Temp: string, Date: string, Time: string): Observable<any> { return this._http.get(url + 'AddEmployeeAttendanceLunchOut?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Temp=' + Temp + '&Date=' + Date + '&Time=' + Time) .map((response: Response) => <any>response.json()); } AttendanceRejectLunchOut(url: string, LunchOutId: number, Employee_Id: number, EntryType: number, Date: string, HODRemarks: string): Observable<any> { return this._http.get(url + 'AttendanceRejectLunchOut?LunchOutId=' + LunchOutId + '&Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks) .map((response: Response) => <any>response.json()); } ApproveAttendanceOkLunchOut(url: string, LunchOutId: number, Remarks: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceOkLunchOut?LunchOutId=' + LunchOutId + '&Remarks=' + Remarks) .map((response: Response) => <any>response.json()); } //----Attendance Approve Lunch In ApproveAttendanceLunchIn(url: string, LunchInId: number, Remarks: string, Time: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceLunchIn?LunchInId=' + LunchInId +'&Remarks=' + Remarks +'&Time=' + Time) .map((response: Response) => <any>response.json()); } AddEmployeeAttendanceLunchIn(url: string, Employee_Id: number, EntryType: number, Remarks: string, Temp: string, Date: string, Time: string): Observable<any> { return this._http.get(url + 'AddEmployeeAttendanceLunchIn?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Temp=' + Temp + '&Date=' + Date + '&Time=' + Time) .map((response: Response) => <any>response.json()); } AttendanceRejectLunchIn(url: string, Employee_Id: number, LunchInId: number,EntryType: number, Date: string, HODRemarks: string): Observable<any> { return this._http.get(url + 'AttendanceRejectLunchIn?Employee_Id=' + Employee_Id + '&LunchInId=' + LunchInId + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks) .map((response: Response) => <any>response.json()); } ApproveAttendanceOkLunchIn(url: string, LunchInId: number, Remarks: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceOkLunchIn?LunchInId=' + LunchInId + '&Remarks=' + Remarks) .map((response: Response) => <any>response.json()); } //----Attendance Approve Work In ApproveAttendanceOther(url: string, OtherId: number, Remarks: string, Time: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceOther?OtherId=' + OtherId + '&Remarks=' + Remarks + '&Time=' + Time) .map((response: Response) => <any>response.json()); } GetEmployeeIsNotHostEmployee(url: string, Employee_Id: number): Observable<any> { return this._http.get(url + 'GetEmployeeIsNotHostEmployee?Employee_Id=' + Employee_Id) .map((response: Response) => <any>response.json()); } AddEmployeeAttendanceOtherwork(url: string, Employee_Id: number, EntryType: number, HODRemarks: string, Temp: string, Date: string, Time: string): Observable<any> { return this._http.get(url + 'AddEmployeeAttendanceOtherwork?Employee_Id=' + Employee_Id + '&EntryType=' + Employee_Id + '&HODRemarks=' + HODRemarks + '&Temp=' + Temp + '&Date=' + Date + '&Time=' + Time) .map((response: Response) => <any>response.json()); } AttendanceRejectOtherWork(url: string, Employee_Id: number, OtherId: number, EntryType: number, Date: string, HODRemarks: string): Observable<any> { return this._http.get(url + 'AttendanceRejectOtherWork?Employee_Id=' + Employee_Id + '&OtherId=' + OtherId + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks) .map((response: Response) => <any>response.json()); } ApproveAttendanceOkOtherWorkIn(url: string, OtherId: number, Remarks: string): Observable<any> { return this._http.get(url + 'ApproveAttendanceOkOtherWorkIn?OtherId=' + OtherId + '&Remarks=' + Remarks) .map((response: Response) => <any>response.json()); } get(url: string): Observable<any> { return this._http.get(url) .map((response: Response) => <any>response.json()); } put(url: string, id: number, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity/' + id, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } delete(url: string, id: number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { PositionService } from '../../../service/Masters/VacancyRelated/Position.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IPosition } from '../../../Model/Masters/VacancyRelated/Position'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component ({ providers: [PositionService], templateUrl: 'app/Components/Masters/VacancyRelated/Position.component.html' }) export class PositionComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; positions: IPosition[]; position: IPosition; msg: string; indLoading: boolean = false; PositionFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; PositionFilter: string; isDesc: boolean = false; column: any = 'PositionName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; constructor(private fb: FormBuilder, private _PositionService: PositionService, private pagerService: PagerService) { } ngOnInit(): void { this.PositionFrm = this.fb.group ({ CompanyId: [''], Id: [''], PositionName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], Remarks: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], EntityMessage: [''], IsActive: [''] }); this.LoadPosition(); } PositionFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.PositionFilter = value; } PositionSort(property: any) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; }; LoadPosition(): void { this.indLoading = true; this._PositionService.get(Global.BASE_POSITION_ENDPOINT) .subscribe(positions => { this.positions = positions; this.indLoading = false; // set items to json response // initialize to page 1 this.JumpOnPage(1); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } //,error => this.msg = <any>error ); } AddPosition() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Position"; this.modalBtnTitle = "Add"; this.PositionFrm.reset(); this.modal.open(); } EditPosition(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Position"; this.modalBtnTitle = "Update"; this.position = this.positions.filter(x => x.Id == id)[0]; this.PositionFrm.setValue(this.position); this.modal.open(); } DeletePosition(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.position = this.positions.filter(x => x.Id == id)[0]; this.PositionFrm.setValue(this.PositionFrm); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.PositionFrm.enable() : this.PositionFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.positions); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._PositionService.post(Global.BASE_POSITION_ENDPOINT, formData._value).subscribe( data => { if (data == "Success") //Success { this.msg = "Position added successfully."; this.LoadPosition(); } else { this.msg = "Error has occurred while adding new Position!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.update: this._PositionService.put(Global.BASE_POSITION_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data == "Success") //Success { this.msg = "Position modified successfully."; this.LoadPosition(); } else { this.msg = "Error has occurred while modifying existing Position!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.delete: this._PositionService.delete(Global.BASE_POSITION_ENDPOINT, formData._value.Id).subscribe( data => { if (data == "Success") //Success { this.msg = "Position status changed successfully."; this.LoadPosition(); } else { this.msg = "Error has occurred while changing status of existing Position!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router } from '@angular/router'; import { ProductivityTrackerReportService } from '../../../Service/Report/Attendance/ProductivityTrackerReport.service'; import { IDepartment, IEmployee, ILineManager, ILookup, IProductivityTracker } from '../../../Model/Report/Attendance/ProductivityTracker'; @Component ({ providers: [ProductivityTrackerReportService], templateUrl: 'app/Components/Report/Attendance/ProductivityTrackerReport.component.html' }) export class ProductivityTrackerReportcomponent implements OnInit { pager: any = {}; pagedItems: any[]; CurrentRecordsPerPage: number = 10; InLoading: boolean; msg: string; UserType: string; InActiveEmp: boolean; Department: IDepartment[]; Employees: IEmployee[]; LineManager: ILineManager[]; Lookup: ILookup[]; ProductivityTracker: IProductivityTracker[]; FromDate: string; ToDate: string; Mode: string; OutIds: string; constructor(private fb: FormBuilder, private router: Router, private pagerService: PagerService, private _ProductivityTrackerReportService: ProductivityTrackerReportService) { } ngOnInit() { $("#radEmployee").prop("checked", true); $("#radDate").prop("checked", true); $("#radAll").prop("checked", true); $("#raddetail").prop("checked", true); $("#radsortname").prop("checked", true); this.HideLMDPOA(); this.showfromtoDate(); this.TypeAll(); this.ViewDetailed(); this.FillEmployee(); this.FillDepartment(); this.FillLineManager(); this.FillLookup(); this.FillOverall(); this.FillYear(); } HideLMDPOA(): void { if ($("#radEmployee").prop("checked", true)) { $('#emp').show(); $('#empAll').show(); $('#LineManager').hide(); $('#Department').hide(); } } HideDPOAEM(): void { $('#emp').hide(); $('#empAll').hide(); $('#Department').hide(); $('#LineManager').show(); } HideOAEMLM(): void { $('#LineManager').hide(); $('#emp').hide(); $('#empAll').hide(); $('#Department').show(); } HideEMLMDP(): void { $('#Department').hide(); $('#LineManager').hide(); $('#emp').hide(); $('#empAll').hide(); } showfromtoDate(): void { if ($("#radDate").prop("checked", true)) { $('#date').show(); $('#month').hide(); //var Mon = new Date().getMonth(); //var Year = new Date().getFullYear(); //this.FromDate = new Date(Year, Mon, 1).toString(); //this.ToDate = new Date(Year, Mon + 1,0).toString(); } } ShowMonthYear(): void { $('#date').hide(); $('#month').show(); } ShowPreviousWorkday(): void { if ($("#radPrevious").prop("checked")) { $('#date').show(); $('#month').hide(); //var day = new Date().getDate() - 1; //var Mon = new Date().getMonth(); //var Year = new Date().getFullYear(); //this.FromDate = new Date(Year, Mon, day).toString(); //this.ToDate = new Date(Year, Mon, day).toString(); } } ShowToday(): void { if ($("#radToday").prop("checked", true)) { $('#date').show(); $('#month').hide(); //this.FromDate = new Date().toString(); //this.ToDate = new Date().toString(); } } TypeAll(): void { if ($("#radAll").prop("checked", true)) { $("#chkall").prop("checked", true); $("#chkall").prop("disabled", true); $("#chkouttype").prop("disabled", true); //$('#chkall').prop('disabled', true); //$('#chklunch').prop('disabled', true); //$('#chkother').prop('disabled', true); //$('#chkmeeting').prop('disabled', true); //$('#chkofficial').prop('disabled', true); //$('#chkidle').prop('disabled', true); } } TypeOther(): void { $("#chkall").prop("checked", false); $("#chkall").prop("disabled", true); $("#chkouttype").prop("disabled", false); //$("#chkall").prop("checked", false); //$('#chkall').prop('disabled', true); //$('#chklunch').prop('disabled', false); //$('#chkother').prop('disabled', false); //$('#chkmeeting').prop('disabled', false); //$('#chkofficial').prop('disabled', false); //$('#chkidle').prop('disabled', false); } ViewDetailed(): void { if ($("#raddetail").prop("checked", true)) { $('#radnoneview').empty(); $('#radnameview').empty(); $('#radtypeview').empty(); $('#radDateview').empty(); $('#viewDetails').hide(); } } ViewConsolidated(): void { if ($("#radconsolidated").prop("checked", true)) { $('#viewDetails').show(); $("#radnoneview").prop("checked", true); } } //-------------------- Change Event---------------------// AllEmployee(event) { if ($("#chkInActive").prop("checked", true)) { this._ProductivityTrackerReportService.FillAllEmployees(Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, true) .subscribe(data => { this.Employees = data; this.InLoading = false; }, error => { this.msg = error; }); } } //-------------------- Change Event---------------------// FillEmployee(): void { if (this.InActiveEmp == null) { this.InActiveEmp = true; } this.UserType = "admin"; if (this.UserType.toLowerCase() == "gh" || this.UserType.toLowerCase() == "admin" || this.UserType.toLowerCase() == "hr" || this.UserType.toLowerCase() == "payroll") { this._ProductivityTrackerReportService.FillEmployee(Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "allemp", this.InActiveEmp) .subscribe(data => { this.Employees = data; this.InLoading = false; }, error => { this.msg = error; }); } else if (this.UserType.toLowerCase() == "bh" || this.UserType.toLowerCase() == "dh") { this._ProductivityTrackerReportService.FillEmployee(Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "self", true) .subscribe(data => { this.Employees = data; this.InLoading = false; }, error => { this.msg = error; }); } else if (this.UserType.toLowerCase() == "PMRole") // else if (Session["PMRole"] != null) Use Session in this condition... { this._ProductivityTrackerReportService.FillEmployee(Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "pmemp", true) .subscribe(data => { this.Employees = data; this.InLoading = false; }, error => { this.msg = error; }); } else { this._ProductivityTrackerReportService.FillEmployee(Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "self", true) .subscribe(data => { this.Employees = data; this.InLoading = false; }, error => { this.msg = error; }); } } FillLineManager(): void { this._ProductivityTrackerReportService.FillLineManager(Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, true) // True Get From Employee_ModuleAccess -> ViewCompEvent value(In Old VIS Store in Session). .subscribe(data => { this.LineManager = data; this.InLoading = false; }, error => { this.msg = error; }); } FillDepartment(): void { this._ProductivityTrackerReportService.FillDepartment(Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(data => { this.Department = data; this.InLoading = false; }, error => { this.msg = error; }); } FillOverall(): void { this._ProductivityTrackerReportService.FillOverall(Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(data => { this.Department = data; this.InLoading = false; }, error => { this.msg = error; }); } FillLookup(): void { this._ProductivityTrackerReportService.FillLookup(Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(data => { this.Lookup = data; this.InLoading = false; }, error => { this.msg = error; }); } FillYear(): void { this._ProductivityTrackerReportService.FillLookup(Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(data => { this.Lookup = data; this.InLoading = false; }, error => { this.msg = error; }); } ToogleMyProfile() { $("#ProductivityTrackerReport").slideToggle(300); } CloseWidgetProfile() { $("#ProductivityTrackerReport").hide(300); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.ProductivityTracker); this.pager = this.pagerService.pager; this.pagedItems = null; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } GetoutId(): void { this.OutIds = ''; for (var i = 0; i < this.Lookup.length; i++) { this.OutIds += this.Lookup[i].Id + ','; } this.OutIds = this.OutIds.substring(1, this.OutIds.lastIndexOf(",")); } validateDate(): void { if ($("#txtdatefrom").val() != '') { if ($("#txtdateto").val() != '') { if ($("txtdatefrom").val() > $("#txtdateto").val()) { alert("Select Proper Dates"); } else { alert("Please select To dates"); } } } } onSubmit(formData: any) { var str; var chk; if (formData.Employee > 0) { str = formData.Employee; } if ($("#raddetail").val() == 'Detailed') { this.Mode = "Detail"; } else if ($("#radconsolidated").val() == 'Consolidated') { this.Mode = "consolidate"; } if ($("#chkall").prop("checked", true)) { chk = "0"; } else if ($("#chkouttype").prop("checked", true)) { chk = "1"; } if (!this.validateDate()) { if ($("#radDate").prop("checked", true)) { this.GetoutId(); this._ProductivityTrackerReportService.GetProductivity(Global.BASE_ProductivityTrackerAPI_ENDPOINT, formData.sort, formData.fromDate, formData.ToDate, str, this.Mode, this.OutIds, formData.Consolidatedview, chk) .subscribe(data => { this.ProductivityTracker = data; this.JumpOnPage(1); this.InLoading = false; }, error => { this.msg = error; }); } } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { MacIdConfigurationService } from '../../../service/Masters/Configuration/MacIdConfiguration.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IMacIdConfiguration } from '../../../Model/Masters/Configuration/MacIdConfiguration'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; import { PagerService } from '../../../Shared/pager.index'; @Component ({ providers: [MacIdConfigurationService], templateUrl: 'app/Components/Masters/Configuration/MacIdConfiguration.component.html' }) export class MacIdConfigurationComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; macidconfigurationsbackup: IMacIdConfiguration[]; macidconfigurations: IMacIdConfiguration[]; macidconfiguration: IMacIdConfiguration; employees: IMacIdConfiguration[]; employee: IMacIdConfiguration; msg: string; indLoading: boolean = false; MacIdConfigurationFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; MacIdConfigurationFilter: string; isDesc: boolean = false; column: any = 'Employee_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchEmployee_Name: string; strSearchMacID: string; strSearchIPAddress: string; strSearchVersion: string; constructor(private fb: FormBuilder, private _MacIdConfigurationService: MacIdConfigurationService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService ) { } ResetModel() { this.macidconfiguration = { Active: false, ApprovalDate: null, ApprovedBy: '', CreatedBy: '', CreatedOn: null, Description: '', EmployeeId: 0, Employee_Name: '', Id: 0, IP1: '', IP2: '', IP3: '', IP4: '', IPAddress: '', IsActive: false, MacID: '', MacID1: '', MacID2: '', MacID3: '', MacID4: '', MacID5: '', MacID6: '', OfficeMacId: false, RequestedDate: null, UpdatedBy: '', UpdatedOn: null, Version: '', Version1: '', Version2: '', Version3: '' } } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.ResetModel(); this.LoadMacIdConfiguration(); this.LoadEmployees(); this.InputNavigator(); } MacIdConfigurationFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.MacIdConfigurationFilter = value; } MackIdConfigurationSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; GetActiveRecord() { if ($("#rbtactive").prop("checked")) { this.macidconfigurations = this.macidconfigurationsbackup; this.macidconfigurations = this.macidconfigurations.filter(x => x.Active === true); this.JumpOnPage(1); } else if ($("#rbtinactive").prop("checked")) { this.macidconfigurations = this.macidconfigurationsbackup; this.macidconfigurations = this.macidconfigurations.filter(x => x.Active === false); this.JumpOnPage(1); } else { this.macidconfigurations = this.macidconfigurationsbackup; this.isDesc = true; this.MackIdConfigurationSort("Active"); this.JumpOnPage(1); } } LoadMacIdConfiguration(): void { this.indLoading = true; this._MacIdConfigurationService.get(Global.BASE_MACIDCONFIGURATION_ENDPOINT) .subscribe(macidconfigurations => { this.macidconfigurations = macidconfigurations; this.macidconfigurationsbackup = macidconfigurations; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchEmployee_Name = (<HTMLInputElement>document.getElementById("searchEmployee_Name")).value; if (this.strSearchEmployee_Name != '') { this.strSearchEmployee_Name = this.strSearchEmployee_Name.toLocaleLowerCase(); this.macidconfigurations = this.macidconfigurations.filter ( x => x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(this.strSearchEmployee_Name) != -1); } this.strSearchMacID = (<HTMLInputElement>document.getElementById("searchMacID")).value; if (this.strSearchMacID != '') { this.strSearchMacID = this.strSearchMacID.toLocaleLowerCase(); this.macidconfigurations = this.macidconfigurations.filter ( x => x.MacID != null && x.MacID.toLocaleLowerCase().indexOf(this.strSearchMacID) != -1); } this.strSearchIPAddress = (<HTMLInputElement>document.getElementById("searchIPAddress")).value; if (this.strSearchIPAddress != '') { this.strSearchIPAddress = this.strSearchIPAddress.toLocaleLowerCase(); this.macidconfigurations = this.macidconfigurations.filter ( x => x.IPAddress != null && x.IPAddress.toLocaleLowerCase().indexOf(this.strSearchIPAddress) != -1); } this.strSearchVersion = (<HTMLInputElement>document.getElementById("searchVersion")).value; if (this.strSearchVersion != '') { this.strSearchVersion = this.strSearchVersion.toLocaleLowerCase(); this.macidconfigurations = this.macidconfigurations.filter ( x => x.Version != null && x.Version.toLocaleLowerCase().indexOf(this.strSearchVersion) != -1); } } //Logic for searching - End this.indLoading = false; this.JumpOnPage(1); } //,error => this.msg = <any>error ); } LoadEmployees(): void { this.indLoading = true; this._MacIdConfigurationService.getallemployee(Global.BASE_MACIDCONFIGURATION_ENDPOINT) .subscribe(employee => { this.employees = employee; this.indLoading = false; } //,error => this.msg = <any>error ); } AddMackId() { this.dbops = DBOperation.create; this.modalTitle = "Add New MackId"; this.modalBtnTitle = "Add"; this.ResetModel(); this.modal.open(); } EditMackId(id: number) { this.dbops = DBOperation.update; this.modalTitle = "Edit MackId"; this.modalBtnTitle = "Update"; this.macidconfiguration = this.macidconfigurations.filter(x => x.Id == id)[0]; this.modal.open(); } DeleteMacId(id: number, status: boolean) { this.dbops = DBOperation.delete; var confimation = confirm("Are you sure ?") if (confimation == true) { this.macidconfiguration.Id = id; this.onSubmit(this.macidconfiguration); } } SetControlsState(isEnable: boolean) { isEnable ? this.MacIdConfigurationFrm.enable() : this.MacIdConfigurationFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.macidconfigurations); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: IMacIdConfiguration) { Number(formData.ApprovedBy='21') formData.MacID = formData.MacID1 + '-' + formData.MacID2 + '-' + formData.MacID3 + '-' + formData.MacID4 + '-' + formData.MacID5 + '-' + formData.MacID6; formData.IPAddress = formData.IP1 + '.' + formData.IP2 + '.' + formData.IP3 + '.' + formData.IP4; formData.Version = formData.Version1 + '.' + formData.Version2 + '.' + formData.Version3; this.msg = ""; switch (this.dbops) { case DBOperation.create: this._MacIdConfigurationService.post(Global.BASE_MACIDCONFIGURATION_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadMacIdConfiguration(); } else { alert(data); } this.modal.dismiss(); }, error => { this.msg = error; } ); break; case DBOperation.update: this._MacIdConfigurationService.put(Global.BASE_MACIDCONFIGURATION_ENDPOINT, formData.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadMacIdConfiguration(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._MacIdConfigurationService.delete(Global.BASE_MACIDCONFIGURATION_ENDPOINT, formData.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "MackId status changed successfully."; this.LoadMacIdConfiguration(); } else { this.msg = "Error has occurred while changing status of existing MackId!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } InputNavigator(): void { $(function () { $("#MacID1").keyup(function () { if ($("#MacID1").val().length == 2) { $("#MacID2").focus(); } }); $("#MacID2").keyup(function () { if ($("#MacID2").val().length == 2) { $("#MacID3").focus(); } }); $("#MacID3").keyup(function () { if ($("#MacID3").val().length == 2) { $("#MacID4").focus(); } }); $("#MacID4").keyup(function () { if ($("#MacID4").val().length == 2) { $("#MacID5").focus(); } }); $("#MacID5").keyup(function () { if ($("#MacID5").val().length == 2) { $("#MacID6").focus(); } }); $("#MacID6").keyup(function () { if ($("#MacID6").val().length == 2) { $("#IP1").focus(); } }); $("#IP1").keyup(function () { if ($("#IP1").val().length == 3) { $("#IP2").focus(); } }); $("#IP2").keyup(function () { if ($("#IP2").val().length == 3) { $("#IP3").focus(); } }); $("#IP3").keyup(function () { if ($("#IP3").val().length == 3) { $("#IP4").focus(); } }); $("#IP4").keyup(function () { if ($("#IP4").val().length == 3) { $("#Version1").focus(); } }); $("#Version1").keyup(function () { if ($("#Version1").val().length == 1) { $("#Version2").focus(); } }); $("#Version2").keyup(function () { if ($("#Version2").val().length == 1) { $("#Version3").focus(); } }); }); } ActivateDeactivateStatus(Id:number) { this._MacIdConfigurationService.activatedeactivatestatus(Global.BASE_MACIDCONFIGURATION_ENDPOINT, Id) .subscribe(data => { this.LoadMacIdConfiguration(); this.GetActiveRecord(); }, error => { this.msg = error; } //,error => this.msg = <any>error ); } }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IHomePageImage } from '../../../Model/Masters/CompanyRelated/HomePageImage'; @Pipe ({ name: 'homepageimageFilter' }) export class HomePageImageFilterPipe implements PipeTransform { transform(value: IHomePageImage[], filter: string): IHomePageImage[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IHomePageImage) => app.ImagePath != null && app.ImagePath.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.HumanResource.Attendance; namespace VIS_Repository.HumanResource.Attendace { public class MySkillRepository : VISDbCommand, VISIBaseRepository<MySkill> { public Int32 intAffectedRecords { get; set; } public MySkillRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { return null; } public MySkill GetEntityByID(Int64 entityId) { return null; } public IEnumerable<MySkill> GetEntityList() { return null; } public string AddEntity(MySkill entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MySkillConstants.const_procSkillUser_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_UserId, 21); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_SkillID, entityObject.id); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); //return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); ; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(MySkill entityObject) { return null; } public IEnumerable<MySkill> GetSkillUserWise(long UserId) { List<MySkill> objListToReturn = new List<MySkill>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MySkillConstants.const_procGetMySkill; base.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_mode, "SelectMySkills"); base.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MySkill>(dt); } return objListToReturn; } public IEnumerable<MySkill> GetAddNewSkill(long UserId) { List<MySkill> objListToReturn = new List<MySkill>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MySkillConstants.const_procGetMySkill; base.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_mode, "AddNewSkillInGrid"); base.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MySkill>(dt); } return objListToReturn; } public IEnumerable<MySkill> GetPopupChildSkill() { List<MySkill> objListToReturn = new List<MySkill>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MySkillConstants.const_procGetMySkill; base.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_mode, "dropdownGroupBind"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MySkill>(dt); } return objListToReturn; } public IEnumerable<MySkill> GetPopupsecondSkill(long lookupSkilId) { List<MySkill> objListToReturn = new List<MySkill>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MySkillConstants.const_procGetMySkill; base.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_mode, "dropdownSkillNameBind"); base.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_skillgroupid, lookupSkilId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MySkill>(dt); } return objListToReturn; } public string DeleteSkill(int SkillID, long UserId) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = MySkillConstants.const_procDeleteSkill; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_UserId, UserId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(MySkillConstants.const_Field_SkillID, SkillID); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); return intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~MySkillRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.Attendance { public class EmployeeFeedback : VISBaseEntity { public Int64 Id { get; set; } public string mode { get; set; } public Int64 UserId { get; set; } public string Remarks { get; set; } public bool IsLike { get; set; } public string EmployeeName { get; set; } public string SenderName { get ;set;} public Int64 EmployeeId { get; set; } public string Employee_Name { get; set; } public Int64 TeamEmployeeId { get; set; } } public static class EmployeeFeedbackConstants { public const string const_Table_EmployeeFeedback = "EmployeeFeedback"; public const string const_Field_Id = "Id"; public const string const_Field_mode = "mode"; public const string const_Field_UserId = "UserId"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_IsLike = "IsLike"; public const string const_Field_EmployeeName = "EmployeeName"; public const string const_Field_Employee_Name = "Employee_Name"; public const string const_Field_EmployeeId = "EmployeeId"; public const string const_Field_SenderName = "SenderName"; public const string const_Field_TeamEmployeeId = "TeamEmployeeId"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_procEmployeeFeedbackDetailUser = "procEmployeeFeedbackDetailUser"; public const string const_procEmployeeFeedbackTeamWiseLm = "procEmployeeFeedbackTeamWiseLm"; public const string const_procEmployeeFeedbackPending = "procEmployeeFeedbackPending"; public const string const_procEmployeeFeedbackAction = "procEmployeeFeedbackAction"; public const string const_procTeamMemberlist = "procTeamMemberlist"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Masters.EmployeeLevels { public class Levels_Achievement : VISBaseEntity { public string AchievementName { get; set; } public int SetUpID { get; set; } public Boolean IsCriteria { get; set; } public Boolean AndAbove { get; set; } public string Description { get; set; } public string Help { get; set; } public string Calculated { get; set; } public int AchievedIn { get; set; } public int Points { get; set; } public string Image { get; set; } public Boolean Active { get; set; } public int LevelSetupId { get; set; } public string CriteriaName { get; set; } public string CalculatedIn { get; set; } public string SelectActive { get; set; } public string Range { get; set; } public int CriteriaId { get; set; } } public static class Levels_AchievementConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Levels_Achievement = "Levels_Achievement"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_AchievementName = "AchievementName"; public const string const_Field_SetUpID = "SetUpID"; public const string const_Field_IsCriteria = "IsCriteria"; public const string const_Field_AndAbove = "AndAbove"; public const string const_Field_Description = "Description"; public const string const_Field_Help = "Help"; public const string const_Field_Calculated = "Calculated"; public const string const_Field_AchievedIn = "AchievedIn"; public const string const_Field_Points = "Points"; public const string const_Field_Image = "Image"; public const string const_Field_Active = "Active"; public const string const_Field_LevelSetupId = "LevelSetupId"; public const string const_Field_Value = "Value"; public const string const_Field_CriteriaId = "CriteriaId"; public const string const_Field_Range = "Range"; public const string const_Field_CriteiaId = "CriteriaId"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procLevels_Achievement_Add = "procLevels_Achievement_Add"; public const string const_procLevels_Achievement_Update = "procLevels_Achievement_Update"; public const string const_procLevels_Achievement_ActiveInActive = "procLevels_Achievement_ActiveInActive"; public const string const_procLevels_Achievement_SelectAll = "procLevels_Achievement_SelectAll"; public const string const_procLevels_Achievement_SelectBaseNonBase = "procLevels_Achievement_SelectBaseNonBase"; public const string const_procLevels_Achievement_SelectById = "procLevels_Achievement_SelectById"; public const string const_procLevels_Achievement_IsCriteria = "Levels_GetCriteriaSetUpList"; public const string const_procLevels_Achievement_GetLevelSetupId = "procGetLevelSetupId"; public const string const_procLevels_Achievement_OnEdit = "procLevels_Achievement_OnEdit"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var Observable_1 = require("rxjs/Observable"); require("rxjs/add/operator/map"); require("rxjs/add/operator/do"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var AttendanceReportService = (function () { function AttendanceReportService(_http) { this._http = _http; } AttendanceReportService.prototype.GetDepartment = function (url) { return this._http.get(url + 'GetDepartment') .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetEmployee = function (url) { return this._http.get(url + 'GetEmployee') .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetAllEmployee = function (url) { return this._http.get(url + 'GetAllEmployee') .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetCompany = function (url) { return this._http.get(url + 'GetCompany') .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetLineManager = function (url) { return this._http.get(url + 'GetLineManager') .map(function (response) { return response.json(); }); }; //GetBindAttendanceData(url: string, Id: number, strDate: string, ToDate: string, name: string, DRPData: number, rdbDate: string, Rdbmonth: string, month: number, year: number, cbDeduction: boolean, cbMissingEntry:boolean): Observable<any> { // return this._http.get(url + 'GetBindAttendanceData?Id=' + Id + '&strDate=' + strDate + '&ToDate=' + ToDate + '&name=' + name + '&DRPData=' + DRPData + '&rdbDate=' + rdbDate + '&Rdbmonth=' + Rdbmonth + '&month=' + month + '&year=' + year + '&cbDeduction=' + cbDeduction + '&cbMissingEntry='+ cbMissingEntry) // .map((response: Response) => <any>response.json()); //} AttendanceReportService.prototype.GetBindAttendanceData = function (url, Id, strDate, ToDate, name, DRPData, rdbDate, Rdbmonth, month, year) { return this._http.get(url + 'GetBindAttendanceData?Id=' + Id + '&strDate=' + strDate + '&ToDate=' + ToDate + '&name=' + name + '&DRPData=' + DRPData + '&rdbDate=' + rdbDate + '&Rdbmonth=' + Rdbmonth + '&month=' + month + '&year=' + year) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetMissingEntry = function (url, fromdate, todate, Employeeids) { return this._http.get(url + 'GetMissingEntry?fromdate=' + fromdate + '&todate=' + todate + '&Employeeids=' + Employeeids) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.SelectDepartment = function (url, Department) { return this._http.get(url + 'SelectDepartment?Department=' + Department) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.SelectCompany = function (url, Company) { return this._http.get(url + 'SelectCompany?Company=' + Company) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.SelectLineManager = function (url, LineManager) { return this._http.get(url + 'SelectLineManager?LineManager=' + LineManager) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetDepartmentEmployee = function (url, Id) { return this._http.get(url + 'GetDepartmentEmployee?Id=' + Id) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetDeductionDetails = function (url, fromdate, todate, Employeeids) { return this._http.get(url + 'GetDeductionDetails?fromdate=' + fromdate + '&todate=' + todate + '&Employeeids=' + Employeeids) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetYear = function (url) { return this._http.get(url + 'GetYear') .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetCheckedData = function (url, name, DRPData) { return this._http.get(url + 'GetCheckedData?name=' + name + '&DRPData=' + DRPData) .map(function (response) { return response.json(); }); }; //----Attendance Approve Punch In AttendanceReportService.prototype.AttendanceApproval = function (url, InId, EntryType, Remarks, Date, Time, Grace, ActualHrs) { return this._http.get(url + 'AttendanceApproval?InId=' + InId + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Date=' + Date + '&Time=' + Time + '&Grace=' + Grace + '&ActualHrs=' + ActualHrs) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetDailyEntryTime = function (url, Employee_Id, Date) { return this._http.get(url + 'GetDailyEntryTime?Employee_Id=' + Employee_Id + '&Date=' + Date) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AddEmployeeAttendance = function (url, Id, Employee_Id, EntryType, HODRemarks, Temp, strDate, Time, Grace) { return this._http.get(url + 'AttendanceApproveAdd?Id=' + Id + '&Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&HODRemarks=' + HODRemarks + '&Temp=' + Temp + '&strDate=' + strDate + '&Time=' + Time + '&Grace=' + Grace) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AttendanceRejectPunchIn = function (url, Employee_Id, EntryType, Date, RemarksIn, InId) { return this._http.get(url + 'AttendanceRejectPunchIn?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Date=' + Date + '&RemarksIn=' + RemarksIn + '&InId=' + InId) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.ApproveAttendanceOkIn = function (url, InId, Remarks) { return this._http.get(url + 'ApproveAttendanceOkIn?InId=' + InId + '&Remarks=' + Remarks) .map(function (response) { return response.json(); }); }; //----Attendance Approve Punch Out AttendanceReportService.prototype.ApproveAttendancePunchOut = function (url, OutId, EntryType, Remarks, Date, Time, Grace, ActualHrs) { return this._http.get(url + 'ApproveAttendancePunchOut?OutId=' + OutId + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Date=' + Date + '&Time=' + Time + '&Grace=' + Grace + '&ActualHrs=' + ActualHrs) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AddEmployeeAttendancePunchOut = function (url, Employee_Id, EntryType, HODRemarks, Temp, strDate, Time, Grace) { return this._http.get(url + 'AddEmployeeAttendancePunchOut?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&HODRemarks=' + HODRemarks + '&Temp=' + Temp + '&strDate=' + strDate + '&Time=' + Time + '&Grace=' + Grace) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AttendanceRejectPunchOut = function (url, Employee_Id, EntryType, Date, HODRemarks, OutId) { return this._http.get(url + 'AttendanceRejectPunchOut?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks + '&OutId=' + OutId) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.ApproveAttendanceOkPunchOut = function (url, OutId, Remarks) { return this._http.get(url + 'ApproveAttendanceOkPunchOut?OutId=' + OutId + '&Remarks=' + Remarks) .map(function (response) { return response.json(); }); }; //----Attendance Approve Lunch Out AttendanceReportService.prototype.ApproveAttendanceLunchOut = function (url, LunchOutId, Remarks, Time) { return this._http.get(url + 'ApproveAttendanceLunchOut?LunchOutId=' + LunchOutId + '&Remarks=' + Remarks + '&Time=' + Time) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AddEmployeeAttendanceLunchOut = function (url, Employee_Id, EntryType, Remarks, Temp, Date, Time) { return this._http.get(url + 'AddEmployeeAttendanceLunchOut?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Temp=' + Temp + '&Date=' + Date + '&Time=' + Time) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AttendanceRejectLunchOut = function (url, LunchOutId, Employee_Id, EntryType, Date, HODRemarks) { return this._http.get(url + 'AttendanceRejectLunchOut?LunchOutId=' + LunchOutId + '&Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.ApproveAttendanceOkLunchOut = function (url, LunchOutId, Remarks) { return this._http.get(url + 'ApproveAttendanceOkLunchOut?LunchOutId=' + LunchOutId + '&Remarks=' + Remarks) .map(function (response) { return response.json(); }); }; //----Attendance Approve Lunch In AttendanceReportService.prototype.ApproveAttendanceLunchIn = function (url, LunchInId, Remarks, Time) { return this._http.get(url + 'ApproveAttendanceLunchIn?LunchInId=' + LunchInId + '&Remarks=' + Remarks + '&Time=' + Time) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AddEmployeeAttendanceLunchIn = function (url, Employee_Id, EntryType, Remarks, Temp, Date, Time) { return this._http.get(url + 'AddEmployeeAttendanceLunchIn?Employee_Id=' + Employee_Id + '&EntryType=' + EntryType + '&Remarks=' + Remarks + '&Temp=' + Temp + '&Date=' + Date + '&Time=' + Time) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AttendanceRejectLunchIn = function (url, Employee_Id, LunchInId, EntryType, Date, HODRemarks) { return this._http.get(url + 'AttendanceRejectLunchIn?Employee_Id=' + Employee_Id + '&LunchInId=' + LunchInId + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.ApproveAttendanceOkLunchIn = function (url, LunchInId, Remarks) { return this._http.get(url + 'ApproveAttendanceOkLunchIn?LunchInId=' + LunchInId + '&Remarks=' + Remarks) .map(function (response) { return response.json(); }); }; //----Attendance Approve Work In AttendanceReportService.prototype.ApproveAttendanceOther = function (url, OtherId, Remarks, Time) { return this._http.get(url + 'ApproveAttendanceOther?OtherId=' + OtherId + '&Remarks=' + Remarks + '&Time=' + Time) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.GetEmployeeIsNotHostEmployee = function (url, Employee_Id) { return this._http.get(url + 'GetEmployeeIsNotHostEmployee?Employee_Id=' + Employee_Id) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AddEmployeeAttendanceOtherwork = function (url, Employee_Id, EntryType, HODRemarks, Temp, Date, Time) { return this._http.get(url + 'AddEmployeeAttendanceOtherwork?Employee_Id=' + Employee_Id + '&EntryType=' + Employee_Id + '&HODRemarks=' + HODRemarks + '&Temp=' + Temp + '&Date=' + Date + '&Time=' + Time) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.AttendanceRejectOtherWork = function (url, Employee_Id, OtherId, EntryType, Date, HODRemarks) { return this._http.get(url + 'AttendanceRejectOtherWork?Employee_Id=' + Employee_Id + '&OtherId=' + OtherId + '&EntryType=' + EntryType + '&Date=' + Date + '&HODRemarks=' + HODRemarks) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.ApproveAttendanceOkOtherWorkIn = function (url, OtherId, Remarks) { return this._http.get(url + 'ApproveAttendanceOkOtherWorkIn?OtherId=' + OtherId + '&Remarks=' + Remarks) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.get = function (url) { return this._http.get(url) .map(function (response) { return response.json(); }); }; AttendanceReportService.prototype.put = function (url, id, model) { var body = JSON.stringify(model); var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity/' + id, body, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; AttendanceReportService.prototype.delete = function (url, id) { var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; AttendanceReportService.prototype.handleError = function (error) { console.error(error); return Observable_1.Observable.throw(error.json().error || 'Server error'); }; AttendanceReportService = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [http_1.Http]) ], AttendanceReportService); return AttendanceReportService; }()); exports.AttendanceReportService = AttendanceReportService; <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var Observable_1 = require("rxjs/Observable"); require("rxjs/add/operator/map"); require("rxjs/add/operator/do"); require("rxjs/add/operator/catch"); var SalaryGrievanceService = (function () { function SalaryGrievanceService(_http) { this._http = _http; } SalaryGrievanceService.prototype.get = function (url) { return this._http.get(url) .map(function (response) { return response.json(); }); }; SalaryGrievanceService.prototype.post = function (url, model) { var body = JSON.stringify(model); var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.post(url, body, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; SalaryGrievanceService.prototype.put = function (url, UpdatedBy, model) { var body = JSON.stringify(model); var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity?UpdatedBy=' + UpdatedBy, body, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; SalaryGrievanceService.prototype.delete = function (url, id) { var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; SalaryGrievanceService.prototype.handleError = function (error) { console.error(error); return Observable_1.Observable.throw(error.json().error || 'Server error'); }; SalaryGrievanceService.prototype.GetGrievance = function (url, UserId, mode) { return this._http.get(url + 'GetGrievance?UserId=' + UserId + '&mode=' + mode) .map(function (response) { return response.json(); }); }; SalaryGrievanceService.prototype.FillDeductionDate = function (url, UserId, mode) { return this._http.get(url + 'FillDeductionDate?UserId=' + UserId + '&mode=' + mode) .map(function (response) { return response.json(); }); }; SalaryGrievanceService.prototype.LoadEmployeeAttendance = function (url, EmployeeId, Date) { return this._http.get(url + 'LoadEmployeeAttendance?EmployeeId=' + EmployeeId + '&Date=' + Date) .map(function (response) { return response.json(); }); }; SalaryGrievanceService.prototype.LoadEmployeeDailyEntry = function (url, EmployeeId, Date) { return this._http.get(url + 'LoadEmployeeDailyEntry?EmployeeId=' + EmployeeId + '&Date=' + Date) .map(function (response) { return response.json(); }); }; SalaryGrievanceService.prototype.AddGrievance = function (url, EmployeeId, Date, PaycutAmt, GrievanceRemark) { return this._http.get(url + 'AddGrievance?EmployeeId=' + EmployeeId + '&Date=' + Date + '&PaycutAmt=' + PaycutAmt + '&GrievanceRemark=' + GrievanceRemark) .map(function (response) { return response.json(); }); }; SalaryGrievanceService.prototype.GetGrievanceData = function (url, id) { return this._http.get(url + 'GetGrievanceData?Id=' + id) .map(function (response) { return response.json(); }); }; SalaryGrievanceService = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [http_1.Http]) ], SalaryGrievanceService); return SalaryGrievanceService; }()); exports.SalaryGrievanceService = SalaryGrievanceService; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Reports; using VIS_Repository; using VIS_Repository.Reports; using System.Configuration; using VIS_Domain.Reports.Attendance; using VIS_Repository.Reports.Attendance; namespace VIS_App.Controllers.Report.Attendance { public class AttendanceReportNewAPIController : BaseAPIController { AttendanceReportNewRepository objAttendanceReportNew = null; public AttendanceReportNewAPIController() { objAttendanceReportNew = new AttendanceReportNewRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/AttendanceReportNewAPI/FillDepartMent")] [HttpGet] public HttpResponseMessage FillDepartMent() { return ToJson(objAttendanceReportNew.FillDepartMent()); } [Route("api/AttendanceReportNewAPI/FillEmployee")] [HttpGet] public HttpResponseMessage FillEmployee(Int64 UserId,string UserType) { return ToJson(objAttendanceReportNew.FillEmployee(UserId,UserType)); } [Route("api/AttendanceReportNewAPI/FillYear")] [HttpGet] public HttpResponseMessage FillYear() { return ToJson(objAttendanceReportNew.FillYear()); } [Route("api/AttendanceReportNewAPI/FillCompany")] [HttpGet] public HttpResponseMessage FillCompany(Boolean Allow) { return ToJson(objAttendanceReportNew.FillCompany(Allow)); } [Route("api/AttendanceReportNewAPI/FillAllLineManager")] [HttpGet] public HttpResponseMessage FillAllLineManager(Boolean Allow,Int64 UserId) { return ToJson(objAttendanceReportNew.FillAllLineManager(Allow,UserId)); } [Route("api/AttendanceReportNewAPI/FillUserType")] [HttpGet] public HttpResponseMessage FillUserType() { return ToJson(objAttendanceReportNew.FillUserType()); } [Route("api/AttendanceReportNewAPI/FillAllEmployee")] [HttpGet] public HttpResponseMessage FillAllEmployee(Boolean Allow, Int64 UserId) { return ToJson(objAttendanceReportNew.FillAllEmployee(Allow,UserId)); } [Route("api/AttendanceReportNewAPI/GetSystemDateTime")] [HttpGet] public HttpResponseMessage GetSystemDateTime() { return ToJson(objAttendanceReportNew.GetSystemDateTime()); } [Route("api/AttendanceReportNewAPI/GetAllAttendanceData")] [HttpGet] public HttpResponseMessage GetAllAttendanceData(string Mode,Int64 ModeId,string StartDate,string EndDate,string SortBy,Boolean IsAdmin) { return ToJson(objAttendanceReportNew.GetAllAttendanceData(Mode,ModeId,StartDate,EndDate,SortBy,IsAdmin)); } [Route("api/AttendanceReportNewAPI/GetAllAttendanceReport")] [HttpGet] public HttpResponseMessage GetAllAttendanceReport(string Mode, Int64 ModeId, string StartDate, string EndDate, string SortBy, Boolean IsAdmin) { return ToJson(objAttendanceReportNew.GetAllAttendanceReport(Mode, ModeId, StartDate, EndDate, SortBy, IsAdmin)); } } } <file_sep>export interface ILevels { CompanyId: number; Id: number; LevelNumber:number; LevelName: string; LevelIcon: string; StartPoint: number; EndPoint: number; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Reports.Attendance; namespace VIS_Domain.Reports.Attendance { public class AttendanceReport : VISBaseEntity { public string Department_Name { get; set; } public string Employee_Name { get; set; } public string CompanyName { get; set; } public string LineManager { get; set; } public string mode { get; set; } //-------BIND DATA Attendance Data -------// public int EmployeeId { get; set; } public string EmployeeName { get; set; } public string Date { get; set; } public string ToDate { get; set; } public int InTimeID { get; set; } public DateTime InTIme { get; set; } public int OutTimeID { get; set; } public DateTime OutTIme { get; set; } public int LunchOutTimeID { get; set; } public DateTime LunchOutTIme { get; set; } public int LunchInTimeID { get; set; } public DateTime LunchInTIme { get; set; } public int OtherTimeID { get; set; } public string TotalOtherTime { get; set; } public string TotalOfficeTime { get; set; } public string TotalLunchTime { get; set; } public string TotalBreakTime { get; set; } public string TotalWorkingTime { get; set; } public int TotalWorksheetHours { get; set; } public bool IsInOffice { get; set; } public bool IsInBreak { get; set; } public bool IsInLunch { get; set; } public bool IsInMeeting { get; set; } public bool IsInOfficeWork { get; set; } public string Days { get; set; } public string ImportRemarks { get; set; } public string EmployeeCode { get; set; } public string MMDDYYYY_DateFormat { get; set; } public string Month { get; set; } public string Year { get; set; } public bool IsChecked { get; set; } public DateTime ForWhichDate { get; set; } public string DaysCount { get; set; } public string Remarks { get; set; } public int UploadedBy { get; set; } public DateTime UploadedDateTime { get; set; } } public class AttendanceReportParam { public Boolean cbMissingEntry { get; set; } public Boolean cbDeduction { get; set; } public Boolean rdbDate { get; set; } public Boolean rdbmonth { get; set; } public Int32 ddlemp { get; set; } } public class SelectedEmp { public int id { get; set; } public string employee_name { get; set; } } public static class AttendanceReportConstatnts { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Organization = "Organization"; public const string const_Table_Employee_Employee_Master = "Employee_Master"; public const string const_Table_Employee_CompanyMaster = "CompanyMaster"; public const string const_Table_FinancialYear = "FinancialYear"; public const string const_Table_SalaryDeductionDetail = "SalaryDeductionDetail"; public const string const_Table_AttendanceTransaction = "AttendanceTransaction"; public const string const_Table_TransactionChange = "TransactionChange"; public const string const_Table_TransactionLog = "TransactionLog"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Id = "Id"; public const string const_Field_DepartmentName = "Department_Name"; public const string const_Field_EmployeeName = "Employee_Name"; public const string const_Field_CompanyName = "CompanyName"; public const string const_Field_LineManager = "LineManager"; public const string const_Field_mode = "mode"; public const string const_Field_EmployeeID = "EmployeeID"; public const string const_Field_EmployeeId = "EmployeeId"; public const string const_FieldEmployeeName_ = "EmployeeName"; public const string const_Field_Date = "fromDate"; public const string const_Field_ToDate = "ToDate"; public const string const_Field_InTimeID = "InTimeID"; public const string const_Field_InTIme = "InTIme"; public const string const_Field_OutTimeID = "OutTimeID"; public const string const_Field_OutTIme = "OutTIme"; public const string const_Field_LunchOutTimeID = "LunchOutTimeID"; public const string const_Field_LunchOutTIme = "LunchOutTIme"; public const string const_Field_LunchInTimeID = "LunchInTimeID"; public const string const_Field_LunchInTIme = "LunchInTIme"; public const string const_Field_OtherTimeID = "OtherTimeID"; public const string const_Field_TotalOtherTime = "TotalOtherTime"; public const string const_Field_TotalOfficeTime = "TotalOfficeTime"; public const string const_Field_TotalLunchTime = "TotalLunchTime"; public const string const_Field_TotalBreakTime = "TotalBreakTime"; public const string const_Field_TotalWorkingTime = "TotalWorkingTime"; public const string const_Field_TotalWorksheetHours = "TotalWorksheetHours"; public const string const_Field_IsInOffice = "IsInOffice"; public const string const_Field_IsInBreak = "IsInBreak"; public const string const_Field_IsInLunch = "IsInLunch"; public const string const_Field_IsInMeeting = "IsInMeeting"; public const string const_Field_IsInOfficeWork = "IsInOfficeWork"; public const string const_Field_Days = "Days"; public const string const_Field_ImportRemarks = "ImportRemarks"; public const string const_Field_EmployeeCode = "EmployeeCode"; public const string const_Field_MMDDYYYY_DateFormat = "MMDDYYYY_DateFormat"; public const string const_Field_IsActive = "IsActive"; public const string const_Field_Month = "Month"; public const string const_Field_Year = "Year"; public const string const_Field_LongLeave = "LongLeaveDays"; public const string const_Field_startdate = "StartDate"; public const string const_Field_ForWhichDate = "ForWhichDate"; public const string const_Field_DaysCount = "DaysCount"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_UploadedBy = "UploadedBy"; public const string const_Field_UploadedDateTime = "UploadedDateTime"; public const string const_Field_LeaveDate = "LeaveDate"; public const string const_Field_fromDate = "Date"; public const string const_Field_EntryType = "Entry_Type"; public const string const_Field_Time = "Time"; public const string const_Field_grace = "grace"; public const string const_Field_actualEntryTime = "actualEntryTime"; public const string const_Field_Transaction_Id = "Transaction_Id"; public const string const_Field_Bit_Approved = "Bit_Approved"; public const string const_Field_HOD_Remarks = "HOD_Remarks"; public const string const_Field_Entry_Time = "Entry_Time"; public const string const_Field_empId = "empId"; public const string const_Field_InId = "InId"; public const string const_Field_OutId = "OutId"; public const string const_Field_LunchOutId = "LunchOutId"; public const string const_Field_LunchInId = "LunchInId"; public const string const_Field_OtherId = "OtherId"; public const string const_Field_Employee_ID = "Employee_Id"; public const string const_Field_employeeIds = "employeeIds"; public const string const_Field_Attendance_TransactionId = "Attendance_TransactionId"; public const string const_Field_ChangeType = "ChangeType"; public const string const_Field_UserId = "UserId"; public const string const_Field_ChangeTime = "ChangeTime"; public const string const_Field_DepartmentId = "DepartmentId"; public const string const_Field_CompanyId = "CompanyId"; public const string const_Field_LineMId = "LineMId"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procAttendanceReport_Add = ""; public const string const_procAttendanceReport_Update = ""; public const string const_procAttendanceReport_ActiveInActive = ""; public const string const_procAttendanceReport_SelectAll = "ProcAttendanceReportBindDropdown"; public const string const_procAttendanceReport_SelectBaseNonBase = ""; public const string const_procAttendanceReport_SelectById = "ProcGetAttendanceData"; public const string const_ProcAttendanceReport_AttendanceApproval = "procreportRecordUpdate"; public const string const_ProcAttendanceReport_CalLeaveNWD_Days = "ProcAttendanceReport_CalLeaveDetails"; public const string const_ProcAttendanceReport_SalaryDeduction = "ProcAttendance_Report"; public const string const_ProcAttendanceReport_BindFinalDetails = "ProcCalTotalAttendanceReport"; public const string const_ProcAttendanceReport_DailyentrytimingAddEdit = "Proc_DailyentrytimingAddEdit"; public const string const_ProcAttendanceReport_Procattendance_transaction = "Procattendance_transaction"; public const string const_ProcAttendanceReport_Proc_TransactionLog = "Proc_TransactionLog"; public const string const_ProcAttendanceReport_Proc_TransactionChange = "Proc_TransactionChange"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.Configuration; using VIS_Repository; using VIS_Repository.Masters; namespace VIS_App.Controllers { public class SecurityKeyAPIController : BaseAPIController { VISIBaseRepository<SecurityKey> SecurityKeyRepository; List<SecurityKey> EntityList = new List<SecurityKey>(); public SecurityKeyAPIController(VISIBaseRepository<SecurityKey> _SecurityKeyRepository) { SecurityKeyRepository = _SecurityKeyRepository; } public HttpResponseMessage Get() { return ToJson(SecurityKeyRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]SecurityKey value) { return ToJson(SecurityKeyRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]SecurityKey value) { return ToJson(SecurityKeyRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(SecurityKeyRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.VacancyRelated { public class Position : VISBaseEntity { /// <summary> /// Position Entity Fields. /// </summary> /// public string PositionName { get; set; } public string Remarks { get; set; } public bool Status { get; set; } public Int64[] SkillId { get; set; } public string SkillName { get; set; } } public class SkillViewList { public Int64 PositionId { get; set; } public Int64 SkillId { get; set; } public string SkillName { get; set; } } public class PositionViewModel { public Int64 Id { get; set; } public string PositionName { get; set; } public string Remarks { get; set; } public bool Status { get; set; } public bool IsActive { get; set; } public Int64 SkillId { get; set; } public string SkillName { get; set; } public string SkillsId { get; set; } } public class SkillList { public Int64 id { get; set; } public string name { get; set; } } public static class PositionConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_PositionMaster_Table = "PositionMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_PositionName = "PositionName"; public const string const_Remarks = "Remarks"; public const string const_Status = "Status"; public const string const_SkillId = "SkillId"; public const string const_PositionId = "PositionId"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procPositionMaster_Add = "procPositionMaster_Add"; public const string const_procPositionMaster_Update = "procPositionMaster_Update"; public const string const_procPositionMaster_ActiveInActive = "procPositionMaster_ActiveInActive"; public const string const_procPositionMaster_SelectAll = "procPositionMaster_SelectAll"; public const string const_procPositionMaster_SelectById = "procPositionMaster_SelectById"; public const string const_procPositionSkill_Add = "procPositionSkill_Add"; public const string const_procPositionSkill_Delete = "procPositionSkill_Delete"; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using VIS_Domain; using VIS_Domain.HumanResource.ProfileAttendance; namespace VIS_Repository.HumanResource.ProfileAttendace { public class ProfileAttendanceRepository : VISDbCommand, VISIBaseRepository<ProfileAttend> { public Int32 intAffectedRecords { get; set; } public ProfileAttendanceRepository(string _connectionstring) : base(_connectionstring) { } public string AddEntity(ProfileAttend entityObject) { throw new NotImplementedException(); } public string DeleteEntity(long Id) { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } public ProfileAttend GetEntityByID(long entityId) { throw new NotImplementedException(); } public IEnumerable<ProfileAttend> GetEntityList() { throw new NotImplementedException(); } public string UpdateEntity(ProfileAttend entityObject) { throw new NotImplementedException(); } //public string ChangePassword(int Id,string VISPassword) //{ // string StrMsg = string.Empty; // using (base.objSqlCommand.Connection) // { // base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // base.objSqlCommand.CommandText = ProfileAttendanceConstants.const_procProfileAttendance_ChangePassword; // //base.objSqlCommand.Parameters.AddWithValue(ProfileAttendanceConstants.VISBaseEntityConstants.const_Field_Id, 2); // base.objSqlCommand.Parameters.AddWithValue(ProfileAttendanceConstants.const_Field_Id, Id); // base.objSqlCommand.Parameters.AddWithValue(ProfileAttendanceConstants.const_Field_VISPassword, VISPassword); // if (base.objSqlCommand.Connection.State != ConnectionState.Open) // { // base.objSqlCommand.Connection.Open(); // } // SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); // DataTable dt = new DataTable(); // da.Fill(dt); // if (dt.Rows.Count > 0) // { // StrMsg = Convert.ToString(objSqlCommand.ExecuteScalar()); // } // else // { // StrMsg = "Please Enter valid Password"; // } // // return dt; // base.objSqlCommand.Connection.Close(); // } // return StrMsg; //} public string userchangepsw(int id, ProfileAttend Profile) { try { VISDbCommand objvisdbcommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objvisdbcommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objvisdbcommand.objSqlCommand.CommandText = ProfileAttendanceConstants.const_procProfileAttendance_ChangePassword; objvisdbcommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, id); objvisdbcommand.objSqlCommand.Parameters.AddWithValue(ProfileAttendanceConstants.const_Field_VISPassword, Profile.VISPassword); objvisdbcommand.objSqlCommand.Parameters.AddWithValue(ProfileAttendanceConstants.const_Field_NewPassword, Profile.NewPassword); objvisdbcommand.objSqlCommand.Parameters.AddWithValue(ProfileAttendanceConstants.const_Field_ConfirmNewPassword, Profile.ConfirmNewPassword); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } //objvisdbcommand.objsqlcommand.parameters.addwithvalue(visbaseentityconstants.const_field_updatedby, entityobject.updatedby); objvisdbcommand.objSqlCommand.Connection.Open(); if (Profile.NewPassword == Profile.ConfirmNewPassword) { intAffectedRecords = objvisdbcommand.objSqlCommand.ExecuteNonQuery(); } objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + base.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } } } <file_sep>export interface IEmployeeFeedback { Id: number; UserID: number; Remarks: string; IsLike: string; CreatedOn: string; EmployeeName: string; SenderName: string; TeamEmployeeId: number; } export interface IEmployee { EmployeeId: number; Employee_Name: string; }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { OutReportService } from '../../../Service/Report/Attendance/OutReport.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { IDepartment } from '../../../Model/Report/Attendance/OutReport'; import { IEmployeeId } from '../../../Model/Report/Attendance/OutReport'; import { IEmployee } from '../../../Model/Report/Attendance/OutReport'; import { ICompany } from '../../../Model/Report/Attendance/OutReport';; import { ILineManager } from '../../../Model/Report/Attendance/OutReport';; import { ICalTotalAttendance } from '../../../Model/Report/Attendance/OutReport'; import { IOutReport } from '../../../Model/Report/Attendance/OutReport'; import { IOutReportBindReport } from '../../../Model/Report/Attendance/OutReport'; import { ExcelService } from '../../../Shared/exportexcel.service'; import { DailyEntrysheetComponent } from '../../../Components/Report/Attendance/DailyEntrysheet.component'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [OutReportService], templateUrl: 'app/Components/Report/Attendance/OutReport.component.html' }) export class OutReportComponent implements OnInit { AttendanceDeparts: IDepartment; AttendanceDepart: IDepartment[]; EmployeeIdByLM: IEmployeeId[]; AttendanceEmployee: IEmployee[]; AttendanceCompany: ICompany[]; AttendanceLineManager: ILineManager[]; AttendancebindData: ICalTotalAttendance[]; AttendanceData: ICalTotalAttendance[]; AttendanceCalculates: ICalTotalAttendance; // modal object outreports: IOutReportBindReport[]; json: any[]; outreport: IOutReport; @ViewChild('modal') modal: ModalComponent; msg: string; msgtimevalidation: string; DailyEntrysheetFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; DailyEntryFilter: string; isDesc: boolean = false; column: any = 'EventName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; pagedItemscount: IOutReportBindReport[]; cnttotal: number; PagerInformation: string; nums: number[]; fulldate: string; newdate: string; newmonth: string; newyear: string; Transaction_Id: number; Date: string; datetoday: string; InLoading: boolean; constructor(private fb: FormBuilder, private _OutReportService: OutReportService, private _ExcelService: ExcelService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService ) { } // Load Event Function ngOnInit() { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.AttendanceDepart = [({ Id: 0, Department_Name: '', mode: '' })]; this.AttendanceEmployee = [({ Id: 0, Employee_Name: '', mode: '' })]; this.AttendanceCompany = [({ Id: 0, CompanyName: '', mode: '' })]; this.AttendanceLineManager = [({ Id: 0, LineManager: '', mode: '' })]; this.AttendancebindData = [({ EmployeeID: 0, EmployeeName: '', Date: '', ToDate: '', InTimeID: 0, InTIme: null, OutTimeID: 0, OutTIme: null, LunchOutTimeID: 0, LunchOutTIme: null, LunchInTimeID: 0, LunchInTIme: null, OtherTimeID: 0, TotalOtherTime: '', TotalOfficeTime: '', TotalLunchTime: '', TotalBreakTime: '', TotalWorkingTime: '', TotalWorksheetHours: 0, IsInOffice: false, IsInBreak: false, IsInLunch: false, IsInMeeting: false, IsInOfficeWork: false, Days: '', ImportRemarks: '', EmployeeCode: '', MMDDYYYY_DateFormat: '' })]; this.outreport = { EmployeeId: 0, Active: 0, AllDate: false, Consolidated: '', Employeelist: '', FromDate: new Date(), Minute: 0, OutType: '', Sort: '', ToDate: new Date() } this.GetEmployee(); this.GetDepartment(); this.GetCompany(); this.GetLineManager(); } // Hide & Show Element jQuery Function ToogleMyProfile() { $("#alltypeoutreportdata").slideToggle(300); } CloseWidgetProfile() { $("#alltypeoutreport").hide(300); } ViewStyleToogle() { if ($("#rbtconsolidated").prop('checked')) { $("#viewstyle").show(); } else { $("#viewstyle").hide(); } } ToogleHideShowOption() { if ($("#rbtdepartment").prop('checked')) { $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); $("#ddldepartment").show(); } else if ($("#rbtcompany").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").show(); $("#ddllinemanager").hide(); } else if ($("#rbtlinemanager").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").show(); } else { $("#ddldepartment").hide(); $("#ddlemployee").show(); $("#chkallemployeediv").show(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); } } ToogleAllDate() { if ($("#alldate").prop('checked')) { $("#fromdate").attr("disabled", "disabled"); $("#todate").attr("disabled", "disabled"); } else { $("#fromdate").removeAttr("disabled"); $("#todate").removeAttr("disabled"); } } ToogleAllTypesofOut() { if ($("#rbtall").prop('checked')) { $("#chkall").attr("disabled", "disabled"); $("#chklunch").attr("disabled", "disabled"); $("#chkother").attr("disabled", "disabled"); $("#chkmeeting").attr("disabled", "disabled"); $("#chkofficeout").attr("disabled", "disabled"); $("#chkall").attr("checked", "checked"); $("#chklunch").prop("checked", false); $("#chkother").prop("checked", false); $("#chkmeeting").prop("checked", false); $("#chkofficeout").prop("checked", false); } else { $("#chkall").attr("disabled", "disabled"); $("#chkall").removeAttr("checked"); $("#chklunch").removeAttr("disabled"); $("#chkother").removeAttr("disabled"); $("#chkmeeting").removeAttr("disabled"); $("#chkofficeout").removeAttr("disabled"); } } ToogleMinute() { if ($("#toogleminute").prop('checked')) { $("#txtminute").removeAttr("disabled"); } else { $("#txtminute").attr("disabled", "disabled"); } } // Dropdown bind Function GetEmployee() { this._OutReportService.getemployee(Global.BASE_OutReportApi_ENDPOINT). subscribe(employee => { this.AttendanceEmployee = employee }, ); } GetAllEmployee() { if ($("#chkallemployee").prop("checked")) { this._OutReportService.getallemployee(Global.BASE_OutReportApi_ENDPOINT). subscribe(allemployee => { this.AttendanceEmployee = allemployee }, ); } else { this.GetEmployee(); } } GetDepartment() { this._OutReportService.getdepartment(Global.BASE_OutReportApi_ENDPOINT). subscribe(department => { this.AttendanceDeparts = department }, ); } GetCompany() { this._OutReportService.getcompany(Global.BASE_OutReportApi_ENDPOINT). subscribe(companydata => { this.AttendanceCompany = companydata }, ); } GetLineManager() { this._OutReportService.getlinemanager(Global.BASE_OutReportApi_ENDPOINT). subscribe(linemanagaer => { this.AttendanceLineManager = linemanagaer }, ); } GetEmployeeIdByLM(LineManager: number) { if ($("#ddllinemanager").val() != '0') { this._OutReportService.getemployeeidbylm(Global.BASE_OutReportApi_ENDPOINT, LineManager). subscribe(emplist => { this.EmployeeIdByLM = emplist; }, ); } } GetEmployeeIdByCompany(Company: number) { if ($("#ddlcompany").val() != '0') { this._OutReportService.getemployeeidbycompany(Global.BASE_OutReportApi_ENDPOINT, Company). subscribe(emplist => { this.EmployeeIdByLM = emplist; }, ); } } GetEmployeeIdByDepartment(ParentId: number) { if ($("#ddldepartment").val() != '0') { this._OutReportService.getemployeeidbydepartment(Global.BASE_OutReportApi_ENDPOINT, ParentId). subscribe(emplist => { this.EmployeeIdByLM = emplist; }, ); } } // Post Report By Selected Category onSubmit(entityobject: IOutReport) { $("html, body").animate({ scrollTop: 590 }, 250); entityobject.Employeelist = ''; if ($("#rbtlinemanager").prop("checked") && $("#ddllinemanager").val() != '0' && $("#ddllinemanager").val() != '' && $("#ddllinemanager").val() != undefined) { for (let item of this.EmployeeIdByLM) { entityobject.Employeelist += item.Id + ',' } } else if ($("#rbtcompany").prop("checked") && $("#ddlcompany").val() != '0' && $("#ddlcompany").val() != '' && $("#ddlcompany").val() != undefined) { for (let item of this.EmployeeIdByLM) { entityobject.Employeelist += item.Id + ',' } } else if ($("#rbtdepartment").prop("checked") && $("#ddldepartment").val() != '0' && $("#ddldepartment").val() != '' && $("#ddldepartment").val() != undefined) { for (let item of this.EmployeeIdByLM) { entityobject.Employeelist += item.Id + ',' } } else if ($("#ddlemployee").val() == '0' || $("#ddldepartment").val() == '0' || $("#ddlcompany").val() == '0' || $("#ddllinemanager").val() == '0' ) { entityobject.EmployeeId = 0; } else { entityobject.Employeelist = entityobject.EmployeeId.toString(); } if ($("#toogleminute").prop("checked")) { entityobject.Minute = $("#txtminute").val(); } else { entityobject.Minute = 0; } if ($("#chkallemployee").prop("checked")) { entityobject.Active = 1; } else { entityobject.Active = 0; } if ($("#alldate").prop("checked")) { entityobject.AllDate = true; } if ($("#rbtall").prop("checked")) { entityobject.OutType = 'All' } else if ($("#rbtother").prop("checked")) { if ($("#chklunch").prop("checked") && $("#chkother").prop("checked") && $("#chkmeeting").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Other Breaks' + ',' + 'Meeting' + ',' + 'office Out'; } else if ($("#chklunch").prop("checked") && $("#chkother").prop("checked") && $("#chkmeeting").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Other Breaks' + ',' + 'Meeting'; } else if ($("#chkother").prop("checked") && $("#chkmeeting").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Other Breaks' + ',' + 'Meeting' + ',' + 'office Out'; } else if ($("#chklunch").prop("checked") && $("#chkother").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Other Breaks'; } else if ($("#chklunch").prop("checked") && $("#chkmeeting").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Meeting'; } else if ($("#chklunch").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'office Out'; } else if ($("#chkother").prop("checked") && $("#chkmeeting").prop("checked")) { entityobject.OutType = 'Other Breaks' + ',' + 'Meeting'; } else if ($("#chkother").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Other Breaks' + ',' + 'office Out'; } else if ($("#chkmeeting").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Meeting' + ',' + 'office Out'; } else if ($("#chklunch").prop("checked")) { entityobject.OutType = 'Lunch' } else if ($("#chkother").prop("checked")) { entityobject.OutType = 'Other Breaks' } else if ($("#chkmeeting").prop("checked")) { entityobject.OutType = 'Meeting' } else if ($("#chkofficeout").prop("checked")) { entityobject.OutType = 'office Out' } } if (($("#toogleminute").prop("checked"))) { entityobject.Minute = ($("#txtminute").val()); entityobject.Consolidated = 'Date'; entityobject.Sort = 'Name'; } else { entityobject.Minute = 0; } if ($("#alldate").prop("checked")) { entityobject.AllDate = true; } else { entityobject.AllDate = false; } if ($("#rbtdetailed").prop("checked")) { entityobject.Consolidated = 'All' } if ($("#rbtconsolidated").prop("checked")) { if ($("#rbtnone").prop("checked")) { entityobject.Consolidated = 'None'; } else if ($("#rbtname").prop("checked")) { entityobject.Consolidated = 'Name' } else if ($("#rbttype").prop("checked")) { entityobject.Consolidated = 'Type' } else { entityobject.Consolidated = 'Date' } } if ($("#rbtsortname").prop("checked")) { entityobject.Sort = 'Name' } else if ($("#rbtsortdate").prop("checked")) { entityobject.Sort = 'Date' } else if ($("#rbtsorttype").prop("checked")) { entityobject.Sort = 'Type' } else { entityobject.Sort = 'Duration' } if ($("#toogleminute").prop("checked")) { entityobject.Consolidated = 'Date'; } this.InLoading = true; this._OutReportService.getoutreportdata(Global.BASE_OutReportApi_ENDPOINT, entityobject). subscribe(reportdata => { this.outreports = reportdata; this.JumpOnPage(1); $("html, body").animate({ scrollTop: 590 }, 250); this.InLoading = false; }, ); if (entityobject.Consolidated == 'None' || entityobject.Consolidated == 'Name' || entityobject.Consolidated == 'Type' || entityobject.Consolidated == 'Date') { $("#headerstarttime").hide(); $("#headerendtime").hide(); $("#headerremarks").hide(); $("#col2starttime").hide(); $("#col2endtime").hide(); $("#col2remarks").hide(); } else { $("#headerstarttime").show(); $("#headerendtime").show(); $("#headerremarks").show(); $("#col2starttime").show(); $("#col2endtime").show(); $("#col2remarks").show(); } } // pagination Function JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.outreports); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; this.pagedItemscount = this.pagerService.pagedItems; var total = 0; for (let item of this.pagedItemscount) { total += item.Duration; this.cnttotal = total; } } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ExportToExcel() { if (this.outreports!=null && this.outreports.length > 0) { this._ExcelService.exportAsExcelFile(this.outreports, 'OutReport'); } else { alert("No Record Found !"); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.MyProfiles; using VIS_Repository.HumanResource.ProfileAttendace; namespace VIS_App.Controllers.HumanResource.ProfileAttendance { public class MyProfilesAPIController : BaseAPIController { //VISIBaseRepository<MyProfiles> MyProfilesRepository; //List<MyProfiles> EntityList = new List<MyProfiles>(); MyProfilesRepository ObjMyProfilesRepository = null; public MyProfilesAPIController() { ObjMyProfilesRepository = new MyProfilesRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjMyProfilesRepository.GetEntityList().AsEnumerable()); } [Route("api/MyProfilesAPI/GetUserDeatils")] [HttpGet] public HttpResponseMessage GetUserDeatils(long UserId) { return ToJson(ObjMyProfilesRepository.GetProfileByUser(UserId)); } [Route("api/MyProfilesAPI/GetEduactionDeatils")] [HttpGet] public HttpResponseMessage GetEduactionDeatils(long UserId) { return ToJson(ObjMyProfilesRepository.GetEducationUser(UserId)); } [Route("api/MyProfilesAPI/GetEmployeeList")] [HttpGet] public HttpResponseMessage GetEmployeeList() { return ToJson(ObjMyProfilesRepository.GetEmployeeList()); } public HttpResponseMessage Post([FromBody]MyProfiles value) { return ToJson(ObjMyProfilesRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]MyProfiles value) { return ToJson(ObjMyProfilesRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjMyProfilesRepository.DeleteEntity(Id)); } } } <file_sep>export interface ILevelConfiguration { Id: number; Period: number; PeriodName: string; StartDate: Date; EndDate: Date; Active: boolean IsCurrentPeriod: boolean; CreatedOn: Date; CreatedBy: number; UpdatedOn: Date; UpdatedBy: number; IsActive: boolean; StartYear: number; StartMonth: number; }<file_sep>import { Component, OnInit, ViewChild, Pipe } from '@angular/core'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IDepartment, IEmployee, ICompany, ILineManager, IYear, ICalTotalAttendance, SaveDailyEntryTime, IAttendanceParam } from '../../../Model/Report/Attendance/AttendanceReport'; import { AttendanceReportService } from '../../../Service/Report/Attendance/AttendanceReport.Service'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; //import { AttendanceReportFilterPipe } from '../../../Filter/Report/Attendance/Attendance_Report'; @Component({ providers: [AttendanceReportService], templateUrl: 'app/Components/Report/Attendance/AttendanceReport.component.html' }) export class AttendanceReportComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('modalAttendanceApprovalPunchIn') modalAttendanceApprovalPunchIn: ModalComponent; @ViewChild('modalAttendanceApprovalPunchOut') modalAttendanceApprovalPunchOut: ModalComponent; @ViewChild('modalAttendanceApprovalLunchOut') modalAttendanceApprovalLunchOut: ModalComponent; @ViewChild('modalAttendanceApprovalLunchIn') modalAttendanceApprovalLunchIn: ModalComponent; @ViewChild('modalAttendanceApprovalWorkIn') modalAttendanceApprovalWorkIn: ModalComponent; AttendanceDepart: IDepartment[]; AttendanceEmployee: IEmployee[]; AttendanceCompany: ICompany[]; AttendanceLineManager: ILineManager[]; AttendanceYear: IYear[]; AttendancebindData: ICalTotalAttendance[]; EmployeeDailyTime: SaveDailyEntryTime[]; InId: number; OutId: number; LunchOutId:number; LunchInId: number; OtherId: number; Id: number; Employee_Id: number; AttendanceDate: string; strDate: string; ToDate: string; month: number; year: number; day: number; EmployeeName: string; msg: string; indLoading: boolean = false; CurrentRecordsPerPage: number = 10; pager: any = {}; pagedItems: any[]; name: string; DRPData: number; RDBDate: string; Rdbmonth: string; Grace: number; ActualHr: string; ActualMin: string; EntryHr: string; EntryMin: string; DrpEntryIn: string; DrpActualIn: string; DrpActualOut: string; strarrdate: string[]; DRPAM_PM: string; HODRemarks: string; EntryType: number; Temp: string; Yearval: number; constructor(private fb: FormBuilder, public _AttendanceReportService: AttendanceReportService, public http: Http, private router: Router, private pagerService: PagerService) { } ngOnInit(): void { $("#depart").hide(); $("#companydata").hide(); $("#LM").hide(); $("#emp").show(); $("#empAll").show(); $("#Employee").prop("checked", true); $("#datedata").hide(); $("#rdbmonth").prop("checked", true); $("#rdbDate").prop("checked", false); $("#RdbSortName").prop("checked", true); $('#ddlmonth option:eq(' + (new Date).getMonth() + ')').prop('selected', true); this.Yearval = new Date().getFullYear(); this.AttendanceDepart = [ ({ Id: 0, Department_Name: '', mode: '' })]; this.AttendanceEmployee = [({ Id: 0, Employee_Name: '', mode: '' })]; this.AttendanceCompany = [({ Id: 0, CompanyName: '', mode: '' })]; this.AttendanceLineManager = [({ Id: 0, LineManager: '', mode: '' })]; this.AttendancebindData = [({ Employee_Id: 0, EmployeeCode: '', Employee_Name: '', Date: '', MMDDYYYY_DateFormat: '', Days: '', ImportRemarks: '', HoverImportRemarks: '', InId: 0, In_Time: null, OutId: 0, Out_Time: null, LunchOutId: 0, LunchOut_Time: null, LunchInId: 0, LunchIn_Time: null, OtherId: 0, Other_Time: null, TotalWorksheet_Hr: 0, status: '', Total_W_Hr: '', Total_Hrs: '', diff: '', TotalId: '', ActualEntryTime: '', Grace: 0, EntryType: '' })] this.AttendanceYear = [({ Id: 0, Month: '', Year: '' })]; this.LoadDepartment(); this.LoadCompany(); this.LoadLineManager(); this.LoadYear(); this.LoadEmployee(); } HideEMCOLM() { $("#emp").hide(-300); $("#empAll").hide(-300); $("#companydata").hide(-300); $("#LM").hide(-300); $("#depart").show(-300); } HideCOLMDP() { $("#depart").hide(-300); $("#companydata").hide(-300); $("#LM").hide(-300); $("#emp").show(-300); $("#empAll").show(-300); } HideLMDPEM() { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#LM").hide(-300); $("#companydata").show(-300); } HideDPEMCO() { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#companydata").hide(-300); $("#LM").show(-300); } HideMonth() { $("#monthData").hide(-300); $("#datedata").show(-300); } HideDate() { $("#monthData").show(-300); $("#datedata").hide(-300); } private btnAttendanceApprovePunchIn(data): void { this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.Employee_Id = data.Employee_Id; this.Grace = data.Grace; this.EntryHr = data.In_Time; this.EntryMin = data.In_Time; let HH_EIN = this.EntryHr.slice(8, 10).trim(); this.EntryHr = HH_EIN; let MIN_EIN = this.EntryMin.slice(11, 13).trim(); this.EntryMin = MIN_EIN; this.DrpEntryIn = data.In_Time; let DrpIn = this.DrpEntryIn.slice(17, 19).trim(); this.InId = data.InId; this.DrpEntryIn = DrpIn; this.ActualHr = data.ActualEntryTime; let HH_AIN = this.ActualHr.slice(0, 2).trim(); this.ActualHr = HH_AIN; this.ActualMin = data.ActualEntryTime; let MIN_AIN = this.ActualMin.slice(3, 5).trim(); this.ActualMin = MIN_AIN; this.modalAttendanceApprovalPunchIn.open(); } private btnAttendanceApprovePunchOut(data): void { this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.Employee_Id = data.Employee_Id; this.Grace = data.Grace; this.EntryHr = data.Out_Time; this.EntryMin = data.Out_Time; let HH_EOUT = this.EntryHr.slice(8, 10).trim(); this.EntryHr = HH_EOUT; let MIN_EOUT = this.EntryMin.slice(11, 13).trim(); this.EntryMin = MIN_EOUT; this.DrpEntryIn = data.Out_Time; let DrpOut = this.DrpEntryIn.slice(17, 19).trim(); this.DrpEntryIn = DrpOut; this.ActualHr = data.ActualEntryTime; let HH_AOUT = this.ActualHr.slice(0, 2).trim(); this.ActualHr = HH_AOUT; this.ActualMin = data.ActualEntryTime; let MIN_AOUT = this.ActualMin.slice(3, 5).trim(); this.ActualMin = MIN_AOUT; this.OutId = data.OutId; this.modalAttendanceApprovalPunchOut.open(); } private btnAttendanceApproveLunchOut(data): void { this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.Employee_Id = data.Employee_Id; this.LunchOutId = data.LunchOutId; this.modalAttendanceApprovalLunchOut.open(); } private btnAttendanceApproveLunchIn(data): void { this.LunchInId = data.LunchInId; this.Employee_Id = data.Employee_Id; this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.modalAttendanceApprovalLunchIn.open(); } private btnAttendanceApproveOtherwork(data): void { this.OtherId = data.OtherId; this.Employee_Id = data.Employee_Id; this.EmployeeName = data.Employee_Name; this.AttendanceDate = data.Date; this.modalAttendanceApprovalWorkIn.open(); } //----Punch-In Attendance Approve ApproveAttendancePunchIn(): void { this.EntryHr = $("#EntryHour").val(); this.EntryMin = $("#EntryMinute").val(); this.DRPAM_PM = $("#ddlIn").val(); this.HODRemarks = $("#HODRemarks").val(); this.Grace = $("#Grace").val(); this.ActualHr = $("#ActualHour").val(); this.ActualMin = $("#ActualMinute").val(); this.DrpActualIn = $("#ddlAIn").val(); if ((parseInt(this.EntryHr.toString()) < 24) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; this.EntryType = 1; if (this.InId.toString().length > 0) { if (this.EntryType < 3) { if (this.DrpActualIn == "PM") { if (parseInt(this.ActualHr) <= 12) { } else { this.ActualHr += 12; } this.ActualHr; } else { this.ActualHr; } this.ActualHr = this.ActualHr + ":" + this.ActualMin; } this.indLoading = true; this._AttendanceReportService.AttendanceApproval(Global.BASE_AttendanceReport_ENDPOINT, this.InId, 1, this.HODRemarks, this.strDate, this.Temp, this.Grace, this.ActualHr) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } else { this._AttendanceReportService.GetDailyEntryTime(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(data => { this.indLoading = false; this.EmployeeDailyTime = data; let Datetime = new Date(this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { let Time = ""; this.EmployeeDailyTime = data; if (this.EntryType == 1) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Mon_Fri; }) } } else if (this.EntryType = 2) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Mon_Fri; }) } } else { Time = ""; } this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; this.EntryType = 1; this._AttendanceReportService.AddEmployeeAttendance(Global.BASE_AttendanceReport_ENDPOINT, 0, this.Employee_Id, this.EntryType, this.HODRemarks, this.Temp, this.strDate, Time, this.Grace) .subscribe(success => { this.indLoading = false; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } } } AttendanceRejectPunchIn(): void { this.EntryType = 1; this.HODRemarks = $("#HODRemarks").val(); this._AttendanceReportService.AttendanceRejectPunchIn(Global.BASE_AttendanceReport_ENDPOINT, this.Id, this.EntryType, this.AttendanceDate, this.HODRemarks, this.InId) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } ApproveAttendanceOkPunchIn(): void { let Remarks = $("#RemarksQuickApprove").val(); this._AttendanceReportService.ApproveAttendanceOkIn(Global.BASE_AttendanceReport_ENDPOINT, this.InId, Remarks) .subscribe(data => { this.indLoading = true; }, error => { this.msg = error; }); } //----Punch-Out Attendance Approve ApproveAttendancePunchOut(): void { this.EntryHr = $("#EntryHrPunchout").val(); this.EntryMin = $("#EntryMinPunchOut").val(); this.DRPAM_PM = $("#ddlout").val(); this.HODRemarks = $("#HODRemarksPunchOut").val(); this.Grace = $("#GracePunchOut").val(); this.ActualHr = $("#ActualHourPunchOut").val(); this.ActualMin = $("#ActualMinute").val(); this.DrpActualOut = $("#ddlout").val(); this.EntryType = 2; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.OutId.toString().length > 0) { if (this.EntryType < 3) { if (this.DrpActualOut == "PM") { if (parseInt(this.ActualHr) <= 12) { } else { this.ActualHr += 12; } this.ActualHr; } else { this.ActualHr; } this.ActualHr = this.ActualHr + ":" + this.ActualMin; } this._AttendanceReportService.ApproveAttendancePunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.OutId, this.EntryType, this.HODRemarks, this.strDate, this.Temp, this.Grace, this.ActualHr) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }) } else { this._AttendanceReportService.GetDailyEntryTime(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(data => { this.indLoading = false; this.EmployeeDailyTime = data; let Datetime = new Date(this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { let Time = ""; this.EmployeeDailyTime = data; if (this.EntryType == 1) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Mon_Fri; }) } } else if (this.EntryType = 2) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Mon_Fri; }) } } else { Time = ""; } this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; this.EntryType = 2; this._AttendanceReportService.AddEmployeeAttendancePunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.EntryType, this.HODRemarks, this.Temp, this.strDate, this.ActualHr, this.Grace) .subscribe(success => { this.indLoading = false; }, error => { this.msg = error }); } }, error => { this.msg = error; }) } } } AttendanceRejectPunchOut(): void { this.EntryType = 2; this.HODRemarks = $("#HODRemarksPunchOut").val(); this._AttendanceReportService.AttendanceRejectPunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.Id, this.EntryType, this.AttendanceDate, this.HODRemarks, this.OutId) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } ApproveAttendanceOkPunchOut(): void { let Remarks = $("#ApprovalRemarksOut").val(); this._AttendanceReportService.ApproveAttendanceOkPunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.OutId, Remarks) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } //----Lunch-Out Attendance Approve ApproveAttendanceLunchOut(): void { this.EntryHr = $("#EntryHrLunchOut").val(); this.EntryMin = $("#EntryMinuteLunchOut").val(); this.DRPAM_PM = $("#ddlLunchOut").val(); this.HODRemarks = $("#RemarksLunchOut").val(); this.EntryType = 3; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.LunchOutId.toString().length > 0) { this._AttendanceReportService.ApproveAttendanceLunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.LunchOutId, this.HODRemarks, this.Temp) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } else { this.strDate = this.AttendanceDate; this._AttendanceReportService.GetDailyEntryTime(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(data => { this.indLoading = false; this.EmployeeDailyTime = data; let Datetime = new Date(this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { let Time = ""; this.EmployeeDailyTime = data; if (this.EntryType == 1) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Mon_Fri; }) } } else if (this.EntryType = 2) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Mon_Fri; }) } } else { Time = ""; } this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; this.EntryType = 3; this._AttendanceReportService.AddEmployeeAttendanceLunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.EntryType, this.HODRemarks, this.Temp, this.strDate, Time) .subscribe(success => { this.indLoading = false; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } } } AttendanceRejectLunchOut(): void { this.EntryType = 3; this.strDate = this.AttendanceDate; this.HODRemarks = $("#RemarksLunchOut").val(); this._AttendanceReportService.AttendanceRejectLunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.LunchOutId, this.Employee_Id, this.EntryType, this.strDate, this.HODRemarks) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } ApproveAttendanceOkLunchOut(): void { let Remarks = $("#ApprovalRemarksLunchOut").val(); this._AttendanceReportService.ApproveAttendanceOkLunchOut(Global.BASE_AttendanceReport_ENDPOINT, this.LunchOutId, Remarks) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } //----Lunch-In Attendance Approve ApproveAttendanceLunchIn(): void { this.EntryHr = $("#EntryHourLunchIn").val(); this.EntryMin = $("#EntryMinuteLunchIn").val(); this.HODRemarks = $("#RemarksLunchIn").val(); this.DRPAM_PM = $("#ddlLunchIn").val(); this.EntryType = 4; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.LunchInId.toString().length > 0) { this._AttendanceReportService.ApproveAttendanceLunchIn(Global.BASE_AttendanceReport_ENDPOINT, this.LunchInId, this.HODRemarks, this.Temp) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }) } else { this.strDate = this.AttendanceDate; this._AttendanceReportService.GetDailyEntryTime(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.strDate) .subscribe(data => { this.indLoading = false; this.EmployeeDailyTime = data; let Datetime = new Date(this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { let Time = ""; this.EmployeeDailyTime = data; if (this.EntryType == 1) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Mon_Fri; }) } } else if (this.EntryType = 2) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Mon_Fri; }) } } else { Time = ""; } this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; this.EntryType = 4; this._AttendanceReportService.AddEmployeeAttendanceLunchIn(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.EntryType, this.HODRemarks, this.Temp, this.strDate, Time) .subscribe(success => { this.indLoading = false; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } } } AttendanceRejectLunchIn(): void { this.EntryType = 4; this.HODRemarks = $("#RemarksLunchIn").val(); this._AttendanceReportService.AttendanceRejectLunchIn(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.LunchInId, this.EntryType, this.AttendanceDate, this.HODRemarks) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } ApproveAttendanceOkLunchIn(): void { let Remarks = $("#approvalRemarkslunchin").val(); this._AttendanceReportService.ApproveAttendanceOkLunchIn(Global.BASE_AttendanceReport_ENDPOINT, this.LunchInId, Remarks) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } //-----Other In Attendance Approve ApproveAttendanceOther(): void { this.EntryHr = $("#EntryHrother").val(); this.EntryMin = $("#EntryMinother").val(); this.DRPAM_PM = $("#ddlotherin").val(); this.HODRemarks = $("#Remarksother").val(); this.EntryType = 6; if ((parseInt(this.EntryHr.toString()) < 12) && (parseInt(this.EntryMin.toString()) < 60)) { this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; if (this.OtherId.toString().length > 0) { this._AttendanceReportService.ApproveAttendanceOther(Global.BASE_AttendanceReport_ENDPOINT, this.OtherId, this.HODRemarks, this.Temp) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }) } else { this._AttendanceReportService.GetEmployeeIsNotHostEmployee(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id) .subscribe(data => { this.indLoading = false; this.EmployeeDailyTime = data; let Datetime = new Date(this.strDate); var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var weekday = weekdays[Datetime.getDay()]; if (data != "") { let Time = ""; this.EmployeeDailyTime = data; if (this.EntryType == 1) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.In_Mon_Fri; }) } } else if (this.EntryType = 2) { if (weekday == "Saturday") { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Sat; }) } else { this.EmployeeDailyTime.forEach((data) => { Time = data.Out_Mon_Fri; }) } } else { Time = ""; } this.strDate = this.AttendanceDate; this.strarrdate = this.strDate.split("/"); this.Temp = this.strarrdate[2] + this.strarrdate[1] + this.strarrdate[0] + " " + this.EntryHr + ":" + this.EntryMin + ":00" + " " + this.DRPAM_PM; this.EntryType = 6; this._AttendanceReportService.AddEmployeeAttendanceOtherwork(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.EntryType, this.HODRemarks, this.Temp, this.strDate, Time) .subscribe(success => { this.indLoading = false; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } } } AttendanceRejectOther(): void { this.EntryType = 6; this.HODRemarks = $("#Remarksother").val(); this._AttendanceReportService.AttendanceRejectOtherWork(Global.BASE_AttendanceReport_ENDPOINT, this.Employee_Id, this.OtherId, this.EntryType, this.AttendanceDate, this.HODRemarks) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } ApproveAttendanceOkOtherWork(): void { let Remarks = $("#approvalRemarksother").val(); this._AttendanceReportService.ApproveAttendanceOkOtherWorkIn(Global.BASE_AttendanceReport_ENDPOINT, this.OtherId, Remarks) .subscribe(data => { this.indLoading = false; }, error => { this.msg = error; }); } //-------Change Event--------// ChangeDepartData(event): void { this.Id = event.target.value; } ChangeEmpData(event): void { this.Id = event.target.value; let empid = event.target.value; } ChangeCompData(event): void { this.Id = event.target.value; } ChangeLMData(event): void { this.Id = event.target.value; } //-------end drop-down----------// LoadEmployee(): void { this.indLoading = true; this._AttendanceReportService.GetEmployee(Global.BASE_AttendanceReport_ENDPOINT) .subscribe(data => { this.AttendanceEmployee = data; this.indLoading = false; }); } LoadAllEmployee(event): void { this.indLoading = true; this._AttendanceReportService.GetAllEmployee(Global.BASE_AttendanceReport_ENDPOINT) .subscribe(data => { this.AttendanceEmployee = data; this.indLoading = false; }); } LoadDepartment(): void { this.indLoading = true; this._AttendanceReportService.GetDepartment(Global.BASE_AttendanceReport_ENDPOINT) .subscribe(data => { this.AttendanceDepart = data; this.indLoading = false; }); } LoadCompany(): void { this.indLoading = true; this._AttendanceReportService.GetCompany(Global.BASE_AttendanceReport_ENDPOINT) .subscribe(data => { this.AttendanceCompany = data; this.indLoading = false; }); } LoadLineManager(): void { this.indLoading = true; this._AttendanceReportService.GetLineManager(Global.BASE_AttendanceReport_ENDPOINT) .subscribe(data => { this.AttendanceLineManager = data; this.indLoading = false; }); } LoadYear(): void { this.indLoading = true; this._AttendanceReportService.GetYear(Global.BASE_AttendanceReport_ENDPOINT) .subscribe(data => { this.AttendanceYear = data; this.indLoading = false; }); } RedirectToAddEmpRecord(data): void { var d1 = data.Date.split('/'); var datval = d1[1] + '/' + d1[0] + '/' + d1[2]; this.router.navigate(['/AddEmployeeRecord'], { queryParams: { EmployeeId: data.Employee_Id, EmployeeName: data.Employee_Name, Date: datval, EntryTime: data.In_Time, Remarks: data.ImportRemarks} }); } RedirectToRecordPerEmp(data): void { this.router.navigate(['/DailyEntryReport'], { queryParams: { EmployeeId: data.Employee_Id, EmployeeName: data.Employee_Name, Date: data.Date, EntryTime: data.In_Time, Remarks: data.ImportRemarks } }); } Getselectedmon(event): void { this.Rdbmonth = $("#ddlmonth").val(); } Getselectedyear(event): void { this.year = parseInt($("#ddlyear option:selected").text()) } ToogleMyProfile() { $("#AttendanceReport").slideToggle(300); } CloseWidgetProfile() { $("#AttendanceReport").hide(300); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.AttendancebindData); this.pager = this.pagerService.pager; this.pagedItems = null; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ColorChange(data) { if (data.Total_W_Hr < data.TotalWorksheet_Hr) { //if ((data.TotalWorksheet_Hr - data.Total_W_Hr) ) //{ //} } } onSubmit(formData: any) { if ($("#LineManager").prop("checked")) { this.DRPData = $("#ddllm").val(); this.name = "LineManager"; } if ($("#Employee").prop("checked")) { this.DRPData = $("#ddlemp").val(); this.name = "Employee"; } if ($("#Department").prop("checked")) { this.name = "DepartMent"; this.DRPData = 0; } if ($("#Company").prop("checked")) { this.DRPData = $("#ddlcompany").val(); this.name = "Company"; } if ($("#rdbDate").prop("checked")) { this.strDate = $("#txtfromdate").val(); this.ToDate = $("#txttodate").val(); this.RDBDate = "checkedDate"; this.month = 0; this.year = 0; this.Rdbmonth = ""; } if ($("#rdbmonth").prop("checked")) { this.Rdbmonth = "Month"; this.RDBDate = ""; this.month = parseInt($("#ddlmonth").val()); this.year = parseInt($("#ddlyear option:selected").text()); this.strDate = ""; this.ToDate = ""; } var fromdate; var todate; if (this.RDBDate == 'checkedDate') { fromdate = this.strDate; todate = this.ToDate; } if (this.Rdbmonth == 'Month') { if (this.month.toString().length == 1) { fromdate = (this.year).toString().concat('0').toString().concat(this.month.toString()).concat('01').toString(); todate = (this.year).toString().concat('0').toString().concat(this.month.toString()).concat('30').toString(); } else { fromdate = (this.year).toString().concat(this.month.toString()).concat('01').toString(); todate = (this.year).toString().concat(this.month.toString()).concat('30').toString(); } } if (formData.cbMissingEntry == true) { var strEmployeeids = ''; if (this.name == "DepartMent") { this._AttendanceReportService.SelectDepartment(Global.BASE_AttendanceReport_ENDPOINT, formData.ddldept) .subscribe(data => { this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); this._AttendanceReportService.GetMissingEntry(Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(data => { this.indLoading = false; this.AttendancebindData = data; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } else if (this.name == "Company") { this._AttendanceReportService.SelectCompany(Global.BASE_AttendanceReport_ENDPOINT, formData.ddlcompany) .subscribe(data => { this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); this._AttendanceReportService.GetMissingEntry(Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(data => { this.indLoading = false; this.AttendancebindData = data; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } else if (this.name == "LineManager") { this._AttendanceReportService.SelectLineManager(Global.BASE_AttendanceReport_ENDPOINT, formData.ddllm) .subscribe(data => { this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); this._AttendanceReportService.GetMissingEntry(Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(data => { this.indLoading = false; this.AttendancebindData = data; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } } else if (formData.cbDeduction == true) { var strEmployeeids = ''; if (this.name == "DepartMent") { this._AttendanceReportService.SelectDepartment(Global.BASE_AttendanceReport_ENDPOINT, formData.ddldept) .subscribe(data => { this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); this._AttendanceReportService.GetDeductionDetails(Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(data => { this.indLoading = false; this.AttendancebindData = data; }, error => { this.msg = error; }); } }); } else if (this.name == "Company") { this._AttendanceReportService.SelectCompany(Global.BASE_AttendanceReport_ENDPOINT, formData.ddlcompany) .subscribe(data => { this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); this._AttendanceReportService.GetDeductionDetails(Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(data => { this.indLoading = false; this.AttendancebindData = data; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } else if (this.name == "LineManager") { this._AttendanceReportService.SelectLineManager(Global.BASE_AttendanceReport_ENDPOINT, formData.ddllm) .subscribe(data => { this.indLoading = false; if (data != '') { for (var i = 0; i < data.length; i++) { strEmployeeids += data[i].id + ','; } strEmployeeids = strEmployeeids.substring(0, strEmployeeids.length - 1); this._AttendanceReportService.GetDeductionDetails(Global.BASE_AttendanceReport_ENDPOINT, fromdate, todate, strEmployeeids) .subscribe(data => { this.indLoading = false; this.AttendancebindData = data; }, error => { this.msg = error; }); } }, error => { this.msg = error; }); } } else { this._AttendanceReportService.GetBindAttendanceData(Global.BASE_AttendanceReport_ENDPOINT, this.Id, this.strDate, this.ToDate, this.name, this.DRPData, this.RDBDate, this.Rdbmonth, this.month, this.year) .subscribe(success => { this.AttendancebindData = success; this.JumpOnPage(1); }, error => { this.msg = error; }); } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using VIS_Domain.DocCentre; using VIS_Repository.DocCenter; namespace VIS_App.Controllers.DocCentre { public class DocumentTemplateAPIController : BaseAPIController { DocumentTemplateRepository objDocumentTemplateRepository = null; public DocumentTemplateAPIController() { objDocumentTemplateRepository = new DocumentTemplateRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } // Step 1 Related API public HttpResponseMessage GetAllApprovedRecord(int EmployeeId, string EmployeeRole, string ApprovedStatus) { return ToJson(objDocumentTemplateRepository.GetEntityListApproved(EmployeeId,EmployeeRole,ApprovedStatus)); } public HttpResponseMessage GetAllModule() { return ToJson(objDocumentTemplateRepository.GetAllModule()); } public HttpResponseMessage GetById(Int64 Id) { return ToJson(objDocumentTemplateRepository.GetById(Id)); } [HttpPost] public HttpResponseMessage AddNewDocumentTemplate(DocumentTemplateModel entityobject) { return ToJson(objDocumentTemplateRepository.AddDocumentTemplate(entityobject)); } [HttpPut] public HttpResponseMessage UpdateDocumentTemplate(DocumentTemplateModel entityobject) { return ToJson(objDocumentTemplateRepository.UpdateDocumentTemplate(entityobject)); } [HttpDelete] public HttpResponseMessage DeleteDocumentTemplate(Int64 Id) { return ToJson(objDocumentTemplateRepository.ActiveInActiveDocumentTemplate(Id)); } // Step 2 Related API [HttpPost] public HttpResponseMessage AddDocumentField(DocMasterFieldDataContract entityobject) { return ToJson(objDocumentTemplateRepository.AddDocumentField(entityobject)); } [HttpPut] public HttpResponseMessage UpdateDocumentField(DocMasterFieldDataContract entityobject) { return ToJson(objDocumentTemplateRepository.UpdateDocumentField(entityobject)); } [HttpDelete] public HttpResponseMessage DeleteDocumentField(Int64 Id,Int64 UpdatedBy) { return ToJson(objDocumentTemplateRepository.DeleteDocumentField(Id,UpdatedBy)); } [HttpGet] public HttpResponseMessage GetAllDocumenetFieldByDocId(Int64 DocTempId) { return ToJson(objDocumentTemplateRepository.GetByDocTemplateId(DocTempId)); } [HttpGet] public HttpResponseMessage GetAllDocumenetFieldById(Int64 Id) { return ToJson(objDocumentTemplateRepository.GetByFieldId(Id)); } [HttpGet] public HttpResponseMessage GetDocTemplateMaxId() { return ToJson(objDocumentTemplateRepository.GetMaxDocTempId()); } [HttpPost] public HttpResponseMessage UploadImage() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/Upload/DocumentCenter/DocumentTemplateImages/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } [HttpGet] public HttpResponseMessage BindTableFieldDropDown(string TableName) { return ToJson(objDocumentTemplateRepository.BindTableFieldDropdown(TableName)); } [HttpGet] public HttpResponseMessage BindCustomFieldDropDown(Int64 DocTempId) { return ToJson(objDocumentTemplateRepository.BindCustomFieldDropdown(DocTempId)); } // Step 3 Related API [HttpPost] public HttpResponseMessage AddDocumentContainerField(List<DocMasterFieldDataContract> entitylist) { return ToJson(objDocumentTemplateRepository.AddDocumentContainerField(entitylist)); } [HttpPost] public HttpResponseMessage AddDocumentMasterField(List<DocMasterFieldDataContract> entitylist) { return ToJson(objDocumentTemplateRepository.AddDocumentMasterField(entitylist)); } [HttpGet] public HttpResponseMessage BindDocumentContainer(Int64 DocTempId) { return ToJson(objDocumentTemplateRepository.BindDocumentContainer(DocTempId)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Notification { public class News : VISBaseEntity { /// <summary> /// News Entity Fields. /// </summary> public string News_Name { get; set; } public string Description { get; set; } public bool IsNew { get; set; } } public static class NewsConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_News = "News"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_News_Name = "News_Name"; public const string const_Field_Description = "Description"; public const string const_Field_IsNew = "IsNew"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procNews_Add = "procNews_Add"; public const string const_procNews_Update = "procNews_Update"; public const string const_procNews_ActiveInActive = "procNews_ActiveInActive"; public const string const_procNews_SelectAll = "procNews_SelectAll"; public const string const_procNews_SelectById = "procNews_SelectById"; public const string const_procNews_View = "procNews_View"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Reports; using VIS_Repository; using VIS_Repository.Reports; using System.Configuration; using VIS_Domain.Reports.Attendance; using VIS_Repository.Reports.Attendance; namespace VIS_App.Controllers.Report.Attendance { public class AttendanceReportAPIController : BaseAPIController { Reports_AttendanceRepository objReports_AttendanceRepository = null; public AttendanceReportAPIController() { objReports_AttendanceRepository = new Reports_AttendanceRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/AttendanceReportAPI/GetBindAttendanceData")] [HttpGet] public HttpResponseMessage GetBindAttendanceData(int Id, string strDate, string ToDate, string name, int DRPData, string rdbDate, string Rdbmonth, int month, int year) { return ToJson(objReports_AttendanceRepository.GetBindAttendanceData(Id, strDate, ToDate, name, DRPData, rdbDate, Rdbmonth, month, year)); } [Route("api/AttendanceReportAPI/GetDepartment")] [HttpGet] public HttpResponseMessage GetDepartment() { return ToJson(objReports_AttendanceRepository.GetDepartment()); } [Route("api/AttendanceReportAPI/GetEmployee")] [HttpGet] public HttpResponseMessage GetEmployee() { return ToJson(objReports_AttendanceRepository.GetEmployee()); } [Route("api/AttendanceReportAPI/GetAllEmployee")] [HttpGet] public HttpResponseMessage GetAllEmployee() { return ToJson(objReports_AttendanceRepository.GetAllEmployee()); } [Route("api/AttendanceReportAPI/GetCompany")] [HttpGet] public HttpResponseMessage GetCompany() { return ToJson(objReports_AttendanceRepository.GetCompany()); } [Route("api/AttendanceReportAPI/GetLineManager")] [HttpGet] public HttpResponseMessage GetLineManager() { return ToJson(objReports_AttendanceRepository.GetLineManager()); } [Route("api/AttendanceReportAPI/GetYear")] [HttpGet] public HttpResponseMessage GetYear() { return ToJson(objReports_AttendanceRepository.GetEntityYear()); } [Route("api/AttendanceReportAPI/GetMissingEntry")] [HttpGet] public HttpResponseMessage GetMissingEntry(string fromdate, string todate, string Employeeids) { return ToJson(objReports_AttendanceRepository.GetMissingEntry(fromdate,todate, Employeeids)); } [Route("api/AttendanceReportAPI/GetDeductionDetails")] [HttpGet] public HttpResponseMessage GetDeductionDetails(string fromdate,string todate,string Employeeids) { return ToJson(objReports_AttendanceRepository.GetDeductionDetails(fromdate,todate,Employeeids)); } [Route("api/AttendanceReportAPI/SelectDepartment")] [HttpGet] public HttpResponseMessage SelectDepartment(string Department) { return ToJson(objReports_AttendanceRepository.SelectDepartment(Department)); } [Route("api/AttendanceReportAPI/SelectCompany")] [HttpGet] public HttpResponseMessage SelectCompany(string Company) { return ToJson(objReports_AttendanceRepository.SelectCompany(Company)); } [Route("api/AttendanceReportAPI/SelectLineManager")] [HttpGet] public HttpResponseMessage SelectLineManager(string LineManager) { return ToJson(objReports_AttendanceRepository.SelectLineManager(LineManager)); } [Route("api/AttendanceReportAPI/GetDepartmentEmployee")] [HttpGet] public HttpResponseMessage GetDepartmentEmployee(int Id) { return ToJson(objReports_AttendanceRepository.GetDepartmentEmployee(Id)); } [Route("api/AttendanceReportAPI/GetCheckedData")] //---Checkbox checked value Get from Server side. [HttpGet] public HttpResponseMessage GetCheckedData(string name, string DRPData) { return ToJson(objReports_AttendanceRepository.GetcheckedData(name, DRPData)); } //---Attendance Approve Punch In API [Route("api/AttendanceReportAPI/AttendanceApproval")] [HttpGet] public HttpResponseMessage AttendanceApproval(int InId, int EntryType, string Remarks, string Date, string Time, int Grace, string ActualHrs) { return ToJson(objReports_AttendanceRepository.UpdateEntity(InId, EntryType, Remarks, Date, Time, Grace, ActualHrs)); } [Route("api/AttendanceReportAPI/GetDailyEntryTime")] [HttpGet] public HttpResponseMessage GetDailyEntryTime(int Employee_Id, string Date) { return ToJson(objReports_AttendanceRepository.GetDailyEntryTime(Employee_Id, Date)); } [Route("api/AttendanceReportAPI/AttendanceApproveAdd")] [HttpGet] public HttpResponseMessage AttendanceApproveAdd(int Id, int Employee_Id, int EntryType, string HODRemarks, string Temp, string strDate, string Time, int Grace) { return ToJson(objReports_AttendanceRepository.AddEntity(Id, Employee_Id, EntryType, HODRemarks, Temp, strDate, Time, Grace)); } [Route("api/AttendanceReportAPI/AttendanceRejectPunchIn")] [HttpGet] public HttpResponseMessage AttendanceRejectPunchIn(int Employee_Id, int EntryType, string Date, string RemarksIn, int InId) { return ToJson(objReports_AttendanceRepository.AttendanceRejectPunchIn(Employee_Id, EntryType, Date, RemarksIn, InId)); } [Route("api/AttendanceReportAPI/ApproveAttendanceOkIn")] [HttpGet] public HttpResponseMessage ApproveAttendanceOkIn(int InId, string Remarks) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceOkIn(InId, Remarks)); } //---Attendance Approve Punch Out API [Route("api/AttendanceReportAPI/ApproveAttendancePunchOut")] [HttpGet] public HttpResponseMessage ApproveAttendancePunchOut(int OutId, int EntryType, string Remarks, string Date, string Time, int Grace, string ActualHrs) { return ToJson(objReports_AttendanceRepository.ApproveAttendancePunchOut(OutId, EntryType, Remarks, Date, Time, Grace, ActualHrs)); } [Route("api/AttendanceReportAPI/AddEmployeeAttendancePunchOut")] [HttpGet] public HttpResponseMessage AddEmployeeAttendancePunchOut(int Employee_Id, int EntryType, string HODRemarks, string Temp, string strDate, string Time, int Grace) { return ToJson(objReports_AttendanceRepository.AddEmployeeAttendancePunchOut(Employee_Id, EntryType, HODRemarks, Temp, strDate, Time, Grace)); } [Route("api/AttendanceReportAPI/AttendanceRejectPunchOut")] [HttpGet] public HttpResponseMessage AttendanceRejectPunchOut(int Employee_Id, int EntryType, string Date, string HODRemarks, int OutId) { return ToJson(objReports_AttendanceRepository.AttendanceRejectPunchOut(Employee_Id, EntryType, Date, HODRemarks, OutId)); } [Route("api/AttendanceReportAPI/ApproveAttendanceOkPunchOut")] [HttpGet] public HttpResponseMessage ApproveAttendanceOkPunchOut(int OutId, string Remarks) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceOkPunchOut(OutId, Remarks)); } //---Attendance Approve Lunch Out API [Route("api/AttendanceReportAPI/ApproveAttendanceLunchOut")] [HttpGet] public HttpResponseMessage ApproveAttendanceLunchOut(int LunchOutId, string Remarks, string Time) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceLunchOut(LunchOutId, Remarks, Time)); } [Route("api/AttendanceReportAPI/AddEmployeeAttendanceLunchOut")] [HttpGet] public HttpResponseMessage AddEmployeeAttendanceLunchOut(int Employee_Id, int EntryType, string Remarks, string Temp, string Date, string Time) { return ToJson(objReports_AttendanceRepository.AddEmployeeAttendanceLunchOut(Employee_Id, EntryType, Remarks, Temp, Date, Time)); } [Route("api/AttendanceReportAPI/AttendanceRejectLunchOut")] [HttpGet] public HttpResponseMessage AttendanceRejectLunchOut(int LunchOutId, int Employee_Id, int EntryType, string Date, string HODRemarks) { return ToJson(objReports_AttendanceRepository.AttendanceRejectLunchOut(LunchOutId, Employee_Id, EntryType, Date, HODRemarks)); } [Route("api/AttendanceReportAPI/ApproveAttendanceOkLunchOut")] [HttpGet] public HttpResponseMessage ApproveAttendanceOkLunchOut(int LunchOutId, string Remarks) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceOkLunchOut(LunchOutId, Remarks)); } [Route("api/AttendanceReportAPI/ApproveAttendanceLunchIn")] [HttpGet] public HttpResponseMessage ApproveAttendanceLunchIn(int LunchInId, string Remarks, string Time) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceLunchIn(LunchInId, Remarks,Time)); } [Route("api/AttendanceReportAPI/AddEmployeeAttendanceLunchIn")] [HttpGet] public HttpResponseMessage AddEmployeeAttendanceLunchIn(int Employee_Id, int EntryType, string Remarks, string Temp, string Date, string Time) { return ToJson(objReports_AttendanceRepository.AddEmployeeAttendanceLunchIn(Employee_Id, EntryType, Remarks, Temp, Date, Time)); } [Route("api/AttendanceReportAPI/AttendanceRejectLunchIn")] [HttpGet] public HttpResponseMessage AttendanceRejectLunchIn(int Employee_Id, int LunchInId, int EntryType, string Date, string HODRemarks) { return ToJson(objReports_AttendanceRepository.AttendanceRejectLunchIn(Employee_Id, LunchInId, EntryType, Date, HODRemarks)); } [Route("api/AttendanceReportAPI/ApproveAttendanceOkLunchIn")] [HttpGet] public HttpResponseMessage ApproveAttendanceOkLunchIn(int LunchInId,string Remarks) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceOkLunchIn(LunchInId,Remarks)); } //---Attendance Approve Other API [Route("api/AttendanceReportAPI/ApproveAttendanceOther")] [HttpGet] public HttpResponseMessage ApproveAttendanceOther(int OtherId, string Remarks,string Time) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceOther(OtherId, Remarks,Time)); } [Route("api/AttendanceReportAPI/GetEmployeeIsNotHostEmployee")] [HttpGet] public HttpResponseMessage GetEmployeeIsNotHostEmployee(int Employee_Id) { return ToJson(objReports_AttendanceRepository.GetEmployeeIsNotHostEmployee(Employee_Id)); } [Route("api/AttendanceReportAPI/AddEmployeeAttendanceOtherwork")] [HttpGet] public HttpResponseMessage AddEmployeeAttendanceOtherwork(int Employee_Id,int EntryType,string HODRemarks,string Temp,string Date,string Time) { return ToJson(objReports_AttendanceRepository.AddEmployeeAttendanceOtherwork(Employee_Id,EntryType,HODRemarks,Temp,Date,Time)); } [Route("api/AttendanceReportAPI/AttendanceRejectOtherWork")] [HttpGet] public HttpResponseMessage AttendanceRejectOtherWork(int Employee_Id, int OtherId,int EntryType,string Date,string HODRemarks) { return ToJson(objReports_AttendanceRepository.AttendanceRejectOtherWork(Employee_Id, OtherId,EntryType,Date,HODRemarks)); } [Route("api/AttendanceReportAPI/ApproveAttendanceOkOtherWorkIn")] [HttpGet] public HttpResponseMessage ApproveAttendanceOkOtherWorkIn(int OtherId,string Remarks) { return ToJson(objReports_AttendanceRepository.ApproveAttendanceOkOtherWorkIn(OtherId,Remarks)); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var MacIdConfiguration_service_1 = require("../../../service/Masters/Configuration/MacIdConfiguration.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var pager_index_1 = require("../../../Shared/pager.index"); var MacIdConfigurationComponent = (function () { function MacIdConfigurationComponent(fb, _MacIdConfigurationService, pagerService, _CommonHelperService) { this.fb = fb; this._MacIdConfigurationService = _MacIdConfigurationService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.indLoading = false; this.isDesc = false; this.column = 'Employee_Name'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; } MacIdConfigurationComponent.prototype.ResetModel = function () { this.macidconfiguration = { Active: false, ApprovalDate: null, ApprovedBy: '', CreatedBy: '', CreatedOn: null, Description: '', EmployeeId: 0, Employee_Name: '', Id: 0, IP1: '', IP2: '', IP3: '', IP4: '', IPAddress: '', IsActive: false, MacID: '', MacID1: '', MacID2: '', MacID3: '', MacID4: '', MacID5: '', MacID6: '', OfficeMacId: false, RequestedDate: null, UpdatedBy: '', UpdatedOn: null, Version: '', Version1: '', Version2: '', Version3: '' }; }; MacIdConfigurationComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.ResetModel(); this.LoadMacIdConfiguration(); this.LoadEmployees(); this.InputNavigator(); }; MacIdConfigurationComponent.prototype.MacIdConfigurationFilterCriteriaChange = function (value) { if (value != '[object Event]') this.MacIdConfigurationFilter = value; }; MacIdConfigurationComponent.prototype.MackIdConfigurationSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; MacIdConfigurationComponent.prototype.GetActiveRecord = function () { if ($("#rbtactive").prop("checked")) { this.macidconfigurations = this.macidconfigurationsbackup; this.macidconfigurations = this.macidconfigurations.filter(function (x) { return x.Active === true; }); this.JumpOnPage(1); } else if ($("#rbtinactive").prop("checked")) { this.macidconfigurations = this.macidconfigurationsbackup; this.macidconfigurations = this.macidconfigurations.filter(function (x) { return x.Active === false; }); this.JumpOnPage(1); } else { this.macidconfigurations = this.macidconfigurationsbackup; this.isDesc = true; this.MackIdConfigurationSort("Active"); this.JumpOnPage(1); } }; MacIdConfigurationComponent.prototype.LoadMacIdConfiguration = function () { var _this = this; this.indLoading = true; this._MacIdConfigurationService.get(global_1.Global.BASE_MACIDCONFIGURATION_ENDPOINT) .subscribe(function (macidconfigurations) { _this.macidconfigurations = macidconfigurations; _this.macidconfigurationsbackup = macidconfigurations; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchEmployee_Name = document.getElementById("searchEmployee_Name").value; if (_this.strSearchEmployee_Name != '') { _this.strSearchEmployee_Name = _this.strSearchEmployee_Name.toLocaleLowerCase(); _this.macidconfigurations = _this.macidconfigurations.filter(function (x) { return x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(_this.strSearchEmployee_Name) != -1; }); } _this.strSearchMacID = document.getElementById("searchMacID").value; if (_this.strSearchMacID != '') { _this.strSearchMacID = _this.strSearchMacID.toLocaleLowerCase(); _this.macidconfigurations = _this.macidconfigurations.filter(function (x) { return x.MacID != null && x.MacID.toLocaleLowerCase().indexOf(_this.strSearchMacID) != -1; }); } _this.strSearchIPAddress = document.getElementById("searchIPAddress").value; if (_this.strSearchIPAddress != '') { _this.strSearchIPAddress = _this.strSearchIPAddress.toLocaleLowerCase(); _this.macidconfigurations = _this.macidconfigurations.filter(function (x) { return x.IPAddress != null && x.IPAddress.toLocaleLowerCase().indexOf(_this.strSearchIPAddress) != -1; }); } _this.strSearchVersion = document.getElementById("searchVersion").value; if (_this.strSearchVersion != '') { _this.strSearchVersion = _this.strSearchVersion.toLocaleLowerCase(); _this.macidconfigurations = _this.macidconfigurations.filter(function (x) { return x.Version != null && x.Version.toLocaleLowerCase().indexOf(_this.strSearchVersion) != -1; }); } } //Logic for searching - End _this.indLoading = false; _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; MacIdConfigurationComponent.prototype.LoadEmployees = function () { var _this = this; this.indLoading = true; this._MacIdConfigurationService.getallemployee(global_1.Global.BASE_MACIDCONFIGURATION_ENDPOINT) .subscribe(function (employee) { _this.employees = employee; _this.indLoading = false; } //,error => this.msg = <any>error ); }; MacIdConfigurationComponent.prototype.AddMackId = function () { this.dbops = enum_1.DBOperation.create; this.modalTitle = "Add New MackId"; this.modalBtnTitle = "Add"; this.ResetModel(); this.modal.open(); }; MacIdConfigurationComponent.prototype.EditMackId = function (id) { this.dbops = enum_1.DBOperation.update; this.modalTitle = "Edit MackId"; this.modalBtnTitle = "Update"; this.macidconfiguration = this.macidconfigurations.filter(function (x) { return x.Id == id; })[0]; this.modal.open(); }; MacIdConfigurationComponent.prototype.DeleteMacId = function (id, status) { this.dbops = enum_1.DBOperation.delete; var confimation = confirm("Are you sure ?"); if (confimation == true) { this.macidconfiguration.Id = id; this.onSubmit(this.macidconfiguration); } }; MacIdConfigurationComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.MacIdConfigurationFrm.enable() : this.MacIdConfigurationFrm.disable(); }; MacIdConfigurationComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; MacIdConfigurationComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.macidconfigurations); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; MacIdConfigurationComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; MacIdConfigurationComponent.prototype.onSubmit = function (formData) { var _this = this; Number(formData.ApprovedBy = '21'); formData.MacID = formData.MacID1 + '-' + formData.MacID2 + '-' + formData.MacID3 + '-' + formData.MacID4 + '-' + formData.MacID5 + '-' + formData.MacID6; formData.IPAddress = formData.IP1 + '.' + formData.IP2 + '.' + formData.IP3 + '.' + formData.IP4; formData.Version = formData.Version1 + '.' + formData.Version2 + '.' + formData.Version3; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._MacIdConfigurationService.post(global_1.Global.BASE_MACIDCONFIGURATION_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadMacIdConfiguration(); } else { alert(data); } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._MacIdConfigurationService.put(global_1.Global.BASE_MACIDCONFIGURATION_ENDPOINT, formData.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadMacIdConfiguration(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._MacIdConfigurationService.delete(global_1.Global.BASE_MACIDCONFIGURATION_ENDPOINT, formData.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "MackId status changed successfully."; _this.LoadMacIdConfiguration(); } else { _this.msg = "Error has occurred while changing status of existing MackId!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; MacIdConfigurationComponent.prototype.InputNavigator = function () { $(function () { $("#MacID1").keyup(function () { if ($("#MacID1").val().length == 2) { $("#MacID2").focus(); } }); $("#MacID2").keyup(function () { if ($("#MacID2").val().length == 2) { $("#MacID3").focus(); } }); $("#MacID3").keyup(function () { if ($("#MacID3").val().length == 2) { $("#MacID4").focus(); } }); $("#MacID4").keyup(function () { if ($("#MacID4").val().length == 2) { $("#MacID5").focus(); } }); $("#MacID5").keyup(function () { if ($("#MacID5").val().length == 2) { $("#MacID6").focus(); } }); $("#MacID6").keyup(function () { if ($("#MacID6").val().length == 2) { $("#IP1").focus(); } }); $("#IP1").keyup(function () { if ($("#IP1").val().length == 3) { $("#IP2").focus(); } }); $("#IP2").keyup(function () { if ($("#IP2").val().length == 3) { $("#IP3").focus(); } }); $("#IP3").keyup(function () { if ($("#IP3").val().length == 3) { $("#IP4").focus(); } }); $("#IP4").keyup(function () { if ($("#IP4").val().length == 3) { $("#Version1").focus(); } }); $("#Version1").keyup(function () { if ($("#Version1").val().length == 1) { $("#Version2").focus(); } }); $("#Version2").keyup(function () { if ($("#Version2").val().length == 1) { $("#Version3").focus(); } }); }); }; MacIdConfigurationComponent.prototype.ActivateDeactivateStatus = function (Id) { var _this = this; this._MacIdConfigurationService.activatedeactivatestatus(global_1.Global.BASE_MACIDCONFIGURATION_ENDPOINT, Id) .subscribe(function (data) { _this.LoadMacIdConfiguration(); _this.GetActiveRecord(); }, function (error) { _this.msg = error; } //,error => this.msg = <any>error ); }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], MacIdConfigurationComponent.prototype, "modal", void 0); MacIdConfigurationComponent = __decorate([ core_1.Component({ providers: [MacIdConfiguration_service_1.MacIdConfigurationService], templateUrl: 'app/Components/Masters/Configuration/MacIdConfiguration.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, MacIdConfiguration_service_1.MacIdConfigurationService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], MacIdConfigurationComponent); return MacIdConfigurationComponent; }()); exports.MacIdConfigurationComponent = MacIdConfigurationComponent; <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { ITechnologyMaster } from '../../../Model/Masters/VacancyRelated/TechnologyMaster'; @Pipe({ name: 'TechnologyMasterFilter' }) export class TechnologyMasterFilterPipe implements PipeTransform { transform(value: ITechnologyMaster[], filter: string): ITechnologyMaster[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: ITechnologyMaster) => app.TechnologyName != null && app.TechnologyName.toLocaleLowerCase().indexOf(filter) != -1 || app.Remarks != null && app.Remarks.toLocaleLowerCase().indexOf(filter) != -1 //|| app.Major != null && app.Major.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } /* 1. In the first line, we are importing the PipeTransform and Pipe interfaces that we are implementing to achieve filtering functionality. 2. In the second line, we are importing the ITechnologyMaster interface that we created in first part to hold the list of technologyMasters. Over here, we are also using it to hold the list of technologyMasters that is the source data for filtering. 3. In next line, we are specifying the pipe selector/name technologyMasterFilter through which we will use the pipe (you will find in future steps, how). 4. Next, we are creating the TechnologyMasterFilterPipe class that is implementing the PipeTransform interface (implementing interface means providing the body to all methods mentioned in the interface). 5. Right click on PipeTransform and select the option Go To Definition: 6. You will be landed to the pipe_transform_d.ts file where you will find the nice brief description how to use the pipe with an example and transform method that we must need to implement: 7. So let’s go back to technologyMaster.pipe.ts where can see we have transform method with first argument as ITechnologyMaster array and second is named as filter that is the input string to be searched in the ITechnologyMaster array. 8. In transform method, the first line is only to check if the filter is not null. 9. The next statement is the actual implementation of search, if you are C# developer, you can compare it to the LINQ to Object. We are calling Array’s filter method, checking through conditional operator that if any of ITechnologyMaster member is matching with technologyMaster input search string and if YES, returning the filtered result. toLocaleLowerCase method is converting string to lower case, to read more about it, click here. If there is no matching record in User list, we are returning the all rows.Now that we have our filter ready, let’s add it to */<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class Lookup : VISBaseEntity { /// <summary> /// Lookup Entity Fields. /// </summary> /// public string Name { get; set; } public string Type { get; set; } public decimal Value { get; set; } public string FullName { get; set; } public string ColorCode { get; set; } public string Country { get; set; } } public static class LookupConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_lookup_Table = "lookup"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Name = "Name"; public const string const_Type = "Type"; public const string const_sName = "sName"; public const string const_sType = "sType"; public const string const_Value = "Value"; public const string const_FullName = "FullName"; public const string const_ColorCode = "ColorCode"; public const string const_Country = "Country"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_proclookup_Add = "proclookup_Add"; public const string const_proclookup_Update = "proclookup_Update"; public const string const_proclookup_ActiveInActive = "proclookup_ActiveInActive"; public const string const_proclookup_SelectAll = "proclookup_SelectAll"; public const string const_proclookup_SelectById = "proclookup_SelectById"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var EventCountDown_service_1 = require("../../../service/Masters/Configuration/EventCountDown.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var EventCountDownComponent = (function () { //Vaiable for For Loop No of Day //noday: number[] = new Array(200) function EventCountDownComponent(fb, _EventCountDownService, pagerService, _CommonHelperService) { this.fb = fb; this._EventCountDownService = _EventCountDownService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.indLoading = false; this.isDesc = false; this.column = 'EventName'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; } EventCountDownComponent.prototype.Resetmodel = function () { this.eventcountdown = { Active: false, CountDownDate: '', CountDownDateTime: null, CountDownText: '', CountDownTime: '0', CreatedBy: '', CreatedOn: null, EventName: '', Id: 0, IsActive: false, NoOfDay: 0, UpdatedBy: '', UpdatedOn: null, CompanyId: 0, EntityMessage: '' }; }; EventCountDownComponent.prototype.ngOnInit = function () { //for (var i = 1; i < this.noday.length ; i++) //{ // //this.noday.push(i); //} this._CommonHelperService.ToogleMenu(); this.EventCountDownFrm = this.fb.group({ Id: [''], EventName: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(100)])], CountDownText: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(100)])], CountDownDate: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(100)])], CountDownTime: ['', forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(3), forms_1.Validators.maxLength(100)])], CountDownDateTime: [''], NoOfDay: [0, forms_1.Validators.compose([forms_1.Validators.required, forms_1.Validators.minLength(1), forms_1.Validators.maxLength(100)])], Active: [''], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], CompanyId: [''], EntityMessage: [''] }); this.LoadEventCountDown(); }; EventCountDownComponent.prototype.EventCountDownFilterCriteriaChange = function (value) { if (value != '[object Event]') this.EventCountDownFilter = value; }; EventCountDownComponent.prototype.EventCountDownSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; EventCountDownComponent.prototype.LoadEventCountDown = function () { var _this = this; this.indLoading = true; this._EventCountDownService.get(global_1.Global.BASE_EVENTCOUNTDOWN_ENDPOINT) .subscribe(function (eventcountdown) { _this.eventcountdowns = eventcountdown; //Logic for searching - start if (_this.ShowHideSearch) { _this.strEventName = document.getElementById("searchEventName").value; if (_this.strEventName != '') { _this.strEventName = _this.strEventName.toLocaleLowerCase(); _this.eventcountdowns = _this.eventcountdowns.filter(function (x) { return x.EventName != null && x.EventName.toLocaleLowerCase().indexOf(_this.strEventName) != -1; }); } _this.strCountDownText = document.getElementById("searchCountDownText").value; if (_this.strCountDownText != '') { _this.strCountDownText = _this.strCountDownText.toLocaleLowerCase(); _this.eventcountdowns = _this.eventcountdowns.filter(function (x) { return x.CountDownText != null && x.CountDownText.toLocaleLowerCase().indexOf(_this.strCountDownText) != -1; }); } } //Logic for searching - End _this.indLoading = false; _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; EventCountDownComponent.prototype.AddEventCountDown = function () { this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Event Count Down"; this.modalBtnTitle = "Add"; this.Resetmodel(); this.EventCountDownFrm.setValue(this.eventcountdown); this.modal.open(); }; EventCountDownComponent.prototype.EditEventCountDown = function (id) { this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Event Count Down"; this.modalBtnTitle = "Update"; this.eventcountdown = this.eventcountdowns.filter(function (x) { return x.Id == id; })[0]; this.eventcountdown.CountDownTime = this.eventcountdown.CountDownDateTime.substr(11, 9); this.eventcountdown.CountDownDate = this.eventcountdown.CountDownDateTime.substr(0, 10); this.EventCountDownFrm.setValue(this.eventcountdown); this.modal.open(); }; EventCountDownComponent.prototype.DeleteEventCountDown = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.eventcountdown = this.eventcountdowns.filter(function (x) { return x.Id == id; })[0]; this.eventcountdown.CountDownTime = this.eventcountdown.CountDownDateTime.substr(11, 9); this.eventcountdown.CountDownDate = this.eventcountdown.CountDownDateTime.substr(0, 10); this.EventCountDownFrm.setValue(this.eventcountdown); this.modal.open(); }; EventCountDownComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.EventCountDownFrm.enable() : this.EventCountDownFrm.disable(); }; EventCountDownComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; EventCountDownComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.eventcountdowns); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; EventCountDownComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; EventCountDownComponent.prototype.onSubmit = function (formData) { var _this = this; //this.eventcountdown.CountDownDateTime = this.eventcountdown.CountDownDate + this.eventcountdown.CountDownTime; console.log(formData); // this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._EventCountDownService.post(global_1.Global.BASE_EVENTCOUNTDOWN_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadEventCountDown(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._EventCountDownService.put(global_1.Global.BASE_EVENTCOUNTDOWN_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadEventCountDown(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._EventCountDownService.delete(global_1.Global.BASE_EVENTCOUNTDOWN_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "EventCountDown status changed successfully."; _this.LoadEventCountDown(); } else { _this.msg = "Error has occurred while changing status of existing EventCountDown!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], EventCountDownComponent.prototype, "modal", void 0); EventCountDownComponent = __decorate([ core_1.Component({ providers: [EventCountDown_service_1.EventCountDownService], templateUrl: 'app/Components/Masters/Configuration/EventCountDown.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, EventCountDown_service_1.EventCountDownService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], EventCountDownComponent); return EventCountDownComponent; }()); exports.EventCountDownComponent = EventCountDownComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace VIS_App.Infrastructure { public class CommonApplicationEnums { public enum ArbManualType { PerformanceBased = 0, Manual = 1 } public enum ArbSubType { Range = 0, Repeated = 1, Once } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { MyProfilesService } from '../../../Service/HumanResource/ProfileAttendance/MyProfiles.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IMyProfiles } from '../../../Model/HumanResource/ProfileAttendance/MyProfiles'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; import { Ng2TabModule } from 'ng2-tab'; @Component({ providers: [MyProfilesService], templateUrl: 'app/Components/HumanResource/ProfileAttendance/MyProfiles.component.html' }) export class MyProfilesComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; MyProfiless: IMyProfiles[]; MyProfiles: IMyProfiles; ViewHistory: IMyProfiles[]; employeeheadlist: IMyProfiles[]; Dropdownlist: IMyProfiles; ViewEducation: IMyProfiles[]; msg: string; indLoading: boolean = false; MyProfilesFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; isDesc: boolean = false; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //other declartion imagePathSignatureOther: string; ImgGlobalPath: string; constructor(private fb: FormBuilder, private _MyProfilesService: MyProfilesService, public http: Http, private router: Router, private pagerService: PagerService, ) { } ngOnInit(): void { this.MyProfilesFrm = this.fb.group({ Mode: [''], UserId: [''], Employee_Name: [''], LineManagerName: [''], FirstName: [''], MiddleName: [''], LastName: [''], Gender: [''], PhotographFileName: [''], CompanyName: [''], Email: [''], JoiningDesignation: [''], DepartmentName: [''], FatherName: [''], MotherName: [''], PermenantAddres: [''], CommunicationAddress: [''], LandlineNumber: [''], MobileNumber: [''], BirthDate: [''], BloodGroup: [''], MaritalStatus: [''], }); this.LoadGetUserProfiles(21); this.LoadEducationDetail(21); this.LoadEmployeeList(); } LoadGetUserProfiles(UserId: number): void { this.ImgGlobalPath = Global.WebAccessURL; this.indLoading = true; this._MyProfilesService.getuserProfile(Global.BASE_MyProfiles_ENDPOINT, UserId) .subscribe(DATADP => { this.ViewHistory = DATADP; this.indLoading = false; } ); } LoadEducationDetail(UserId: number): void { this.indLoading = true; this._MyProfilesService.getEducatinDeatils(Global.BASE_MyProfiles_ENDPOINT, UserId) .subscribe(DATADP => { this.ViewEducation = DATADP; this.indLoading = false; } ); } LoadSelectValue(event) { debugger this.indLoading = true; this.Dropdownlist = this.employeeheadlist.filter(x => x.UserId == event.target.value)[0]; console.log(this.Dropdownlist); this._MyProfilesService.getuserProfile(Global.BASE_MyProfiles_ENDPOINT, this.Dropdownlist.UserId) .subscribe(DATADP => { this.ViewHistory = DATADP; console.log(DATADP); this.indLoading = false; } ); this._MyProfilesService.getEducatinDeatils(Global.BASE_MyProfiles_ENDPOINT, this.Dropdownlist.UserId) .subscribe(DATADP => { this.ViewEducation = DATADP; console.log(DATADP); this.indLoading = false; }); //this.LoadGetUserProfiles(event.traget.value); //this.LoadEducationDetail(event.traget.value); // this.indLoading = false; } LoadEmployeeList() { this.indLoading = true; this._MyProfilesService.getEmployeeList(Global.BASE_MyProfiles_ENDPOINT) .subscribe(data => { this.employeeheadlist = data this.indLoading = false; } ); } onSubmit(formData: any) { } }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { ILevels } from '../../../Model/Masters/EmployeeLevels/levels'; @Pipe({ name: 'levelsFilter' }) export class LevelsFilterPipe implements PipeTransform { transform(value: ILevels[], filter: string): ILevels[] { return filter ? value.filter((app: ILevels) => app.LevelName != null && app.LevelName.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var router_1 = require("@angular/router"); var AddEmployeeRecord_service_1 = require("../../../Service/Report/Attendance/AddEmployeeRecord.service"); var AddEmployeeRecordcomponent = (function () { function AddEmployeeRecordcomponent(fb, _AddEmployeeRecordService, router, pagerService, route) { this.fb = fb; this._AddEmployeeRecordService = _AddEmployeeRecordService; this.router = router; this.pagerService = pagerService; this.route = route; this.indLoading = false; this.CurrentRecordsPerPage = 10; this.pager = {}; } AddEmployeeRecordcomponent.prototype.ngOnInit = function () { this.FillEmployee(); this.EmpId = this.route.snapshot.queryParams["EmployeeId"]; this.Date = this.route.snapshot.queryParams["Date"]; if (this.EmpId != 0 && this.Date != null) { $("#Id").prop("disabled", true); $("#txtDate").prop("disabled", true); } this.BindEmployeeDetails(); this.BindEmployeeAttendance(); this.BindHRAttendanceDetails(); }; AddEmployeeRecordcomponent.prototype.FillEmployee = function () { var _this = this; this._AddEmployeeRecordService.FillEmployee(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT) .subscribe(function (data) { _this.indLoading = false; _this.Employees = data; }, function (error) { _this.msg = error; }); }; AddEmployeeRecordcomponent.prototype.BindEmployeeDetails = function () { var _this = this; this._AddEmployeeRecordService.BindEmployeeDetails(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, this.EmpId, this.Date, 21) .subscribe(function (data) { _this.indLoading = false; _this.EmployeeDailyEntrySheet = data; _this.JumpOnPage(1); }, function (error) { _this.msg = error; }); }; AddEmployeeRecordcomponent.prototype.BindEmployeeAttendance = function () { var _this = this; this._AddEmployeeRecordService.BindEmployeeAttendance(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, this.EmpId, this.Date) .subscribe(function (data) { _this.indLoading = false; _this.EmployeeAttendance = data; }, function (error) { _this.msg = error; }); }; AddEmployeeRecordcomponent.prototype.BindHRAttendanceDetails = function () { var _this = this; this._AddEmployeeRecordService.BindHRAttendanceDetails(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, this.EmpId, this.Date) .subscribe(function (data) { _this.indLoading = false; if (data != '') { _this.HRAttendance = data; _this.HRAttendance.forEach(function (data) { _this.Grade = data.Grade; _this.Grace = data.Grace; _this.InTime = data.HRInTime; _this.OutTime = data.HROutTime; if (_this.Grade == "A1" || _this.Grade == "A2") { _this.Mode = "Flexible"; } else { _this.Mode = "Non-Flexible"; } }); } }, function (error) { _this.msg = error; }); }; AddEmployeeRecordcomponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeDailyEntrySheet); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; AddEmployeeRecordcomponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; AddEmployeeRecordcomponent.prototype.ClearFields = function () { $("#ddltype").empty(); $("#txtHr").val(''); $("#txtMinute").val(''); $("#Remarks").val('<NAME>' + ':'); // Session Storage Login User Name $("#grace").val(''); }; AddEmployeeRecordcomponent.prototype.EditReport = function (EmployeeEntrySheet) { this.EmployeeEntrySheet = EmployeeEntrySheet; var HH = this.EmployeeEntrySheet.Entry_Time; var MM = this.EmployeeEntrySheet.Entry_Time; var AMPM = this.EmployeeEntrySheet.Entry_Time; if (this.EmployeeEntrySheet.Entry_Type == "In Time") { this.EntryType = 1; } else if (this.EmployeeEntrySheet.Entry_Type == "Out Time") { this.EntryType = 2; } else if (this.EmployeeEntrySheet.Entry_Type == "Lunch Out Time") { this.EntryType = 3; } else if (this.EmployeeEntrySheet.Entry_Type == "Lunch In Time") { this.EntryType = 4; } else if (this.EmployeeEntrySheet.Entry_Type == "Other Out Time") { this.EntryType = 5; } else if (this.EmployeeEntrySheet.Entry_Type == "Other In Time") { this.EntryType = 6; } else if (this.EmployeeEntrySheet.Entry_Type == "Meeting Out Time") { this.EntryType = 7; } else if (this.EmployeeEntrySheet.Entry_Type == "Meeting In Time") { this.EntryType = 8; } else if (this.EmployeeEntrySheet.Entry_Type == "Official Work Out Time (Approved)") { this.EntryType = 9; } else if (this.EmployeeEntrySheet.Entry_Type == "Official Work In Time (Approved)") { this.EntryType = 10; } if (HH.length <= 10) { HH.split(':'); this.HR = HH[0]; } else { HH.split(':'); this.HR = HH[0] + HH[1]; } if (MM.length <= 10) { MM.split(':'); this.MIN = MM[2] + MM[3]; } else { MM.split(':'); this.MIN = MM[3] + MM[4]; } if (AMPM.length <= 10) { AMPM.split(" "); this.AMPM_Data = AMPM[8] + AMPM[9]; } else { AMPM.split(" "); this.AMPM_Data = AMPM[9] + AMPM[10]; } }; AddEmployeeRecordcomponent.prototype.ReBindAllDetails = function () { this.BindEmployeeDetails(); this.ClearFields(); this.BindEmployeeAttendance(); this.TransactionId = null; }; AddEmployeeRecordcomponent.prototype.onSubmit = function (formData) { var _this = this; if (formData.EmployeeId > 0) { if (formData.EntryType > 0) { var Hr = $("#txtHr").val(); var Minute = $("#txtMinute").val(); var Remarks_1 = $("#Remarks").val(); var Grace_1 = $("#grace").val(); if ((parseInt($("#txtHr").val()) < 13) && (parseInt($("#txtMinute").val())) < 60) { this._AddEmployeeRecordService.BindEmployeeDetails(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.Date, 21) .subscribe(function (data) { _this.indLoading = false; var StrEntryType; if (formData.EntryType == 1) { StrEntryType = "In Time"; } else if (formData.EntryType == 2) { StrEntryType = "Out Time"; } else if (formData.EntryType == 3) { StrEntryType = "Lunch Out Time"; } else if (formData.EntryType == 4) { StrEntryType = "Lunch In Time"; } _this.EmployeeDailyEntrySheet = data; var first; var firstdata; var EntryType; _this.EmployeeDailyEntrySheet.forEach(function (data) { first = function (element) { return !!element; }; firstdata = _this.EmployeeDailyEntrySheet.find(first); EntryType = firstdata.Entry_Type; StrEntryType == EntryType; }); var IsExist = false; if (StrEntryType == EntryType) { first = function (element) { return !!element; }; firstdata = _this.EmployeeDailyEntrySheet.find(first); } else { IsExist = true; } if (IsExist) { _this._AddEmployeeRecordService.GetAttendanceTransaction(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.Date, formData.EntryType) .subscribe(function (success) { _this.indLoading = false; _this.Attendance = success; var date = $("#txtEntryDate").val(); var strDate = date.toString().split('-'); var stDate = strDate[0] + strDate[1] + strDate[2]; _this.EntryTime = stDate + " " + $("#txtHr").val() + ":" + $("#txtMinute").val() + ":00" + " "; var strActualEntry = ""; if (success != '') { var id_1; var actualEntryTime_1; _this.Attendance.forEach(function (success) { id_1 = _this.TransactionId != null ? _this.TransactionId : parseInt(success.Id.toString()); actualEntryTime_1 = success.actualEntryTime; }); if (formData.EntryType < 3) { var ActualHr = actualEntryTime_1.trim().toString(); ActualHr.split(':'); var A_HR = ActualHr[0] + ActualHr[1]; var A_MIN = ActualHr[3] + ActualHr[4]; if (_this.AMPM_Data == "PM") { if (A_HR <= 12) { } else { A_HR += 12; } strActualEntry = A_HR.toString(); } else { strActualEntry = A_HR; } strActualEntry = strActualEntry + ":" + A_MIN; } _this._AddEmployeeRecordService.GetUpdateEmployeeAttendance(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, id_1, formData.EmployeeId, formData.EntryType, Remarks_1, _this.EntryTime, formData.Date, Grace_1, 21, strActualEntry) .subscribe(function (AddEmployee) { _this.indLoading = false; _this.ReBindAllDetails(); alert("Record Updated"); }, function (error) { _this.msg = error; }); } else if (_this.TransactionId != null) { var id_2; var actualEntryTime_2; _this.Attendance.forEach(function (success) { id_2 = _this.TransactionId != null ? _this.TransactionId : parseInt(success.Id.toString()); actualEntryTime_2 = success.actualEntryTime; }); if (formData.EntryType < 3) { if (_this.AMPM_Data == "PM") { var ActualHr = actualEntryTime_2.trim().toString(); ActualHr.split(':'); var A_HR = ActualHr[0] + ActualHr[1]; var A_MIN = ActualHr[3] + ActualHr[4]; if (A_HR <= 12) { } else { A_HR += 12; } strActualEntry = A_HR.toString(); } else { strActualEntry = A_HR; } strActualEntry = strActualEntry + ":" + A_MIN; } _this._AddEmployeeRecordService.GetUpdateEmployeeAttendance(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, id_2, formData.EmployeeId, formData.EntryType, Remarks_1, _this.EntryTime, formData.Date, Grace_1, 21, strActualEntry) .subscribe(function (AddEmployee) { _this.indLoading = false; _this.ReBindAllDetails(); alert("Record Updated"); }, function (error) { _this.msg = error; }); } else { _this._AddEmployeeRecordService.BindHRAttendanceDetails(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.Date) .subscribe(function (HRAttendance) { _this.indLoading = false; _this.HRAttendance = HRAttendance; var Time = ""; if (formData.EntryType == 1) { _this.HRAttendance.forEach(function (HRAttendance) { Time = HRAttendance.HRInTime.toString(); }); } else if (formData.EntryType == 2) { _this.HRAttendance.forEach(function (HRAttendance) { Time = HRAttendance.HROutTime.toString(); }); } else { Time = ""; } _this._AddEmployeeRecordService.AddEmployee(global_1.Global.BASE_AddEmployeeRecord_ENDPOINT, formData.EmployeeId, formData.EntryType, Remarks_1, _this.EntryTime, formData.Date, Time, Grace_1) .subscribe(function (Add) { _this.indLoading = false; _this.ReBindAllDetails(); alert("Record Saved"); }, function (error) { _this.msg = error; }); }, function (error) { _this.msg = error; }); } }, function (error) { _this.msg = error; }); } else { _this.ReBindAllDetails(); alert("Record Exist"); } }, function (error) { _this.msg = error; }); } else { alert("Invalid Time Information !"); } } else { alert("Select Type !"); } } else { alert("Select Employee !"); } }; AddEmployeeRecordcomponent = __decorate([ core_1.Component({ providers: [AddEmployeeRecord_service_1.AddEmployeeRecordService], templateUrl: 'app/Components/Report/Attendance/AddEmployeeRecord.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, AddEmployeeRecord_service_1.AddEmployeeRecordService, router_1.Router, pager_index_1.PagerService, router_1.ActivatedRoute]) ], AddEmployeeRecordcomponent); return AddEmployeeRecordcomponent; }()); exports.AddEmployeeRecordcomponent = AddEmployeeRecordcomponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class UserRole : VISBaseEntity { /// <summary> /// UserRole Entity Fields. /// </summary> /// public string Name { get; set; } public string Type { get; set; } public string FullName { get; set; } } public static class UserRoleConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_UserRole_Table = "UserRole"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Name = "Name"; public const string const_Type = "Type"; public const string const_FullName = "FullName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procUserRole_Add = "procUserRole_Add"; public const string const_procUserRole_Update = "procUserRole_Update"; public const string const_procUserRole_ActiveInActive = "procUserRole_ActiveInActive"; public const string const_procUserRole_SelectAll = "procUserRole_SelectAll"; public const string const_procUserRole_SelectById = "procUserRole_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters; namespace VIS_Repository.Masters.Configuration { public class CommonConfigurationRepository : VISDbCommand, VISIBaseRepository<CommonConfiguration> { public Int32 intAffectedRecords { get; set; } public CommonConfigurationRepository(string _connectionstring) : base(_connectionstring) { } public CommonConfiguration GetCommonConfiguration() { CommonConfiguration objEntityToReturn = new CommonConfiguration(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CommonConfigurationConstant.const_procCommonConfiguration_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<CommonConfiguration>(dt.Rows[0]); } return objEntityToReturn; } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText =CommonConfigurationConstant.const_procCommonConfiguration_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public CommonConfiguration GetEntityByID(Int64 Id) { CommonConfiguration objEntityToReturn = new CommonConfiguration(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CommonConfigurationConstant.const_procCommonConfiguration_SelectById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<CommonConfiguration>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<CommonConfiguration> GetEntityList() { List<CommonConfiguration> objListToReturn = new List<CommonConfiguration>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CommonConfigurationConstant.const_procCommonConfiguration_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<CommonConfiguration>(dt); } return objListToReturn; } public string AddEntity(CommonConfiguration entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CommonConfigurationConstant.const_procCommonConfiguration_Add; if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(CommonConfiguration entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CommonConfigurationConstant.const_procCommonConfiguration_Update; ; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_URLLocal,entityObject.URLLocal); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_URLLive, entityObject.URLLive); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_MinimumLunchBreak, entityObject.MinimumLunchBreak); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_MinimumOtherBreak, entityObject.MinimumOtherBreak); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_MouseMinutes, entityObject.MouseMinutes); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_PlusMouseMinutes, entityObject.PlusMouseMinutes); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_MouseTracking, entityObject.MouseTracking); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_ProductivityTracker, entityObject.ProductivityTracker); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_WorksheetPrompt, entityObject.WorksheetPrompt); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_MinimumPunchoutInterval, entityObject.MinimumPunchoutInterval); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_InTimeMondayToFridayHH, entityObject.InTimeMondayToFridayHH); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_InTimeMondayToFridayMM, entityObject.InTimeMondayToFridayMM); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_OutTimeMondayToFridayHH, entityObject.OutTimeMondayToFridayHH); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_OutTimeMondayToFridayMM, entityObject.OutTimeMondayToFridayMM); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_InTimeSaturdayHH, entityObject.InTimeSaturdayHH); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_InTimeSaturdayMM, entityObject.InTimeSaturdayMM); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_OutTimeSaturdayHH, entityObject.OutTimeSaturdayHH); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_OutTimeSaturdayMM, entityObject.OutTimeSaturdayMM); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_ShiftDurationHH, entityObject.ShiftDurationHH); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_ShiftDurationMM, entityObject.ShiftDurationMM); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CommonConfigurationConstant.const_TDSMenuHideOrShow, entityObject.TDSMenuHideOrShow); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo @Injectable() export class AttendanceReportNewService { constructor(private _http: Http) { } FillDepartMent(url: string): Observable<any> { return this._http.get(url + 'FillDepartMent') .map((response: Response) => <any>response.json()); } FillEmployee(url: string, UserId: number, UserType: string): Observable<any> { return this._http.get(url + 'FillEmployee?UserId=' + UserId + '&UserType=' + UserType) .map((response: Response) => <any>response.json()); } FillYear(url: string): Observable<any> { return this._http.get(url + 'FillYear') .map((response: Response) => <any>response.json()); } FillCompany(url: string,Allow: boolean): Observable<any> { return this._http.get(url + 'FillCompany?Allow=' + Allow) .map((response: Response) => <any>response.json()); } FillAllLineManager(url: string, Allow: boolean,UserId:number): Observable<any> { return this._http.get(url + 'FillAllLineManager?Allow=' + Allow + '&UserId=' + UserId) .map((response: Response) => <any>response.json()); } FillUserType(url: string): Observable<any> { return this._http.get(url + 'FillUserType') .map((response: Response) => <any>response.json()); } FillAllEmployee(url: string, Allow: boolean, UserId: number): Observable<any> { return this._http.get(url + 'FillAllEmployee?Allow=' + Allow + '&UserId=' + UserId) .map((response: Response) => <any>response.json()); } GetSystemDateTime(url: string): Observable<any> { return this._http.get(url + 'GetSystemDateTime') .map((response: Response) => <any>response.json()); } GetAllAttendanceReport(url: string, Mode: string, ModeId: number, StartDate: string, EndDate: string, SortBy: string, IsAdmin: boolean): Observable<any> { return this._http.get(url + 'GetAllAttendanceReport?Mode=' + Mode + '&ModeId=' + ModeId + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&SortBy=' + SortBy + '&IsAdmin=' + IsAdmin) .map((response: Response) => <any>response.json()); } GetAllAttendanceData(url: string, Mode: string, ModeId: number, StartDate: string, EndDate: string, SortBy: string, IsAdmin:boolean): Observable<any> { return this._http.get(url + 'GetAllAttendanceData?Mode=' + Mode + '&ModeId=' + ModeId + '&StartDate=' + StartDate + '&EndDate=' + EndDate + '&SortBy=' + SortBy + '&IsAdmin=' + IsAdmin) .map((response: Response) => <any>response.json()); } get(url: string): Observable<any> { return this._http.get(url) .map((response: Response) => <any>response.json()); } put(url: string, id: number, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity/' + id, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } delete(url: string, id: number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.Grievance { public class SalaryGrievance : VISBaseEntity { public Int64 Employee_Id { get; set; } public string Employee_Name { get; set; } public DateTime Deduction_Date { get; set; } public string Grievance_Remarks { get; set; } public string PaycutAmount { get; set; } public string GrievanceType_PE { get; set; } public string GrievanceType_PH { get; set; } public Int64 PE_Status { get; set; } public string PE_Remarks { get; set; } public Int64 PE_UpdatedBy { get; set; } public DateTime PE_UpdatedDate { get; set; } public Int64 PH_Status { get; set; } public string PH_Remarks { get; set; } public Int64 PH_UpdatedBy { get; set; } public DateTime PH_UpdatedDate { get; set; } public DateTime CreatedDateTime { get; set; } public DateTime UpdateDateTime { get; set; } public Boolean Active { get; set; } public Int64 verified_By { get; set; } } public class FillGrievance { public Int64 Id { get; set; } public Int64 Employee_Id { get; set; } public string Employee_Name { get; set; } public DateTime Deduction_Date { get; set; } public string Grievance_Remarks { get; set; } public string PaycutAmount { get; set; } public string GrievanceType_PE { get; set; } public string GrievanceType_PH { get; set; } public Int64 PE_Status { get; set; } public string PE_Remarks { get; set; } public Int64 PE_UpdatedBy { get; set; } public DateTime PE_UpdatedDate { get; set; } public Int64 PH_Status { get; set; } public string PH_Remarks { get; set; } public Int64 PH_UpdatedBy { get; set; } public DateTime PH_UpdatedDate { get; set; } public Int64 CreatedBy { get; set; } public DateTime CreatedDateTime { get; set; } public Int64 UpdatedBy { get; set; } public DateTime UpdateDateTime { get; set; } public Boolean Active { get; set; } public Int64 verified_By { get; set; } } public class FillGrievanceDate { public Int64 Id { get; set; } public Int64 EmployeeId { get; set; } public string Deduction_Date { get; set; } public DateTime CreatedOn { get; set; } public string PayrollCut { get; set; } public string PayrollRemarks { get; set; } public Int64 LineManagerId { get; set; } public string LineManagerName { get; set; } } public class UpdateGrievance { public Int64 Id { get; set; } public string Grievance_Remarks { get; set; } } public static class SalaryGrievanceConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_SalaryGrievance = "SalaryGrievance"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Id = "Id"; public const string const_Field_EmployeeId = "EmployeeId"; public const string const_Field_mode = "mode"; public const string const_Field_empId = "empId"; public const string const_Field_forWhichDate = "forWhichDate"; public const string const_Field_Date = "Date"; public const string const_Field_DeductionDate = "DeductionDate"; public const string const_Field_PC_AMT = "PC_AMT"; public const string const_Field_Grievance_Remark = "Grievance_Remark"; public const string const_Field_UpdatedBy = "UpdatedBy"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_ProcSalaryGrievanceProcessing_SelectAll = "ProcSalaryGrievanceProcessing"; public const string const_Proc_PA_GetGrievanceDate = "Proc_PA_GetGrievanceDate"; public const string const_Proc_ReportPerEmp_Grievance = "Proc_ReportPerEmp_Grievance"; public const string const_Proc_GetAttendancePerEmp_Grievance = "Proc_GetAttendancePerEmp_Grievance"; public const string const_Proc_InsertupdateGrievance = "Proc_InsertupdateGrievance"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var router_1 = require("@angular/router"); var ProductivityTrackerReport_service_1 = require("../../../Service/Report/Attendance/ProductivityTrackerReport.service"); var ProductivityTrackerReportcomponent = (function () { function ProductivityTrackerReportcomponent(fb, router, pagerService, _ProductivityTrackerReportService) { this.fb = fb; this.router = router; this.pagerService = pagerService; this._ProductivityTrackerReportService = _ProductivityTrackerReportService; this.pager = {}; this.CurrentRecordsPerPage = 10; } ProductivityTrackerReportcomponent.prototype.ngOnInit = function () { $("#radEmployee").prop("checked", true); $("#radDate").prop("checked", true); $("#radAll").prop("checked", true); $("#raddetail").prop("checked", true); $("#radsortname").prop("checked", true); this.HideLMDPOA(); this.showfromtoDate(); this.TypeAll(); this.ViewDetailed(); this.FillEmployee(); this.FillDepartment(); this.FillLineManager(); this.FillLookup(); this.FillOverall(); this.FillYear(); }; ProductivityTrackerReportcomponent.prototype.HideLMDPOA = function () { if ($("#radEmployee").prop("checked", true)) { $('#emp').show(); $('#empAll').show(); $('#LineManager').hide(); $('#Department').hide(); } }; ProductivityTrackerReportcomponent.prototype.HideDPOAEM = function () { $('#emp').hide(); $('#empAll').hide(); $('#Department').hide(); $('#LineManager').show(); }; ProductivityTrackerReportcomponent.prototype.HideOAEMLM = function () { $('#LineManager').hide(); $('#emp').hide(); $('#empAll').hide(); $('#Department').show(); }; ProductivityTrackerReportcomponent.prototype.HideEMLMDP = function () { $('#Department').hide(); $('#LineManager').hide(); $('#emp').hide(); $('#empAll').hide(); }; ProductivityTrackerReportcomponent.prototype.showfromtoDate = function () { if ($("#radDate").prop("checked", true)) { $('#date').show(); $('#month').hide(); //var Mon = new Date().getMonth(); //var Year = new Date().getFullYear(); //this.FromDate = new Date(Year, Mon, 1).toString(); //this.ToDate = new Date(Year, Mon + 1,0).toString(); } }; ProductivityTrackerReportcomponent.prototype.ShowMonthYear = function () { $('#date').hide(); $('#month').show(); }; ProductivityTrackerReportcomponent.prototype.ShowPreviousWorkday = function () { if ($("#radPrevious").prop("checked")) { $('#date').show(); $('#month').hide(); //var day = new Date().getDate() - 1; //var Mon = new Date().getMonth(); //var Year = new Date().getFullYear(); //this.FromDate = new Date(Year, Mon, day).toString(); //this.ToDate = new Date(Year, Mon, day).toString(); } }; ProductivityTrackerReportcomponent.prototype.ShowToday = function () { if ($("#radToday").prop("checked", true)) { $('#date').show(); $('#month').hide(); //this.FromDate = new Date().toString(); //this.ToDate = new Date().toString(); } }; ProductivityTrackerReportcomponent.prototype.TypeAll = function () { if ($("#radAll").prop("checked", true)) { $("#chkall").prop("checked", true); $("#chkall").prop("disabled", true); $("#chkouttype").prop("disabled", true); //$('#chkall').prop('disabled', true); //$('#chklunch').prop('disabled', true); //$('#chkother').prop('disabled', true); //$('#chkmeeting').prop('disabled', true); //$('#chkofficial').prop('disabled', true); //$('#chkidle').prop('disabled', true); } }; ProductivityTrackerReportcomponent.prototype.TypeOther = function () { $("#chkall").prop("checked", false); $("#chkall").prop("disabled", true); $("#chkouttype").prop("disabled", false); //$("#chkall").prop("checked", false); //$('#chkall').prop('disabled', true); //$('#chklunch').prop('disabled', false); //$('#chkother').prop('disabled', false); //$('#chkmeeting').prop('disabled', false); //$('#chkofficial').prop('disabled', false); //$('#chkidle').prop('disabled', false); }; ProductivityTrackerReportcomponent.prototype.ViewDetailed = function () { if ($("#raddetail").prop("checked", true)) { $('#radnoneview').empty(); $('#radnameview').empty(); $('#radtypeview').empty(); $('#radDateview').empty(); $('#viewDetails').hide(); } }; ProductivityTrackerReportcomponent.prototype.ViewConsolidated = function () { if ($("#radconsolidated").prop("checked", true)) { $('#viewDetails').show(); $("#radnoneview").prop("checked", true); } }; //-------------------- Change Event---------------------// ProductivityTrackerReportcomponent.prototype.AllEmployee = function (event) { var _this = this; if ($("#chkInActive").prop("checked", true)) { this._ProductivityTrackerReportService.FillAllEmployees(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, true) .subscribe(function (data) { _this.Employees = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); } }; //-------------------- Change Event---------------------// ProductivityTrackerReportcomponent.prototype.FillEmployee = function () { var _this = this; if (this.InActiveEmp == null) { this.InActiveEmp = true; } this.UserType = "admin"; if (this.UserType.toLowerCase() == "gh" || this.UserType.toLowerCase() == "admin" || this.UserType.toLowerCase() == "hr" || this.UserType.toLowerCase() == "payroll") { this._ProductivityTrackerReportService.FillEmployee(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "allemp", this.InActiveEmp) .subscribe(function (data) { _this.Employees = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); } else if (this.UserType.toLowerCase() == "bh" || this.UserType.toLowerCase() == "dh") { this._ProductivityTrackerReportService.FillEmployee(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "self", true) .subscribe(function (data) { _this.Employees = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); } else if (this.UserType.toLowerCase() == "PMRole") { this._ProductivityTrackerReportService.FillEmployee(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "pmemp", true) .subscribe(function (data) { _this.Employees = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); } else { this._ProductivityTrackerReportService.FillEmployee(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, "self", true) .subscribe(function (data) { _this.Employees = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); } }; ProductivityTrackerReportcomponent.prototype.FillLineManager = function () { var _this = this; this._ProductivityTrackerReportService.FillLineManager(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT, 21, true) // True Get From Employee_ModuleAccess -> ViewCompEvent value(In Old VIS Store in Session). .subscribe(function (data) { _this.LineManager = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); }; ProductivityTrackerReportcomponent.prototype.FillDepartment = function () { var _this = this; this._ProductivityTrackerReportService.FillDepartment(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(function (data) { _this.Department = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); }; ProductivityTrackerReportcomponent.prototype.FillOverall = function () { var _this = this; this._ProductivityTrackerReportService.FillOverall(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(function (data) { _this.Department = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); }; ProductivityTrackerReportcomponent.prototype.FillLookup = function () { var _this = this; this._ProductivityTrackerReportService.FillLookup(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(function (data) { _this.Lookup = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); }; ProductivityTrackerReportcomponent.prototype.FillYear = function () { var _this = this; this._ProductivityTrackerReportService.FillLookup(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT) .subscribe(function (data) { _this.Lookup = data; _this.InLoading = false; }, function (error) { _this.msg = error; }); }; ProductivityTrackerReportcomponent.prototype.ToogleMyProfile = function () { $("#ProductivityTrackerReport").slideToggle(300); }; ProductivityTrackerReportcomponent.prototype.CloseWidgetProfile = function () { $("#ProductivityTrackerReport").hide(300); }; ProductivityTrackerReportcomponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.ProductivityTracker); this.pager = this.pagerService.pager; this.pagedItems = null; this.pagedItems = this.pagerService.pagedItems; }; ProductivityTrackerReportcomponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; ProductivityTrackerReportcomponent.prototype.GetoutId = function () { this.OutIds = ''; for (var i = 0; i < this.Lookup.length; i++) { this.OutIds += this.Lookup[i].Id + ','; } this.OutIds = this.OutIds.substring(1, this.OutIds.lastIndexOf(",")); }; ProductivityTrackerReportcomponent.prototype.validateDate = function () { if ($("#txtdatefrom").val() != '') { if ($("#txtdateto").val() != '') { if ($("txtdatefrom").val() > $("#txtdateto").val()) { alert("Select Proper Dates"); } else { alert("Please select To dates"); } } } }; ProductivityTrackerReportcomponent.prototype.onSubmit = function (formData) { var _this = this; var str; var chk; if (formData.Employee > 0) { str = formData.Employee; } if ($("#raddetail").val() == 'Detailed') { this.Mode = "Detail"; } else if ($("#radconsolidated").val() == 'Consolidated') { this.Mode = "consolidate"; } if ($("#chkall").prop("checked", true)) { chk = "0"; } else if ($("#chkouttype").prop("checked", true)) { chk = "1"; } if (!this.validateDate()) { if ($("#radDate").prop("checked", true)) { this.GetoutId(); this._ProductivityTrackerReportService.GetProductivity(global_1.Global.BASE_ProductivityTrackerAPI_ENDPOINT, formData.sort, formData.fromDate, formData.ToDate, str, this.Mode, this.OutIds, formData.Consolidatedview, chk) .subscribe(function (data) { _this.ProductivityTracker = data; _this.JumpOnPage(1); _this.InLoading = false; }, function (error) { _this.msg = error; }); } } }; ProductivityTrackerReportcomponent = __decorate([ core_1.Component({ providers: [ProductivityTrackerReport_service_1.ProductivityTrackerReportService], templateUrl: 'app/Components/Report/Attendance/ProductivityTrackerReport.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, router_1.Router, pager_index_1.PagerService, ProductivityTrackerReport_service_1.ProductivityTrackerReportService]) ], ProductivityTrackerReportcomponent); return ProductivityTrackerReportcomponent; }()); exports.ProductivityTrackerReportcomponent = ProductivityTrackerReportcomponent; <file_sep>export interface ICurrency { CompanyId: number; Id: number; Full_Name: string; Short_Name: string; Sub_Unit: string; Symbol: string; Is_Base_Currency: boolean; Default_Exchange: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.Finance { public class Reports_FinanceRepository : VISDbCommand { private static Reports_FinanceRepository instance = new Reports_FinanceRepository(string.Empty); private Reports_FinanceRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_FinanceRepository getInstance() { return instance; } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var AttendanceAccessCardComparisionReport_service_1 = require("../../../Service/Report/Attendance/AttendanceAccessCardComparisionReport.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var AttendanceAccessCardComparisionReportComponent = (function () { function AttendanceAccessCardComparisionReportComponent(fb, _AttendanceAccessCardComparisionReportService, pagerService, _CommonHelperService) { this.fb = fb; this._AttendanceAccessCardComparisionReportService = _AttendanceAccessCardComparisionReportService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.pager = {}; this.CurrentRecordsPerPage = 10; this.frommonth = new Date().getMonth() + 1; this.fromyear = new Date().getFullYear(); this.tomonth = new Date().getMonth() + 1; this.toyear = new Date().getFullYear(); } AttendanceAccessCardComparisionReportComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.ParameterModel = ({ EmployeeId: 0, FromDate: '', LoginUserId: 0, OrderBy: '', ToDate: '', FromMonth: '', FromYear: '', ToMonth: '', IssueOnly: '', Search: '', ToYear: '', MonthWise: false }); this.Year = [({ CurrentYear: '' })]; this.GetEmployee(); this.GetYear(); }; AttendanceAccessCardComparisionReportComponent.prototype.HideShowPanel = function () { if ($("#rbtdate").prop("checked")) { $("#paneldatewise").show(); $("#panelmonthwise").hide(); $("#panelmonthwise2").hide(); $("#panelmonthwise3").hide(); $("#panelmonthwise4").hide(); } else { $("#paneldatewise").hide(); $("#panelmonthwise").show(); $("#panelmonthwise2").show(); $("#panelmonthwise3").show(); $("#panelmonthwise4").show(); } if ($("#rbtconsolidated").prop("checked")) { $("#panelconsolidate").show(); } else { $("#panelconsolidate").hide(); } }; AttendanceAccessCardComparisionReportComponent.prototype.ToogleMyProfile = function () { $("#alltypeoutreportdata").slideToggle(300); }; AttendanceAccessCardComparisionReportComponent.prototype.CloseWidgetProfile = function () { $("#alltypeoutreport").hide(300); }; AttendanceAccessCardComparisionReportComponent.prototype.GetEmployee = function () { var _this = this; this._AttendanceAccessCardComparisionReportService.getemployee(global_1.Global.BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT). subscribe(function (employee) { _this.Employee = employee; }); }; AttendanceAccessCardComparisionReportComponent.prototype.GetYear = function () { var _this = this; this._AttendanceAccessCardComparisionReportService.getyear(global_1.Global.BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT). subscribe(function (year) { _this.Year = year; }); }; AttendanceAccessCardComparisionReportComponent.prototype.onSubmit = function (ParameterModel) { var _this = this; ParameterModel.Search = ''; if ($("#rbtdate").prop("checked")) { ParameterModel.MonthWise = false; } else { ParameterModel.MonthWise = true; ParameterModel.FromMonth = this.frommonth.toString(); ParameterModel.FromYear = this.fromyear.toString(); ParameterModel.ToMonth = this.tomonth.toString(); ParameterModel.ToYear = this.toyear.toString(); } if ($("#chkissueonly").prop("checked")) { ParameterModel.IssueOnly = '1'; } else { ParameterModel.IssueOnly = '0'; } ParameterModel.LoginUserId = 158; this.EmployeeAccessCardComparisions = null; this.InLoading = true; this._AttendanceAccessCardComparisionReportService.getoutreportdata(global_1.Global.BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT, ParameterModel). subscribe(function (employeescreencapture) { _this.EmployeeAccessCardComparisions = employeescreencapture; _this.JumpOnPage(1); $("html, body").animate({ scrollTop: 310 }, 150); _this.InLoading = false; }); }; AttendanceAccessCardComparisionReportComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeAccessCardComparisions); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; AttendanceAccessCardComparisionReportComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; AttendanceAccessCardComparisionReportComponent.prototype.ImportAccessCardDetail = function () { alert("Import Access Card Detail"); }; AttendanceAccessCardComparisionReportComponent.prototype.ExportAccessCardDetail = function () { alert("Export Access Card Detail"); }; AttendanceAccessCardComparisionReportComponent.prototype.DownloadSampleAccessCardDetail = function () { alert("Download Sample Access Card Detail"); }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AttendanceAccessCardComparisionReportComponent.prototype, "modal", void 0); AttendanceAccessCardComparisionReportComponent = __decorate([ core_1.Component({ providers: [AttendanceAccessCardComparisionReport_service_1.AttendanceAccessCardComparisionReportService], templateUrl: 'app/Components/Report/Attendance/AttendanceAccessCardReportComparisionReport.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, AttendanceAccessCardComparisionReport_service_1.AttendanceAccessCardComparisionReportService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], AttendanceAccessCardComparisionReportComponent); return AttendanceAccessCardComparisionReportComponent; }()); exports.AttendanceAccessCardComparisionReportComponent = AttendanceAccessCardComparisionReportComponent; <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var Observable_1 = require("rxjs/Observable"); require("rxjs/add/operator/map"); require("rxjs/add/operator/do"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var CommonHelperService = (function () { function CommonHelperService(_http) { this._http = _http; } CommonHelperService.prototype.handleError = function (error) { console.error(error); return Observable_1.Observable.throw(error.json().error || 'Server error'); }; CommonHelperService.prototype.UploadImageToServer = function (url, formData) { var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return this._http.post(url, formData, options) .map(function (response) { return response.json(); }) .catch(this.handleError); }; CommonHelperService.prototype.ToogleMenu = function () { var vProp; var vStyleOfElement = document.getElementById("VISNavigationBar"); var vNewVisNavBarWidth = "300px"; var vMainContentLeftMargin = "305px"; var vCurrentStyleInAnchor = "labeldisplayblock"; var vChangeStyleInAnchor = "labeldisplaynone"; var vCurrentArrowClass = "arrow"; var vChangeInArrowClass = "arrownone"; if (vStyleOfElement.style.width == "300px") { vNewVisNavBarWidth = "50px"; vMainContentLeftMargin = "55px"; } else { vNewVisNavBarWidth = "300px"; vMainContentLeftMargin = "305px"; vCurrentStyleInAnchor = "labeldisplaynone"; vChangeStyleInAnchor = "labeldisplayblock"; vCurrentArrowClass = "arrownone"; vChangeInArrowClass = "arrow"; } var vArrayOfAnchorTag = document.getElementsByClassName(vCurrentStyleInAnchor); while (vArrayOfAnchorTag.length > 0) { vArrayOfAnchorTag[0].setAttribute('class', vChangeStyleInAnchor); } var vArrayOfArrowClass = document.getElementsByClassName(vCurrentArrowClass); while (vArrayOfArrowClass.length > 0) { vArrayOfArrowClass[0].setAttribute('class', vChangeInArrowClass); } var vArrayOfMainContentDivTag = document.getElementById("MainDivToLoadChild"); vArrayOfMainContentDivTag.style.marginLeft = vMainContentLeftMargin; vStyleOfElement.style.width = vNewVisNavBarWidth; $(".navbar-collapse in").addClass("navbar-collapse"); $(".navbar-collapse in").toggleClass("collapsed"); }; CommonHelperService = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [http_1.Http]) ], CommonHelperService); return CommonHelperService; }()); exports.CommonHelperService = CommonHelperService; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Masters.EmployeeLevels { public class LevelsPointLog { public int Id { get; set; } public long EmployeeID { get; set; } public long SetupID { get; set; } public DateTime Date { get; set; } public int Points { get; set; } public int GroupID { get; set; } public string Remarks { get; set; } public int Count { get; set; } public Boolean IsActive { get; set; } } public static class LevelsPointLogConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_ManualPointEntry = ""; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_EmployeeID = "EmployeeID"; public const string const_Field_SetupID = "SetupID"; public const string const_Field_Date = "Date"; public const string const_Field_Points = "Points"; public const string const_Field_GroupID = "GroupID"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_Count = "Count"; public const string const_Field_IsActive = "IsActive"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> //public const string const_procSaveLevelsPointLog = "procSaveLevelsPointLog"; } } <file_sep> import { Component, OnInit, ViewChild } from '@angular/core'; import { LevelsService } from '../../../service/Masters/EmployeeLevels/levels.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ILevels } from '../../../Model/Masters/EmployeeLevels/levels'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component({ selector: "page-levels", providers: [LevelsService], templateUrl: 'app/Components/Masters/EmployeeLevels/levels.component.html' }) export class LevelsComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; levelss: ILevels[]; levels: ILevels; msg: string; indLoading: boolean = false; levelsFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; LevelsFilter: string; isDesc: boolean = false; column: any = 'LevelName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchLevelNumber: number; strSearchLevelName: string; strSearchStartPoint: number; strSearchEndPoint: number; constructor(private fb: FormBuilder, private _levelsService: LevelsService, private pagerService: PagerService) { } ngOnInit(): void { this.levelsFrm = this.fb.group({ CompanyId: [''], Id: [''], LevelNumber: ['', Validators.compose([Validators.required])], LevelName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], LevelIcon: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], StartPoint: ['', Validators.compose([Validators.required])], EndPoint: ['', Validators.compose([Validators.required])], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); this.LoadLevelss(); } LevelsSearchCriteriaChange(value: string): void { if (value != '[object Event]') this.LevelsFilter = value; } LevelsSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } LoadLevelss(): void { this.indLoading = true; this._levelsService.get(Global.BASE_LEVELS_ENDPOINT) .subscribe(levelss => { this.levelss = levelss; //Logic for searching - start if (this.ShowHideSearch) { //if (this.strSearchLevelNumber > 0 ) { // this.strSearchLevelNumber = this.strSearchLevelNumber; // this.levelss = this.levelss.filter( // x => x.LevelNumber != null && x.LevelNumber>=this.strSearchLevelNumber); //} this.strSearchLevelName = (<HTMLInputElement>document.getElementById("searchLevelName")).value; if (this.strSearchLevelName != '') { this.strSearchLevelName = this.strSearchLevelName.toLocaleLowerCase(); this.levelss = this.levelss.filter( x => x.LevelName != null && x.LevelName.toLocaleLowerCase().indexOf(this.strSearchLevelName) != -1); } //this.strSearchStartPoint = (<HTMLInputElement>document.getElementById("searchStartPoint")).value; //if (this.strSearchStartPoint > 0) { // this.strSearchStartPoint = this.strSearchStartPoint; // this.levelss = this.levelss.filter( // x => x.StartPoint != null && x.StartPoint >= this.strSearchStartPoint); //} //this.strSearchEndPoint = (<HTMLInputElement>document.getElementById("searchEndPoint")).value; //if (this.strSearchEndPoint > 0) { // this.strSearchEndPoint = this.strSearchEndPoint; // this.levelss = this.levelss.filter( // x => x.EndPoint != null && x.EndPoint<= this.strSearchEndPoint); //} } this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addLevels() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Levels"; this.modalBtnTitle = "Add"; this.levelsFrm.reset(); this.modal.open(); } editLevels(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Levels"; this.modalBtnTitle = "Update"; this.levels = this.levelss.filter(x => x.Id == id)[0]; this.levelsFrm.setValue(this.levels); this.modal.open(); } deleteLevels(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.levels = this.levelss.filter(x => x.Id == id)[0]; this.levelsFrm.setValue(this.levels); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.levelsFrm.enable() : this.levelsFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.levelss); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._levelsService.post(Global.BASE_LEVELS_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLevelss(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._levelsService.put(Global.BASE_LEVELS_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLevelss(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._levelsService.delete(Global.BASE_LEVELS_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Levels status changed successfully."; this.LoadLevelss(); } else { this.msg = "Error has occurred while changing status of existing levels!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository; using VIS_Repository.Masters; namespace VIS_App.Controllers.Masters.CompanyRelated { public class ContactMasterAPIController : BaseAPIController { VISIBaseRepository<ContactMaster> ContactMasterRepository; List<ContactMaster> EntityList = new List<ContactMaster>(); public ContactMasterAPIController(VISIBaseRepository<ContactMaster> _ContactMasterRepository) { ContactMasterRepository = _ContactMasterRepository; } public HttpResponseMessage Get() { return ToJson(ContactMasterRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]ContactMaster value) { return ToJson(ContactMasterRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]ContactMaster value) { return ToJson(ContactMasterRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ContactMasterRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CurrencyRelated { public class Currency : VISBaseEntity { /// <summary> /// Currency Entity Fields. /// </summary> public string Full_Name { get; set; } public string Short_Name { get; set; } public string Sub_Unit { get; set; } public string Symbol { get; set; } public bool Is_Base_Currency { get; set; } public string Default_Exchange { get; set; } } public static class CurrencyConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Currency = "Currency"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Full_Name = "Full_Name"; public const string const_Field_Short_Name = "Short_Name"; public const string const_Field_Sub_Unit = "Sub_Unit"; public const string const_Field_Symbol = "Symbol"; public const string const_Field_Is_Base_Currency = "Is_Base_Currency"; public const string const_Field_Default_Exchange = "Default_Exchange"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procCurrency_Add = "procCurrency_Add"; public const string const_procCurrency_Update = "procCurrency_Update"; public const string const_procCurrency_ActiveInActive = "procCurrency_ActiveInActive"; public const string const_procCurrency_SelectAll = "procCurrency_SelectAll"; public const string const_procCurrency_SelectBaseNonBase = "procCurrency_SelectBaseNonBase"; public const string const_procCurrency_SelectById = "procCurrency_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Master.CurrencyRelated; using VIS_Repository; using VIS_Repository.Masters.CurrencyRelated; namespace VIS_App.Controllers.Masters.CurrencyRelated { public class CurrencyHistoryAPIController : BaseAPIController { CurrencyHistoryRepository CurrencyHistoryRepository = null; public CurrencyHistoryAPIController() { CurrencyHistoryRepository = new CurrencyHistoryRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(CurrencyHistoryRepository.GetEntityList()); } public HttpResponseMessage GetById(Int64 Id) { return ToJson(CurrencyHistoryRepository.GetEntityByID(Id)); } public HttpResponseMessage Post([FromBody]CurrencyHistory value) { return ToJson(CurrencyHistoryRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]CurrencyHistory value) { return ToJson(CurrencyHistoryRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(CurrencyHistoryRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_App.Infrastructure; using VIS_Domain.Master; using VIS_Domain.Registration; using VIS_Repository; using VIS_Repository.Registration; namespace VIS_App.Controllers { public class VISUserAPIController : BaseAPIController { VISIBaseRepository<VISUser> VISUserRepository; VISUserRepository objVISUserRepository = new VISUserRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); List<VISUser> EntityList = new List<VISUser>(); public VISUserAPIController(VISIBaseRepository<VISUser> _visUserRepository) { VISUserRepository = _visUserRepository; } public HttpResponseMessage Get() { return ToJson(VISUserRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage GetActivateLoginImage() { return ToJson(objVISUserRepository.GetActivateLoginImage()); } [HttpPost] public HttpResponseMessage AddEntity([FromBody]VISUser value) { return ToJson(VISUserRepository.AddEntity(value)); } [HttpPost] public HttpResponseMessage PostUserByUserIdPassword([FromBody]VISUser value) { value.VISPassword = CommonCode.Encrypt(value.VISPassword, "<PASSWORD>"); return ToJson(objVISUserRepository.PostUserByUserIdPassword(value.VISUsername, value.VISPassword)); } public HttpResponseMessage Put(Int64 id, [FromBody]VISUser value) { return ToJson(VISUserRepository.UpdateEntity(value)); } public HttpResponseMessage Delete(Int64 Id) { return ToJson(VISUserRepository.DeleteEntity(Id)); } [HttpGet] [Route("api/VISUserAPI/GetForgotPassword")] public HttpResponseMessage GetForgotPassword(string Email) { return ToJson(objVISUserRepository.ForgotPassword(Email)); } } } <file_sep>import { Injectable } from '@angular/core' @Injectable() export class VISSession { private _IsLoggedIn: boolean; private _IsAdmin: boolean; private _IsLineManager: boolean; private _DepartmentId: number; private _IsFormerEmployee: number; private _Email: number; private _FirstName: string; private _LastName: string; constructor() { if (1 == 1) { this._IsLoggedIn = true; } console.log("New SessionService"); } isLoggedIn() { return this._IsLoggedIn; } logOut() { this._IsLoggedIn = !this._IsLoggedIn; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; namespace VIS_App.Controllers.Masters.Configuration { public class CommonConfigurationAPIController : BaseAPIController { CommonConfigurationRepository objCommonConfigurationRepository = null; //VISIBaseRepository<CommonConfiguration> CommonConfigurationRepository; //List<CommonConfiguration> EntityList = new List<CommonConfiguration>(); //CommonConfiguration SingleEntity = new CommonConfiguration(); public CommonConfigurationAPIController() { //CommonConfigurationRepository = _CommonConfigurationRepository; objCommonConfigurationRepository = new CommonConfigurationRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [HttpGet] [Route("api/CommonConfigurationAPI/GetAllCommonConfiguration")] public HttpResponseMessage GetAllCommonConfiguration() { return ToJson(objCommonConfigurationRepository.GetCommonConfiguration()); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]CommonConfiguration value) { return ToJson(objCommonConfigurationRepository.UpdateEntity(value)); } } } <file_sep>export interface IEducationType { Id: number; Name: string; Type: string; FullName: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string; IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.Attendance; using VIS_Repository.HumanResource.Attendace; namespace VIS_App.Controllers.HumanResource.Attendance { public class WorkSheetAPIController : BaseAPIController { WorkSheetRepository ObjWorkSheetRepository = null; public WorkSheetAPIController() { ObjWorkSheetRepository = new WorkSheetRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjWorkSheetRepository.GetEntityList().AsEnumerable()); } //[Route("api/WorkSheetAPI/AddWorkSheet")] //[HttpGet] //public HttpResponseMessage AddWorkSheet([FromBody]WorkSheet value) //{ // return ToJson(ObjWorkSheetRepository.AddWorkSheet(value)); //} [Route("api/WorkSheetAPI/GetDropDownList")] [HttpGet] public HttpResponseMessage GetDropDownList() { return ToJson(ObjWorkSheetRepository.GetDefaultConfigure()); } [Route("api/WorkSheetAPI/GetDate")] [HttpGet] public HttpResponseMessage GetDate() { return ToJson(ObjWorkSheetRepository.GetDate()); } [Route("api/WorkSheetAPI/GetProjectList")] [HttpGet] public HttpResponseMessage GetProjectList(Int64 UserId, string Date) { return ToJson(ObjWorkSheetRepository.GetProjectList(UserId, Date)); } [Route("api/WorkSheetAPI/GetChildtaskDropDown")] [HttpGet] public HttpResponseMessage GetChildtaskDropDown(Int64 ProjectId, Int64 UserId, string Date) { return ToJson(ObjWorkSheetRepository.GetTaskDropDownFill(ProjectId, UserId, Date)); } [Route("api/WorkSheetAPI/SaveWorksheet")] [HttpPost] public HttpResponseMessage SaveWorksheet(List<WorkSheet> value) { return ToJson(ObjWorkSheetRepository.SaveWorksheet(value)); } public HttpResponseMessage Post([FromBody]WorkSheet value) { return ToJson(ObjWorkSheetRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]WorkSheet value) { return ToJson(ObjWorkSheetRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjWorkSheetRepository.DeleteEntity(Id)); } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { HelpTicketAddService } from '../../service/Notification/HelpTicketAdd.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IHelpAddTicket } from '../../Model/Notification/HelpTicketAdd'; import { IOraganization } from '../../Model/Notification/Organization'; import { FileDropDirective, FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-upload'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { DatePipe } from '@angular/common'; @Component({ providers: [HelpTicketAddService], templateUrl: 'app/Components/Notification/HelpTicketAdd.component.html' }) export class HelpTicketAddComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; HelpAddTickets: IHelpAddTicket[]; HelpAddTicket: IHelpAddTicket; Oraganization: IOraganization[]; msg: string; indLoading: boolean = false; HelpAddTicketFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; HelpAddTicketFilter: string; isDesc: boolean = false; column: any = 'Subject'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchHelpAddTicket_Name: string; strSearchDescription: string; //File Add fileList1: FileList; fileList2: FileList; fileList3: FileList; constructor(private fb: FormBuilder, private _HelpAddTicketService: HelpTicketAddService, private pagerService: PagerService, private http: Http) { } ngOnInit(): void { this.HelpAddTicketFrm = this.fb.group({ CompanyId: [''], Id: [''], Subject: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], Message: ['', Validators.required], Remarks: [''], AssignTo: [''], AddressToGroup: [''], Priority: [''], Status: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], FileName: [''], FileName1: [''], FileName2: [''], EntityMessage: [''] }); // this.LoadHelpAddTickets() this.LoadDp(); } //file upload event fileChange1(event) { this.fileList1 = event.target.files; } fileChange2(event) { this.fileList2 = event.target.files; } fileChange3(event) { this.fileList3 = event.target.files; } HelpAddTicketFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.HelpAddTicketFilter = value; } HelpAddTicketSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } LoadDp(): void { this.indLoading = true; this._HelpAddTicketService.getDp(Global.BASE_HelpTicketAdd_ENDPOINT) .subscribe(DATADP => { this.Oraganization = DATADP; } //,error => this.msg = <any>error ); } LoadHelpAddTickets(): void { this.indLoading = true; this._HelpAddTicketService.get(Global.BASE_HelpTicketAdd_ENDPOINT) .subscribe(HelpAddTickets => { this.HelpAddTickets = HelpAddTickets; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchHelpAddTicket_Name = (<HTMLInputElement>document.getElementById("searchMessage")).value; if (this.strSearchHelpAddTicket_Name != '') { this.strSearchHelpAddTicket_Name = this.strSearchHelpAddTicket_Name.toLocaleLowerCase(); this.HelpAddTickets = this.HelpAddTickets.filter( x => x.Message != null && x.Message.toLocaleLowerCase().indexOf(this.strSearchHelpAddTicket_Name) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addHelpAddTicket() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New HelpAddTicket"; this.modalBtnTitle = "Add"; this.HelpAddTicketFrm.reset(); this.modal.open(); } editHelpAddTicket(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit HelpAddTicket"; this.modalBtnTitle = "Update"; this.HelpAddTicket = this.HelpAddTickets.filter(x => x.Id == id)[0]; this.HelpAddTicketFrm.setValue(this.HelpAddTicket); this.modal.open(); } deleteHelpAddTicket(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.HelpAddTicket = this.HelpAddTickets.filter(x => x.Id == id)[0]; this.HelpAddTicketFrm.setValue(this.HelpAddTicket); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.HelpAddTicketFrm.enable() : this.HelpAddTicketFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.HelpAddTickets); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } //onSubmit(formData: IHelpAddTicket) { // this.msg = ""; // console.log(formData); // this._HelpAddTicketService.put(Global.BASE_HelpTicketAdd_ENDPOINT, formData.Id, formData).subscribe( // data => { // if data.startsWith("Success: "){ // this.msg = "Common Configuration Save successfully."; // this.LoadHelpAddTickets(); // } // else { // this.msg = "Error has occurred while modifying existing Common Configuration!" // } // }, // error => { // this.msg = error; // } // ); //} onSubmit(formData: any) { console.log(formData); this.msg = ""; switch (this.dbops) { case DBOperation.create: if (this.fileList1 != null) { formData._value.FileName = this.fileList1.item(0).name; } else { formData._value.FileName = null } if (this.fileList2 != null) { formData._value.FileName1 = this.fileList2.item(0).name; } else { formData._value.FileName1 = null } if (this.fileList3 != null) { formData._value.FileName2 = this.fileList3.item(0).name; } else { formData._value.FileName2 = null } this._HelpAddTicketService.post(Global.BASE_HelpTicketAdd_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { if (this.fileList1 != null) { if (this.fileList1.length > 0) { this.fileList1.item(0).name let file: File = this.fileList1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { formData._value.FileName = null } if (this.fileList2 != null) { if (this.fileList2.length > 0) { this.fileList2.item(0).name let file: File = this.fileList2[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { formData._value.FileName2 = null } if (this.fileList3 != null) { if (this.fileList3.length > 0) { this.fileList3.item(0).name let file: File = this.fileList3[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { formData._value.FileName3 = null } this.msg = data; this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._HelpAddTicketService.put(Global.BASE_HelpTicketAdd_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadHelpAddTickets(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._HelpAddTicketService.delete(Global.BASE_HelpTicketAdd_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "HelpAddTicket status changed successfully."; this.LoadHelpAddTickets(); } else { this.msg = "Error has occurred while changing status of existing HelpAddTicket!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.VacancyRelated { public class Skill : VISBaseEntity { /// <summary> /// Skill Entity Fields. /// </summary> /// public string SkillName { get; set; } public string Description { get; set; } public Int64 SkillGroupID { get; set; } public string SkillGroupName { get; set; } public string RatingGroup { get; set; } public bool Status { get; set; } public Int64[] Level { get; set; } } public class SkillViewModel : VISBaseEntity { /// <summary> /// Skill Entity Fields. /// </summary> /// public string SkillName { get; set; } public string Description { get; set; } public Int64 SkillGroupID { get; set; } public string SkillGroupName { get; set; } public string RatingGroup { get; set; } public bool Status { get; set; } public string Level { get; set; } } public static class SkillConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_SkillGroup_Table = "SkillMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_SkillName = "SkillName"; public const string const_Description = "Description"; public const string const_SkillGroupId = "SkillGroupId"; public const string const_Status = "Status"; public const string const_SkillLevelText = "SkillLevelText"; public const string const_SkillLevelOrder = "SkillLevelOrder"; public const string const_SkillId = "SkillId"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procSkillMaster_Add = "procSkillMaster_Add"; public const string const_procSkillMaster_Update = "procSkillMaster_Update"; public const string const_procSkillMaster_ActiveInActive = "procSkillMaster_ActiveInActive"; public const string const_procSkillMaster_SelectAll = "procSkillMaster_SelectAll"; public const string const_procSkillMaster_SelectById = "procSkillMaster_SelectById"; public const string const_procGetSkill = "procGetSkill"; public const string const_procSkillMasterLevel_Add = "procSkillMasterLevel_Add"; public const string const_procSkillMasterLevel_Delete = "procSkillMasterLevel_Delete"; } } <file_sep>export interface ITicketListClosed { CompanyId: number; Mode: string; Id: number; Subject: string; CreatedOn: Date; AddressToGroup: string; AssignTo: string; CreatedByName: string; UpdatedByName: string; UpdatedOn: Date; Priority: string; Status: string; CreatedBy: number; UpdatedBy: number IsActive: boolean; UserId: number; FileName: string; }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var SalaryGrievance_service_1 = require("../../../Service/HumanResource/Grievance/SalaryGrievance.service"); var global_1 = require("../../../../app/Shared/global"); var pager_service_1 = require("../../../../app/Shared/pager.service"); var router_1 = require("@angular/router"); var http_1 = require("@angular/http"); var enum_1 = require("../../../Shared/enum"); var SalaryGrievanceComponent = (function () { function SalaryGrievanceComponent(fb, _SalaryGrievanceService, http, router, pagerService) { this.fb = fb; this._SalaryGrievanceService = _SalaryGrievanceService; this.http = http; this.router = router; this.pagerService = pagerService; this.indLoading = false; this.CurrentRecordsPerPage = 10; this.pager = {}; } SalaryGrievanceComponent.prototype.ngOnInit = function () { this.objGrievance = ({ Id: 0, Employee_Id: 0, Employee_Name: '', Deduction_Date: null, Grievance_Remarks: '', PaycutAmount: '', GrievanceType_PE: '', GrievanceType_PH: '', PE_Status: 0, PE_Remarks: '', PE_UpdatedBy: 0, PE_UpdatedDate: null, PH_Status: 0, PH_Remarks: '', PH_UpdatedBy: 0, PH_UpdatedDate: null, CreatedBy: 0, CreatedOn: null, UpdatedBy: 0, UpdatedOn: null, Active: false, verified_By: 0, }); $("#txtDeductDate").hide(); this.objGrievance.Employee_Id = Number(sessionStorage.getItem('Id')); this.objGrievance.Employee_Name = sessionStorage.getItem('UserFullName'); this.LoadGrievanceDetails(); // Add Grievance Method.. $("#AttendanceData").hide(); $("#DailyEntryData").hide(); $("#txtempname").prop('disabled', true); $("#txtDeductionDate").prop('disabled', true); $("#txtpcremark").prop('disabled', true); $("#txtPCAmt").prop('disabled', true); $("#txtremark_by").prop('disabled', true); this.FillDeductionDate(); }; SalaryGrievanceComponent.prototype.LoadGrievanceDetails = function () { var _this = this; this.indLoading = true; this._SalaryGrievanceService.GetGrievance(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "Pending") .subscribe(function (Grievance) { _this.Grievance = Grievance; _this.indLoading = false; _this.JumpOnPage(1); }); }; SalaryGrievanceComponent.prototype.GetPendingGrievance = function (event) { this.LoadGrievanceDetails(); }; SalaryGrievanceComponent.prototype.GetCompletedGrievance = function (event) { var _this = this; this._SalaryGrievanceService.GetGrievance(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "Completed") .subscribe(function (Grievance) { _this.Grievance = Grievance; _this.indLoading = false; _this.JumpOnPage(1); }); }; SalaryGrievanceComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.Grievance); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; SalaryGrievanceComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; //SetControlsState(isEnable: boolean) { // isEnable ? this.SalaryGrievanceForm.enable() : this.SalaryGrievanceForm.disable(); //} SalaryGrievanceComponent.prototype.ResetModal = function () { this.objGrievance = ({ Id: 0, Employee_Id: 0, Employee_Name: '', Deduction_Date: null, Grievance_Remarks: '', PaycutAmount: '', GrievanceType_PE: '', GrievanceType_PH: '', PE_Status: 0, PE_Remarks: '', PE_UpdatedBy: 0, PE_UpdatedDate: null, PH_Status: 0, PH_Remarks: '', PH_UpdatedBy: 0, PH_UpdatedDate: null, CreatedBy: 0, CreatedOn: null, UpdatedBy: 0, UpdatedOn: null, Active: false, verified_By: 0, }); }; SalaryGrievanceComponent.prototype.GoToAddGrievance = function () { this.ResetModal(); this.modalTitle = 'Add Grievance'; this.modalButton = 'Save'; this.dbops = enum_1.DBOperation.create; this.modal.open(); }; // Add Grievance Functions... SalaryGrievanceComponent.prototype.FillDeductionDate = function () { var _this = this; this._SalaryGrievanceService.FillDeductionDate(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "GetDeductDate") .subscribe(function (GetDeductionDate) { _this.indLoading = false; _this.GrievanceDate = GetDeductionDate; }, function (error) { _this.msg = error; }); }; SalaryGrievanceComponent.prototype.LoadEmployeeAttendance = function (EmployeeId, DeductionDate) { var _this = this; this._SalaryGrievanceService.LoadEmployeeAttendance(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, EmployeeId, DeductionDate) .subscribe(function (GetAttendance) { _this.indLoading = false; _this.Attendance = GetAttendance; }, function (error) { _this.msg = error; }); }; SalaryGrievanceComponent.prototype.LoadEmployeeDailyEntry = function (EmployeeId, DeductionDate) { var _this = this; this._SalaryGrievanceService.LoadEmployeeDailyEntry(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, EmployeeId, DeductionDate) .subscribe(function (GetDailyEntry) { debugger; _this.indLoading = false; _this.DailyEntry = GetDailyEntry; }, function (error) { _this.msg = error; }); }; SalaryGrievanceComponent.prototype.GetAttendanceDetailOfEmployee = function (event) { var _this = this; this._SalaryGrievanceService.FillDeductionDate(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "GetDeductDate") .subscribe(function (GetDeduction) { _this.GrievanceDeductionDate = GetDeduction; if (_this.GrievanceDeductionDate != null) { $("#AttendanceData").show(); $("#DailyEntryData").show(); _this.Id = event.target.value; if (_this.Id == 0) { _this.objGrievance.PaycutAmount = ""; _this.PayCutAmtRemark = ""; _this.RemarkBy = ""; } else { for (var _i = 0, _a = _this.GrievanceDeductionDate.filter(function (x) { return x.Id == _this.Id; }); _i < _a.length; _i++) { var item = _a[_i]; _this.objGrievance.PaycutAmount = item.PayrollCut; _this.PayCutAmtRemark = item.PayrollRemarks; _this.RemarkBy = item.LineManagerName; _this.LoadEmployeeAttendance(item.EmployeeId, item.Deduction_Date); _this.LoadEmployeeDailyEntry(item.EmployeeId, item.Deduction_Date); } } } }); }; SalaryGrievanceComponent.prototype.EditGrievance = function (Id) { $("#ddDeductDate").hide(); $("#txtDeductDate").show(); this.modalTitle = 'Edit Grievance'; this.modalButton = 'Update'; this.dbops = enum_1.DBOperation.update; //this.SetControlsState(true); this.objGrievance = this.Grievance.filter(function (x) { return x.Id == Id; })[0]; this.modal.open(); }; SalaryGrievanceComponent.prototype.onSubmit = function (objGrievance) { var _this = this; this.msg = ""; debugger; var dateval = $("#ddlDeductDate option:selected").text(); var Pc_AMT = $("#txtPCAmt").val(); var GrievanceRemark = $("#txtGrievanceremark").val(); this.EmployeeId = Number(sessionStorage.getItem('Id')); switch (this.dbops) { case enum_1.DBOperation.create: this._SalaryGrievanceService.AddGrievance(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.EmployeeId, dateval, Pc_AMT, GrievanceRemark) .subscribe(function (Success) { _this.modal.close(); }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._SalaryGrievanceService.put(global_1.Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.EmployeeId, objGrievance) .subscribe(function (Success) { _this.modal.close(); }, function (error) { _this.msg = error; }); } }; __decorate([ core_1.ViewChild('modalAddGrievance'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], SalaryGrievanceComponent.prototype, "modal", void 0); SalaryGrievanceComponent = __decorate([ core_1.Component({ providers: [SalaryGrievance_service_1.SalaryGrievanceService], templateUrl: 'app/Components/HumanResource/Grievance/SalaryGrievance.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, SalaryGrievance_service_1.SalaryGrievanceService, http_1.Http, router_1.Router, pager_service_1.PagerService]) ], SalaryGrievanceComponent); return SalaryGrievanceComponent; }()); exports.SalaryGrievanceComponent = SalaryGrievanceComponent; <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var MySkill_service_1 = require("../../../Service/HumanResource/Attendance/MySkill.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var MySkillComponent = (function () { function MySkillComponent(fb, _MySkillService, pagerService) { this.fb = fb; this._MySkillService = _MySkillService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'SkillName'; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; //Variables for Filter this.ShowHideSearch = false; } MySkillComponent.prototype.ngOnInit = function () { this.MySkillFrm = this.fb.group({ CompanyId: [''], mode: [''], UserID: [''], SkillName: [''], SkillGroup: [''], Skilltext: [''], SkillID: [''], lookupSkilId: [''], Name: [''], status: [''], IsApproved: [''], id: [''], }); this.LoadMySkills(21); }; MySkillComponent.prototype.MySkillFilterCriteriaChange = function (value) { if (value != '[object Event]') this.MySkillFilter = value; }; MySkillComponent.prototype.MySkillSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; MySkillComponent.prototype.deleteNewSkill = function (SkillID, UserId) { var _this = this; this.indLoading = true; this._MySkillService.DeleteSkill(global_1.Global.BASE_MySkill_ENDPOINT, SkillID, 21) .subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadMySkills(21); } else { alert(data); } _this.indLoading = false; // initialize to page 1 //this.JumpOnPageNewSkill(1); } //,error => this.msg = <any>error ); }; MySkillComponent.prototype.LoadChildgrop = function () { var _this = this; this.indLoading = true; this._MySkillService.GetPopupChildSkill(global_1.Global.BASE_MySkill_ENDPOINT) .subscribe(function (data) { _this.Childdata = data; _this.indLoading = false; }); }; MySkillComponent.prototype.LoadSkillName = function (event) { var _this = this; this.indLoading = true; this._MySkillService.GetPopupSecondSkill(global_1.Global.BASE_MySkill_ENDPOINT, event.target.value) .subscribe(function (data) { _this.SecondData = data; _this.indLoading = false; }); }; MySkillComponent.prototype.LoadMySkills = function (UserId) { var _this = this; this.indLoading = true; this._MySkillService.GetMySkill(global_1.Global.BASE_MySkill_ENDPOINT, UserId) .subscribe(function (MySkills) { _this.MySkills = MySkills; console.log(MySkills); //Logic for searching - start if (_this.ShowHideSearch) { _this.searchSkillName = document.getElementById("searchSkillName").value; if (_this.searchSkillName != '') { _this.searchSkillName = _this.searchSkillName.toLocaleLowerCase(); _this.MySkills = _this.MySkills.filter(function (x) { return x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(_this.searchSkillName) != -1; }); } } if (_this.ShowHideSearch) { _this.searchSkillGroupName = document.getElementById("searchSkillGroupName").value; if (_this.searchSkillGroupName != '') { _this.searchSkillGroupName = _this.searchSkillGroupName.toLocaleLowerCase(); _this.MySkills = _this.MySkills.filter(function (x) { return x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(_this.searchSkillGroupName) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; MySkillComponent.prototype.addMySkill = function () { this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New MySkill"; this.modalBtnTitle = "Add"; this.MySkillFrm.reset(); this.modal.open(); this.LoadChildgrop(); }; MySkillComponent.prototype.editMySkill = function (id) { this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit MySkill"; this.modalBtnTitle = "Update"; this.MySkillFrm.setValue(this.MySkill); this.modal.open(); }; MySkillComponent.prototype.deleteMySkill = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.MySkillFrm.setValue(this.MySkill); this.modal.open(); }; MySkillComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.MySkillFrm.enable() : this.MySkillFrm.disable(); }; MySkillComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; MySkillComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.MySkills); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; MySkillComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; MySkillComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._MySkillService.post(global_1.Global.BASE_MySkill_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadMySkills(21); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._MySkillService.put(global_1.Global.BASE_MySkill_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data == "Success") { _this.msg = "MySkill modified successfully."; } else { _this.msg = "Error has occurred while modifying existing MySkill!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._MySkillService.DeleteSkill(global_1.Global.BASE_MySkill_ENDPOINT, formData._value.UserId, formData._value.SkillID).subscribe(function (data) { if (data == "Success") { _this.msg = "MySkill status changed successfully."; } else { _this.msg = "Error has occurred while changing status of existing MySkill!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], MySkillComponent.prototype, "modal", void 0); MySkillComponent = __decorate([ core_1.Component({ providers: [MySkill_service_1.MySkillService], templateUrl: 'app/Components/HumanResource/Attendance/MySkill.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, MySkill_service_1.MySkillService, pager_index_1.PagerService]) ], MySkillComponent); return MySkillComponent; }()); exports.MySkillComponent = MySkillComponent; <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var LateEarlyReport_service_1 = require("../../../Service/Report/Attendance/LateEarlyReport.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var LateEarlyReportComponent = (function () { function LateEarlyReportComponent(fb, _LateEarlyReportService, pagerService, _CommonHelperService) { this.fb = fb; this._LateEarlyReportService = _LateEarlyReportService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.pager = {}; this.CurrentRecordsPerPage = 10; this.EmployeeId = 0; this.DepartmentId = 0; this.CompanyId = 0; this.frommonth = new Date().getMonth() + 1; this.fromyear = new Date().getFullYear(); } LateEarlyReportComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.Year = [({ CurrentYear: '' })]; this.Department = [({ Department_Name: '', Id: 0 })]; this.Company = [({ CompanyName: '', Id: 0 })]; this.ParameterModel = { Id: 0, Fromdate: new Date(), Todate: new Date(), MonthWise: false, FromMonth: '', FromYear: '' }; this.GetDepartment(); this.GetEmployee(); this.GetCompany(); this.GetYear(); }; LateEarlyReportComponent.prototype.ToogleMyProfile = function () { $("#alltypeoutreportdata").slideToggle(300); }; LateEarlyReportComponent.prototype.CloseWidgetProfile = function () { $("#alltypeoutreport").hide(300); }; LateEarlyReportComponent.prototype.ViewStyleToogle = function () { if ($("#rbtconsolidated").prop('checked')) { $("#viewstyle").show(); } else { $("#viewstyle").hide(); } }; LateEarlyReportComponent.prototype.ToogleHideShowOption = function () { if ($("#rbtdepartment").prop('checked')) { $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); $("#ddldepartment").show(); } else if ($("#rbtcompany").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").show(); $("#ddllinemanager").hide(); } else if ($("#rbtlinemanager").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").show(); } else { $("#ddldepartment").hide(); $("#ddlemployee").show(); $("#chkallemployeediv").show(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); } }; LateEarlyReportComponent.prototype.ToogleDateOption = function () { if ($("#rbtdate").prop("checked")) { $("#searchbydate").show(); $("#searchbymonth").hide(); } else { $("#searchbydate").hide(); $("#searchbymonth").show(); } }; LateEarlyReportComponent.prototype.GetDepartment = function () { var _this = this; this._LateEarlyReportService.getdepartment(global_1.Global.BASE_LateEarlyReport_ENDPOINT). subscribe(function (department) { _this.Department = department; }); }; LateEarlyReportComponent.prototype.GetEmployee = function () { var _this = this; this._LateEarlyReportService.getemployee(global_1.Global.BASE_LateEarlyReport_ENDPOINT). subscribe(function (employee) { _this.Employee = employee; }); }; LateEarlyReportComponent.prototype.GetCompany = function () { var _this = this; this._LateEarlyReportService.getcompany(global_1.Global.BASE_LateEarlyReport_ENDPOINT). subscribe(function (company) { _this.Company = company; }); }; LateEarlyReportComponent.prototype.GetYear = function () { var _this = this; this._LateEarlyReportService.getyear(global_1.Global.BASE_LateEarlyReport_ENDPOINT). subscribe(function (year) { _this.Year = year; }); }; LateEarlyReportComponent.prototype.GetIdByDepartment = function (Id, Fromdate, Todate, MonthWise, FromMonth, FromYear) { var _this = this; this.LateEarlyReports = null; this.InLoading = true; this._LateEarlyReportService.getemployeeidbydepartment(global_1.Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(function (lateearlyreports) { _this.LateEarlyReports = lateearlyreports; _this.JumpOnPage(1); _this.InLoading = false; }); }; LateEarlyReportComponent.prototype.GetIdByEmployee = function (Id, Fromdate, Todate, MonthWise, FromMonth, FromYear) { var _this = this; this.LateEarlyReports = null; this.InLoading = true; this._LateEarlyReportService.getemployeeidbyemployee(global_1.Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(function (lateearlyreports) { _this.LateEarlyReports = lateearlyreports; _this.JumpOnPage(1); _this.InLoading = false; }); }; LateEarlyReportComponent.prototype.GetIdByCompany = function (Id, Fromdate, Todate, MonthWise, FromMonth, FromYear) { var _this = this; this._LateEarlyReportService.getemployeeidbycompany(global_1.Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(function (employees) { _this.Employees = employees; _this.JumpOnPage(1); }); }; LateEarlyReportComponent.prototype.GetIdBySelectAll = function (Id, Fromdate, Todate, MonthWise, FromMonth, FromYear) { var _this = this; this._LateEarlyReportService.getemployeeidbyselectall(global_1.Global.BASE_LateEarlyReport_ENDPOINT, Id, Fromdate, Todate, MonthWise, FromMonth, FromYear). subscribe(function (employees) { _this.Employees = employees; _this.JumpOnPage(1); }); }; LateEarlyReportComponent.prototype.onSubmit = function (formData) { if (formData.Id != 0) { this.Employees = null; if ($("#rbtemployee").prop("checked")) { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdByEmployee(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } else if ($("#rbtdepartment").prop("checked")) { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdByDepartment(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } else if ($("#rbtcompany").prop("checked")) { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdByCompany(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } } else { if ($("#rbtdate").prop("checked")) { formData.MonthWise = false; } else { formData.MonthWise = true; formData.FromMonth = this.frommonth.toString(); formData.FromYear = this.fromyear.toString(); } this.GetIdBySelectAll(formData.Id, formData.Fromdate, formData.Todate, formData.MonthWise, formData.FromMonth, formData.FromYear); $("html, body").animate({ scrollTop: 500 }, 150); } }; LateEarlyReportComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.LateEarlyReports); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; LateEarlyReportComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], LateEarlyReportComponent.prototype, "modal", void 0); LateEarlyReportComponent = __decorate([ core_1.Component({ providers: [LateEarlyReport_service_1.LateEarlyReportService], templateUrl: 'app/Components/Report/Attendance/LateEarlyReport.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, LateEarlyReport_service_1.LateEarlyReportService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], LateEarlyReportComponent); return LateEarlyReportComponent; }()); exports.LateEarlyReportComponent = LateEarlyReportComponent; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { MyTeamService } from '../../../Service/HumanResource/Attendance/MyTeam.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IMyTeam } from '../../../Model/HumanResource/Attendance/MyTeam'; import { ILinemanager } from '../../../Model/HumanResource/Attendance/MyTeam'; import { ISkillLevel } from '../../../Model/HumanResource/Attendance/MyTeam'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; @Component({ providers: [MyTeamService], templateUrl: 'app/Components/HumanResource/Attendance/MyTeam.component.html' }) export class MyTeamComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; MyTeams: IMyTeam[]; MyTeam: IMyTeam; HoverList: IMyTeam[]; Childdata: IMyTeam[]; SecondData: IMyTeam[]; Linemangers: ILinemanager[]; Linemanger: ILinemanager; Skillleavels: ISkillLevel[]; SkillLevel: ISkillLevel; Skillleavellist: ISkillLevel[]; msg: string; indLoading: boolean = false; MyTeamFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; MyTeamFilter: string; isDesc: boolean = false; column: any = 'SkillName'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; ShowHideSearchNew: boolean = false; searchName: string; searchNumberOfSkill: string; searchNumberToBeApproved: string; //second table searchSkillName: string; searchSkillGroup: string; searchleavel: string; constructor(private fb: FormBuilder, private _MyTeamService: MyTeamService, private pagerService: PagerService) { } ngOnInit(): void { this.MyTeamFrm = this.fb.group({ CompanyId: [''], mode: [''], UserID: [''], Name: [''], NumberOfSkill: [''], NumberToBeApproved: [''], SkillName: [''], SkillGroup: [''], leavel: [''], SkillID: [''], id: [''], IsApproved: [''], Status: [''], }); this.LoadMyTeams(21); } MyTeamFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.MyTeamFilter = value; } MyTeamSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } MyTeamSortNew(property: any) { if (!this.ShowHideSearchNew) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } MouseHover(id: number): void { //this.LoadhoverPopup(event.target.value); this.indLoading = true; this._MyTeamService.GetHoverPopup(Global.BASE_MyTeam_ENDPOINT, id) .subscribe(data => { this.HoverList = data; console.log(data); //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } LoadMyTeams(UserId: number): void { this.indLoading = true; this._MyTeamService.GetMyTeam(Global.BASE_MyTeam_ENDPOINT, UserId) .subscribe(MyTeams => { this.MyTeams = MyTeams; console.log(MyTeams) //Logic for searching - start if (this.ShowHideSearch) { this.searchName = (<HTMLInputElement>document.getElementById("searchName")).value; if (this.searchName != '') { this.searchName = this.searchName.toLocaleLowerCase(); this.MyTeams = this.MyTeams.filter( x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.searchName) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addMyTeam() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New MyTeam"; this.modalBtnTitle = "Add"; this.MyTeamFrm.reset(); this.modal.open(); } editMyTeam(id: number) { debugger; this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit MyTeam"; this.modalBtnTitle = "Update"; this.indLoading = true; this._MyTeamService.GetLinemanager(Global.BASE_MyTeam_ENDPOINT, id) .subscribe(Linemangers => { this.Linemangers = Linemangers; //Logic for searching - start if (this.ShowHideSearchNew) { this.searchSkillName = (<HTMLInputElement>document.getElementById("searchSkillName")).value; if (this.searchSkillName != '') { this.searchSkillName = this.searchSkillName.toLocaleLowerCase(); this.Linemangers = this.Linemangers.filter( x => x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(this.searchName) != -1); } this.searchSkillGroup = (<HTMLInputElement>document.getElementById("searchSkillGroup")).value; if (this.searchSkillGroup != '') { this.searchSkillGroup = this.searchSkillGroup.toLocaleLowerCase(); this.Linemangers = this.Linemangers.filter( x => x.SkillGroup != null && x.SkillGroup.toLocaleLowerCase().indexOf(this.searchSkillGroup) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 } //,error => this.msg = <any>error ); this.modal.open(); } GetSkillOrderLeavel(SkillId: number) { if (SkillId != null) { this._MyTeamService.GetSkill(Global.BASE_MyTeam_ENDPOINT, SkillId) .subscribe(Skillleavels => { this.Skillleavels = Skillleavels; //Logic for searching - End this.indLoading = false; // initialize to page 1 } //,error => this.msg = <any>error ); } else { alert(SkillId) } } deleteMyTeam(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.MyTeamFrm.setValue(this.MyTeam); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.MyTeamFrm.enable() : this.MyTeamFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.MyTeams); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } ShowHideSearchControlsNew() { this.ShowHideSearchNew = !this.ShowHideSearchNew; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._MyTeamService.post(Global.BASE_MyTeam_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadMyTeams(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._MyTeamService.put(Global.BASE_MyTeam_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadMyTeams(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._MyTeamService.delete(Global.BASE_MyTeam_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.LoadMyTeams(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; } } }<file_sep>export interface ISecurityKey { Id: number; Key1: string; Key2: string; Key3: string; Key4: string; Key5: string; Active: boolean; UniqueKey: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>export class Global { public static BASE_CURRENCY_ENDPOINT = 'api/currencyapi/'; public static BASE_VISUSER_ENDPOINT = 'api/visuserapi/'; public static BASE_LEVELS_ENDPOINT = 'api/levelsapi/'; public static BASE_CONTACTMASTER_ENDPOINT = 'api/contactmasterapi/'; public static BASE_BANKMASTER_ENDPOINT = 'api/bankmasterapi/'; public static BASE_RATINGTYPE_ENDPOINT = 'api/RatingTypeAPI/'; public static BASE_LOOKUPTYPE_ENDPOINT = 'api/LookupTypeAPI/'; public static BASE_LOOKUP_ENDPOINT = 'api/lookupapi/'; public static BASE_SKILLGROUP_ENDPOINT = 'api/skillgroupapi/'; public static BASE_FORGOTPASSWORD_ENDPOINT = 'api/VISUserAPI/'; public static BASE_SKILL_ENDPOINT = 'api/skillapi/'; public static BASE_POSITION_ENDPOINT = 'api/positionapi/'; public static BASE_TECHNOLOGYMASTER_ENDPOINT = 'api/technologymasterapi/'; public static BASE_COMPANYMASTER_ENDPOINT = 'api/companymasterapi/'; public static BASE_MACIDCONFIGURATION_ENDPOINT = 'api/macidconfigurationapi/'; public static BASE_SECURITYKEY_ENDPOINT = 'api/securitykeyapi/'; public static BASE_FINANCIALYEAR_ENDPOINT = 'api/financialyearapi/'; public static BASE_EVENTCOUNTDOWN_ENDPOINT = 'api/eventcountdownapi/'; public static BASE_DASHBOARD_ENDPOINT = 'api/dashboardapi/'; public static BASE_COMMONCONFIGURATION_ENDPOINT = 'api/commonconfigurationapi/'; public static BASE_LEVELCONFIGURATION_ENDPOINT = 'api/levelconfigurationapi/'; public static BASE_POLICY_ENDPOINT = 'api/policyapi/'; public static BASE_CONFIGUREWORKSHEET_ENDPOINT = 'api/configureworksheetapi/'; public static BASE_News_ENDPOINT = 'api/Newsapi/'; public static BASE_LEVELCRITERIASETUP_ENDPOINT = 'api/levelcriteriasetupapi/'; public static BASE_CONFIGURETICKET_ENDPOINT = 'api/configureticketapi/'; public static BASE_HelpTicketAdd_ENDPOINT = 'api/HelpTicketAddAPI/'; public static BASE_MyTicket_ENDPOINT = 'api/MyTicketapi/'; public static BASE_HOMEPAGEIMAGE_ENDPOINT = 'api/homepageimageapi/'; public static BASE_ChhangePassword_ENDPOINT = 'api/ProfileAttendanceAPI/'; public static BASE_MyTicketListOpen_ENDPOINT = 'api/TicketListOpenapi/'; public static BASE_MyTicketListClosed_ENDPOINT = 'api/TicketListClosedapi/'; public static BASE_MyProfiles_ENDPOINT = 'api/MyProfilesAPI/'; public static BASE_LeaveType_ENDPOINT = 'api/LeaveTypeapi/'; public static BASE_GroupName_ENDPOINT = 'api/GroupNameapi/'; public static BASE_DailyEntrysheet_ENDPOINT = 'api/DailyEntrysheetAPI/'; public static BASE_AttendanceReport_ENDPOINT = 'api/AttendanceReportAPI/'; public static BASE_OutReportApi_ENDPOINT = 'api/OutReportAPI/'; public static BASE_WorkSheet_ENDPOINT = 'api/WorkSheetAPI/'; public static BASE_MySkill_ENDPOINT = 'api/MySkillAPI/'; public static BASE_MyTeam_ENDPOINT = 'api/MyTeamAPI/'; public static BASE_EmployeeFeedback_ENDPOINT = 'api/EmployeeFeedbackAPI/'; public static BASE_Levels_Achievement_ENDPOINT = 'api/Levels_AchievementAPI/'; public static BASE_AttendanceEntry_ENDPOINT = 'api/AttendanceEntryApi/'; public static BASE_EmployeeScreenCaptureReportAPI_ENDPOINT = 'api/EmployeeScreenCaptureReportAPI/'; public static BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT = 'api/EmployeeDashboarHeartBeatAPI/'; public static BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT = 'api/AttendanceAccessCardComparisionReportAPI/'; public static BASE_EmployeeList_ENDPOINT = 'api/EmployeeListAPI/'; public static BASE_EmpInfoTabular_ENDPOINT = 'api/EmpInfoTabularAPI/'; public static BASE_ManualPointEntry_ENDPOINT = 'api/ManualPointEntryAPI/'; public static BASE_LateEarlyReport_ENDPOINT = 'api/LateEarlyReportAPI/'; public static BASE_UserRole_ENDPOINT = 'api/UserRoleAPI/'; public static BASE_EducationType_ENDPOINT = 'api/EducationTypeAPI/'; public static BASE_SalaryBreakupType_ENDPOINT = 'api/SalaryBreakupTypeAPI/'; public static BASE_AddEmployeeRecord_ENDPOINT = 'api/AddEmployeeRecordAPI/'; public static BASE_AttendanceReportNew_ENDPOINT = 'api/AttendanceReportNewAPI/'; public static BASE_OfficialWorkReportAPI_ENDPOINT = 'api/OfficialWorkReportAPI/'; public static BASE_ProductivityTrackerAPI_ENDPOINT = 'api/ProductivityTrackerReportAPI/'; public static BASE_ConfigureSurveyAPI_ENDPOINT = 'api/ConfigureSurveyAPI/'; public static BASE_RFQ_ENDPOINT = 'api/RFQAPI/'; public static BASE_RFQResponse_ENDPOINT = 'api/RFQResponseAPI/'; public static BASE_CurrencyHistoryAPI_ENDPOINT = 'api/CurrencyHistoryAPI/'; public static BASE_SalaryGrievanceAPI_ENDPOINT = 'api/SalaryGrievanceAPI/'; public static BASE_DocumentTemplateAPI_ENDPOINT = 'api/DocumentTemplateAPI/'; AttendanceAccessCardComparisionReportAPI public ShowMenu: boolean; public static WebAccessURL ='http://localhost:53349'; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { // model For Bind Data public class EmployeeDashboardHeartBeatReport : VISBaseEntity { public string Employee_Name { get; set; } public DateTime Date { get; set; } public string OutTime { get; set; } public string InTime { get; set; } public string TotalTime { get; set; } public string Duration { get; set; } } // model For Send Parameter public class EmployeeDashboardHeartBeatReportParameterModel { public int EmployeeId { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } public string ViewBy { get; set; } public string ConsolidateBy { get; set; } public string OrderBy { get; set; } public int LoginUserId { get; set; } public string FromMonth { get; set; } public string FromYear { get; set; } public string ToMonth { get; set; } public string ToYear { get; set; } public bool MonthWise { get; set; } } public static class EmployeeDashboardHeartBeatReportParameterModelConstant { // Constance For Parameter public const string const_EmployeeId = "employeeId"; public const string const_FromDate = "fromDate"; public const string const_ToDate = "toDate"; public const string const_ViewBy = "viewBy"; public const string const_ConsolidateBy = "consolidateBy"; public const string const_OrderBy = "orderBy"; public const string const_LoginUserId = "LoginUserId"; // Constance For Store Procedure public const string const_procEmployee_DashboardHeartBeatReport = "procEmployee_DashboardHeartBeatReport"; public const string const_ProcAttendanceReportBindDropdown = "ProcAttendanceReportBindDropdown"; public const string const_procFinancialYear_SelectAll = "procGetYear"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var SearchComponent = (function () { function SearchComponent() { this.change = new core_1.EventEmitter(); } SearchComponent.prototype.getEachChar = function (value) { this.change.emit(value); }; SearchComponent.prototype.clearFilter = function () { this.listFilter = null; this.change.emit(null); }; SearchComponent.prototype.getPasteData = function (value) { var pastedVal = value.clipboardData.getData('text/plain'); this.change.emit(pastedVal); value.preventDefault(); }; __decorate([ core_1.Input(), __metadata("design:type", String) ], SearchComponent.prototype, "title", void 0); __decorate([ core_1.Output(), __metadata("design:type", core_1.EventEmitter) ], SearchComponent.prototype, "change", void 0); SearchComponent = __decorate([ core_1.Component({ selector: 'search-list', template: "<div class=\"form-inline\" style=\"float:right;clear:both\">\n <div class=\"form-group\">\n <label><h3>{{title}}</h3></label>\n </div>\n <div class=\"form-group\">\n <div class=\"col-lg-12\">\n <input class=\"form-control\" placeholder=\"Enter any text to filter\" (paste)=\"getPasteData($event)\" (keyup)=\"getEachChar($event.target.value)\" type=\"text\" [(ngModel)]=\"listFilter\" /><img src=\"../../images/cross.png\" class=\"cross-btn\" (click)=\"clearFilter()\" *ngIf=\"listFilter\"/>\n </div>\n </div>\n <div class=\"form-group\">\n <div *ngIf='listFilter'>\n \n </div>\n </div>\n </div> " }) ], SearchComponent); return SearchComponent; }()); exports.SearchComponent = SearchComponent; /* 1. In first line we are importing Input, Output interfaces and EventEmitter class. Input and Output interfaces are self-explanatory, to take the input parameter from CurrencyComponent (in our case the search string from user), Output is to send the value back from SearchComponent but it is little interesting, the output is sent back through event using EventEmitter class. This will get more clear in the further steps. 2. In next line, we are providing the Component metadata, i.e. selector (tag name through which we will use SearchComponent in CurrencyComponent e.g. <search-list></search-list>). template is the HTML part of component. You can also put it in separate HTML file and specify the templateUrl property instead but since this is quite slim, I would prefer to have it in the same file. 3. In SearchComponent class, we are declaring one local variable listFilter that is search string we will use to display here <div class="h3 text-muted">Filter by: {{listFilter}}</div>. That is only for cosmetic purpose to show what we are searching. 4. Second variable title is with @Input decorator, we will send search textbox title from CurrencyComponent. Third variable change is with @Output decorator and of EventEmitter type. This is how we send data back to parent component. change EventEmitter<string> means change is an event that parent component needs to subscribe and will get string argument type. We will explicitly call emit function (i.e. change.emit(“test”)) to send the value back to the parent component. 5. getEachChar(value: any): this function will be called for every character user will enter in search textbox. We are only calling this.change.emit(value); that is sending that character to parent component where it is being sent to the CurrencyFilterPipe pipe to be filtered from Currency list. Just for revision, in CurrencyPipeFilter we are comparing that character with and returning only those records where this character(s) exist. So as long the user would be entering characters in Search textbox, data would be filtering on runtime. 6. clearFilter(): Will clear the filter to reset the Currency list to default without any filtering. 7. getPasteData(value: any): This is little interesting function that will take care if user would copy search string from somewhere and paste it in search textbox to filter the Currencys list. Through value.clipboardData.getData('text/plain') we are getting the pasted data and sending it through change.emit(value) function to parent component. 8. Now, we got some idea about these function, if you jump back to SearchComponent template (HTML). We are calling getEachChar on keyup event that will trigger every time user would type in Search textbox, getPasteData is being called on paste event that will occur when user would paste value in Search textbox, clearFilter function would be called on clicking the cross image that would only be visible if search textbox would have at least one character. */ <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.VacancyRelated { public class RatingType : VISBaseEntity { /// <summary> /// Lookuptype Entity Fields. /// </summary> /// public string TypeName { get; set; } } public static class RatingTypeConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_RatingType_Table = "RatingType"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_TypeName = "TypeName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procRatingType_Add = "procRatingType_Add"; public const string const_procRatingType_Update = "procRatingType_Update"; public const string const_procRatingType_ActiveInActive = "procRatingType_ActiveInActive"; public const string const_procRatingType_SelectAll = "procRatingType_SelectAll"; public const string const_procRatingType_SelectById = "procRatingType_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.RFQ { public class RFQResponse :VISBaseEntity { public long RFQ_InitialID { get; set; } public bool IsEstimateReady { get; set; } public bool IsChangeToAction { get; set; } public int Hours { get; set; } public int Timeline { get; set; } public string Timeline_Unit { get; set; } public int Leadtime { get; set; } public string Leadtime_Unit { get; set; } public string Technology { get; set; } public List<long> TechnologyIdList { get; set; } public string Description { get; set; } public long ActionRequestedBy { get; set; } public DateTime ActionByDate { get; set; } public long EmpId { get; set; } public long UserId { get; set; } public bool Access { get; set; } public long RFQId { get; set; } public string hdnEmployee { get; set; } public string EmployeeName { get; set; } public string Employee_Name { get; set; } public long hdnEmployeeId { get; set; } } public class RFQResponseConstant { /// <summary> /// Database table field Name Constants.Industries /// </summary> /// public const string const_Field_RFQ_InitialID = "RFQ_InitialID"; public const string const_Field_IsEstimateReady = "IsEstimateReady"; public const string const_Field_Hours = "Hours"; public const string const_Field_Timeline = "Timeline"; public const string const_Field_Timeline_Unit = "Timeline_Unit"; public const string const_Field_Leadtime = "Leadtime"; public const string const_Field_Leadtime_Unit = "Leadtime_Unit"; public const string const_Field_Technology = "Technology"; public const string const_Field_Description = "Description"; public const string const_Field_ActionRequestedBy = "ActionRequestedBy"; public const string const_Field_ActionByDate = "ActionByDate"; public const string const_Field_UserId = "UserId"; public const string const_Field_Access = "Access"; public const string const_Field_RFQId = "RFQId"; /// <summary> /// Procedure /// </summary> public const string const_Field_GetEmployeeActionId = "procGetEmployeeActionId"; public const string const_Field_GetEmployeeNameById = "procGetEmployeeNameById"; public const string const_Field_RFQResponse_Add = "procRFQResponse_Add"; public const string const_Field_GetMaxResponseId = "procGetMaxResponseId"; public const string const_Field_GetRFQDetailByRFQInitialId = "procGetRFQDetailByRFQInitialId"; public const string const_Field_GetRFQResponseByResponseId = "procGetRFQResponseByResponseId"; public const string const_Field_GetTechnologyNameById = "procGetTechnologyNameById"; } public class AutoPointAdd { public long empId { get; set; } public string criteria { get; set; } public string forWhichData { get; set; } public decimal rangeCount { get; set; } public bool isTodo { get; set; } } public class AutoPointAddConstant { public const string const_Field_empId = "empId"; public const string const_Field_criteria = "criteria"; public const string const_Field_forWhichData = "forWhichData"; public const string const_Field_rangeCount = "rangeCount"; public const string const_Field_isTodo = "isTodo"; /// <summary> /// Procedure /// </summary> public const string const_Field_Levels_AutomaticPointsEntry = "procLevels_AutomaticPointsEntry"; } public class ActionTakenBy { public long EmpId { get; set; } public string Employee_Name { get; set; } } public class HiddenValue { public long hdnEmployeeId { get; set; } public string hdnEmployee { get; set; } } public class ActionTakenByConstatnt { public const string const_Field_Id = "Id"; public const string const_Field_Employee_Name = "Employee_Name"; public const string const_Field_GetActionTaken = "procGetActionTaken"; } public class MainAddResponse { public SessionData SessionData { get; set; } public RFQResponse RFQResponse { get; set; } public List<RFQDoc> RFQDoc { get; set; } public List<RFQLink> RFQLink { get; set; } public long RFQId { get; set; } } } <file_sep>export interface IBankMaster { Id: number; CompanyId: number; CurrencyId: number BankAlias: string; BankName: string; BranchName: string; BankAddress: string; BankDetail: string; AccountNumber: string; Status: boolean; IsActive: boolean; CreatedOn: Date; UpdatedOn: Date; CreatedBy: string; UpdatedBy: string; EntityMessage: string; } export interface ICompany { Id: number; CompanyName: string; } export interface ICurrency { Id: number; Short_Name: string; }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using VIS_Domain; using VIS_Domain.Master.CurrencyRelated; namespace VIS_Repository.Masters.CurrencyRelated { public class CurrencyHistoryRepository : VISDbCommand { public Int32 intAffectedRecords { get; set; } public CurrencyHistoryRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CurrencyHistoryConstants.const_procCurrencyHistory_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string GetEntityByID(Int64 entityId) { string Default_ExchangeRate = ""; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CurrencyHistoryConstants.procCurrencyHistory_SelectById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if(dt.Rows.Count>0) { Default_ExchangeRate = dt.Rows[0][0].ToString(); } } return Default_ExchangeRate; } public List<CurrencyHistory> GetEntityList() { List<CurrencyHistory> objListToReturn = new List<CurrencyHistory>(); List<CurrencyHistory> lstCurrencyHistory = new List<CurrencyHistory>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = CurrencyHistoryConstants.procCurrencyHistory_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<CurrencyHistory>(dt); foreach (CurrencyHistory item in objListToReturn) { CurrencyHistory objCurrencyHistory = new CurrencyHistory(); objCurrencyHistory.FromDate = new DateTime(Convert.ToInt32(item.Year_Entered), Convert.ToInt32(item.Month_Entered), 01); objCurrencyHistory.ToDate = new DateTime(Convert.ToInt32(item.Year_Entered), Convert.ToInt32(item.Month_Entered), DateTime.DaysInMonth(Convert.ToInt32(item.Year_Entered), Convert.ToInt32(item.Month_Entered))); objCurrencyHistory.Currency_Id = item.Currency_Id; objCurrencyHistory.Default_Exch_Rate = item.Default_Exch_Rate; objCurrencyHistory.Current_Exch_Rate = item.Current_Exch_Rate; objCurrencyHistory.Month_Entered = item.Month_Entered; objCurrencyHistory.Year_Entered = item.Year_Entered; objCurrencyHistory.Date_Entered = item.Date_Entered; objCurrencyHistory.IsActive = item.IsActive; objCurrencyHistory.CreatedOn = item.CreatedOn; objCurrencyHistory.CreatedBy = item.CreatedBy; objCurrencyHistory.UpdatedOn = item.UpdatedOn; objCurrencyHistory.UpdatedBy = item.UpdatedBy; objCurrencyHistory.Id = item.Id; lstCurrencyHistory.Add(objCurrencyHistory); } } return lstCurrencyHistory; } public string AddEntity(CurrencyHistory entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CurrencyHistoryConstants.const_procCurrencyHistory_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Currency_Id, entityObject.Currency_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Default_Exch_Rate, entityObject.Default_Exch_Rate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Current_Exch_Rate, entityObject.Current_Exch_Rate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Month_Entered, entityObject.Month_Entered); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Year_Entered, entityObject.Year_Entered); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(CurrencyHistory entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = CurrencyHistoryConstants.const_procCurrencyHistory_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Currency_Id, entityObject.Currency_Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Default_Exch_Rate, entityObject.Default_Exch_Rate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Current_Exch_Rate, entityObject.Current_Exch_Rate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Month_Entered, entityObject.Month_Entered); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(CurrencyHistoryConstants.const_Field_Year_Entered, entityObject.Year_Entered); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } //void IDisposable.Dispose() //{ // throw new NotImplementedException(); //} // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; using VIS_Repository.Reports.Attendance; using VIS_Repository.Dashboard; using VIS_Repository.Reports; namespace VIS_App.Controllers.Report.Attendance { public class EmployeeDashboarHeartBeatAPIController : BaseAPIController { EmployeeDashboardHeartBeatReportRepository objEmployeeDashboardHeartBeatReportRepository = null; public EmployeeDashboarHeartBeatAPIController() { objEmployeeDashboardHeartBeatReportRepository = new EmployeeDashboardHeartBeatReportRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/EmployeeDashboarHeartBeatAPI/GetEmployee")] [HttpGet] public HttpResponseMessage GetEmployee() { return ToJson(objEmployeeDashboardHeartBeatReportRepository.GetEmployee()); } [Route("api/EmployeeDashboarHeartBeatAPI/GetYear")] [HttpGet] public HttpResponseMessage GetYear() { return ToJson(objEmployeeDashboardHeartBeatReportRepository.GetYear()); } [Route("api/EmployeeDashboarHeartBeatAPI/GetEmployeeDashboardHeartBeatReport")] [HttpPost] public HttpResponseMessage GetEmployeeDashboardHeartBeatReport(EmployeeDashboardHeartBeatReportParameterModel entityobject) { if (entityobject.MonthWise == true) { entityobject.FromDate = new DateTime(Convert.ToInt32(entityobject.FromYear), Convert.ToInt32(entityobject.FromMonth), 01); entityobject.ToDate = new DateTime(Convert.ToInt32(entityobject.ToYear), Convert.ToInt32(entityobject.ToMonth), DateTime.DaysInMonth(Convert.ToInt32(entityobject.ToYear), Convert.ToInt32(entityobject.ToMonth))); } return ToJson(objEmployeeDashboardHeartBeatReportRepository.GetEmployeeDashboardHeartBeatReporytByEmployeeId(entityobject)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class ConfigureTicket : VISBaseEntity { /// <summary> /// organization Entity Fields. /// </summary> public Int64 Parent_Id { get; set; } public Int64 User_Id { get; set; } public string Department_Name { get; set; } public Int64 Position_Id { get; set; } public bool IsActiveSuggestion { get; set; } public string SuggestionAlie { get; set; } public Int64 Organization_Id { get; set; } public Int64 Suggestion_Dep_Emp_Id { get; set; } public bool Flag { get; set; } /// <summary> /// Employee_Master Entity Fields. /// </summary> public string Employee_Name { get; set; } /// <summary> /// SuggestionsOrganizationEmployeeMapping Entity Fields. /// </summary> public Int64 Employee_Id { get; set; } public string Mode { get; set; } } public static class ConfigureTicketConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_organization_Table = "organization"; public const string const_Employee_Master_Table = "Employee_Master"; public const string const_SuggestionsOrganizationEmployeeMapping_Table = "SuggestionsOrganizationEmployeeMapping"; /// <summary> /// Table organization field Name Constants. /// </summary> public const string const_Suggestion_Dep_Emp_Id = "Suggestion_Dep_Emp_Id"; public const string const_Organization_Id = "Organization_Id"; public const string const_Parent_Id = "Parent_Id"; public const string const_User_Id = "User_Id"; public const string const_Department_Name = "Department_Name"; public const string const_Position_Id = "Position_Id"; public const string const_IsActiveSuggestion = "IsActiveSuggestion"; public const string const_SuggestionAlie = "SuggestionAlie"; public const string const_Flag = "Flag"; /// <summary> /// Table Employee_Master field Name Constants. /// </summary> public const string const_Employee_Name = "Employee_Name"; /// <summary> /// Table SuggestionsOrganizationEmployeeMapping field Name Constants. /// </summary> public const string const_Employee_Id = "Employee_Id"; public const string const_Mode = "Mode"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procSelectParent = "procSelectParent"; public const string const_procSelectChildGroup = "procSelectChildGroup"; public const string const_procSelectHead = "procSelectHead"; public const string const_procorganization_Update = "procorganization_Update"; public const string const_proSuggestionsOrganizationEmployeeMapping = "proSuggestionsOrganizationEmployeeMapping"; public const string const_procSuggestionsOrganizationEmployeeMapping_UpdateEmployeeId = "procSuggestionsOrganizationEmployeeMapping_UpdateEmployeeId"; public const string const_procSuggestionsOrganizationEmployeeMapping_Compare = "procSuggestionsOrganizationEmployeeMappingCompare"; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using VIS_Domain.HumanResource.MyProfiles; namespace VIS_Repository.HumanResource.ProfileAttendace { public class MyProfilesRepository : VISDbCommand, VISIBaseRepository<MyProfiles> { public Int32 intAffectedRecords { get; set; } public MyProfilesRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { return null; } public MyProfiles GetEntityByID(Int64 Id) { return null; } public IEnumerable<MyProfiles> GetEntityList() { return null; ; } public string AddEntity(MyProfiles entityObject) { return null; } public string UpdateEntity(MyProfiles entityObject) { return null; } public IEnumerable<MyProfiles> GetProfileByUser(long UserId) { List<MyProfiles> objListToReturn = new List<MyProfiles>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyProfilesConstants.const_procGetUserProfile; base.objSqlCommand.Parameters.AddWithValue(MyProfilesConstants.const_Field_Mode, "ProFileUser"); base.objSqlCommand.Parameters.AddWithValue(MyProfilesConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyProfiles>(dt); } return objListToReturn; } public IEnumerable<MyProfiles> GetEducationUser(long UserId) { List<MyProfiles> objListToReturn = new List<MyProfiles>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyProfilesConstants.const_procGetUserProfile; base.objSqlCommand.Parameters.AddWithValue(MyProfilesConstants.const_Field_Mode, "EducationUser"); base.objSqlCommand.Parameters.AddWithValue(MyProfilesConstants.const_Field_UserId, UserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyProfiles>(dt); } return objListToReturn; } public IEnumerable<MyProfiles> GetEmployeeList() { List<MyProfiles> objListToReturn = new List<MyProfiles>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = MyProfilesConstants.const_procGetEmployeeList; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<MyProfiles>(dt); } return objListToReturn; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } //TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~CurrencyRepository() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); //} //This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep> import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { RFQService } from '../../Service/RFQ/RFQ.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IRFQ } from '../../Model/RFQ/RFQEstimateListing'; import { DBOperation } from '../../Shared/enum'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; @Component({ providers: [RFQService], templateUrl: 'app/Components/RFQ/MyActionRFQ.component.html' }) export class MyActionRFQcomponent implements OnInit { @ViewChild('modal') modal: ModalComponent; RFQs: IRFQ[]; public RFQ: IRFQ; msg: string; indLoading: boolean = false; RFQFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; RFQFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strsearchTitle: string; strsearchInitiatedBy: string; // strsearchDateOfInitiation: string; strsearchEstimateBy: string; // strsearchSubmittedOn: string; strsearchStatus: string; strsearchrfqStatus: string; strsearchLastResponseBy: string; // strsearchLastResponseDate: string; strsearchActionRequestedBy: string; sub: any; Mode: number; Parameter: any; constructor(private fb: FormBuilder, private _RFQService: RFQService, private router: Router, private pagerService: PagerService, private route: ActivatedRoute ) { //this.route.params.subscribe(params => { // this.Parameter = params['param']; // this.LoadRFQs(this.Parameter); //}); } ngOnInit(): void { debugger; //////////////// //this.sub = this.route // .queryParams // .subscribe(params => { // // Defaults to 0 if no query param provided. // this.Mode = +params['Mode'] || 0; // }); //if (this.Mode == 1) { // this.Param = "myrfq"; //} //else if (this.Mode == 2) { // this.Param = "allrfq" //} //else if (this.Mode == 3) { // this.Param = "estimateby" //} //else if (this.Mode == 4) { // this.Param = "mywatch" //} //else { // this.Param = "myaction" //} ////////////////////// this.RFQFrm = this.fb.group({ RFQInitialId: [''], OpportunityId: [''], Title: [''], InitiatedBy: [''], DateOfInitiation: [''], EstimateBy: [''], SubmittedOn: [''], LastResponseBy: [''], LastResponseDate: [''], ActionRequestedBy: [''], Status: [''], rfqStatus: [''], OtherComments: [''], CreatedBy: [''] }); this.LoadRFQs(); } RFQFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.RFQFilter = value; } RFQSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadRFQs(): void { debugger; var UserName = sessionStorage.getItem('VISUsername'); var UserType = sessionStorage.getItem('UserType'); this.indLoading = true; this._RFQService.GetMyActionRFQ(Global.BASE_RFQ_ENDPOINT, UserName) .subscribe(RFQs => { this.RFQs = RFQs; //Logic for searching - start if (this.ShowHideSearch) { ////////// this.strsearchTitle = (<HTMLInputElement>document.getElementById("searchTitle")).value; if (this.strsearchTitle != '') { this.strsearchTitle = this.strsearchTitle.toLocaleLowerCase(); this.RFQs = this.RFQs.filter( x => x.Title != null && x.Title.toLocaleLowerCase().indexOf(this.strsearchTitle) != -1); } ///////// this.strsearchInitiatedBy = (<HTMLInputElement>document.getElementById("searchInitiatedBy")).value; if (this.strsearchInitiatedBy != '') { this.strsearchInitiatedBy = this.strsearchInitiatedBy.toLocaleLowerCase(); this.RFQs = this.RFQs.filter( x => x.InitiatedBy != null && x.InitiatedBy.toLocaleLowerCase().indexOf(this.strsearchInitiatedBy) != -1); } ////////// //this.strsearchDateOfInitiation = (<HTMLInputElement>document.getElementById("searchName")).value; //if (this.strsearchDateOfInitiation != '') { // this.strsearchDateOfInitiation = this.strsearchDateOfInitiation.toLocaleLowerCase(); // this.RFQs = this.RFQs.filter( // x => x.DateOfInitiation != null && x.DateOfInitiation.toLocaleLowerCase().indexOf(this.strsearchDateOfInitiation) != -1); //} ///////// this.strsearchEstimateBy = (<HTMLInputElement>document.getElementById("searchEstimateBy")).value; if (this.strsearchEstimateBy != '') { this.strsearchEstimateBy = this.strsearchEstimateBy.toLocaleLowerCase(); this.RFQs = this.RFQs.filter( x => x.EstimateBy != null && x.EstimateBy.toLocaleLowerCase().indexOf(this.strsearchEstimateBy) != -1); } ////////// //this.strSearchName = (<HTMLInputElement>document.getElementById("searchName")).value; //if (this.strSearchName != '') { // this.strSearchName = this.strSearchName.toLocaleLowerCase(); // this.RFQs = this.RFQs.filter( // x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strSearchName) != -1); //} ///////// this.strsearchStatus = (<HTMLInputElement>document.getElementById("searchStatus")).value; if (this.strsearchStatus != '') { this.strsearchStatus = this.strsearchStatus.toLocaleLowerCase(); this.RFQs = this.RFQs.filter( x => x.Status != null && x.Status.toLocaleLowerCase().indexOf(this.strsearchStatus) != -1); } ////////// this.strsearchrfqStatus = (<HTMLInputElement>document.getElementById("searchrfqStatus")).value; if (this.strsearchrfqStatus != '') { this.strsearchrfqStatus = this.strsearchrfqStatus.toLocaleLowerCase(); this.RFQs = this.RFQs.filter( x => x.rfqStatus != null && x.rfqStatus.toLocaleLowerCase().indexOf(this.strsearchrfqStatus) != -1); } ///////// this.strsearchLastResponseBy = (<HTMLInputElement>document.getElementById("searchLastResponseBy")).value; if (this.strsearchLastResponseBy != '') { this.strsearchLastResponseBy = this.strsearchLastResponseBy.toLocaleLowerCase(); this.RFQs = this.RFQs.filter( x => x.LastResponseBy != null && x.LastResponseBy.toLocaleLowerCase().indexOf(this.strsearchLastResponseBy) != -1); } ////////// //this.strSearchName = (<HTMLInputElement>document.getElementById("searchName")).value; //if (this.strSearchName != '') { // this.strSearchName = this.strSearchName.toLocaleLowerCase(); // this.RFQs = this.RFQs.filter( // x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strSearchName) != -1); //} ///////// this.strsearchActionRequestedBy = (<HTMLInputElement>document.getElementById("searchActionRequestedBy")).value; if (this.strsearchActionRequestedBy != '') { this.strsearchActionRequestedBy = this.strsearchActionRequestedBy.toLocaleLowerCase(); this.RFQs = this.RFQs.filter( x => x.ActionRequestedBy != null && x.ActionRequestedBy.toLocaleLowerCase().indexOf(this.strsearchActionRequestedBy) != -1); } ////////// } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addRFQ(): void { this.router.navigate(['/AddRFQ']); } deleteRFQ(id: number, status: boolean) { //this.dbops = DBOperation.delete; //this.SetControlsState(false); //if (status == true) { // this.modalTitle = "Confirm to Delete?"; // this.modalBtnTitle = "Delete"; //} //else { // this.modalTitle = "Confirm to Undo Delete?"; // this.modalBtnTitle = "Undo Delete"; //} //this.RFQ = this.RFQs.filter(x => x.Id == id)[0]; //this.RFQFrm.setValue(this.RFQ); //this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.RFQFrm.enable() : this.RFQFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.RFQs); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } }<file_sep>export interface IMyAlerts { Name: string; Status: string; Type: string; }<file_sep>export interface IMacIdConfiguration { Id: number; EmployeeId: number; Employee_Name: string; MacID1: string; MacID2: string; MacID3: string; MacID4: string; MacID5: string; MacID6: string; MacID: string; IP1: string; IP2: string; IP3: string; IP4: string; IPAddress: string; RequestedDate: Date; ApprovalDate: Date; ApprovedBy: string; Version1: string; Version2: string; Version3: string; Version: string; Active: boolean; OfficeMacId: boolean; Description: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; namespace VIS_App.Controllers.Masters.Configuration { public class ConfigureTicketAPIController : BaseAPIController { ConfigureTicketRepository objConfigureTicketRepository = null; VISIBaseRepository<ConfigureTicket> ConfigureTicketRepository; public ConfigureTicketAPIController(VISIBaseRepository<ConfigureTicket> _ConfigureTicketRepository) { objConfigureTicketRepository = new ConfigureTicketRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); ConfigureTicketRepository = _ConfigureTicketRepository; } [Route("api/ConfigureTicketAPI/GetParentGroupData")] [HttpGet] public HttpResponseMessage GetParentGroupData() { return ToJson(objConfigureTicketRepository.GetParantGroup()); } [Route("api/ConfigureTicketAPI/GetChildGroupData")] [HttpGet] public HttpResponseMessage GetChildGroupData(int Parent_Id) { return ToJson(objConfigureTicketRepository.GetChildGroup(Parent_Id)); } [Route("api/ConfigureTicketAPI/GetEmployeeHeadData")] [HttpGet] public HttpResponseMessage GetEmployeeHeadData() { return ToJson(objConfigureTicketRepository.GetEmployeeHead()); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]ConfigureTicket value) { value.Id = Id; return ToJson(ConfigureTicketRepository.UpdateEntity(value)); } [Route("api/ConfigureTicketAPI/GetListofTicketDisplay")] [HttpGet] public HttpResponseMessage GetListofTicketDisplay(int Organization_Id) { return ToJson(objConfigureTicketRepository.GetListofTicketDisplayTo(Organization_Id)); } [Route("api/ConfigureTicketAPI/SaveEmployeeId")] [HttpPut] public HttpResponseMessage SaveEmployeeId(List<ConfigureTicket> value) { return ToJson(objConfigureTicketRepository.UpdateEmployeeNew(value)); } } } <file_sep>import { DatePipe } from '@angular/common'; import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { LevelConfigurationService } from '../../../service/Masters/EmployeeLevels/LevelConfiguration.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ILevelConfiguration } from '../../../Model/Masters/EmployeeLevels/LevelConfiguration'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; @Component({ providers: [LevelConfigurationService], templateUrl: 'app/Components/Masters/EmployeeLevels/LevelConfiguration.component.html' }) export class LevelConfigurationComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; LevelConfigurations: ILevelConfiguration[]; public LevelConfiguration: ILevelConfiguration; msg: string; indLoading: boolean = false; LevelConfigurationFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; LevelConfigurationFilter: string; isDesc: boolean = false; column: any = 'Full_Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; //Variables for Filter ShowHideSearch: boolean = false; strsearchPeriodName: string; strSearchLevelConfigurationDetails: string; ArrayYear: number[] = new Array(); CurrentYear: number; YearforEdit: number; constructor(private fb: FormBuilder, private _LevelConfigurationService: LevelConfigurationService, private pagerService: PagerService) { } ngOnInit(): void { this.LevelConfigurationFrm = this.fb.group({ Id: [''], Period: [''], PeriodName: [''], StartDate: [''], EndDate: [''], Active: [''], IsCurrentPeriod: [''], StartYear: [''], StartMonth: [''], CompanyId: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); this.LoadLevelConfigurations() this.YearforEdit = ((new Date()).getFullYear())-1; } LevelConfigurationFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.LevelConfigurationFilter = value; } LevelConfigurationSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadLevelConfigurations(): void { debugger this.indLoading = true; this._LevelConfigurationService.get(Global.BASE_LEVELCONFIGURATION_ENDPOINT) .subscribe(LevelConfigurations => { debugger; this.LevelConfigurations = LevelConfigurations; //Logic for searching - start if (this.ShowHideSearch) { this.strsearchPeriodName = (<HTMLInputElement>document.getElementById("searchPeriodName")).value; if (this.strsearchPeriodName != '') { this.strsearchPeriodName = this.strsearchPeriodName.toLocaleLowerCase(); this.LevelConfigurations = this.LevelConfigurations.filter( x => x.PeriodName != null && x.PeriodName.toLocaleLowerCase().indexOf(this.strsearchPeriodName) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } FillYear() { this.ArrayYear = []; var displayDate = (new Date()).getFullYear(); var EndDate = displayDate; var j: number = 6; for (var i = 0; i < j; i++) { this.ArrayYear.push(EndDate); EndDate = EndDate + 1; } } addLevelConfiguration() { this.FillYear(); this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New LevelConfiguration"; this.modalBtnTitle = "Add"; this.LevelConfigurationFrm.reset(); this.modal.open(); } editLevelConfiguration(id: number) { debugger; this.FillYear(); this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit LevelConfiguration"; this.modalBtnTitle = "Update"; this.LevelConfiguration = this.LevelConfigurations.filter(x => x.Id == id)[0]; this.LevelConfigurationFrm.setValue(this.LevelConfiguration); this.modal.open(); } deleteLevelConfiguration(id: number, status: boolean) { this.FillYear(); this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.LevelConfiguration = this.LevelConfigurations.filter(x => x.Id == id)[0]; this.LevelConfigurationFrm.setValue(this.LevelConfiguration); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.LevelConfigurationFrm.enable() : this.LevelConfigurationFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.LevelConfigurations); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._LevelConfigurationService.post(Global.BASE_LEVELCONFIGURATION_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLevelConfigurations(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._LevelConfigurationService.put(Global.BASE_LEVELCONFIGURATION_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLevelConfigurations(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._LevelConfigurationService.delete(Global.BASE_LEVELCONFIGURATION_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "LevelConfiguration status changed successfully."; this.LoadLevelConfigurations(); } else { this.msg = "Error has occurred while changing status of existing LevelConfiguration!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { AttendanceReportNewService } from '../../../Service/Report/Attendance/AttendanceReportNew.service'; import { IDepartment, IEmployee, ICompany, ILineManager, IUserType, IYear, IAttendanceReport } from '../../../Model/Report/Attendance/AttendanceReportNew'; @Component({ providers: [AttendanceReportNewService], templateUrl: 'app/Components/Report/Attendance/AttendanceReportNew.component.html' }) export class AttendanceReportNewcomponent implements OnInit { @ViewChild('modalAttendanceApprovalPunchIn') modalAttendanceApprovalPunchIn: ModalComponent; @ViewChild('modalAttendanceApprovalPunchOut') modalAttendanceApprovalPunchOut: ModalComponent; @ViewChild('modalAttendanceApprovalLunchOut') modalAttendanceApprovalLunchOut: ModalComponent; @ViewChild('modalAttendanceApprovalLunchIn') modalAttendanceApprovalLunchIn: ModalComponent; @ViewChild('modalAttendanceApprovalOtherWork') modalAttendanceApprovalOtherWork: ModalComponent; Department: IDepartment[]; Employee: IEmployee[]; Company: ICompany[]; LineManager: ILineManager[]; User: IUserType[]; Year: IYear[]; Attendance: IAttendanceReport[]; AttendanceReportNewFrm: FormGroup; indLoading: boolean = false; CurrentRecordsPerPage: number = 10; pager: any = {}; pagedItems: any[]; msg: string; Yearval: number; Month: number; StartDate: string; EndDate: string; SystemDate: Date; IsAdmin: boolean; ModeId: number; EmployeeName: string; Date: string; Grace: number; EntryHr: string; EntryMin: string; ActualEHr: string; ActualEMin: string; constructor(private fb: FormBuilder, public _AttendanceReportNewService: AttendanceReportNewService, private router: Router, private pagerService: PagerService) { this.GetSystemDateTime(); } ngOnInit(): void { $("#depart").hide(); $("#company").hide(); $("#LineManager").hide(); $("#usertType").hide(); $("#emp").show(); $("#empAll").show(); $("#date").hide(); $("#rbtemployee").prop("checked", true); $("#rbtMonth").prop("checked", true); $("#rbtsortname").prop("checked", true); $("#rbtgrid").prop("checked", true); this.Yearval = new Date().getFullYear(); $("#tdAdmin").hide(); $('#ddlmonth option:eq(' + (new Date).getMonth() + ')').prop('selected', true); $('#ddlemp option[value="0"]').attr("selected", "SelectALL"); this.Month = new Date().getMonth() + 1; this.FillDepartMent(); this.FillEmployee(); this.FillCompany(); this.FillAllLineManager(); this.FillUserType(); this.FillYear(); } HideECLU() { $("#emp").hide(-300); $("#empAll").hide(-300); $("#company").hide(-300); $("#LineManager").hide(-300); $("#usertType").hide(-300); $("#depart").show(-300); } HideDCLU() { $("#depart").hide(-300); $("#company").hide(-300); $("#LineManager").hide(-300); $("#usertType").hide(-300); $("#emp").show(-300); $("#empAll").show(-300); } HideDELU() { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#LineManager").hide(-300); $("#usertType").hide(-300); $("#company").show(-300); } HideDECU() { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#company").hide(-300); $("#usertType").hide(-300); $("#LineManager").show(-300); } HideDECL() { $("#depart").hide(-300); $("#emp").hide(-300); $("#empAll").hide(-300); $("#company").hide(-300); $("#LineManager").hide(-300); $("#usertType").show(-300); } HideDate() { $("#date").hide(-300); $("#month").show(-300); } HideMonth() { $("#date").show(-300); $("#month").hide(-300); } FillDepartMent(): void { this._AttendanceReportNewService.FillDepartMent(Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(data => { this.indLoading = false; this.Department = data; }, error => { this.msg = error; }); } FillEmployee(): void { var UserId = 21; var UserType = 'Admin'; this._AttendanceReportNewService.FillEmployee(Global.BASE_AttendanceReportNew_ENDPOINT, UserId, UserType) .subscribe(data => { this.indLoading = false; this.Employee = data; }, error => { this.msg = error; }); } FillAllEmployee(event): void { if ($('#chkallemployee').is(':checked')) { this._AttendanceReportNewService.FillAllEmployee(Global.BASE_AttendanceReportNew_ENDPOINT, true, 21) .subscribe(data => { this.indLoading = false; this.Employee = data; }, error => { this.msg = error; }); } else { this._AttendanceReportNewService.FillEmployee(Global.BASE_AttendanceReportNew_ENDPOINT, 21, 'Admin') .subscribe(data => { this.indLoading = false; this.Employee = data; }, error => { this.msg = error; }); } } FillCompany(): void { this._AttendanceReportNewService.FillCompany(Global.BASE_AttendanceReportNew_ENDPOINT, true) .subscribe(data => { this.indLoading = false; this.Company = data; }, error => { this.msg = error; }); } FillAllLineManager(): void { this._AttendanceReportNewService.FillAllLineManager(Global.BASE_AttendanceReportNew_ENDPOINT, true, 21) .subscribe(data => { this.indLoading = false; this.LineManager = data; }, error => { this.msg = error; }); } FillUserType(): void { this._AttendanceReportNewService.FillUserType(Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(data => { this.indLoading = false; this.User = data; }, error => { this.msg = error; }); } FillYear(): void { this._AttendanceReportNewService.FillYear(Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(data => { this.indLoading = false; this.Year = data; }, error => { this.msg = error; }); } GetSystemDateTime(): void { this._AttendanceReportNewService.GetSystemDateTime(Global.BASE_AttendanceReportNew_ENDPOINT) .subscribe(data => { this.indLoading = false; this.SystemDate = data; }, error => { this.msg = error; }); } ChangeId(event): void { this.ModeId = event.target.value; } lastday = function (y, m) { return new Date(y, m + 1, 0).getDate(); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.Attendance); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } btnAttendanceApprovePunchIn(ATRPNEW): void { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.PunchIntime != null) { this.EntryHr = ATRPNEW.PunchIntime.trim().slice(11, 13); this.EntryMin = ATRPNEW.PunchIntime.trim().slice(14, 16); } this.modalAttendanceApprovalPunchIn.open(); } } btnAttendanceApprovePunchOut(ATRPNEW): void { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.PunchOuttime != null) { this.EntryHr = ATRPNEW.PunchOuttime.trim().slice(11, 13); this.EntryMin = ATRPNEW.PunchOuttime.trim().slice(14, 16); } this.modalAttendanceApprovalLunchOut.open(); } } btnAttendanceApproveLunchOut(ATRPNEW): void { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.LunchOutTime != null) { this.EntryHr = ATRPNEW.LunchOutTime.trim().slice(11, 13); this.EntryMin = ATRPNEW.LunchOutTime.trim().slice(14, 16); } this.modalAttendanceApprovalLunchOut.open(); } } btnAttendanceApproveLunchIn(ATRPNEW): void { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.LunchInTime != null) { this.EntryHr = ATRPNEW.LunchInTime.trim().slice(11, 13); this.EntryMin = ATRPNEW.LunchInTime.trim().slice(14, 16); } this.modalAttendanceApprovalLunchIn.open(); } } btnAttendanceApproveOtherwork(ATRPNEW): void { if (ATRPNEW.IsAdmin == true) { this.EmployeeName = ATRPNEW.EmployeeName; this.Date = ATRPNEW.Date; this.Grace = ATRPNEW.Grace; if (ATRPNEW.HR_In_Time.length > 4) { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 2); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(3, 5); } else { this.ActualEHr = ATRPNEW.HR_In_Time.trim().slice(0, 1); this.ActualEMin = ATRPNEW.HR_In_Time.trim().slice(2, 4); } if (ATRPNEW.OtherWork != null) { this.EntryHr = ATRPNEW.OtherWork.trim().slice(0, 2); this.EntryMin = ATRPNEW.OtherWork.trim().slice(3, 5); } this.modalAttendanceApprovalOtherWork.open(); } } RedirectToTimeSheet(ATRPNEW): void { } RedirectToRecordPerEmp(ATRPNEW): void { this.router.navigate(['/DailyEntryReport'], { queryParams: { EmployeeId: ATRPNEW.EmployeeId, EmployeeName: ATRPNEW.EmployeeName, Date: ATRPNEW.Date, EntryTime: ATRPNEW.PunchIntime, Remarks: ATRPNEW.In_Remarks } }); } RedirectToAddEmpRecord(ATRPNEW): void { var d1 = ATRPNEW.Date.split('/'); var datval = d1[1] + '/' + d1[0] + '/' + d1[2]; this.router.navigate(['/AddEmployeeRecord'], { queryParams: { EmployeeId: ATRPNEW.EmployeeId, EmployeeName: ATRPNEW.EmployeeName, Date: datval, EntryTime: ATRPNEW.PunchIntime, Remarks: ATRPNEW.In_Remarks } }); } onSubmit(formData: any) { var month = formData.Month; var year = formData.year; year = jQuery("#ddlyear option:selected").text(); var day = 1; var SortBy; var Mode; if ($('#rbtDate').is(':checked')) { if ($('#txtfromdate').val() != "") { this.StartDate = $('#txtfromdate').val(); } else { this.StartDate = this.SystemDate.toString(); } if ($('#txttodate').val() != "") { this.EndDate = $('#txttodate').val(); } else { this.EndDate = this.StartDate; } } if ($('#rbtMonth').is(':checked')) { this.StartDate = year + '/' + month + '/' + day + ' '.concat('12:00:00 AM'); var y = this.SystemDate.toString().trim(); y = y.slice(6, 10); var dat = this.SystemDate.toString().trim(); var mon = this.SystemDate.toString().trim(); var lastDate = this.lastday(year, month).toString(); if (year == y) { mon = mon.slice(0, 2); if (month == mon) { dat = dat.slice(3, 5); this.EndDate = year + '/' + month + '/' + lastDate + ' '.concat('12:00:00 AM'); var diff = Date.parse(this.EndDate) - Date.parse(this.StartDate); day = diff / 1000 / 60 / 60 / 24; } else { this.EndDate = year + '/' + month + '/' + lastDate + ' '.concat('12:00:00 AM'); } } else { this.EndDate = year + '/' + month + '/' + lastDate + ' '.concat('12:00:00 AM'); } } if ($('#rbtsortdate').is(':checked')) { SortBy = "Date"; } else { SortBy = "Name"; } if ($('#rbtdepartment').is(':checked')) { Mode = "department" this.ModeId = formData.Department; } else if ($('#rbtemployee').is(':checked')) { Mode = "employee"; if (formData.Employee == '') { if ($('#chkallemployee').is(':checked')) { this.ModeId = -1; } else { this.ModeId = 0; } } else { this.ModeId = formData.Employee; } } else if ($('#rbtcompany').is(':checked')) { Mode = "company"; if (formData.Company == '') { this.ModeId = 0; } else { this.ModeId = formData.Company; } } else if ($('#rbtlinemanager').is(':checked')) { Mode = "linemanager"; if (formData.LineManager == '') { this.ModeId = 0; } else { this.ModeId = formData.LineManager; } } else if ($('#rbtusertype').is(':checked')) { Mode = "usertype"; if (formData.UserType == '') { this.ModeId = 0; } else { this.ModeId = formData.UserType; } } this.IsAdmin = true; if ($('#rbtreport').is(':checked')) { this._AttendanceReportNewService.GetAllAttendanceReport(Global.BASE_AttendanceReportNew_ENDPOINT, Mode, this.ModeId, this.StartDate, this.EndDate, SortBy, this.IsAdmin) .subscribe(data => { this.indLoading = false; this.Attendance = data; if (data != '' && data.length > 0) { this.JumpOnPage(1);//Report Generated } }) } else { this._AttendanceReportNewService.GetAllAttendanceData(Global.BASE_AttendanceReportNew_ENDPOINT, Mode, this.ModeId, this.StartDate, this.EndDate, SortBy, this.IsAdmin) .subscribe(data => { this.indLoading = false; this.Attendance = data; if (data != '' && data.length > 0) { if ($('#rbtgrid').is(':checked')) { this.JumpOnPage(1); } else if ($('#rbtexcel').is(':checked')) { // Download } else { //rdlc Report Generate } } }, error => { this.msg = error; }); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var RFQ_service_1 = require("../../Service/RFQ/RFQ.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var router_1 = require("@angular/router"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); //import * as _ from 'underscore'; var pager_index_1 = require("../../Shared/pager.index"); var ResponceRequestedRFQcomponent = (function () { function ResponceRequestedRFQcomponent(fb, _RFQService, router, pagerService, route) { //this.route.params.subscribe(params => { // this.Parameter = params['param']; // this.LoadRFQs(this.Parameter); this.fb = fb; this._RFQService = _RFQService; this.router = router; this.pagerService = pagerService; this.route = route; this.indLoading = false; this.isDesc = false; this.column = 'Full_Name'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; //}); } ResponceRequestedRFQcomponent.prototype.ngOnInit = function () { debugger; //////////////// //this.sub = this.route // .queryParams // .subscribe(params => { // // Defaults to 0 if no query param provided. // this.Mode = +params['Mode'] || 0; // }); //if (this.Mode == 1) { // this.Param = "myrfq"; //} //else if (this.Mode == 2) { // this.Param = "allrfq" //} //else if (this.Mode == 3) { // this.Param = "estimateby" //} //else if (this.Mode == 4) { // this.Param = "mywatch" //} //else { // this.Param = "myaction" //} ////////////////////// this.RFQFrm = this.fb.group({ RFQInitialId: [''], OpportunityId: [''], Title: [''], InitiatedBy: [''], DateOfInitiation: [''], EstimateBy: [''], SubmittedOn: [''], LastResponseBy: [''], LastResponseDate: [''], ActionRequestedBy: [''], Status: [''], rfqStatus: [''], OtherComments: [''], CreatedBy: [''] }); this.LoadRFQs(); }; ResponceRequestedRFQcomponent.prototype.RFQFilterCriteriaChange = function (value) { if (value != '[object Event]') this.RFQFilter = value; }; ResponceRequestedRFQcomponent.prototype.RFQSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; ResponceRequestedRFQcomponent.prototype.LoadRFQs = function () { var _this = this; debugger; var UserName = sessionStorage.getItem('VISUsername'); var UserType = sessionStorage.getItem('UserType'); this.indLoading = true; this._RFQService.getResponceRequestedRFQ(global_1.Global.BASE_RFQ_ENDPOINT, UserName) .subscribe(function (RFQs) { _this.RFQs = RFQs; //Logic for searching - start if (_this.ShowHideSearch) { ////////// _this.strsearchTitle = document.getElementById("searchTitle").value; if (_this.strsearchTitle != '') { _this.strsearchTitle = _this.strsearchTitle.toLocaleLowerCase(); _this.RFQs = _this.RFQs.filter(function (x) { return x.Title != null && x.Title.toLocaleLowerCase().indexOf(_this.strsearchTitle) != -1; }); } ///////// _this.strsearchInitiatedBy = document.getElementById("searchInitiatedBy").value; if (_this.strsearchInitiatedBy != '') { _this.strsearchInitiatedBy = _this.strsearchInitiatedBy.toLocaleLowerCase(); _this.RFQs = _this.RFQs.filter(function (x) { return x.InitiatedBy != null && x.InitiatedBy.toLocaleLowerCase().indexOf(_this.strsearchInitiatedBy) != -1; }); } ////////// //this.strsearchDateOfInitiation = (<HTMLInputElement>document.getElementById("searchName")).value; //if (this.strsearchDateOfInitiation != '') { // this.strsearchDateOfInitiation = this.strsearchDateOfInitiation.toLocaleLowerCase(); // this.RFQs = this.RFQs.filter( // x => x.DateOfInitiation != null && x.DateOfInitiation.toLocaleLowerCase().indexOf(this.strsearchDateOfInitiation) != -1); //} ///////// _this.strsearchEstimateBy = document.getElementById("searchEstimateBy").value; if (_this.strsearchEstimateBy != '') { _this.strsearchEstimateBy = _this.strsearchEstimateBy.toLocaleLowerCase(); _this.RFQs = _this.RFQs.filter(function (x) { return x.EstimateBy != null && x.EstimateBy.toLocaleLowerCase().indexOf(_this.strsearchEstimateBy) != -1; }); } ////////// //this.strSearchName = (<HTMLInputElement>document.getElementById("searchName")).value; //if (this.strSearchName != '') { // this.strSearchName = this.strSearchName.toLocaleLowerCase(); // this.RFQs = this.RFQs.filter( // x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strSearchName) != -1); //} ///////// _this.strsearchStatus = document.getElementById("searchStatus").value; if (_this.strsearchStatus != '') { _this.strsearchStatus = _this.strsearchStatus.toLocaleLowerCase(); _this.RFQs = _this.RFQs.filter(function (x) { return x.Status != null && x.Status.toLocaleLowerCase().indexOf(_this.strsearchStatus) != -1; }); } ////////// _this.strsearchrfqStatus = document.getElementById("searchrfqStatus").value; if (_this.strsearchrfqStatus != '') { _this.strsearchrfqStatus = _this.strsearchrfqStatus.toLocaleLowerCase(); _this.RFQs = _this.RFQs.filter(function (x) { return x.rfqStatus != null && x.rfqStatus.toLocaleLowerCase().indexOf(_this.strsearchrfqStatus) != -1; }); } ///////// _this.strsearchLastResponseBy = document.getElementById("searchLastResponseBy").value; if (_this.strsearchLastResponseBy != '') { _this.strsearchLastResponseBy = _this.strsearchLastResponseBy.toLocaleLowerCase(); _this.RFQs = _this.RFQs.filter(function (x) { return x.LastResponseBy != null && x.LastResponseBy.toLocaleLowerCase().indexOf(_this.strsearchLastResponseBy) != -1; }); } ////////// //this.strSearchName = (<HTMLInputElement>document.getElementById("searchName")).value; //if (this.strSearchName != '') { // this.strSearchName = this.strSearchName.toLocaleLowerCase(); // this.RFQs = this.RFQs.filter( // x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strSearchName) != -1); //} ///////// //this.strsearchActionRequestedBy = (<HTMLInputElement>document.getElementById("searchDesignation")).value; //if (this.strsearchActionRequestedBy != '') { // this.strsearchActionRequestedBy = this.strsearchActionRequestedBy.toLocaleLowerCase(); // this.RFQs = this.RFQs.filter( // x => x.ActionRequestedBy != null && x.ActionRequestedBy.toLocaleLowerCase().indexOf(this.strsearchActionRequestedBy) != -1); //} ////////// } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; ResponceRequestedRFQcomponent.prototype.addRFQ = function () { this.router.navigate(['/AddRFQ']); }; ResponceRequestedRFQcomponent.prototype.deleteRFQ = function (id, status) { //this.dbops = DBOperation.delete; //this.SetControlsState(false); //if (status == true) { // this.modalTitle = "Confirm to Delete?"; // this.modalBtnTitle = "Delete"; //} //else { // this.modalTitle = "Confirm to Undo Delete?"; // this.modalBtnTitle = "Undo Delete"; //} //this.RFQ = this.RFQs.filter(x => x.Id == id)[0]; //this.RFQFrm.setValue(this.RFQ); //this.modal.open(); }; ResponceRequestedRFQcomponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.RFQFrm.enable() : this.RFQFrm.disable(); }; ResponceRequestedRFQcomponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; ResponceRequestedRFQcomponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.RFQs); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; ResponceRequestedRFQcomponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], ResponceRequestedRFQcomponent.prototype, "modal", void 0); ResponceRequestedRFQcomponent = __decorate([ core_1.Component({ providers: [RFQ_service_1.RFQService], templateUrl: 'app/Components/RFQ/ResponceRequestedRFQ.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, RFQ_service_1.RFQService, router_1.Router, pager_index_1.PagerService, router_1.ActivatedRoute]) ], ResponceRequestedRFQcomponent); return ResponceRequestedRFQcomponent; }()); exports.ResponceRequestedRFQcomponent = ResponceRequestedRFQcomponent; <file_sep> import { Component, OnInit, ViewChild } from '@angular/core'; import { TicketListClosedService } from '../../service/Notification/TicketListClosed.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ITicketListClosed } from '../../Model/Notification/TicketListClosed'; import { IOraganization } from '../../Model/Notification/Organization'; import { FileDropDirective, FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-upload'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { DatePipe } from '@angular/common'; @Component({ providers: [TicketListClosedService], templateUrl: 'app/Components/Notification/TicketListClosed.component.html' }) export class TicketListClosedComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('modal1') modal1: ModalComponent; TicketListCloseds: ITicketListClosed[]; TicketListClosed: ITicketListClosed; ViewHistory: ITicketListClosed[]; GetDetail: ITicketListClosed[]; GetDetails: ITicketListClosed; ClosedTicketCount: number; TerminatedTicketCount: number; msg: string; indLoading: boolean = false; TicketListClosedFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; TicketListClosedFilter: string; isDesc: boolean = false; column: any = 'Subject'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchSubject: string; strSearchMessage: string; strSearchAddressToGroup: string; strSearchAssignTo: string; strSearchPriority: string; strSearchUpdatebyName: string; strSearchStatus: string; Count: number; constructor(private fb: FormBuilder, private _TicketListClosedService: TicketListClosedService, private pagerService: PagerService) { } ngOnInit(): void { this.TicketListClosedFrm = this.fb.group({ CompanyId: [''], Id: 0, Subject: [''], Message: [''], Remarks: [''], AddressToGroup: [''], AssignTo: [''], CreatedByName: [''], UpdatedByName: [''], Priority: [''], Status: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], Mode: [''], HelpTicketId: [''], FileName: [''], RoleType: [''], EntityMessage: [''] }); this.LoadGetTicketDetailUser(21); //this.loadcount(); //this.Loadstore(); // this.LoadOpenTicket(21); } TicketListClosedFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.TicketListClosedFilter = value; } TicketListClosedSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } //Loadstore() { // // this.TicketListCloseds = this.TicketListCloseds.filter(x => x.Status == "Open"); // this.JumpOnPage(1); // for (var i = 0; i < this.TicketListCloseds.length; i++) { // if (this.TicketListCloseds[i].Status == "Open") // return this.TicketListCloseds[i]; // } //} LoadCount() { this.ClosedTicketCount = this.TicketListCloseds.filter(x => x.Status.toLowerCase() == "closed").length; this.TerminatedTicketCount = this.TicketListCloseds.filter(x => x.Status.toLowerCase() == "terminated").length; } LoadGetTicketDetailUser(UserId: number): void { this.indLoading = true; this._TicketListClosedService.getTicketuser(Global.BASE_MyTicketListClosed_ENDPOINT, UserId) .subscribe(data => { // console.log(data) this.TicketListCloseds = data; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchSubject = (<HTMLInputElement>document.getElementById("searchSubject")).value; if (this.strSearchSubject != '') { this.strSearchSubject = this.strSearchSubject.toLocaleLowerCase(); this.TicketListCloseds = this.TicketListCloseds.filter( x => x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(this.strSearchSubject) != -1); } } if (this.ShowHideSearch) { this.strSearchAddressToGroup = (<HTMLInputElement>document.getElementById("searchAddressToGroup")).value; if (this.strSearchAddressToGroup != '') { this.strSearchAddressToGroup = this.strSearchAddressToGroup.toLocaleLowerCase(); this.TicketListCloseds = this.TicketListCloseds.filter( x => x.AddressToGroup != null && x.AddressToGroup.toLocaleLowerCase().indexOf(this.strSearchAddressToGroup) != -1); } } if (this.ShowHideSearch) { this.strSearchAssignTo = (<HTMLInputElement>document.getElementById("searchAssignTo")).value; if (this.strSearchAssignTo != '') { this.strSearchAssignTo = this.strSearchAssignTo.toLocaleLowerCase(); this.TicketListCloseds = this.TicketListCloseds.filter( x => x.AssignTo != null && x.AssignTo.toLocaleLowerCase().indexOf(this.strSearchAssignTo) != -1); } if (this.ShowHideSearch) { this.strSearchPriority = (<HTMLInputElement>document.getElementById("searchPriority")).value; if (this.strSearchPriority != '') { this.strSearchPriority = this.strSearchPriority.toLocaleLowerCase(); this.TicketListCloseds = this.TicketListCloseds.filter( x => x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(this.strSearchPriority) != -1); } } if (this.ShowHideSearch) { this.strSearchStatus = (<HTMLInputElement>document.getElementById("searchStatus")).value; if (this.strSearchStatus != '') { this.strSearchStatus = this.strSearchStatus.toLocaleLowerCase(); this.TicketListCloseds = this.TicketListCloseds.filter( x => x.Status != null && x.Status.toLocaleLowerCase().indexOf(this.strSearchStatus) != -1); } } } //Logic for searching - End this.ClosedTicketCount = this.TicketListCloseds.filter(x => x.Status.toLowerCase() == "closed").length; this.TerminatedTicketCount = this.TicketListCloseds.filter(x => x.Status.toLowerCase() == "terminated").length; this.indLoading = false; this.JumpOnPage(1); } ); } LoadGetTicketDetail(id: number): void { this.indLoading = true; this._TicketListClosedService.getTicketDetail(Global.BASE_MyTicketListClosed_ENDPOINT, id) .subscribe(DATADP => { this.GetDetail = DATADP; } ); } addTicketListClosed() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New News"; this.modalBtnTitle = "Add"; this.TicketListClosedFrm.reset(); this.modal.open(); } editTicketListClosed(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit News"; this.modalBtnTitle = "Update"; this.TicketListClosed = this.TicketListCloseds.filter(x => x.Id == id)[0]; this.TicketListClosedFrm.setValue(this.TicketListClosed); this.modal.open(); this.LoadGetTicketDetail(id); } ViewTicketListClosed(id: number) { this.dbops = DBOperation.View; this.SetControlsState(true); this.modalTitle = "Conversation Ticket"; this.TicketListClosed = this.TicketListCloseds.filter(x => x.Id == id)[0]; this.TicketListClosedFrm.setValue(this.TicketListClosed); this.LoadViwHistory(id); this.modal1.open(); this.modal.dismiss(); } deleteTicketListClosed(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.TicketListClosed = this.TicketListCloseds.filter(x => x.Id == id)[0]; this.TicketListClosedFrm.setValue(this.TicketListClosed); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.TicketListClosedFrm.enable() : this.TicketListClosedFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.TicketListCloseds); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } LoadViwHistory(id: number): void { this.indLoading = true; this._TicketListClosedService.getViewHistory(Global.BASE_MyTicket_ENDPOINT, id) .subscribe(DATADP => { this.ViewHistory = DATADP; } ); } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._TicketListClosedService.post(Global.BASE_MyTicketListClosed_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadGetTicketDetailUser(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._TicketListClosedService.put(Global.BASE_MyTicketListClosed_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadGetTicketDetailUser(21); // this.LoadTicketListCloseds(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._TicketListClosedService.delete(Global.BASE_MyTicketListClosed_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "TicketListClosed status changed successfully."; this.LoadGetTicketDetailUser(21); // this.LoadTicketListCloseds(); } else { this.msg = "Error has occurred while changing status of existing TicketListClosed!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Component, OnInit, ViewChild,Input } from '@angular/core'; import { DocumentTemplateService } from '../../Service/DocCenter/DocumentTemplate.service'; import { IDocumentTemplateViewModel } from '../../Model/DocCenter/DocumentTemplate'; import { IDocTemplateModule } from '../../Model/DocCenter/DocumentTemplate'; import { IListItem } from '../../Model/DocCenter/DocumentTemplate'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import { PagerService } from '../../Shared/pager.index'; import { DatePipe } from '@angular/common'; import { CommonHelperService } from '../../Shared/CommonHelper.service'; import { IDocumentTemplateModel } from '../../Model/DocCenter/DocumentTemplate'; import { IDocMasterFieldDataContract } from '../../Model/DocCenter/DocumentTemplate'; import { IDropdownTableField } from '../../Model/DocCenter/DocumentTemplate'; import { IDropdownCustomField } from '../../Model/DocCenter/DocumentTemplate'; import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; @Component ({ providers: [DocumentTemplateService], templateUrl: 'app/Components/DocCenter/DocumentTemplate.component.html' }) export class DocumentTemplateComponent implements OnInit { fileList1: FileList; strImgpath: string = '../../../Upload/DocumentCenter/DocumentTemplateImages/'; strTableField: string=''; strCustomField; string = ''; IsStep1Completed: boolean = false; @ViewChild('modal') modal: ModalComponent; @ViewChild('modaldelete') modaldelete: ModalComponent; msg: string; indLoading: boolean = false; dashboardFrm: FormGroup; dbops: DBOperation; modalTitle: string; direction: number; modalBtnTitle: string; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; objentitybyid: IDocumentTemplateModel; step2Option: string = 'Text'; IsEditStep2: boolean = false; objIDocMasterFieldDataContract: IDocMasterFieldDataContract; lstIDocMasterFieldDataContract: IDocMasterFieldDataContract[]; lstMasterField: IDocMasterFieldDataContract[]; lstContainerField: IDocMasterFieldDataContract[]=[]; objContainerField: IDocMasterFieldDataContract; lstIDropdownTableField: IDropdownTableField[]; lstIDropdownCustomField: IDropdownCustomField[]; objIDocumentTemplateModel: IDocumentTemplateModel; objIDocumentTemplateViewModel: IDocumentTemplateViewModel; listIDocumentTemplateViewModel: IDocumentTemplateViewModel[]; listIDocTemplateModule: IDocTemplateModule[]; listIListItem: IListItem[]; listIListItemRole: IListItem[]; EmployeeId: number; EmployeeRole: string; ApprovedStatus: string; ShowHideSearch: boolean = false; isDesc: boolean = false; column: any = 'Employee_Name'; DocTempId: number=0; strTemplateName: string; strOwnerName: string; strModuleName: string; strPageHeader: string; TodayDate: Date = new Date(); constructor(private fb: FormBuilder, private _DocumentTemplateService: DocumentTemplateService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService, private http: Http) { this.ResetModal(); } // Step 1 & Step 2 Related Function ResetModal() { this.objIDocumentTemplateModel =({ AddRecurrenceType: false, AllowFooter: false, AllowHeader: false, ApprovedOn: null, ContributorsId: '', DateFormat: 'Date(dd/mm/yyyy)', DocRightsId: 0, DocTemplateId: 0, DocTemplateInProgressId: 0, EmployeeId: 0, EmployeeName: '', FooterContent: '', HeaderContent: '', IsApproved: false, IsBehalf: false, IsDMSPdf: false, IsDMSWord: false, IsDownloadPdf: false, IsDownloadWord: false, IsEmailPdf: false, IsEmailWord: false, IsFinalSubmited: false, IsPortrait: true, IsRecurrence: false, IsSelf: true, ModuleId: '', ModuleName: '', OwnerId:Number(sessionStorage.getItem('Id')), PublishDate: '', SharingVariableType: '', StartingVariableRole: '', stringDate: null, TemplateDescription: '', TemplateName: '', TemplateRightsData: '', CreatedBy:0 }); this.objIDocMasterFieldDataContract = ({ AttachmentList: '', CreatedBy: 0, CreatedOn: null, DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: 0, FieldDescription: '', FieldId: '', FieldName: '', FieldType: 'Text', Id: 0, ImageName: '', ImageAlign: 'left', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.listIListItem = null; this.listIListItemRole = null; } ngOnInit(): void { this.lstIDropdownTableField = [ { FieldName: '', IsActive: false, ModuleId: 0, VariableId: 0, VarName: '', TableName: '' }] this.lstIDropdownCustomField = [ { MasterFieldId: 0, TokenName: '', TokenValue: '' }] this._CommonHelperService.ToogleMenu(); this.GetApprovedDocumentData(); } BindTableFieldDropDown(TableName:string) { this._DocumentTemplateService.bindtablefielddropdown(Global.BASE_DocumentTemplateAPI_ENDPOINT, TableName). subscribe(data => { this.lstIDropdownTableField = data; }); } BindCustomFieldDropDown(DocTempId:number) { this._DocumentTemplateService.bindcustomfielddropdown(Global.BASE_DocumentTemplateAPI_ENDPOINT, DocTempId). subscribe(data => { this.lstIDropdownCustomField = data; }); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.listIDocumentTemplateViewModel); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } DocumentTemplateSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } GetApprovedDocumentData() { // get id this.EmployeeId = Number(sessionStorage.getItem('Id')); // get role if (JSON.parse(sessionStorage.getItem('IsAdmin'))) { this.EmployeeRole = 'Admin'; } else if (JSON.parse(sessionStorage.getItem('IsLineManager')) && this.EmployeeRole != 'Admin') { this.EmployeeRole = 'LM'; } // get status if ($("#rbtapproved").prop("checked")) { this.ApprovedStatus = 'Approved'; } else if ($("#rbtpending").prop("checked")) { this.ApprovedStatus = 'Pending'; } else if ($("#rbtreject").prop("checked")) { this.ApprovedStatus = 'Reject'; } if (this.EmployeeRole == 'Admin' || this.EmployeeRole == 'LM') { this.strPageHeader = 'Document Template'; } else { this.strPageHeader = 'My Suggestion'; } this._DocumentTemplateService.getapprovedrecord(Global.BASE_DocumentTemplateAPI_ENDPOINT, this.EmployeeId, this.EmployeeRole, this.ApprovedStatus). subscribe(data => { this.indLoading = true; this.listIDocumentTemplateViewModel = data; //Logic for searching - start if (this.ShowHideSearch) { this.strTemplateName = (<HTMLInputElement>document.getElementById("searchTemplateName")).value; if (this.strTemplateName != '') { this.strTemplateName = this.strTemplateName.toLocaleLowerCase(); this.listIDocumentTemplateViewModel = this.listIDocumentTemplateViewModel.filter ( x => x.TemplateName != null && x.TemplateName.toLocaleLowerCase().indexOf(this.strTemplateName) != -1); } this.strOwnerName = (<HTMLInputElement>document.getElementById("searchOwnerName")).value; if (this.strOwnerName != '') { this.strOwnerName = this.strOwnerName.toLocaleLowerCase(); this.listIDocumentTemplateViewModel = this.listIDocumentTemplateViewModel.filter ( x => x.OwnerName != null && x.OwnerName.toLocaleLowerCase().indexOf(this.strOwnerName) != -1); } this.strModuleName = (<HTMLInputElement>document.getElementById("searchModuleName")).value; if (this.strModuleName != '') { this.strModuleName = this.strModuleName.toLocaleLowerCase(); this.listIDocumentTemplateViewModel = this.listIDocumentTemplateViewModel.filter ( x => x.ModuleName != null && x.ModuleName.toLocaleLowerCase().indexOf(this.strModuleName) != -1); } } //Logic for searching - End this.indLoading = false; this.JumpOnPage(1); }); } AddNewTemplate() { this.DisableAllSteps(); this.BindModuleDropDown(); this.modalTitle = 'Document Template'; this.modalBtnTitle = 'Save & Next'; this.dbops = DBOperation.create; this.ResetModal(); this.GetDocumentFieldByDocId(0); this.DocTempId = 0; this.IsStep1Completed = false; this.modal.open(); } EditTempalte(id:number) { this.DisableAllSteps(); this.BindModuleDropDown(); this.modalTitle = 'Document Template'; this.modalBtnTitle = 'Save & Next'; this.dbops = DBOperation.update; this._DocumentTemplateService.getbyid(Global.BASE_DocumentTemplateAPI_ENDPOINT, id). subscribe(data => { this.objentitybyid = data; this.BindStartingVariableNameDropdown(this.objentitybyid.ModuleId); this.objIDocumentTemplateModel = this.objentitybyid; this.DocTempId = this.objentitybyid.DocTemplateId; this.GetDocumentFieldByDocId(this.DocTempId); this.BindContainerField(); this.BindMasterField(); this.IsStep1Completed = true; }); this.modal.open(); } DeleteTemplate(id:number,status:boolean) { this.objIDocumentTemplateModel.DocTemplateId = this.listIDocumentTemplateViewModel.filter(x => x.DocTemplateId == id)[0].DocTemplateId; this.objIDocumentTemplateModel.TemplateName = this.listIDocumentTemplateViewModel.filter(x => x.DocTemplateId == id)[0].TemplateName; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.dbops = DBOperation.delete; this.modaldelete.open(); } CopyTemplate() { } ActivateDeactivateStatus(id: number) { alert(id); } EnableDisableApproveButton() { if (this.listIDocumentTemplateViewModel[0].ApprovedStatus == 'Approved') { let styles = { 'filter': 'grayscale(100%)', 'cursor': 'not-allowed' } $(".btnstatus").prop('disabled', true); return styles; } else { let styles = { 'filter': 'grayscale(0%)', 'cursor': 'allowed' } $(".btnstatus").prop('disabled', false); return styles; } } BindModuleDropDown() { this._DocumentTemplateService.getallmodule(Global.BASE_DocumentTemplateAPI_ENDPOINT). subscribe(data => { this.listIDocTemplateModule = data; } ); } BindStartingVariableNameDropdown(modulevalue:string) { if (modulevalue == 'DocTemplateModuleVariables') { this.listIListItem = [{ text: '<NAME>', value:'' } , { text: '<NAME>', value:'interviewsheetmaster' }] $("#rbtself").prop('disabled', false); $("#rbtself").prop('checked', true); $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', false); } else if (modulevalue =='Other') { this.listIListItem = [{ text: 'Employee Name', value: 'Employee_Master' } , { text: '<NAME>', value: 'interviewsheetmaster' }] $("#rbtself").prop('disabled', false); $("#rbtself").prop('checked', false); $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', true); } else if (modulevalue == "ProjectMaster") { this.listIListItem = [{ text: 'Project Name', value: 'ProjectMaster' }] $("#rbtself").prop('checked', false); $("#rbtself").prop('disabled', true); $("#rbtbehalf").prop('checked', true); $("#rbtbehalf").prop('disabled', false); } else if (modulevalue == "RFQ_Initial") { this.listIListItem = [{ text: 'RFQ Initial', value: 'RFQ_Initial' }] $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', true); $("#rbtself").prop('checked', false); $("#rbtself").prop('disabled', true); } else if (modulevalue == "ManageProjectMaster") { this.listIListItem = [{ text: 'BD Project Name', value: 'ManageProjectMaster' }] $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', true); $("#rbtself").prop('checked', false); $("#rbtself").prop('disabled', true); } this.objIDocumentTemplateModel.SharingVariableType = this.listIListItem[0].value this.BindStartingVariableTypeDropdown(modulevalue); } BindStartingVariableTypeDropdown(modulevalue: string) { if (modulevalue == 'DocTemplateModuleVariables') { this.listIListItemRole = [{ text: 'None', value: 'none' } , { text: 'Admin', value: 'admin' }, { text: 'HR', value:'hr' }, { text: 'HRH', value: 'hrh' }, { text: 'LM', value: 'lm' }] } else if (modulevalue == 'Other') { this.listIListItemRole = [{ text: 'None', value: 'none' } , { text: 'Admin', value: 'admin' }, { text: 'HR', value: 'hr' }, { text: 'HRH', value: 'hrh' }, { text: 'LM', value: 'lm' }] } else if (modulevalue == "ProjectMaster") { this.listIListItemRole = [{ text: 'None', value: 'none' } , { text: 'Admin', value: 'admin' }, { text: 'AManager', value: 'amanager' }, { text: 'AMG', value: 'amg' }, { text: 'BH', value: 'bh' }, { text: 'BM', value: 'bm' }, { text: 'DH', value: 'dh' }, { text: 'PM', value: 'pm' }, { text: 'RMG', value: 'rmg' }, { text: 'SH', value: 'sh' }] } else if (modulevalue == "RFQ_Initial") { this.listIListItemRole = [{ text: 'None', value: 'none' } , { text: 'Admin', value: 'admin' }, { text: 'BH', value: 'bh' }, { text: 'BM', value: 'bm' }, { text: 'SH', value: 'sh' }] } else if (modulevalue == "ManageProjectMaster") { this.listIListItemRole = [{ text: 'None', value: 'none' } , { text: 'Admin', value: 'admin' }, { text: 'BH', value: 'bh' }, { text: 'BM', value: 'bm' }, { text: 'SH', value: 'sh' }] } this.objIDocumentTemplateModel.StartingVariableRole = this.listIListItemRole[0].value; } onSubmitStep1(formData: IDocumentTemplateModel) { formData.OwnerId = Number(sessionStorage.getItem('Id')); formData.CreatedBy = Number(sessionStorage.getItem('Id')); if ($("#rbtself").prop("checked")) { formData.IsSelf = true; formData.IsBehalf = false } else { formData.IsSelf = false; formData.IsBehalf = true; } if (JSON.parse(sessionStorage.getItem('IsAdmin')) || JSON.parse(sessionStorage.getItem('IsLineManager'))) { formData.ApprovedOn = new Date(); formData.IsApproved = true; formData.IsFinalSubmited = true; } switch (this.dbops) { case DBOperation.create: this._DocumentTemplateService.addnewdocument(Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { alert('Document Template Saved sucessfully...'); this.ResetModal(); this._DocumentTemplateService.getmaxid(Global.BASE_DocumentTemplateAPI_ENDPOINT). subscribe(id => { this.DocTempId = id; if (this.DocTempId > 0) { this.IsStep1Completed = true; this.NextStep1(); } }); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._DocumentTemplateService.updatedocument(Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { alert('Document Template Saved sucessfully...'); this.ResetModal(); this.NextStep1(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._DocumentTemplateService.deletedocument(Global.BASE_DocumentTemplateAPI_ENDPOINT, formData.DocTemplateId).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.GetApprovedDocumentData(); this.modaldelete.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); } } onSubmitStep2(formData: IDocMasterFieldDataContract) { if (formData.DataSourceColumn == '' && formData.DataSourceColumnForCustom == '') { alert('Select Table Field or Custom Control Field'); } else { if (formData.DataSourceColumn == '') { formData.DataSourceColumn = '0'; } if (this.fileList1 != null) { if (this.fileList1.length > 0) { formData.ImageName = this.fileList1.item(0).name; formData.ImageHeight = 100; formData.ImageWidth = 100; } } else { formData.ImageName = this.objIDocMasterFieldDataContract.ImageName; } if (this.IsEditStep2 == false) { formData.DocTemplateId = this.DocTempId; formData.CreatedBy = Number(sessionStorage.getItem('Id')); this._DocumentTemplateService.addnewdocumentfield(Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { alert('Field saved Successfully...'); this.GetDocumentFieldByDocId(this.DocTempId); this.BindContainerField(); this.BindMasterField(); this.ResetModal(); } else { alert(data); } }, error => { this.msg = error; } ); } else { formData.UpdatedBy = Number(sessionStorage.getItem('Id')); this._DocumentTemplateService.updatedocumentfield(Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { alert('Field saved Successfully...'); this.GetDocumentFieldByDocId(this.DocTempId); this.BindContainerField(); this.BindMasterField(); this.ResetModal(); } else { alert(data); } }, error => { this.msg = error; } ); } } } CheckEnableDisableOption() { if ($("#rbtself").prop('checked')) { $("#SharingVariableType").prop('disabled', true); $("#StartingVariableRole").prop('disabled', true); } else { $("#SharingVariableType").prop('disabled', false); $("#StartingVariableRole").prop('disabled', false); } } EditField(id:number) { this.IsEditStep2 = true; this.objIDocMasterFieldDataContract = this.lstIDocMasterFieldDataContract.filter(x => x.Id == id)[0]; this.strImgpath = '../../../Upload/DocumentCenter/DocumentTemplateImages/' + this.objIDocMasterFieldDataContract.ImageName; } DeleteField(id:number) { var confirmation = confirm('Are you sure want to delete User Input?'); if (confirmation == true) { this._DocumentTemplateService.deletedocumentfield(Global.BASE_DocumentTemplateAPI_ENDPOINT, id, Number(sessionStorage.getItem('Id'))).subscribe( data => { if (data.startsWith("Success: "))//Success { alert('Field deleted Successfully...'); this.GetDocumentFieldByDocId(this.DocTempId); this.ResetModal(); } else { alert(data); } }, error => { this.msg = error; } ); } } CopyField(id:number) { this.IsEditStep2 = false; this.objIDocMasterFieldDataContract = this.lstIDocMasterFieldDataContract.filter(x => x.Id == id)[0]; this.objIDocMasterFieldDataContract.FieldName = ''; } GetDocumentFieldByDocId(doctempid:number) { this._DocumentTemplateService.getbydoctempid(Global.BASE_DocumentTemplateAPI_ENDPOINT, doctempid). subscribe(data => { this.lstIDocMasterFieldDataContract = data; this.lstIDocMasterFieldDataContract = this.lstIDocMasterFieldDataContract.filter(x => x.FieldType == 'Text' || x.FieldType == 'Image' || x.FieldType == 'TokenText'); }); } EnableDisableSteps() { if (this.IsStep1Completed == true) { let styles = { 'pointer-events': 'auto', 'color':'#337ab7' } return styles; } else { let styles = { 'pointer-events': 'none', 'color':'#dce2e8' } return styles; } } GetImageFile(event) { this.fileList1 = event.target.files; } UploadImage() { if (this.fileList1 != null) { if (this.fileList1.length > 0) { this.fileList1.item(0).name; let file: File = this.fileList1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers(); let options = new RequestOptions({ headers: headers }); this.http.post(Global.BASE_DocumentTemplateAPI_ENDPOINT + 'UploadImage', formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => { } , error => { console.log(error) } ); this.strImgpath = '../../../Upload/DocumentCenter/DocumentTemplateImages/' + this.fileList1.item(0).name; } } else { alert('Please Select Image'); } } BindDropDownTableField() { this.IsEditStep2 = false; this.objIDocMasterFieldDataContract.AttachmentList = ''; this.objIDocMasterFieldDataContract.DataSourceColumn = ''; this.objIDocMasterFieldDataContract.DataSourceColumnForCustom = ''; this.objIDocMasterFieldDataContract.DataSourceTable = ''; this.objIDocMasterFieldDataContract.FieldDescription = ''; this.objIDocMasterFieldDataContract.FieldName = ''; this.objIDocMasterFieldDataContract.ImageAlign = 'left'; this.objIDocMasterFieldDataContract.ImageHeight = 0; this.objIDocMasterFieldDataContract.ImageWidth = 0; this.objIDocMasterFieldDataContract.PageContent = ''; this.strImgpath = ''; this.GetDocumentFieldByDocId(this.DocTempId); if (this.DocTempId > 0 ) { this.BindCustomFieldDropDown(this.DocTempId) } if (this.objIDocumentTemplateModel.ModuleName != '') { this.BindTableFieldDropDown(this.objIDocumentTemplateModel.ModuleId); } } ChangeTableFieldDropDown(value) { this.strTableField = '<p>' + value + '</p>' } AddTableFieldToTextEditor() { if (this.strTableField != '') { this.objIDocMasterFieldDataContract.PageContent += this.strTableField; } else { alert("Select Table Field."); } } AddCustomFieldToTextEditor(value) { if (value != '') { var todayDate = new Date(), day = todayDate.getDate(), month = todayDate.getMonth(), year = todayDate.getFullYear(), hour = todayDate.getHours(), minute = todayDate.getMinutes(), second = todayDate.getSeconds(), miSecond = todayDate.getMilliseconds(); if (value == "{Textbox}") { value = "{Textbox_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{TextArea}") { value = "{TextArea_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{CKEditor}") { value = "{CKEditor_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{SingleDate}") { value = "{SingleDate_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{Time}") { value = "{Time_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{DateRange}") { value = "{DateRange_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "DropDownList") { value = "{DropDownList_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "ListBox") { value = "{ListBox_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "CheckBoxList") { value = "{CheckBoxList_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "RadioButtonList") { value = "{RadioButtonList_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } this.strCustomField = '<p>' + value + '</p>' this.objIDocMasterFieldDataContract.PageContent += this.strCustomField; } else { alert("Select Custom Field."); } } NextStep1() { $("#Step1Content").hide(); $("#Step2Content").show(); $("#Step2Content").scrollTop(0); } CancelStep2() { this.IsEditStep2 = false this.strImgpath = ''; this.strTableField = ''; this.strCustomField = ''; this.fileList1 = null; var FieldType = this.objIDocMasterFieldDataContract.FieldType; this.objIDocMasterFieldDataContract = ({ AttachmentList: '', CreatedBy: 0, CreatedOn: null, DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: 0, FieldDescription: '', FieldId: '', FieldName: '', FieldType: 'Text', Id: 0, ImageName: '', ImageAlign: 'left', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.objIDocMasterFieldDataContract.FieldType = FieldType; $("#Step2Content").scrollTop(0); } PreviousStep2() { $("#Step2Content").hide(); $("#Step1Content").show(); $("#Step1Content").scrollTop(0); } NextStep2() { $("#Step2Content").hide(); $("#Step3Content").show(); $("#Step3Content").scrollTop(0); } DisableAllSteps() { $("#Step1Content").hide(); $("#Step2Content").hide(); $("#Step3Content").hide(); $("#Step4Content").hide(); $("#Step5Content").hide(); $("#Step6Content").hide(); $("#Step7Content").hide(); $("#Step8Content").hide(); $("#Step1Content").show(); $("#Step1Content").scrollTop(0); } // Step 3 Related Function BindContainerField() { this._DocumentTemplateService.GetDocumentContainer(Global.BASE_DocumentTemplateAPI_ENDPOINT, this.DocTempId). subscribe(data => { this.lstContainerField = []; this.lstContainerField = data; }); } BindMasterField() { this._DocumentTemplateService.getbydoctempid(Global.BASE_DocumentTemplateAPI_ENDPOINT, this.DocTempId). subscribe(data => { this.lstMasterField = data; }); } AddAllField() { if (this.lstMasterField.length > 0) { for (var item of this.lstMasterField) { this.lstContainerField.push(item); } this.lstMasterField = this.lstIDocMasterFieldDataContract.filter(x => x.FieldType == 'Text' || x.FieldType=='Image'); } } RemoveAllField() { if (this.lstContainerField.length > 0) { for (let item of this.lstContainerField) { if (item.FieldType != 'Text' && item.FieldType != 'Image') { this.lstMasterField.push(item); } } this.lstContainerField = []; } } AddLineBreak() { this.objContainerField = ({ AttachmentList: '', CreatedBy: Number(sessionStorage.getItem('Id')), CreatedOn: new Date(), DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: this.DocTempId, FieldDescription: '', FieldId: '', FieldName: 'Line Break', FieldType: '<BR>', Id: 0, ImageName: '', ImageAlign: '', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.lstContainerField.push(this.objContainerField); } AddPageBreak() { this.objContainerField = ({ AttachmentList: '', CreatedBy: Number(sessionStorage.getItem('Id')), CreatedOn: new Date(), DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: this.DocTempId, FieldDescription: '', FieldId: '', FieldName: 'Page Break', FieldType: '<PageBreak>', Id: 0, ImageName: '', ImageAlign: '', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.lstContainerField.push(this.objContainerField); this.lstContainerField = this.lstContainerField; } NextStep3() { $("#Step3Content").hide(); $("#Step4Content").show(); $("#Step4Content").scrollTop(0); } CancelStep3() { this.BindContainerField(); this.BindMasterField(); $("#Step3Content").scrollTop(0); $(".contentscrollermasterfield").scrollTop(0); } PreviousStep3() { $("#Step3Content").hide(); $("#Step2Content").show(); $("#Step2Content").scrollTop(0); } onSubmitStep3() { if (this.lstContainerField.length == 0) { this.objContainerField = ({ AttachmentList: '', CreatedBy: 0, CreatedOn: null, DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: this.DocTempId, FieldDescription: '', FieldId: '', FieldName: '', FieldType: '', Id: 0, ImageName: '', ImageAlign: '', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.lstContainerField.push(this.objContainerField); } this._DocumentTemplateService.AddDocumentContainerField(Global.BASE_DocumentTemplateAPI_ENDPOINT, this.lstContainerField). subscribe(data => { this.BindContainerField(); alert('My Document Container Saved Successfully...'); }); } RemoveLineBreakPageBreak(CreatedOn) { this.objContainerField = this.lstContainerField.filter(x => x.CreatedOn == CreatedOn)[0]; const index: number = this.lstContainerField.indexOf(this.objContainerField); if (index !== -1) { this.lstContainerField.splice(index,1); } } RemoveLineBreakPageBreakMaster(CreatedOn) { this.objContainerField = this.lstMasterField.filter(x => x.CreatedOn == CreatedOn)[0]; const index: number = this.lstMasterField.indexOf(this.objContainerField); if (index !== -1) { this.lstMasterField.splice(index, 1); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using VIS_Domain.HumanResource.EmployeeManagement; using VIS_Repository.HumanResource.EmployeeManagement; namespace VIS_App.Controllers.HumanResource.EmployeeManagement { public class EmpInfoTabularAPIController : BaseAPIController { EmpInfoTabularRepository ObjEmpInfoTabularRepository = null; public EmpInfoTabularAPIController() { ObjEmpInfoTabularRepository = new EmpInfoTabularRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/EmpInfoTabularAPI/AddRole")] [HttpPost] public HttpResponseMessage AddRole(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.AddRole(entityobject)); } [Route("api/EmpInfoTabularAPI/GetRoleAdd")] [HttpGet] public HttpResponseMessage GetRoleAdd() { return ToJson(ObjEmpInfoTabularRepository.GetRoleAdd()); } [Route("api/EmpInfoTabularAPI/SaveMain")] [HttpPost] public HttpResponseMessage SaveMain(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SaveMain(entityobject)); } [Route("api/EmpInfoTabularAPI/SavePersonal")] [HttpPost] public HttpResponseMessage SavePersonal(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SavePersonal(entityobject)); } [Route("api/EmpInfoTabularAPI/SaveEducation")] [HttpPost] public HttpResponseMessage SaveEducation(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SaveEducation(entityobject)); } [Route("api/EmpInfoTabularAPI/SaveSalary")] [HttpPost] public HttpResponseMessage SaveSalary(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SaveSalary(entityobject)); } [Route("api/EmpInfoTabularAPI/SaveAttendance")] [HttpPost] public HttpResponseMessage SaveAttendance(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SaveAttendance(entityobject)); } [Route("api/EmpInfoTabularAPI/SaveJoining")] [HttpPost] public HttpResponseMessage SaveJoining(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SaveJoining(entityobject)); } [Route("api/EmpInfoTabularAPI/SaveIncrement")] [HttpPost] public HttpResponseMessage SaveIncrement(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SaveIncrement(entityobject)); } [Route("api/EmpInfoTabularAPI/SaveOfficial")] [HttpPost] public HttpResponseMessage SaveOfficial(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.SaveOfficial(entityobject)); } [Route("api/EmpInfoTabularAPI/Saveskill")] [HttpPost] public HttpResponseMessage Saveskill(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.Saveskill(entityobject)); } [Route("api/EmpInfoTabularAPI/AddLeave")] [HttpPost] public HttpResponseMessage AddLeave(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.AddLeave(entityobject)); } [Route("api/EmpInfoTabularAPI/btnAddExp")] [HttpPost] public HttpResponseMessage btnAddExp(EmpInfoTabular entityobject) { return ToJson(ObjEmpInfoTabularRepository.btnAddExp(entityobject)); } [Route("api/EmpInfoTabularAPI/GetAccountNo")] [HttpGet] public HttpResponseMessage GetAccountNo(string AccountNumber, string UserId) { return ToJson(ObjEmpInfoTabularRepository.GetAccountNo(AccountNumber,UserId)); } [Route("api/EmpInfoTabularAPI/FillProjectDetail")] [HttpGet] public HttpResponseMessage FillProjectDetail(string FromDate, string ToDate,long UserId) { return ToJson(ObjEmpInfoTabularRepository.FillProjectDetail(FromDate, ToDate, UserId)); } [Route("api/EmpInfoTabularAPI/FillProjectDetailWbs")] [HttpGet] public HttpResponseMessage FillProjectDetailWbs(string FromDate, string ToDate,long UserId) { return ToJson(ObjEmpInfoTabularRepository.FillProjectDetailWbs(FromDate, ToDate, UserId)); } [Route("api/EmpInfoTabularAPI/GetOfferdeatils")] [HttpGet] public HttpResponseMessage GetOfferdeatils(long UserId) { return ToJson(ObjEmpInfoTabularRepository.GetOfferdeatils(UserId)); } [Route("api/EmpInfoTabularAPI/GetSkill")] [HttpGet] public HttpResponseMessage GetSkill() { return ToJson(ObjEmpInfoTabularRepository.GetSkill()); } [Route("api/EmpInfoTabularAPI/GetPopupSkill")] [HttpGet] public HttpResponseMessage GetPopupSkill(long lookupSkilId) { return ToJson(ObjEmpInfoTabularRepository.GetPopupSkill(lookupSkilId)); } [Route("api/EmpInfoTabularAPI/GetGridViewList")] [HttpGet] public HttpResponseMessage GetGridViewList(long UserId) { return ToJson(ObjEmpInfoTabularRepository.GetGridViewList(UserId)); } [Route("api/EmpInfoTabularAPI/GetEmployeeDeatils")] [HttpGet] public HttpResponseMessage GetEmployeeDeatils(string UserId) { return ToJson(ObjEmpInfoTabularRepository.GetEmployeeDeatils(UserId)); } [Route("api/EmpInfoTabularAPI/GetAdustmentleave")] [HttpGet] public HttpResponseMessage GetAdustmentleave(long UserId) { return ToJson(ObjEmpInfoTabularRepository.GetAdustmentleave(UserId)); } [Route("api/EmpInfoTabularAPI/FillLeaveDeatil")] [HttpGet] public HttpResponseMessage FillLeaveDeatil() { return ToJson(ObjEmpInfoTabularRepository.FillLeaveDeatil()); } [Route("api/EmpInfoTabularAPI/GetPendingList")] [HttpGet] public HttpResponseMessage GetPendingList(long UserId) { return ToJson(ObjEmpInfoTabularRepository.GetPendingList(UserId)); } [Route("api/EmpInfoTabularAPI/GetFeedbackList")] [HttpGet] public HttpResponseMessage GetFeedbackList(long UserId) { return ToJson(ObjEmpInfoTabularRepository.GetFeedbackList(UserId)); } public HttpResponseMessage Get() { return ToJson(ObjEmpInfoTabularRepository.GetEntityList().AsEnumerable()); } [Route("api/EmpInfoTabularAPI/GetRole")] [HttpGet] public HttpResponseMessage GetRole() { return ToJson(ObjEmpInfoTabularRepository.GetRole()); } [Route("api/EmpInfoTabularAPI/FillPassingYear")] [HttpGet] public HttpResponseMessage FillPassingYear(string EditEmployeeid,string Editmode) { return ToJson(ObjEmpInfoTabularRepository.FillPassingYear(EditEmployeeid,Editmode)); } [Route("api/EmpInfoTabularAPI/GetTechnology")] [HttpGet] public HttpResponseMessage GetTechnology() { return ToJson(ObjEmpInfoTabularRepository.GetTechnology()); } [Route("api/EmpInfoTabularAPI/GetCompany")] [HttpGet] public HttpResponseMessage GetCompany() { return ToJson(ObjEmpInfoTabularRepository.GetCompany()); } [Route("api/EmpInfoTabularAPI/GetWorking")] [HttpGet] public HttpResponseMessage GetWorking() { return ToJson(ObjEmpInfoTabularRepository.GetWorking()); } [Route("api/EmpInfoTabularAPI/GetJoiningDesignation")] [HttpGet] public HttpResponseMessage GetJoiningDesignation() { return ToJson(ObjEmpInfoTabularRepository.GetJoiningDesignation( )); } [Route("api/EmpInfoTabularAPI/GetDepartmentname")] [HttpGet] public HttpResponseMessage GetDepartmentname() { return ToJson(ObjEmpInfoTabularRepository.GetDepartmentname()); } [Route("api/EmpInfoTabularAPI/GetPositionName")] [HttpGet] public HttpResponseMessage GetPositionName() { return ToJson(ObjEmpInfoTabularRepository.GetPositionName()); } [Route("api/EmpInfoTabularAPI/GetEmployeeGrade")] [HttpGet] public HttpResponseMessage GetEmployeeGrade() { return ToJson(ObjEmpInfoTabularRepository.GetEmployeeGrade()); } [Route("api/EmpInfoTabularAPI/GetLinemanager")] [HttpGet] public HttpResponseMessage GetLinemanager(string Usertype, long UserId) { return ToJson(ObjEmpInfoTabularRepository.GetLinemanager(Usertype, UserId)); } [Route("api/EmpInfoTabularAPI/GetUserRole")] [HttpGet] public HttpResponseMessage GetUserRole() { return ToJson(ObjEmpInfoTabularRepository.GetUserRole()); } [Route("api/EmpInfoTabularAPI/GetEducationType")] [HttpGet] public HttpResponseMessage GetEducationType() { return ToJson(ObjEmpInfoTabularRepository.GetEducationType()); } [Route("api/EmpInfoTabularAPI/GetSalaryRangeDropDown")] [HttpGet] public HttpResponseMessage GetSalaryRangeDropDown(long Salary) { return ToJson(ObjEmpInfoTabularRepository.GetSalaryRangeDropDown(Salary)); } [Route("api/EmpInfoTabularAPI/GetSalaryBrakup")] [HttpGet] public HttpResponseMessage GetSalaryBrakup(long SalaryRangeId) { return ToJson(ObjEmpInfoTabularRepository.GetSalaryBrakup(SalaryRangeId)); } [Route("api/EmpInfoTabularAPI/FillEmployee")] [HttpGet] public HttpResponseMessage FillEmployee() { return ToJson(ObjEmpInfoTabularRepository.FillEmployee()); } [Route("api/EmpInfoTabularAPI/GetNonWorking")] [HttpGet] public HttpResponseMessage GetNonWorking() { return ToJson(ObjEmpInfoTabularRepository.GetNonWorking()); } [Route("api/EmpInfoTabularAPI/GetInTimeOutTimeSelected")] [HttpGet] public HttpResponseMessage GetInTimeOutTimeSelected() { return ToJson(ObjEmpInfoTabularRepository.GetInTimeOutTimeSelected()); } [Route("api/EmpInfoTabularAPI/GetEmployeeTime")] [HttpGet] public HttpResponseMessage GetEmployeeTime(long CompanyId) { return ToJson(ObjEmpInfoTabularRepository.GetEmployeeTime(CompanyId)); } public HttpResponseMessage Post([FromBody]EmpInfoTabular value) { return ToJson(ObjEmpInfoTabularRepository.AddEntity(value)); } [Route("api/EmpInfoTabularAPI/GetIncrementType")] [HttpGet] public HttpResponseMessage GetIncrementType() { return ToJson(ObjEmpInfoTabularRepository.GetIncrementType()); } [Route("api/EmpInfoTabularAPI/GetIncrementList")] [HttpGet] public HttpResponseMessage GetIncrementList() { return ToJson(ObjEmpInfoTabularRepository.GetIncrementList()); } [Route("api/EmpInfoTabularAPI/GetLeaveType")] [HttpGet] public HttpResponseMessage GetLeaveType() { return ToJson(ObjEmpInfoTabularRepository.GetLeaveType()); } [Route("api/EmpInfoTabularAPI/GetAttendanceDetail")] [HttpGet] public HttpResponseMessage GetAttendanceDetail(int AccessCardId, long UserId) { return ToJson(ObjEmpInfoTabularRepository.GetAttendanceDetail(AccessCardId, UserId)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]EmpInfoTabular value) { return ToJson(ObjEmpInfoTabularRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 id) { return ToJson(ObjEmpInfoTabularRepository.DeleteEntity(id)); } [Route("api/EmpInfoTabularAPI/DeleteRole")] [HttpDelete] public HttpResponseMessage DeleteRole(Int64 id) { return ToJson(ObjEmpInfoTabularRepository.DeleteEntity(id)); } [HttpPost] [Route("api/EmpInfoTabularAPI/UploadJsonFile")] public HttpResponseMessage UploadJsonFile() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/Upload/JoiningDocuments/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; using VIS_Repository; using VIS_Domain.Master.VacancyRelated; namespace VIS_App.Controllers.Masters.VacancyRelated { public class TechnologyMasterAPIController : BaseAPIController { VISIBaseRepository<TechnologyMaster> TechnologyMasterRepository; List<TechnologyMaster> EntityList = new List<TechnologyMaster>(); public TechnologyMasterAPIController(VISIBaseRepository<TechnologyMaster> _currencyRepository) { TechnologyMasterRepository = _currencyRepository; } public HttpResponseMessage Get() { return ToJson(TechnologyMasterRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]TechnologyMaster value) { return ToJson(TechnologyMasterRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]TechnologyMaster value) { return ToJson(TechnologyMasterRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(TechnologyMasterRepository.DeleteEntity(Id)); } } } <file_sep>export interface IForHeaddl { Id: number; Employee_Name: string; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.Masters.CompanyRelated; using System.Web; namespace VIS_App.Controllers.Masters.CompanyRelated { public class FinancialYearAPIController : BaseAPIController { FinancialYearRepository objFinancialYear = null; VISIBaseRepository<FinancialYear> FinancialYearRepository; List<FinancialYear> EntityList = new List<FinancialYear>(); public FinancialYearAPIController(VISIBaseRepository<FinancialYear> _FinancialYearRepository) { FinancialYearRepository = _FinancialYearRepository; objFinancialYear = new FinancialYearRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(FinancialYearRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]FinancialYear value) { return ToJson(FinancialYearRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]FinancialYear value) { return ToJson(FinancialYearRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(FinancialYearRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Opinion { public class ConfigureSurvey : VISBaseEntity { public Boolean RoleName { get; set; } } public class SurveyType { public Int64 Id { get; set; } public string Name { get; set; } } public class GetUserListForOwnerSelection { public Int64 ID { get; set; } public string EmployeeName { get; set; } } public static class ConfigureSurveyConstant { /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_EmployeeID = "EmployeeID"; public const string const_Field_RoleName = "RoleName"; public const string const_Field_SearchField = "SearchField"; public const string const_Field_SearchValue = "SearchValue"; public const string const_Field_RoleType = "RoleType"; public const string const_Field_SurveyType = "SurveyType"; public const string const_Field_ApproveType = "ApproveType"; public const string const_Field_Mode = "mode"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string Const_Proc_CheckUserRolesById = "Proc_CheckUserRolesById"; public const string const_ProcSurvey_GetAllSurvey_SelectAll = "ProcSurvey_GetAllSurvey"; public const string const_ProcEmployeeDropDown = "procEmployeeDropDown"; } } <file_sep>export interface IOraganization { SuggestionId: number; SuggestionAlie: string; }<file_sep>export interface IMySkills { Level_Text: string; SkillName: string; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.RFQ { public class RFQGeneral { public class RFQDoc : VISBaseEntity { public long FileTypeID { get; set; } public string FileType { get; set; } public string FileName { get; set; } public long AuthorId { get; set; } public string Author { get; set; } public string RemarkDoc { get; set; } public string Remark { get; set; } public int RFQ_DocumentID { get; set; } public long ReferenceID { get; set; } public string OriginalFileName { get; set; } public string PopUp { get; set; } public Boolean IsResponse { get; set; } } public static class RFQDocConstant { /// <summary> /// Database table field Name Constants.Industries /// </summary> /// public const string const_Field_FileTypeID = "FileTypeID"; public const string const_Field_FileType = "FileType"; public const string const_Field_FileName = "FileName"; public const string const_Field_AuthorId = "AuthorId"; public const string const_Field_Author = "Author"; public const string const_Field_RemarkDoc = "RemarkDoc"; public const string const_Field_Remark = "Remark"; public const string const_Field_RFQ_DocumentID = "RFQ_DocumentID"; public const string const_Field_ReferenceID = "ReferenceID"; public const string const_Field_OriginalFileName = "OriginalFileName"; public const string const_Field_PopUp = "PopUp"; public const string const_Field_IsResponse = "IsResponse"; /// <summary> /// Procedure /// </summary> public const string const_Field_procRFQDocument_Add = "procRFQDocument_Add"; } public class RFQLink : VISBaseEntity { public string RemarkLink { get; set; } public string URL { get; set; } public long UserId { get; set; } public string Password { get; set; } public int RFQ_LinkID { get; set; } public long ReferenceID { get; set; } public string Remark { get; set; } public string PopUp { get; set; } public Boolean IsResponse { get; set; } } public static class RFQLinkConstant { /// <summary> /// Database table field Name Constants.Industries /// </summary> /// public const string const_Field_RemarkLink = "RemarkLink"; public const string const_Field_URL = "URL"; public const string const_Field_UserId = "UserId"; public const string const_Field_Password = "<PASSWORD>"; public const string const_Field_RFQ_LinkID = "RFQ_LinkID"; public const string const_Field_ReferenceID = "ReferenceID"; public const string const_Field_Remark = "Remark"; public const string const_Field_RFQ_DocumentID = "RFQ_DocumentID"; public const string const_Field_PopUp = "PopUp"; public const string const_Field_IsResponse = "IsResponse"; /// <summary> ///procedure /// </summary> /// public const string const_Field_RFQLink_Add = "procRFQLink_Add"; } } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import { Component, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../Shared/enum'; import { Global } from '../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../Shared/pager.index'; @Injectable() export class entityService { @ViewChild('modal') modal: ModalComponent; public entityCollection: any[]; public entityObject: any; public entityEmptyObjectForView : any; public msg: string; public entityObjectFrm: FormGroup; public dbops: DBOperation; public modalTitle: string; public modalBtnTitle: string; public entityFilter: string; public isDesc: boolean = false; public column: string; public direction: number; public CurrentRecordsPerPage: number = 10; public GetURL: string; public CreateURL: string; public UpdateURL: string; public DeleteURL: string; // pager object public pager: any = {}; // paged items public pagedItems: any[]; public PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; constructor(private _http: Http, private fb: FormBuilder, private pagerService: PagerService) { } get(url: string): Observable<any> { return this._http.get(url) .map((response: Response) => <any>response.json()); } post(url: string, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } put(url: string, id: number, model: any): Observable<any> { let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.put(url + 'UpdateEntity/' + id, body, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } delete(url: string, id: number): Observable<any> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.delete(url + 'DeleteEntity/' + id, options) .map((response: Response) => <any>response.json()) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } ngOnInit(): void { this.entityObjectFrm = this.fb.group(this.entityEmptyObjectForView); } entityFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.entityFilter = value; } entitySort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } addentity() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New entity"; this.modalBtnTitle = "Add"; this.entityObjectFrm.reset(); this.modal.open(); } editentity(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit entity"; this.modalBtnTitle = "Update"; this.entityObject = this.entityCollection.filter(x => x.Id == id)[0]; this.entityObjectFrm.setValue(this.entityObject); this.modal.open(); } deleteentity(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.entityObject = this.entityCollection.filter(x => x.Id == id)[0]; this.entityObjectFrm.setValue(this.entityObject); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.entityObjectFrm.enable() : this.entityObjectFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.entityCollection); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this.post(this.GetURL, formData._value); break; case DBOperation.update: this.put(this.GetURL, formData._value.Id, formData._value); break; case DBOperation.delete: this.delete(this.GetURL, formData._value.Id); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Reports.Attendance; namespace VIS_Repository.Reports.Attendance { public class OfficialWorkReportRepository : VISDbCommand { int intAffectedRecords; public OfficialWorkReportRepository(string _connectionstring) : base(_connectionstring) { } public DataTable GetEmployee() { try { string mode = "Employee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OfficialWorkReportConstant.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_Mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } catch (Exception) { throw; } } public DataTable GetYear() { try { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OfficialWorkReportConstant.const_procFinancialYear_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } catch (Exception) { throw; } } public DataTable GetOfficialWorkReport(OfficialWorkReportParamterModel objOfficialWorkReportParamterModel) { try { string Mode = "Report"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OfficialWorkReportConstant.const_procUSP_OfficeWorkInOut; base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_Mode, Mode); base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_EmployeeId, objOfficialWorkReportParamterModel.EmployeeId); base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_FromDate, objOfficialWorkReportParamterModel.FromDate); base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_ToDate, objOfficialWorkReportParamterModel.ToDate); base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_ReportSort, objOfficialWorkReportParamterModel.ReportSort); base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_Sort, objOfficialWorkReportParamterModel.Sort); base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_UserId, objOfficialWorkReportParamterModel.UserId); base.objSqlCommand.Parameters.AddWithValue(OfficialWorkReportConstant.const_UserType, objOfficialWorkReportParamterModel.UserType); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } catch (Exception) { throw; } } } } <file_sep>export interface IPolicy { CompanyId: number; Id: number; Policy_Name: string; Description: string; IsNewPolicy: boolean; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var EmployeeScreenCaptureReport_service_1 = require("../../../Service/Report/Attendance/EmployeeScreenCaptureReport.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var EmployeeScreenCaptureReportComponent = (function () { function EmployeeScreenCaptureReportComponent(fb, _EmployeeScreenCaptureReportService, pagerService, _CommonHelperService) { this.fb = fb; this._EmployeeScreenCaptureReportService = _EmployeeScreenCaptureReportService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.pager = {}; this.CurrentRecordsPerPage = 10; this.frommonth = new Date().getMonth() + 1; this.fromyear = new Date().getFullYear(); this.tomonth = new Date().getMonth() + 1; this.toyear = new Date().getFullYear(); } EmployeeScreenCaptureReportComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.ParameterModel = ({ EmployeeId: 0, FromDate: '', LoginUserId: 0, OrderBy: '', ToDate: '', FromMonth: '', FromYear: '', ToMonth: '', ToYear: '', MonthWise: false }); this.Year = [({ CurrentYear: '' })]; this.GetEmployee(); this.GetYear(); }; EmployeeScreenCaptureReportComponent.prototype.HideShowPanel = function () { if ($("#rbtdate").prop("checked")) { $("#paneldatewise").show(); $("#panelmonthwise").hide(); $("#panelmonthwise2").hide(); $("#panelmonthwise3").hide(); $("#panelmonthwise4").hide(); } else { $("#paneldatewise").hide(); $("#panelmonthwise").show(); $("#panelmonthwise2").show(); $("#panelmonthwise3").show(); $("#panelmonthwise4").show(); } }; EmployeeScreenCaptureReportComponent.prototype.ToogleMyProfile = function () { $("#alltypeoutreportdata").slideToggle(300); }; EmployeeScreenCaptureReportComponent.prototype.CloseWidgetProfile = function () { $("#alltypeoutreport").hide(300); }; EmployeeScreenCaptureReportComponent.prototype.GetEmployee = function () { var _this = this; this._EmployeeScreenCaptureReportService.getemployee(global_1.Global.BASE_EmployeeScreenCaptureReportAPI_ENDPOINT). subscribe(function (employee) { _this.Employee = employee; }); }; EmployeeScreenCaptureReportComponent.prototype.GetYear = function () { var _this = this; this._EmployeeScreenCaptureReportService.getyear(global_1.Global.BASE_EmployeeScreenCaptureReportAPI_ENDPOINT). subscribe(function (year) { debugger; _this.Year = year; }); }; EmployeeScreenCaptureReportComponent.prototype.onSubmit = function (ParameterModel) { var _this = this; if ($("#rbtdate").prop("checked")) { ParameterModel.OrderBy = 'Name'; ParameterModel.MonthWise = false; } else { ParameterModel.MonthWise = true; ParameterModel.FromMonth = this.frommonth.toString(); ParameterModel.FromYear = this.fromyear.toString(); ParameterModel.ToMonth = this.tomonth.toString(); ParameterModel.ToYear = this.toyear.toString(); if ($("#rbtsortdate").prop("checked")) { ParameterModel.OrderBy = 'Date'; } else { ParameterModel.OrderBy = 'Name'; } } ParameterModel.LoginUserId = 158; this.EmployeeScreenCaptures = null; this.InLoading = true; this._EmployeeScreenCaptureReportService.getoutreportdata(global_1.Global.BASE_EmployeeScreenCaptureReportAPI_ENDPOINT, ParameterModel). subscribe(function (employeescreencapture) { _this.EmployeeScreenCaptures = employeescreencapture; _this.JumpOnPage(1); $("html, body").animate({ scrollTop: 310 }, 150); _this.InLoading = false; }); }; EmployeeScreenCaptureReportComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeScreenCaptures); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; EmployeeScreenCaptureReportComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; EmployeeScreenCaptureReportComponent.prototype.ShowPopup = function () { this.modal.open(); this.modalTitle = 'Screen Capture Images'; }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], EmployeeScreenCaptureReportComponent.prototype, "modal", void 0); EmployeeScreenCaptureReportComponent = __decorate([ core_1.Component({ providers: [EmployeeScreenCaptureReport_service_1.EmployeeScreenCaptureReportService], templateUrl: 'app/Components/Report/Attendance/EmployeeScreenCapture.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, EmployeeScreenCaptureReport_service_1.EmployeeScreenCaptureReportService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], EmployeeScreenCaptureReportComponent); return EmployeeScreenCaptureReportComponent; }()); exports.EmployeeScreenCaptureReportComponent = EmployeeScreenCaptureReportComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; using VIS_Domain.Master.CurrencyRelated; using VIS_Repository; namespace VIS_App.Controllers.Masters.CurrencyRelated { public class CurrencyAPIController : BaseAPIController { VISIBaseRepository<Currency> CurrencyRepository; List<Currency> EntityList = new List<Currency>(); public CurrencyAPIController(VISIBaseRepository<Currency> _currencyRepository) { CurrencyRepository = _currencyRepository; } public HttpResponseMessage Get() { return ToJson(CurrencyRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]Currency value) { return ToJson(CurrencyRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]Currency value) { return ToJson(CurrencyRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(CurrencyRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.VacancyRelated { public class TechnologyMaster : VISBaseEntity { /// <summary> /// TechnologyMaster Entity Fields. /// </summary> public string TechnologyName { get; set; } public string Remarks { get; set; } public bool Major { get; set; } } public static class TechnologyMasterConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_TechnologyMaster = "TechnologyMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_TechnologyName = "TechnologyName"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_Major = "Major"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procTechnologyMaster_Add = "procTechnologyMaster_Add"; public const string const_procTechnologyMaster_Update = "procTechnologyMaster_Update"; public const string const_procTechnologyMaster_ActiveInActive = "procTechnologyMaster_ActiveInActive"; public const string const_procTechnologyMaster_SelectAll = "procTechnologyMaster_SelectAll"; public const string const_procTechnologyMaster_SelectBaseNonBase = "procTechnologyMaster_SelectBaseNonBase"; public const string const_procTechnologyMaster_SelectById = "procTechnologyMaster_SelectById"; } } <file_sep>export interface ILegend{ Criteria: String; CalculatedOn: String; From: number; To: number; Points: number; }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net.Mail; using System.Web; namespace VIS_App.Helper { public class MailInbox { } }<file_sep>//Saurabh import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { RFQResponseService } from '../../Service/RFQ/RFQResponse.service'; import { RFQService } from '../../Service/RFQ/RFQ.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IAddRFQResponse, IActionTakenBy, IHiddenValue, IForRFQId} from '../../Model/RFQ/RFQResponse'; import { ITechMultiCheckBox, ITechnology, IRFQDocEntity, IRFQLink, IRFQDoc, IRFQLinkEntity } from '../../Model/RFQ/GeneralRFQ'; import { IRFQInitial} from '../../Model/RFQ/RFQEstimateListing'; import { ForSessionData } from '../../Model/RFQ/RFQEstimateListing'; import { DBOperation } from '../../Shared/enum'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; @Component({ providers: [RFQResponseService, RFQService], templateUrl: 'app/Components/RFQ/AddResponse.component.html' }) export class AddRFQResponsecomponent implements OnInit { @ViewChild('modal') modal: ModalComponent; hiddenValue: IHiddenValue; addRFQResponse: IAddRFQResponse; actionTakenByList: IActionTakenBy[]; actionTakenBy: IActionTakenBy; msg: string; indLoading: boolean = false; RFQFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; RFQFilter: string; isDesc: boolean = false; direction: number; forSessionData: ForSessionData; myOptions: ITechMultiCheckBox[]; myOptionsEmp: ITechMultiCheckBox[]; MultiTechnologys: ITechMultiCheckBox; Technology: ITechnology[] = []; FileTypeDDL: IRFQInitial; AuthorDDL: IRFQDoc; Access: boolean = true; forRFQId: IForRFQId; RFQDocList: IRFQDoc[] = []; RFQDoc: IRFQDoc; RFQDocEntity: IRFQDocEntity; RFQDocEntityList: IRFQDocEntity[] = []; RFQLinkList: IRFQLink[] = []; RFQLink: IRFQLink; RFQLinkEntityList: IRFQLink[] = []; RFQLinkEntity: IRFQLink; fileList: FileList; i: number; fileListForAPI: FileList[] = []; constructor(private fb: FormBuilder, private _RFQResponseService: RFQResponseService,private _RFQService: RFQService, private router: Router, private pagerService: PagerService, private route: ActivatedRoute, private http: Http) { } fileChangeDoc(event) { this.fileList = event.target.files; this.fileListForAPI[this.i] = this.fileList; this.i = this.i + 1; } ngOnInit(): void { this.addRFQResponse = ({ RFQ_InitialID: 0, IsEstimateReady: false, IsChangeToAction:false, Hours: 0, Timeline: 0, Timeline_Unit: '', Leadtime: 0, Leadtime_Unit: '', Technology: '', TechnologyIdList: 0, Description: '', ActionRequestedBy: 0, ActionByDate: null, EmployeeName: '', hdnEmployee: '', CurruntDate: null, hdnEmployeeId: 0, EmpId:0 }); this.forRFQId = ({ RFQId :0 }); this.forSessionData = ({ SessionId: 0 }); this.actionTakenBy = ({ EmpId: 0, Employee_Name: '' }); this.RFQDoc = ({ FileTypeID: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQDocEntity = ({ FileTypeId: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQLink = ({ RemarkLink: '', UserId: '', Password: '', URL: '' }) this.forSessionData.SessionId = +sessionStorage.getItem('Id'); this.LoadActionTaken(); this.GetTechnology(); this.LoadData(); this.GetFileType(); this.GetAuthor(); } LoadActionTaken(): void { this.indLoading = true; this._RFQResponseService.GetActionTaken(Global.BASE_RFQResponse_ENDPOINT, this.forSessionData.SessionId, this.Access) .subscribe(RFQs => { this.actionTakenByList = RFQs; } //,error => this.msg = <any>error ); } LoadData(): void { this._RFQResponseService.GetOnLoadData(Global.BASE_RFQResponse_ENDPOINT, this.forSessionData.SessionId, 21)//21==rfqid .subscribe(RFQs => { this.hiddenValue = RFQs; this.addRFQResponse.EmployeeName = this.hiddenValue.hdnEmployee; this.addRFQResponse.hdnEmployeeId = this.hiddenValue.hdnEmployeeId; debugger; this.addRFQResponse.CurruntDate = new Date(); } //,error => this.msg = <any>error ); } GetTechnology(): void { this.indLoading = true; this._RFQResponseService.GetTechnology(Global.BASE_RFQ_ENDPOINT) .subscribe(Technology => { this.Technology = Technology; this.myOptions = []; for (let item of this.Technology) { this.myOptions.push({ id: item.TechnologyId, name: item.TechnologyName }); } this.indLoading = false; }); } GetFileType(): void { this.indLoading = true; this._RFQService.GetFileType(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.FileTypeDDL = RFQs; this.indLoading = false; }); } GetAuthor(): void { this.indLoading = true; this._RFQService.GetAuthor(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.AuthorDDL = RFQs; this.indLoading = false; }); } onAddRFQSubmit(formData: any) { debugger; this.forRFQId.RFQId = 21; debugger; var MainAddResponse = { SessionData: this.forSessionData, RFQResponse: formData, RFQDoc: this.RFQDocEntityList, RFQLink: this.RFQLinkEntityList, RFQId: this.forRFQId.RFQId // RFQDoc: this.RFQDocList, //RFQLink: this.RFQLinkList } this._RFQResponseService.post(Global.BASE_RFQResponse_ENDPOINT, MainAddResponse).subscribe( data => { if (data.startsWith("Success:"))//Success { this.msg = data; if (this.fileListForAPI.length > 0) { var k = 0; for (let fileToBeUpload of this.fileListForAPI) { let file: File = fileToBeUpload[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/RFQAPI/UploadRFQDoc"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) file = null; formData = null; headers = null; options = null; k = k + 1; } this.fileListForAPI = null; } alert('Record Added Successfully.'); this.router.navigate(['/MyRFQ']); } else { alert(data); } }, error => { this.msg = error; } ); } onDocSubmit(formDocData: any) { if (this.fileList != null) { this.RFQDocEntity = formDocData; this.RFQDocEntity.FileName = this.fileList.item(0).name; this.RFQDocEntityList.push(this.RFQDocEntity); this.clearDoc(); } else { alert('please select Any document file') } } deleteRFQDoc(FileName: any) { var elementPos = this.RFQDocList.map(function (x) { return x.FileName; }).indexOf(FileName); this.RFQDocEntityList.splice(elementPos, 1); } onLinkSubmit(formLinkData: any) { this.RFQLinkEntity = formLinkData; this.RFQLinkEntityList.push(this.RFQLinkEntity); this.clearLink(); } deleteRFQLink(UserId: any) { var elementPos = this.RFQLinkList.map(function (x) { return x.UserId; }).indexOf(UserId); this.RFQLinkEntityList.splice(elementPos, 1); } clearDoc() { this.RFQDoc.Author = ""; this.RFQDoc.AuthorId = 0; this.RFQDoc.FileName = ""; this.RFQDoc.FileType = ""; this.RFQDoc.RemarkDoc = ""; } clearLink() { this.RFQLink.Password = ""; this.RFQLink.RemarkLink = ""; this.RFQLink.URL = ""; this.RFQLink.UserId = ''; } SetControlsState(isEnable: boolean) { isEnable ? this.RFQFrm.enable() : this.RFQFrm.disable(); } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { DashboardService } from '../../Service/Dashboard/dashboard.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IDashboard } from '../../Model/Dashboard/dashboard'; import { ILegend } from '../../Model/Dashboard/Legend'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import { PagerService } from '../../Shared/pager.index'; import { IMyAttendance } from '../../Model/Dashboard/MyAttendance'; import { DatePipe } from '@angular/common'; import { CommonHelperService } from '../../Shared/CommonHelper.service'; @Component({ providers: [DashboardService], templateUrl: 'app/Components/Dashboard/dashboard.component.html' }) export class DashboardComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('modalAchievements') modalAchievements: ModalComponent; @ViewChild('modalPoints') modalPoints: ModalComponent; @ViewChild('modalLegend') modalLegend: ModalComponent; @ViewChild('modalLevels') modalLevels: ModalComponent; dashboard: IDashboard; dashboards: ILegend[]; msg: string; indLoading: boolean = false; dashboardFrm: FormGroup; dbops: DBOperation; modalTitle: string; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; PagerInformation: string; // paged items pagedItems: any[]; attendancedata: IMyAttendance[]; constructor(private fb: FormBuilder, private _DashboardService: DashboardService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService ) { } ngOnInit(): void { this.dashboard = ({ UserProfileData: { EmployeeName: '', LineManagerName: '', FirstName: '', MiddleName: '', LastName: '', Gender: '', PhotographFileName: '', CompanyName: '', EmailID: '', Designation: '', DepartmentName: '', FatherName: '', PermenantAddress: '', CommunicationAddress: '', LandlineNumber: '', MobileNumber: '', MotherName: '', BirthDate: '', BloodGroup: '', MaritalStatus: '', EmplopyeeGrade: '' }, UserSkillData: [ { Level_Text: '', SkillName: '' }, ], MyAttendanceData: [ { Date: null, InTime: null, OutTime: null, Status: '', TotalWorksheetHours: null }, ], UserAllocationData: [ { FromDate: '', ToDate: '', AllocatedHr: 0, TotalHr: 0, ProjectName: '' }, ], UserAlertData: [ { Name: '', Status: '', Type: '' }, ], UserTeamData: [ { EmployeeId: 0, ProjectId: 0, ProjectName: '', EmployeeName: '' }, ], WorksheetLeaveDeta: { ID: 0, EmployeeID: 0, ToDate: null, FromDate: null, Reason: '', ContactDetail: '', AppliedTo: 0, LeaveType: 0, Status: 0, GHID: 0, EnteredDate: null, ResponsiblePersonID: 0, Remarks: '', IsFullDay: false, IsFirstHalf: false, IsSecondHalf: false, CreatedDate: null, contact: '', CallOnDate: null, CallOnTime: '', EmergencyLeave: false, LongleaveEntry: false }, WorksheetNwdHistoryData: [ { id: 0, employeeId: 0, date: null, leaveType: '', nwdId: 0 }, ], WorksheetCalTotalAttendanceData: { EmployeeID: 0, EmployeeName: '', Date: '', InTimeID: 0, InTime: null, OutTimeID: 0, OutTime: null, LunchOutTimeID: 0, LunchOutTime: null, LunchInTimeID: 0, LunchInTime: null, OtherTimeID: 0, TotalOtherTime: '', TotalOfficeTime: '', TotalLunchTime: '', TotalBreakTime: '', TotalWorkingTime: '', TotalWorksheetHour: 0, IsInOffice: false, IsInBreak: false, IsInLunch: false, IsInMeeting: false, IsInOfficeWork: false, Days: '', ImportRemarks: '', EmployeeCode: '', MMDDYYYY_DateFormate: '' }, WorksheetGetActualEntryTimeAndGraceData: { actualEntryTime: '', grace: 0 }, WorksheetGetEmpLeaveLedgerData: [ { leaveDuration: '', leaveType: '', approveType: '', shortLeaveType: '' }, ], WorksheetGetLeaveDetailsByDateData: [ { ID: 0, LeaveType: '', LeaveStatus: '', EmployeeId: 0, FromDate: null, ToDate: null, CalendarDays: null, IsFullDay: false, IsFirstHalf: false, IsSecondhalf: false }, ], WorksheetGetEmpHolidayListData: [ { id: 0, holidayName: '', fromDate: null, toDate: null, remarks: '', active: false, noOfDays: 0 }, ], WorksheetGetHolidayForDateData: [ { id: 0, holidayName: '', fromDate: null, toDate: null, remarks: '', active: false, noOfDays: 0 }, ], ProfileGetLevelsListData: [ { levelnumber: 0, Name: '', Icon: '', startpoint: 0, endpoint: 0 }, ], ProfileGetPointsLegendData: [ { Criteria: '', CalculatedOn: '', From: 0, To: 0, Points: 0 }, ], ProfileGetPointsDeta: [ { EventName: '', Type: false, CalculatedOn: '', PointsGained: 0, Date: '' }, ], }); this.LoadDashboards(); this.GetAttendanceDetail(); } LoadDashboards(): void { this.indLoading = true; this._DashboardService.get(Global.BASE_DASHBOARD_ENDPOINT + 'GetDashboardDataSets?UserId=158&IsApproved=true&FromDate=2014-01-01&ToDate=2017-09-06&IsLineManager=true&date=2014-01-01&PunchInId=158&IsAdmin=true') .subscribe(dashboarddata => { debugger; this.dashboard = dashboarddata; }); this.indLoading = false; } GetAttendanceDetail() { this.indLoading = true; this._DashboardService.get(Global.BASE_DASHBOARD_ENDPOINT + 'GetMyAttendance?Id=158&&Date=01/01/2015') .subscribe(attendancedata => { this.attendancedata = attendancedata; }); this.indLoading = false; } ProgressiveData() { this.modal.open(); //this.dbops = DBOperation.create; //this.SetControlsState(true); this.modalTitle = "Progressive Point Details"; //this.modalBtnTitle = "Add"; //this.ContactMasterFrm.reset(); } AchievementsData() { this.modalAchievements.open(); this.modalTitle = "Achievements Details"; } PointsData() { this.modalPoints.open(); this.modalTitle = "Points Details"; } LegendData() { this.modalLegend.open(); this.modalTitle = "Points Details"; } LevelsData() { this.modalLevels.open(); this.modalTitle = "Employee Levels Details"; } onSubmit(formData: any) { this.msg = ""; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.dashboards); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } // Function For Close Widget CloseWidgetProfile() { $("#adminProfile").hide(1000); } CloseWidgetWorkSheet() { $("#worksheetwidget").hide(1000); } CloseWidgetAttendance() { $("#MyAttendance").hide(1000); } CloseWidgetLeave() { $("#MyLeave").hide(1000); } CloseWidgetAllocation() { $("#MyAllocation").hide(1000); } CloseWidgetTeam() { $("#MyTeam").hide(1000); } CloseWidgetAlert() { $("#MyAlert").hide(1000); } CloseWidgetSkill() { $("#MySkill").hide(1000); } // Function For Collapse & Expand Widget ToogleMyProfile() { $("#myprofiledata").slideToggle(1000); } ToogleWorkSheet() { $("#myworksheetdata").slideToggle(1000); } ToogleAttendance() { $("#myattendancedata").slideToggle(1000); } ToogleLeave() { $("#myleavedata").slideToggle(1000); } ToogleAllocation() { $("#myallocationdata").slideToggle(1000); } ToogleTeam() { $("#myteamdata").slideToggle(1000); } ToogleAlert() { $("#myalertdata").slideToggle(1000); } ToogleSkill() { $("#myskilldata").slideToggle(1000); } // Function For Full Screen & Actual Size Widget MyProfileFullScreen() { if ($("#adminProfile").hasClass("widgetfullscreen")) { $("#adminProfile").removeClass("widgetfullscreen"); $("#myprofiledata").removeClass("widgetfullscreen"); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#adminProfile").addClass("widgetfullscreen"); $("#myprofiledata").addClass("widgetfullscreen"); $("#worksheetwidget").hide(1000); $("#MyAttendance").hide(1000); $("#MyLeave").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); } } WorkSheetFullScreen() { if ($("#worksheetwidget").hasClass("widgetfullscreen")) { $("#worksheetwidget").removeClass("widgetfullscreen"); $("#myworksheetdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#worksheetwidget").addClass("widgetfullscreen"); $("#myworksheetdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyLeave").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); } } AttendanceFullScreen() { if ($("#MyAttendance").hasClass("widgetfullscreen")) { $("#MyAttendance").removeClass("widgetfullscreen"); $("#myattendancedata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyAttendance").addClass("widgetfullscreen"); $("#myattendancedata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyLeave").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); } } MyLeaveFullScreen() { if ($("#MyLeave").hasClass("widgetfullscreen")) { $("#MyLeave").removeClass("widgetfullscreen"); $("#myleavedata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyLeave").addClass("widgetfullscreen"); $("#myleavedata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); } } MyAllocationFullScreen() { if ($("#MyAllocation").hasClass("widgetfullscreen")) { $("#MyAllocation").removeClass("widgetfullscreen"); $("#myallocationdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyAllocation").addClass("widgetfullscreen"); $("#myallocationdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } } MyTeamFullScreen() { if ($("#MyTeam").hasClass("widgetfullscreen")) { $("#MyTeam").removeClass("widgetfullscreen"); $("#myteamdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyTeam").addClass("widgetfullscreen"); $("#myteamdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } } MyAlertFullScreen() { if ($("#MyAlert").hasClass("widgetfullscreen")) { $("#MyAlert").removeClass("widgetfullscreen"); $("#myalertdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MySkill").show(1000); } else { $("#MyAlert").addClass("widgetfullscreen"); $("#myalertdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } } MySkillFullScreen() { if ($("#MySkill").hasClass("widgetfullscreen")) { $("#MySkill").removeClass("widgetfullscreen"); $("#myskilldata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); } else { $("#MySkill").addClass("widgetfullscreen"); $("#myskilldata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.ProfileAttendance { public class ProfileAttend : VISBaseEntity { //public ChangePassword ChangePasswordData { get; set; } /// <summary> /// ProfileAttendance Entity Fields. /// </summary> public String VISUsername { get; set; } public String VISPassword { get; set; } public String NewPassword { get; set; } public String ConfirmNewPassword { get; set; } //public String Employee_Name { get; set; } //public String Password { get; set; } //public String Email { get; set; } //public String In_Mon_Fri { get; set; } //public String Out_Mon_Fri { get; set; } //public String In_Sat { get; set; } //public String Out_Sat { get; set; } //public int Grace { get; set; } //public bool Active { get; set; } //public String userType { get; set; } //public DateTime joiningDate { get; set; } //public DateTime relevingDate { get; set; } //public Decimal totalCL { get; set; } //public Decimal totalSL { get; set; } //public int additionalRights { get; set; } //public bool validForLogin { get; set; } //public int leaveApproveBy { get; set; } //public String employeeCode { get; set; } //public DateTime probationTill { get; set; } //public int ActivityId { get; set; } //public bool Gender { get; set; } //public bool IsConfirmed { get; set; } //public int JoiningSalary { get; set; } //public String PhotographFileName { get; set; } //public int SalaryAfterRevision { get; set; } //public bool IsSLASigned { get; set; } //public DateTime ConfirmationDate { get; set; } //public DateTime AppraisalDate { get; set; } //public bool IsAppraisalRequired { get; set; } //public int SLAYear { get; set; } //public String FirstName { get; set; } //public String MiddleName { get; set; } //public String LastName { get; set; } //public int JoiningDesignation { get; set; } //public String Technology { get; set; } //public bool IsPasswordChange { get; set; } //public String OtherTechnology { get; set; } //public int SalaryRangeId { get; set; } //public int LineManagerId { get; set; } //public int TotalCOff { get; set; } //public int enrollnumber { get; set; } //public bool AllowScreenCapture { get; set; } //public bool ActiveDashboard { get; set; } //public bool IsSwitchUser { get; set; } //public int WorkingLocation { get; set; } //public String WorkingLocationAddress { get; set; } //public int Education { get; set; } //public String CommunicationID { get; set; } //public int SatGrace { get; set; } //public bool IsWebAccess { get; set; } //public String OtherRemark { get; set; } //public bool WorksheetThruWeb { get; set; } //public bool IsWorksheetFill { get; set; } //public float CL { get; set; } //public float SL { get; set; } //public bool IsjoiningLeave { get; set; } //public bool IsConfirmationLeave { get; set; } //public int EmployeeGradeID { get; set; } //public bool IsResigned { get; set; } //public bool isMailAlert { get; set; } //public bool IsAllowMouseMovement { get; set; } //public int accessCardId { get; set; } //public DateTime CreatedDateTime { get; set; } //public DateTime UpdatedDateTime { get; set; } //public bool IsMouseTracking { get; set; } //public bool IsScreenCaptureRemarks { get; set; } //public bool IsHost { get; set; } //public bool IsProductivityTracker { get; set; } //public bool WorkFromHome { get; set; } //public String attendancePolicy { get; set; } //public bool IsHostForEmpMaster { get; set; } //public DateTime ResignedDate { get; set; } } public static class ProfileAttendanceConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_VISUser = "VISUser"; //public const string const_Table_Employee_Master = "Employee_Master"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Id = "Id"; public const string const_Field_VISUsername = "VISUsername"; public const string const_Field_VISPassword = "<PASSWORD>"; public const string const_Field_NewPassword = "<PASSWORD>"; public const string const_Field_ConfirmNewPassword = "<PASSWORD>"; //public const string const_Field_Employee_Name = "Employee_Name"; //public const string const_Field_Password = "<PASSWORD>"; //public const string const_Field_Email = "Email"; //public const string const_Field_In_Mon_Fri = "In_Mon_Fri"; //public const string const_Field_Out_Mon_Fri = "Out_Mon_Fri"; //public const string const_Field_In_Sat = "In_Sat"; //public const string const_Field_Out_Sat = "Out_Sat"; //public const string const_Field_Grace = "Grace"; //public const string const_Field_Active = "Active"; //public const string const_Field_userType = "userType"; //public const string const_Field_joiningDate = "joiningDate"; //public const string const_Field_relevingDate = "relevingDate"; //public const string const_Field_totalCL = "totalCL"; //public const string const_Field_totalSL = "totalSL"; //public const string const_Field_additionalRights = "additionalRights"; //public const string const_Field_validForLogin = "validForLogin"; //public const string const_Field_leaveApproveBy = "leaveApproveBy"; //public const string const_Field_employeeCode = "employeeCode"; //public const string const_Field_probationTill = "probationTill"; //public const string const_Field_ActivityId = "ActivityId"; //public const string const_Field_CompanyId = "CompanyId"; //public const string const_Field_Gender = "Gender"; //public const string const_Field_IsConfirmed = "IsConfirmed"; //public const string const_Field_JoiningSalary = "JoiningSalary"; //public const string const_Field_PhotographFileName = "PhotographFileName"; //public const string const_Field_SalaryAfterRevision = "SalaryAfterRevision"; //public const string const_Field_IsSLASigned = "IsSLASigned"; //public const string const_Field_ConfirmationDate = "ConfirmationDate"; //public const string const_Field_AppraisalDate = "AppraisalDate"; //public const string const_Field_IsAppraisalRequired = "IsAppraisalRequired"; //public const string const_Field_SLAYear = "SLAYear"; //public const string const_Field_FirstName = "FirstName"; //public const string const_Field_MiddleName = "MiddleName"; //public const string const_Field_LastName = "LastName"; //public const string const_Field_JoiningDesignation = "JoiningDesignation"; //public const string const_Field_Technology = "Technology"; //public const string const_Field_IsPasswordChange = "IsPasswordChange"; //public const string const_Field_OtherTechnology = "OtherTechnology"; //public const string const_Field_SalaryRangeId = "SalaryRangeId"; //public const string const_Field_LineManagerId = "LineManagerId"; //public const string const_Field_TotalCOff = "TotalCOff"; //public const string const_Field_enrollnumber = "enrollnumber"; //public const string const_Field_AllowScreenCapture = "AllowScreenCapture"; //public const string const_Field_ActiveDashboard = "ActiveDashboard"; //public const string const_Field_IsSwitchUser = "IsSwitchUser"; //public const string const_Field_WorkingLocation = "WorkingLocation"; //public const string const_Field_WorkingLocationAddress = "WorkingLocationAddress"; //public const string const_Field_Education = "Education"; //public const string const_Field_CommunicationID = "CommunicationID"; //public const string const_Field_SatGrace = "SatGrace"; //public const string const_Field_IsWebAccess = "IsWebAccess"; //public const string const_Field_OtherRemark = "OtherRemark"; //public const string const_Field_WorksheetThruWeb = "WorksheetThruWeb"; //public const string const_Field_IsWorksheetFill = "IsWorksheetFill"; //public const string const_Field_CL = "CL"; //public const string const_Field_SL = "SL"; //public const string const_Field_IsjoiningLeave = "IsjoiningLeave"; //public const string const_Field_IsConfirmationLeave = "IsConfirmationLeave"; //public const string const_Field_EmployeeGradeID = "EmployeeGradeID"; //public const string const_Field_IsResigned = "IsResigned"; //public const string const_Field_isMailAlert = "isMailAlert"; //public const string const_Field_IsAllowMouseMovement = "IsAllowMouseMovement"; //public const string const_Field_accessCardId = "accessCardId"; //public const string const_Field_CreatedDateTime = "CreatedDateTime"; //public const string const_Field_UpdatedDateTime = "UpdatedDateTime"; //public const string const_Field_IsMouseTracking = "IsMouseTracking"; //public const string const_Field_IsScreenCaptureRemarks = "IsScreenCaptureRemarks"; //public const string const_Field_IsHost = "IsHost"; //public const string const_Field_IsProductivityTracker = "IsProductivityTracker"; //public const string const_Field_WorkFromHome = "WorkFromHome"; //public const string const_Field_attendancePolicy = "attendancePolicy"; //public const string const_Field_IsHostForEmpMaster = "IsHostForEmpMaster"; //public const string const_Field_ResignedDate = "ResignedDate"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procProfileAttendance_Add = ""; public const string const_procProfileAttendance_Update = ""; public const string const_procProfileAttendance_ActiveInActive = ""; public const string const_procProfileAttendance_SelectAll = ""; public const string const_procProfileAttendance_SelectBaseNonBase = ""; public const string const_procProfileAttendance_SelectById = ""; public const string const_procProfileAttendance_ChangePassword = "<PASSWORD>"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class SecurityKey : VISBaseEntity { /// <summary> /// SecurityKey Entity Fields. /// </summary> /// public string Key1 { get; set; } public string Key2 { get; set; } public string Key3 { get; set; } public string Key4 { get; set; } public string Key5 { get; set; } public bool Active { get; set; } public string UniqueKey { get; set; } } public static class SecurityKeyConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_SecurityKey_Table = "SecurityKey"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Key1 = "Key1"; public const string const_Key2 = "Key2"; public const string const_Key3 = "Key3"; public const string const_Key4 = "Key4"; public const string const_Key5 = "Key5"; public const string const_Active = "Active"; public const string const_UniqueKey = "UniqueKey"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procSecurityKey_Add = "procSecurityKey_Add"; public const string const_procSecurityKey_Update = "procSecurityKey_Update"; public const string const_procSecurityKey_ActiveInActive = "procSecurityKey_ActiveInActive"; public const string const_procSecurityKey_SelectAll = "procSecurityKey_SelectAll"; public const string const_procSecurityKey_SelectById = "procSecurityKey_SelectById"; } } <file_sep>export interface IRFQ { RFQInitialId: number; OpportunityId: number; Title: string; InitiatedBy: string; DateOfInitiation: Date; EstimateBy: string; SubmittedOn: Date; LastResponseBy: string; LastResponseDate: Date; ActionRequestedBy: string; Status: string; rfqStatus: string; OtherComments: string; CreatedBy: number; } export interface IRFQInitial { Id: number; BusinessHeadId: number; BusinessManagerId: number; UserIdList: number; UserId: number; Employee_Name: string; Source: string; ProspectClient: string; Title: string; DateOfInitiation: Date; BusinessTypeId: number; BusinessType: string; ProjectTypeId: number; ProjectType: string; IndustryId: number; Industries: string; ServiceOfferingId: number; ServiceOffering: string; SolutionId: number; Solution: string; TechnologyIdList: number; TechnologyId: number; TechnologyName: string; Remark: string; ResponseRequiredBy: Date; SupportedBy: string; ConfidenceLevel: number; OpportunityStatus: string; StatusId: number; RFQStatus: string; ExpectedClosureDate: Date; ResponseRequiredFrom: number; CreatedOn: Date; CreatedBy: number; UpdatedBy: number; UpdatedDate: Date; } export interface IRFQDoc { FileTypeID: number; FileType: string; FileName: string; AuthorId: number; Author: string; RemarkDoc: string; } export interface IRFQDocEntity { FileTypeId: number; FileType: string; FileName: string; AuthorId: number; Author: string; RemarkDoc: string; } export interface IRFQLink { RemarkLink: string; URL: string; UserId: number; Password: string; } export interface IRFQLinkEntity { RemarkLink: string; URL: string; UserId: number; Password: string; } export interface ITechnology { TechnologyId: number; TechnologyName: string } export interface ITechMultiCheckBox { id: number; name: string; } export interface IEmployee { UserId: number; Employee_Name: string; } export interface ForSessionData { SessionId: number; } export interface ProspectClient { Id: number; CompanyName : string Country :string FilterRadioButton: string; } export interface SessionValues { UserType: string; UserId: number; } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Web.Http; using VIS_Domain.Notification; using VIS_Repository; using VIS_Repository.Notification; namespace VIS_App.Controllers.Notification { public class PolicyAPIController : BaseAPIController { //VISIBaseRepository<Policy> PolicyRepository; //List<Policy> EntityList = new List<Policy>(); PolicyRepository ObjPolicyRepository = null; public PolicyAPIController() { ObjPolicyRepository = new PolicyRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); //PolicyRepository = _PolicyRepository; } public HttpResponseMessage Get() { return ToJson(ObjPolicyRepository.GetEntityList().AsEnumerable()); } [Route("api/policyapi/GetViewPolicyList")] [HttpGet] public HttpResponseMessage GetViewPolicyList(int id) { return ToJson(ObjPolicyRepository.GetViewPolicy(id)); } public HttpResponseMessage Post([FromBody]Policy value) { return ToJson(ObjPolicyRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]Policy value) { return ToJson(ObjPolicyRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjPolicyRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Reports.Attendance; using VIS_Repository.Reports.Attendance; namespace VIS_App.Controllers.Report.Attendance { public class AddEmployeeRecordAPIController : BaseAPIController { AddEmployeeRecordRepository objAddEmployeeRecordRepository = null; public AddEmployeeRecordAPIController() { objAddEmployeeRecordRepository = new AddEmployeeRecordRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/AddEmployeeRecordAPI/FillEmployee")] [HttpGet] public HttpResponseMessage FillEmployee() { return ToJson(objAddEmployeeRecordRepository.GetEmployee()); } [Route("api/AddEmployeeRecordAPI/BindEmployeeDetails")] [HttpGet] public HttpResponseMessage BindEmployeeDetails(Int64 EmpId,string Date,Int64 LoginUserId) { return ToJson(objAddEmployeeRecordRepository.GetEmployeeDetails(EmpId,Date,LoginUserId)); } [Route("api/AddEmployeeRecordAPI/BindEmployeeAttendance")] [HttpGet] public HttpResponseMessage BindEmployeeAttendance(Int64 EmployeeID,string Date) { return ToJson(objAddEmployeeRecordRepository.BindEmployeeAttendance(EmployeeID,Date)); } [Route("api/AddEmployeeRecordAPI/BindHRAttendanceDetails")] [HttpGet] public HttpResponseMessage BindHRAttendanceDetails(Int64 EmployeeId, string forWhichDate) { return ToJson(objAddEmployeeRecordRepository.BindHRAttendanceDetails(EmployeeId, forWhichDate)); } [Route("api/AddEmployeeRecordAPI/GetAttendanceTransaction")] [HttpGet] public HttpResponseMessage GetAttendanceTransaction(Int64 EmployeeId, string Date,Int64 EntryType) { return ToJson(objAddEmployeeRecordRepository.GetAttendanceTransaction(EmployeeId, Date,EntryType)); } [Route("api/AddEmployeeRecordAPI/GetUpdateEmployeeAttendance")] [HttpGet] public HttpResponseMessage GetUpdateEmployeeAttendance(Int64 id,Int64 EmployeeId,Int64 EntryType,string Remarks,string entryTime, string Date, Int64 Grace,Int64 LoginId,string ActualEntryTime) { return ToJson(objAddEmployeeRecordRepository.GetUpdateEmployeeAttendance(id,EmployeeId,EntryType,Remarks,entryTime, Date,Grace,LoginId,ActualEntryTime)); } [Route("api/AddEmployeeRecordAPI/AddEmployee")] [HttpGet] public HttpResponseMessage AddEmployee(Int64 EmployeeId,Int64 EntryType,string Remarks,string entryTime, string Date,string Time,Int64 Grace) { return ToJson(objAddEmployeeRecordRepository.AddEmployee(EmployeeId,EntryType,Remarks,entryTime,Date,Time,Grace)); } } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IWorkSheet } from '../../../Model/HumanResource/Attendance/WorkSheet'; @Pipe ({ name: 'WorkSheetFilter' }) export class WorkSheetFilterPipe implements PipeTransform { transform(value: IWorkSheet[], filter: string): IWorkSheet[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IWorkSheet) => app.ActivityName != null && app.ActivityName.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>"use strict"; //Saurabh var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var RFQResponse_service_1 = require("../../Service/RFQ/RFQResponse.service"); var RFQ_service_1 = require("../../Service/RFQ/RFQ.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var router_1 = require("@angular/router"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); //import * as _ from 'underscore'; var pager_index_1 = require("../../Shared/pager.index"); var http_1 = require("@angular/http"); var AddRFQResponsecomponent = (function () { function AddRFQResponsecomponent(fb, _RFQResponseService, _RFQService, router, pagerService, route, http) { this.fb = fb; this._RFQResponseService = _RFQResponseService; this._RFQService = _RFQService; this.router = router; this.pagerService = pagerService; this.route = route; this.http = http; this.indLoading = false; this.isDesc = false; this.Technology = []; this.Access = true; this.RFQDocList = []; this.RFQDocEntityList = []; this.RFQLinkList = []; this.RFQLinkEntityList = []; this.fileListForAPI = []; } AddRFQResponsecomponent.prototype.fileChangeDoc = function (event) { this.fileList = event.target.files; this.fileListForAPI[this.i] = this.fileList; this.i = this.i + 1; }; AddRFQResponsecomponent.prototype.ngOnInit = function () { this.addRFQResponse = ({ RFQ_InitialID: 0, IsEstimateReady: false, IsChangeToAction: false, Hours: 0, Timeline: 0, Timeline_Unit: '', Leadtime: 0, Leadtime_Unit: '', Technology: '', TechnologyIdList: 0, Description: '', ActionRequestedBy: 0, ActionByDate: null, EmployeeName: '', hdnEmployee: '', CurruntDate: null, hdnEmployeeId: 0, EmpId: 0 }); this.forRFQId = ({ RFQId: 0 }); this.forSessionData = ({ SessionId: 0 }); this.actionTakenBy = ({ EmpId: 0, Employee_Name: '' }); this.RFQDoc = ({ FileTypeID: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQDocEntity = ({ FileTypeId: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQLink = ({ RemarkLink: '', UserId: '', Password: '', URL: '' }); this.forSessionData.SessionId = +sessionStorage.getItem('Id'); this.LoadActionTaken(); this.GetTechnology(); this.LoadData(); this.GetFileType(); this.GetAuthor(); }; AddRFQResponsecomponent.prototype.LoadActionTaken = function () { var _this = this; this.indLoading = true; this._RFQResponseService.GetActionTaken(global_1.Global.BASE_RFQResponse_ENDPOINT, this.forSessionData.SessionId, this.Access) .subscribe(function (RFQs) { _this.actionTakenByList = RFQs; } //,error => this.msg = <any>error ); }; AddRFQResponsecomponent.prototype.LoadData = function () { var _this = this; this._RFQResponseService.GetOnLoadData(global_1.Global.BASE_RFQResponse_ENDPOINT, this.forSessionData.SessionId, 21) //21==rfqid .subscribe(function (RFQs) { _this.hiddenValue = RFQs; _this.addRFQResponse.EmployeeName = _this.hiddenValue.hdnEmployee; _this.addRFQResponse.hdnEmployeeId = _this.hiddenValue.hdnEmployeeId; debugger; _this.addRFQResponse.CurruntDate = new Date(); } //,error => this.msg = <any>error ); }; AddRFQResponsecomponent.prototype.GetTechnology = function () { var _this = this; this.indLoading = true; this._RFQResponseService.GetTechnology(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (Technology) { _this.Technology = Technology; _this.myOptions = []; for (var _i = 0, _a = _this.Technology; _i < _a.length; _i++) { var item = _a[_i]; _this.myOptions.push({ id: item.TechnologyId, name: item.TechnologyName }); } _this.indLoading = false; }); }; AddRFQResponsecomponent.prototype.GetFileType = function () { var _this = this; this.indLoading = true; this._RFQService.GetFileType(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.FileTypeDDL = RFQs; _this.indLoading = false; }); }; AddRFQResponsecomponent.prototype.GetAuthor = function () { var _this = this; this.indLoading = true; this._RFQService.GetAuthor(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (RFQs) { _this.AuthorDDL = RFQs; _this.indLoading = false; }); }; AddRFQResponsecomponent.prototype.onAddRFQSubmit = function (formData) { var _this = this; debugger; this.forRFQId.RFQId = 21; debugger; var MainAddResponse = { SessionData: this.forSessionData, RFQResponse: formData, RFQDoc: this.RFQDocEntityList, RFQLink: this.RFQLinkEntityList, RFQId: this.forRFQId.RFQId // RFQDoc: this.RFQDocList, //RFQLink: this.RFQLinkList }; this._RFQResponseService.post(global_1.Global.BASE_RFQResponse_ENDPOINT, MainAddResponse).subscribe(function (data) { if (data.startsWith("Success:")) { _this.msg = data; if (_this.fileListForAPI.length > 0) { var k = 0; for (var _i = 0, _a = _this.fileListForAPI; _i < _a.length; _i++) { var fileToBeUpload = _a[_i]; var file = fileToBeUpload[0]; var formData_1 = new FormData(); formData_1.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/RFQAPI/UploadRFQDoc"; _this.http.post(apiUrl1, formData_1, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); file = null; formData_1 = null; headers = null; options = null; k = k + 1; } _this.fileListForAPI = null; } alert('Record Added Successfully.'); _this.router.navigate(['/MyRFQ']); } else { alert(data); } }, function (error) { _this.msg = error; }); }; AddRFQResponsecomponent.prototype.onDocSubmit = function (formDocData) { if (this.fileList != null) { this.RFQDocEntity = formDocData; this.RFQDocEntity.FileName = this.fileList.item(0).name; this.RFQDocEntityList.push(this.RFQDocEntity); this.clearDoc(); } else { alert('please select Any document file'); } }; AddRFQResponsecomponent.prototype.deleteRFQDoc = function (FileName) { var elementPos = this.RFQDocList.map(function (x) { return x.FileName; }).indexOf(FileName); this.RFQDocEntityList.splice(elementPos, 1); }; AddRFQResponsecomponent.prototype.onLinkSubmit = function (formLinkData) { this.RFQLinkEntity = formLinkData; this.RFQLinkEntityList.push(this.RFQLinkEntity); this.clearLink(); }; AddRFQResponsecomponent.prototype.deleteRFQLink = function (UserId) { var elementPos = this.RFQLinkList.map(function (x) { return x.UserId; }).indexOf(UserId); this.RFQLinkEntityList.splice(elementPos, 1); }; AddRFQResponsecomponent.prototype.clearDoc = function () { this.RFQDoc.Author = ""; this.RFQDoc.AuthorId = 0; this.RFQDoc.FileName = ""; this.RFQDoc.FileType = ""; this.RFQDoc.RemarkDoc = ""; }; AddRFQResponsecomponent.prototype.clearLink = function () { this.RFQLink.Password = ""; this.RFQLink.RemarkLink = ""; this.RFQLink.URL = ""; this.RFQLink.UserId = ''; }; AddRFQResponsecomponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.RFQFrm.enable() : this.RFQFrm.disable(); }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], AddRFQResponsecomponent.prototype, "modal", void 0); AddRFQResponsecomponent = __decorate([ core_1.Component({ providers: [RFQResponse_service_1.RFQResponseService, RFQ_service_1.RFQService], templateUrl: 'app/Components/RFQ/AddResponse.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, RFQResponse_service_1.RFQResponseService, RFQ_service_1.RFQService, router_1.Router, pager_index_1.PagerService, router_1.ActivatedRoute, http_1.Http]) ], AddRFQResponsecomponent); return AddRFQResponsecomponent; }()); exports.AddRFQResponsecomponent = AddRFQResponsecomponent; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core' import { EmpInfoTabularService } from '../../../Service/HumanResource/EmployeeManagement/EmpInfoTabular.service' import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms' import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal' import { IEmpInfoTabular } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IPersonalInformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IEducationInformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IExperienceInformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { ISalaryInformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IAttendanceInformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IJoiningInformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IIncrementformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IOfficialInformation } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IProjectInfoFrm } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { ILeaveInfoFrm } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { IMySkillFrm } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular' import { DBOperation } from '../../../Shared/enum' import { Observable } from 'rxjs/Rx' import 'rxjs/add/operator/map' import 'rxjs/add/operator/catch' import 'rxjs/add/observable/throw' // fixed typo import { Global } from '../../../Shared/global' import { PagerService } from '../../../Shared/pager.index' import { Router, ActivatedRoute, Params } from '@angular/router' import { Http, RequestOptions, Headers, Response } from '@angular/http'; @Component({ providers: [EmpInfoTabularService], templateUrl: 'app/Components/HumanResource/EmployeeManagement/EmpInfoTabular.component.html' }) export class EmpInfoTabularComponent implements OnInit { @ViewChild('modal') modal: ModalComponent EmpInfoTabulars: IEmpInfoTabular[] EmpInfoTabular: IEmpInfoTabular PersonalInformations: IPersonalInformation[] PersonalInformation: IPersonalInformation EducationInformations: IEducationInformation[] EducationInformation: IEducationInformation ExperienceInformations: IExperienceInformation[] ExperienceInformation: IExperienceInformation SalaryInformations: ISalaryInformation[] SalaryInformation: ISalaryInformation SalaryAccounts: ISalaryInformation[] SalaryAccount: ISalaryInformation AttendanceInformations: IAttendanceInformation[] AttendanceInformation: IAttendanceInformation GetAttendances: IAttendanceInformation[] GetAttendance: IAttendanceInformation JoiningInformations: IJoiningInformation[] JoiningInformation: IJoiningInformation Incrementformations: IIncrementformation[] Incrementformation: IIncrementformation Increments: IIncrementformation[] Increment: IIncrementformation IncrementLists: IIncrementformation[] IncrementList: IIncrementformation OfficialInformations: IOfficialInformation[] OfficialInformation: IOfficialInformation ProjectInfoFrms: IProjectInfoFrm[] ProjectInfoFrm: IProjectInfoFrm Projects: IProjectInfoFrm[] Project: IProjectInfoFrm ProjectWBSs: IProjectInfoFrm[] ProjectWBS: IProjectInfoFrm LeaveInfoFrms: ILeaveInfoFrm[] LeaveInfoFrm: ILeaveInfoFrm LeaveDeatils: ILeaveInfoFrm[] LeaveDeatil: ILeaveInfoFrm AdjustmentLeaveDeatils: ILeaveInfoFrm[] AdjustmentLeaveDeatil: ILeaveInfoFrm Joingoffers: IEmpInfoTabular[] Joingoffer: IEmpInfoTabular; PendingTasks: IEmpInfoTabular[] PendingTask: IEmpInfoTabular; Feedbacks: IEmpInfoTabular[] Feedback: IEmpInfoTabular; Companys: IEmpInfoTabular[] Company: IEmpInfoTabular Linemanagers: IEmpInfoTabular[] Linemanager: IEmpInfoTabular Workings: IEmpInfoTabular[] Working: IEmpInfoTabular JoiningDesignations: IEmpInfoTabular[] JoiningDesignation: IEmpInfoTabular Departmentnames: IEmpInfoTabular[] Departmentname: IEmpInfoTabular PositionNames: IEmpInfoTabular[] PositionName: IEmpInfoTabular EmployeeGrades: IEmpInfoTabular[] EmployeeGrade: IEmpInfoTabular UserRoles: IEmpInfoTabular[] UserRole: IEmpInfoTabular EducationTypes: IEmpInfoTabular[] EducationType: IEmpInfoTabular Technologs: IEmpInfoTabular[] Technolog: IEmpInfoTabular Roles: IEmpInfoTabular[] Role: IEmpInfoTabular RoleAdds: IExperienceInformation[] RoleAdd: IExperienceInformation Salarys: IEmpInfoTabular[] Salary: IEmpInfoTabular; SalaryBreakups: IEmpInfoTabular[] SalaryBreakup: IEmpInfoTabular Employees: IEmpInfoTabular[] Employee: IEmpInfoTabular EmployeeDetails: IEmpInfoTabular[] EmployeeDetail: IEmpInfoTabular Nwds: IEmpInfoTabular[] Nwd: IEmpInfoTabular LeaveTypes: IEmpInfoTabular[] LeaveType: IEmpInfoTabular INTimeOutTimes: IEmpInfoTabular[] INTimeOutTime: IEmpInfoTabular //skill MySkillFrms: IMySkillFrm[] MySkillFrm: IMySkillFrm Secondlists: IMySkillFrm[] Secondlist: IMySkillFrm GetViews: IMySkillFrm[] GetView: IMySkillFrm Forstrcode: IEmpInfoTabular; msg: string indLoading: boolean = false ExperienceInfoFrm: FormGroup EmpInfoTabularFrm: FormGroup dbops: DBOperation InLoading: boolean; modalTitle: string modalBtnTitle: string EmpInfoTabularFilter: string isDesc: boolean = false column: any = '' direction: number CurrentRecordsPerPage: number = 10 Joingdate: string; Age: number EmployeeCodes: string Email: string usetype: string NwdDaySelect: any[] Year: string // pager object pager: any = {} // paged items pagedItems: any[] PagerInformation: string Status: number Type: string; Output: string; SlA: string; MaritalStatus: string; //Variables for Filter ShowHideSearch: boolean = false ShowHideSearchNew: boolean = false parment: string; SlASigned: number; //second table searchID: string searchCompanyName: string searchEmployeeName: string searchEmail: string searchDepartment: string searchTotalExp: string searchJoiningDate: string searchRelevingDate: string searchGrace: string searchSL_CL: string numbers: number; //declare id tempUserId: number = 21 tempUSertype: string = "Admin" item: number; IsSLASigned: string; Errormsg: string; Validation: string; strError: string; JoiningstrError: string; leaveerror: string; lblError: string; curentyear: string; //File Add Relieving: FileList; Experience: FileList; LastSalarySlip: FileList; DegreeCertificate: FileList; LastMarksheet: FileList; Passport: FileList; DrivingLicense: FileList; PANCard: FileList; CurriculamVitae: FileList; Other: FileList; Other0: FileList; Other1: FileList; UserId: number; leavestartdate: string; leaveenddate: string; Editmode: string; EditEmployeeid: string; constructor(private fb: FormBuilder, private _EmpInfoTabularService: EmpInfoTabularService, private pagerService: PagerService, private http: Http, private activatedRoute: ActivatedRoute) { this.Age = null this.parment = null; // this.EmployeeCode = null this.IsSLASigned = "Yes"; debugger; this.EditEmployeeid = this.activatedRoute.snapshot.queryParams["UserId"]; let mode = this.activatedRoute.snapshot.queryParams["mode"]; this.Editmode = mode this.EditEmployeeid = this.EditEmployeeid alert(this.Editmode) alert(this.EditEmployeeid) } ngOnInit(): void { this.EmpInfoTabular = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, returnid: 0, mode: '', id: 0, URoleId: 0, PositionId: 0, DepartmentID: 0, PID: 0, EID: 0, EducationID: 0, EmployeeID: 0, CompanyName: '', Employee_Name: '', Name: '', positionName: '', Department_name: '', Remarks: '', UserId: 0, SalaryRangeId: 0, Salary: 0, salaryrangetitle: '', Parentid: 0, Value: 0, TechnologyID: 0, technologyName: '', NWID: 0, NonWorkingDay: '', IntimeMondayToFridayHH: 0, IntimeMondayToFridayMM: 0, IntimeSaturdayHH: 0, IntimeSaturdayMM: 0, OutTimeMondayToFridayHH: 0, OutTimeMondayToFridayMM: 0, OutTimeSaturdayHH: 0, OutTimeSaturdayMM: 0, CompanyId: 0, strCode: '', EmployeeName: ' ', FirstName: ' ', MiddleName: ' ', LastName: ' ', Password: ' ', Email: ' ', Active: true, UserType: ' ', JoiningDate: null, RelevingDate: null, ResignedDate: null, TotalCL: 0, TotalSl: 0, AdditionalRights: 0, ValidForLogin: false, Employeecode: '', ProbationTill: null, ActivityId: 0, Gender: true, IsConfirmed: false, JoiningSalary: 0, JoiningDesignation: 0, PhotographFileName: '', SalaryAfterRevision: 0, IsSLASigned: false, ConfirmationDate: null, AppraisalDate: null, IsAppraisalRequired: false, SLAYear: 0, Technology: ' ', OtherTechnology: ' ', LineManagerID: 0, WorkingLocation: 0, WorkingLocationAddress: ' ', CommunicationID: ' ', OtherRemark: ' ', IsWebAccess: false, WorksheetThruWeb: false, IsSwitchUser: false, AllowScreenCapture: true, IsWorksheetFill: true, IsConfirmationLeave: false, EmployeeGradeID: 0, IsResigned: false, isMailAlert: false, IsAllowMouseMovement: true, CreatedDateTime: null, IsMouseTracking: false, IsScreenCaptureRemarks: true, IsHost: false, IsHostForEmpMaster: false, IsProductivityTracker: true, WorkFromHome: false, Sar: 0, YearEducation: '', joingdate: '', Designation: '', SLASigned: '', Department: '', }); this.PersonalInformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, FatherName: ' ', Birthdate: null, Paddress: ' ', Caddress: ' ', Landlineno: ' ', Mobileno: ' ', Emergencyno: ' ', Age: 0, Bloodgroup: ' ', Status: ' ', Spouse: ' ', Numberofchild: 0, Childname: ' ', AnniversaryDate: null, Grandfathername: ' ', Spousedob: ' ', MotherName: ' ', BrotherName: ' ', SisterName: ' ', FatherOccupation: ' ', MotherOccupation: ' ', BrotherOccupation: ' ', SisterOccupation: ' ', SpouseOccupation: ' ', }); this.EducationInformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, Eduid: 0, UserId: 0, HighestEducation: false, ClassDegree: '', Schoolinstitute: '', Medium: '', Passingyear: 0, Boarduniversity: '', Percentage: 0, mode: '', }); this.ExperienceInformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, Efficiency: 0, RoleId: 0, RoleName: '', ExpRoleId: 0, Expid: 0, Skills: '', Totalexp: '', Org: '', Url: '', Designation: '', Joiningdate: '', Relievingdate: '', Reportingto: '', Contactno: '', Reason: '', Lastsalary: '', experiencesummary: '', skills: '', ProjectHandled: '', RelevanceExp: '', expyear: 0, expmonth: 0, relevanceExpYear: '', relevanceExpMonth: '', hdnProjectsToSave: '', }); this.SalaryInformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, UserId: 0, Salary: 0, Bankname: '', Accountno: '', PFAccountNo: '', CurrentDesignation: '', ISPFApplicable: true, AdharNumber: 0, UANNumber: 0, Employee_Name: '', Type: '', }); this.AttendanceInformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, UserId: 0, Intime: '', Outitme: '', Intimesat: '', Outtimesat: '', Grace: 0, Leaveapproveby: 0, SatGrace: 0, IsAlertRequired: false, AccessCardId: 0, UpdatedBy: 0, AttendancePolicy: '', Nwdday: '', NWID: 0, Output: '', }); this.JoiningInformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, Panno: ' ', Passportno: ' ', Placeofissue: ' ', Issuedate: null, Expirydate: null, Isrelevingletter: false, Isexperienceletter: false, Issalaryslip: false, IsDegreeCertificate: false, IsMarkSheet: false, IsPassport: false, Isdrivinglicense: false, Ispancard: false, Iscv: false, Isother: false, Other: ' ', RelievingLetterFileName: ' ', ExperienceLetterFileName: ' ', LastSalarySlipFileName: ' ', DegreeCertificateFileName: ' ', LastMarksheetFileName: ' ', PassportFileName: ' ', DrivingLicenseFileName: ' ', PANCardFileName: ' ', CurriculamVitaeFilName: ' ', OtherFileName: ' ', OtherFileName0: ' ', OtherFileName1: ' ', Other0: ' ', Other1: ' ', HR_Remark: ' ', Isother0: false, Isother1: false, }); this.Incrementformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, AppraisalDate: null, Incrementdate: null, Designationchange: 0, Increment: 0, Salarychange: 0, Isfirst: false, Incrementid: 0, SalaryRangeId: 0, }); this.OfficialInformation = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, Verveemail: '', Vervepassword: '', Gmail: '', Gmailpassword: '', Yahoo: '', Yahoopassword: '', Skype: '', Skypepassword: '', Othersitename: '', Otherid: '', Otherpassword: '', }); this.ProjectInfoFrm = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, FromDate: null, ToDate: null, UserId: 0, }) this.LeaveInfoFrm = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, Leavetype: '', Balance: 0, Transactiontype: '', Isadjusted: false, AdjustedValue: 0, Lastyear: '', UUPLBalance: 0, Leavedate: null, Createddate: null, Remarks: '', Leavename: '', Isaupl: false, leavestartdate: '', leaveenddate: '', }) this.MySkillFrm = ({ EditEmployeeid: this.EditEmployeeid, Editmode: this.Editmode, Name :'', lookupSkilId: 0, SkillName: '', id:0, }) this.GetSkill(); this.checkMaritalStatus(event) this.LoadGetRole() this.LoadGetTechnology() this.LoadGetCompany() this.LoadGetWorking() this.LoadGetJoiningDesignation() this.LoadGetDepartmentname() this.LoadGetPositionName() this.LoadGetEmployeeGrade() this.LoadGetEducationType() this.LoadGetUserRole() this.LoadGetLinemanager(this.tempUSertype, this.tempUserId) this.FillEmployee() this.GetNonWorking() this.GetInTimeOutTimeSelected() this.GetRoleAdd() this.GetIncrementType() this.GetIncrementList() // this.GetOfferdeatils(parseInt(this.EditEmployeeid)) debugger; if (this.EditEmployeeid != null && this.Editmode) { this.GetPendingList(this.EditEmployeeid) this.GetFeedbackList(this.EditEmployeeid) this.GetOfferdeatils(parseInt(this.EditEmployeeid)) this.GetAdustmentleave(parseInt(this.EditEmployeeid)) this.GetEmployeeDeatils(parseInt(this.EditEmployeeid)) this.FillPassingYear(this.EditEmployeeid, this.Editmode) } this.GetLeaveType() this.FillLeaveDeatil() $("#Age").attr("disabled", "disabled"); $("#showSalaryBreakup").hide(); $("#SalaryBreakup").hide(); $("#SpouseName").attr("disabled", "disabled"); $("#Spouseoccupation").attr("disabled", "disabled"); $("#SpouseDateofBirth").attr("disabled", "disabled"); $("#RemoveSpouse").attr("disabled", "disabled"); $("#AniversayDate").attr("disabled", "disabled"); $("#NumberOfChild").attr("disabled", "disabled"); $("#ChildName").attr("disabled", "disabled"); //$("#DemoEmployee").show(); //$("#Employeecode").hide(); $("#pnlRelevingInformation").hide(); $("#pnlConfirmationDate").hide(); $("#Resigned").hide(); $("#SalaryBreakupchange").hide(); $("#SalaryBreakupDemochange").show(); $("#Errormsgdemo").show(); $("#lblNonwbsprojects").hide(); $("#GVNonwbsprojects").hide(); $("#lblwbsprojects").hide(); $("#gvwbsprojects").hide(); } fileRelieving(event) { this.Relieving = event.target.files; } fileExperience(event) { this.Experience = event.target.files; } fileLastSalarySlip(event) { this.LastSalarySlip = event.target.files; } fileDegreeCertificate(event) { this.DegreeCertificate = event.target.files; } fileLastMarksheet(event) { this.LastMarksheet = event.target.files; } filePassport(event) { this.Passport = event.target.files; } fileDrivingLicense(event) { this.DrivingLicense = event.target.files; } filePANCard(event) { this.PANCard = event.target.files; } fileCurriculamVitae(event) { this.CurriculamVitae = event.target.files; } fileOther(event) { this.Other = event.target.files; } fileOther0(event) { this.Other0 = event.target.files; } fileOther1(event) { this.Other1 = event.target.files; } moveItems(origin, dest) { $(origin).find(':selected').appendTo(dest); } moveAllItems(origin, dest) { $(origin).children().appendTo(dest); } moveRightAll(origin, dest) { this.moveAllItems("#ddlTechnical1", "#ddlTechnical2"); } moveLeftAll(origin, dest) { this.moveAllItems("#ddlTechnical2", "#ddlTechnical1"); } moveRight(origin, dest) { this.moveItems("#ddlTechnical1", "#ddlTechnical2"); } moveLeft(origin, dest) { this.moveItems("#ddlTechnical2", "#ddlTechnical1"); } checkMaritalStatus(event) { if (event.target.value == 'Unmarried') { $("#SpouseName").attr("disabled", "disabled"); $("#Spouseoccupation").attr("disabled", "disabled"); $("#SpouseDateofBirth").attr("disabled", "disabled"); $("#RemoveSpouse").attr("disabled", "disabled"); $("#AniversayDate").attr("disabled", "disabled"); $("#NumberOfChild").attr("disabled", "disabled"); $("#ChildName").attr("disabled", "disabled"); } else if (event.target.value == 'Engaged') { $("#SpouseName").removeAttr("disabled"); $("#Spouseoccupation").removeAttr("disabled"); $("#SpouseDateofBirth").removeAttr("disabled"); $("#RemoveSpouse").removeAttr("disabled"); $("#AniversayDate").attr("disabled", "disabled"); $("#NumberOfChild").attr("disabled", "disabled"); $("#ChildName").attr("disabled", "disabled"); } else if (event.target.value == 'Married') { $("#SpouseName").removeAttr("disabled"); $("#Spouseoccupation").removeAttr("disabled"); $("#SpouseDateofBirth").removeAttr("disabled"); $("#RemoveSpouse").removeAttr("disabled"); $("#AniversayDate").removeAttr("disabled"); $("#NumberOfChild").removeAttr("disabled"); $("#ChildName").removeAttr("disabled"); } else if (event.target.value == 'Divorced') { $("#SpouseName").removeAttr("disabled"); $("#Spouseoccupation").removeAttr("disabled"); $("#SpouseDateofBirth").removeAttr("disabled"); $("#RemoveSpouse").removeAttr("disabled"); $("#AniversayDate").removeAttr("disabled"); $("#NumberOfChild").removeAttr("disabled"); $("#ChildName").removeAttr("disabled"); } else { $("#SpouseName").removeAttr("disabled"); $("#Spouseoccupation").removeAttr("disabled"); $("#SpouseDateofBirth").removeAttr("disabled"); $("#RemoveSpouse").removeAttr("disabled"); $("#AniversayDate").removeAttr("disabled"); $("#NumberOfChild").removeAttr("disabled"); $("#ChildName").removeAttr("disabled"); } } Resigned(e) { if (e.target.checked) { $("#Resigned").show(); } else { $("#Resigned").hide(); } } chMd(event) { if (event.target.value == 'No') { var SlASigned = (<HTMLInputElement>document.getElementById("SLASigned")).value; this.SlASigned = 0; $("#SLASigned").attr("disabled", "disabled"); } else { $("#SLASigned").removeAttr("disabled"); this.SlASigned = null; } } copyaddress(e) { if (e.target.checked) { var Communiction = (<HTMLInputElement>document.getElementById("txtpermenantaddress")).value; var parment = (<HTMLInputElement>document.getElementById("txtCommunicationaddress")).value; this.parment = Communiction $("#txtCommunicationaddress").attr("disabled", "disabled"); } else { var parment = (<HTMLInputElement>document.getElementById("txtCommunicationaddress")).value; this.parment = null; $("#txtCommunicationaddress").removeAttr("disabled"); } } JoinDiv(e) { if (e.target.checked) { $("#divJoining").show(); } else { $("#divJoining").hide(); } } Confirmed(e) { if (e.target.checked) { $("#pnlConfirmationDate").show(); } else { $("#pnlConfirmationDate").hide(); } } calAge() { $("#Age").attr("disabled", "disabled"); var birthDay = $("#date").val() var now = new Date() var b_split = birthDay.split('-') if (b_split.length == 3) { var birthDate = new Date(b_split[0], b_split[1] * 1 - 1, b_split[2]) var years = Math.floor((now.getTime() - birthDate.getTime()) / (365.25 * 24 * 60 * 60 * 1000)) this.Age = years } } calEmailId() { var FirstName = $("#FirstName").val() var Email = FirstName + "@vervesys.local" this.Email = Email } CalEmployeecode(event) { var x = ($('input[name="Type"]:checked').val()); if (x == "E%") { //$("#DemoEmployee").hide(); //$("#Employeecode").show(); this.GetEmployeeTime(event.target.value) } else { } } GetEmployeeTime(CompanyId: number) { this.indLoading = true this._EmpInfoTabularService.GetEmployeeTime(Global.BASE_EmpInfoTabular_ENDPOINT, CompanyId) .subscribe(data => { this.Forstrcode = data[0] var Employeecode = this.Forstrcode.strCode this.EmployeeCodes = Employeecode; alert(this.EmployeeCodes); this.indLoading = false } ) } FillPassingYear(EditEmployeeid: string, Editmode: string) { ; this.indLoading = true this._EmpInfoTabularService.FillPassingYear(Global.BASE_EmpInfoTabular_ENDPOINT, EditEmployeeid, Editmode) .subscribe(data => { this.Year = data } ) } PfChange(e) { if (e.target.checked) { $("#PFNumber").removeAttr("disabled"); $("#UANNumber").removeAttr("disabled"); } else { $("#PFNumber").val(""); $("#UANNumber").val(""); $("#PFNumber").attr("disabled", "disabled"); $("#UANNumber").attr("disabled", "disabled"); } } calSalary(e) { if (e.target.click) { var Salary = $("#Salary").val() $("#SalaryBreakupDemo").hide(); $("#showSalaryBreakup").show(); this.GetSalaryRangeDropDown(Salary) } else { $("#showSalaryBreakup").hide(); $("#SalaryBreakup").hide(); $("#SalaryBreakupDemo").show(); } } calSalarychange() { var salarychange = $("#salarychange").val() if ((salarychange != null && salarychange != "")) { $("#SalaryBreakupchange").show(); $("#SalaryBreakupDemochange").hide(); $("#Errormsg").hide(); $("#Errormsgdemo").show(); this.GetSalaryRangechangedropdown(salarychange) } else { this.Errormsg = "Salary must be Enterd" $("#Errormsgdemo").hide(); } } ChkTotalSalaryClick() { debugger; alert('test') var totalsalary = $("#lblTotalSalaryPwd").val(); if (($("#ChkTotalSalary").prop("checked"))) { var totalsal = $("#lblTotalSalary").val(); var total = $("#txtSalary").val(); total = ""; var total = totalsal; $("#chkSAJoiningSalary").prop("checked", false); } else { $("#txtSalary").val("totalsalary"); } } SameJoiiningSalary() { debugger; if (($("#chkSAJoiningSalary").prop("checked"))) { if ($("#ChkTotalSalary").prop("checked")) { var total = $("#txtSalary").val(); var Joingsalary = $("#joiningsalary").val(); total = Joingsalary; $("#ChkTotalSalary").prop("checked", false); } else { var total = $("#txtSalary").val(); var lblMainJoiningSalary = $("#lblMainJoiningSalary").val(); } $('#txtSalary').attr("readonly", 'true'); $("#ChkTotalSalary").prop("checked", false); } else { $("#txtSalary").val(" "); $('#txtSalary').attr("readonly", 'false'); } } calRelevingDate() { var RelevingDate = $("#Salary").val() if (RelevingDate != null) { $("#pnlRelevingInformation").show(); } else { $("#pnlRelevingInformation").hide(); } } LoadGetRole() { this.indLoading = true this._EmpInfoTabularService.GetRole(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Roles = data this.indLoading = false } ) } LoadGetTechnology() { this.indLoading = true this._EmpInfoTabularService.GetTechnology(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Technologs = data this.indLoading = false } ) } LoadGetCompany() { this.indLoading = true this._EmpInfoTabularService.GetCompany(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Companys = data this.indLoading = false } ) } LoadGetWorking() { this.indLoading = true this._EmpInfoTabularService.GetWorking(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Workings = data this.indLoading = false } ) } LoadGetJoiningDesignation() { this.indLoading = true this._EmpInfoTabularService.GetJoiningDesignation(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.JoiningDesignations = data this.indLoading = false } ) } LoadGetDepartmentname() { this.indLoading = true this._EmpInfoTabularService.GetDepartmentname(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Departmentnames = data this.indLoading = false } ) } LoadGetPositionName() { this.indLoading = true this._EmpInfoTabularService.GetPositionName(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.PositionNames = data this.indLoading = false } ) } LoadGetEmployeeGrade() { this.indLoading = true this._EmpInfoTabularService.GetEmployeeGrade(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.EmployeeGrades = data this.indLoading = false } ) } LoadGetUserRole() { this.indLoading = true this._EmpInfoTabularService.GetUserRole(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.UserRoles = data this.indLoading = false } ) } LoadGetLinemanager(Usertype: string, UserId: number) { this.indLoading = true this._EmpInfoTabularService.GetLinemanager(Global.BASE_EmpInfoTabular_ENDPOINT, Usertype, UserId) .subscribe(data => { this.Linemanagers = data this.indLoading = false } ) } LoadGetEducationType() { this.indLoading = true this._EmpInfoTabularService.GetEducationType(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.EducationTypes = data this.indLoading = false } ) } GetNonWorking() { this.indLoading = true this._EmpInfoTabularService.GetNonWorking(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Nwds = data this.indLoading = false } ) } GetSalaryRangeDropDown(Salary: number) { $("#SalaryBreakup").show(); this.indLoading = true this._EmpInfoTabularService.GetSalaryRangeDropDown(Global.BASE_EmpInfoTabular_ENDPOINT, Salary) .subscribe(data => { this.Salarys = data this.indLoading = false } ) } GetSalaryRangechangedropdown(Salary: number) { $("#SalaryBreakupchange").show(); this.indLoading = true this._EmpInfoTabularService.GetSalaryRangeDropDown(Global.BASE_EmpInfoTabular_ENDPOINT, Salary) .subscribe(data => { this.Salarys = data this.indLoading = false } ) } GetIncrementType() { this.indLoading = true this._EmpInfoTabularService.GetIncrementType(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Increments = data this.indLoading = false } ) } GetIncrementList() { this.indLoading = true this._EmpInfoTabularService.GetIncrementList(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.IncrementLists = data this.indLoading = false } ) } FillEmployee() { this.indLoading = true this._EmpInfoTabularService.FillEmployee(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.Employees = data this.indLoading = false } ) } //Project Get FillProjectDeatil(ProjectInfoFrm: IProjectInfoFrm) { $("#lblNonwbsprojects").show(); $("#GVNonwbsprojects").show(); $("#lblwbsprojects").show(); $("#gvwbsprojects").show(); ProjectInfoFrm.UserId = parseInt(this.EditEmployeeid); ProjectInfoFrm.EditEmployeeid = this.EditEmployeeid; ProjectInfoFrm.Editmode = this.Editmode; this.indLoading = true this._EmpInfoTabularService.FillProjectDetail(Global.BASE_EmpInfoTabular_ENDPOINT, ProjectInfoFrm.FromDate, ProjectInfoFrm.ToDate, ProjectInfoFrm.UserId) .subscribe(data => { this.ProjectWBSs = data this.indLoading = false } ) this._EmpInfoTabularService.FillProjectDetailWbs(Global.BASE_EmpInfoTabular_ENDPOINT, ProjectInfoFrm.FromDate, ProjectInfoFrm.ToDate, ProjectInfoFrm.UserId) .subscribe(data => { this.Projects = data this.indLoading = false } ) } JoingAggrimentDownload() { alert("joingAggrent") } GetSalaryBrakup(event) { this.indLoading = true this._EmpInfoTabularService.GetSalaryBrakup(Global.BASE_EmpInfoTabular_ENDPOINT, event.target.value) .subscribe(data => { this.SalaryBreakups = data this.indLoading = false } ) } GetOfferdeatils(UserId: number) { this.indLoading = true this._EmpInfoTabularService.GetOfferdeatils(Global.BASE_EmpInfoTabular_ENDPOINT, parseInt(this.EditEmployeeid)) .subscribe(data => { this.Joingoffers = data console.log(this.Joingoffers) this.indLoading = false } ) } GetAdustmentleave(UserId: number) { this.indLoading = true this._EmpInfoTabularService.GetAdustmentleave(Global.BASE_EmpInfoTabular_ENDPOINT, parseInt(this.EditEmployeeid)) .subscribe(data => { this.AdjustmentLeaveDeatils = data this.indLoading = false } ) } GetEmployeeDeatils(UserId: number) { debugger; this.indLoading = true this._EmpInfoTabularService.GetEmployeeDeatils(Global.BASE_EmpInfoTabular_ENDPOINT, this.EditEmployeeid) .subscribe(data => { this.EmployeeDetails = data this.indLoading = false } ) } FillLeaveDeatil() { debugger; this.indLoading = true this._EmpInfoTabularService.FillLeaveDeatil(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.LeaveDeatil = data this.leavestartdate = this.LeaveDeatil[0].leavestartdate; this.leaveenddate = this.LeaveDeatil[0].leaveenddate; console.log(this.leaveenddate) console.log(this.leavestartdate) this.indLoading = false } ) } GetPendingList(UserId: string) { this.indLoading = true this._EmpInfoTabularService.GetPendingList(Global.BASE_EmpInfoTabular_ENDPOINT, UserId) .subscribe(data => { this.PendingTasks = data this.indLoading = false } ) } GetFeedbackList(UserId: string) { debugger; this.indLoading = true this._EmpInfoTabularService.GetFeedbackList(Global.BASE_EmpInfoTabular_ENDPOINT, UserId) .subscribe(data => { this.Feedbacks = data console.log(this.Feedbacks) this.indLoading = false } ) } GetInTimeOutTimeSelected() { this.indLoading = true this._EmpInfoTabularService.GetInTimeOutTimeSelected(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.INTimeOutTimes = data this.indLoading = false } ) } GetLeaveType() { this.indLoading = true this._EmpInfoTabularService.GetLeaveType(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.LeaveTypes = data this.indLoading = false } ) } SaveUserType() { debugger; var slvals = [] $('input:checkbox[name=UserRole]:checked').each(function () { var usertype = slvals.push($(this).val()) this.usetype = usertype }) } SaveEmployee(EmpInfoTabular: IEmpInfoTabular) { this.SaveUserType(); EmpInfoTabular.Employeecode = this.EmployeeCodes; EmpInfoTabular.Email = this.Email; EmpInfoTabular.UserType = this.usetype; if ($("#JoingDiv").prop("checked")) { EmpInfoTabular.JoiningDate; } else { EmpInfoTabular.JoiningDate = null } if (EmpInfoTabular.RelevingDate != null) { EmpInfoTabular.RelevingDate = EmpInfoTabular.RelevingDate } else { EmpInfoTabular.RelevingDate = null } if ($("#Male").prop("checked")) { EmpInfoTabular.Gender = true } else { EmpInfoTabular.Gender = false; } if ($("#isActive").prop("checked")) { EmpInfoTabular.Active = true } else { EmpInfoTabular.Active = false } if ($("#ScreenCapture").prop("checked")) { EmpInfoTabular.AllowScreenCapture = true } else { EmpInfoTabular.AllowScreenCapture = false; } if ($("#IsWorksheetFill").prop("checked")) { EmpInfoTabular.IsWorksheetFill = true } else { EmpInfoTabular.IsWorksheetFill = false; } if ($("#isScreenCaptureRemarks").prop("checked")) { EmpInfoTabular.IsScreenCaptureRemarks = true } else { EmpInfoTabular.IsScreenCaptureRemarks = false; } if ($("#MouseMovement").prop("checked")) { EmpInfoTabular.AllowScreenCapture = true } else { EmpInfoTabular.AllowScreenCapture = false; } if ($("#IsProductivityTracker").prop("checked")) { EmpInfoTabular.IsProductivityTracker = true } else { EmpInfoTabular.IsProductivityTracker = false; } if ($("#IsSLASigned").prop("checked")) { EmpInfoTabular.IsSLASigned = true EmpInfoTabular.SLAYear = this.SlASigned; } else { EmpInfoTabular.IsSLASigned = false; EmpInfoTabular.SLAYear = this.SlASigned; } if ($("#IsHost").prop("checked")) { EmpInfoTabular.IsHost = true } else { EmpInfoTabular.IsHost = false; } if ($("#IsHostForEmpMaster").prop("checked")) { EmpInfoTabular.IsHost = true } else { EmpInfoTabular.IsHost = false; } if ($("#WorksheetThruWeb").prop("checked")) { EmpInfoTabular.WorksheetThruWeb = true } else { EmpInfoTabular.WorksheetThruWeb = false; } if ($("#WorksheetThruWeb").prop("checked")) { EmpInfoTabular.WorksheetThruWeb = true } else { EmpInfoTabular.WorksheetThruWeb = false; } if ($("#IsSwitchUser").prop("checked")) { EmpInfoTabular.IsSwitchUser = true } else { EmpInfoTabular.IsSwitchUser = false; } if ($("#ValidForLogin").prop("checked")) { EmpInfoTabular.ValidForLogin = true } else { EmpInfoTabular.ValidForLogin = false; } if ($("#IsMouseTracking").prop("checked")) { EmpInfoTabular.IsMouseTracking = true } else { EmpInfoTabular.IsMouseTracking = false; } if ($("#WorkFromHome").prop("checked")) { EmpInfoTabular.WorkFromHome = true } else { EmpInfoTabular.WorkFromHome = false; } this._EmpInfoTabularService.SaveMain(Global.BASE_EmpInfoTabular_ENDPOINT, EmpInfoTabular).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } SavePersonalData(PersonalInformation: IPersonalInformation) { debugger; PersonalInformation.Age = this.Age; PersonalInformation.Caddress = $("#txtCommunicationaddress").val(); PersonalInformation.EditEmployeeid = this.EditEmployeeid; PersonalInformation.Editmode = this.Editmode; if ($("#Engaged").prop("checked")) { PersonalInformation.Status = "Engaged" } else if ($("#Married").prop("checked")) { PersonalInformation.Status = "Married" } else if ($("#Divorced").prop("checked")) { PersonalInformation.Status = "Divorced" } else if ($("#Widow").prop("checked")) { PersonalInformation.Status = "Widow" } else { PersonalInformation.Status = "Unmarried" } // PersonalInformation.AnniversaryDate = $("#AniversayDate").val(); this._EmpInfoTabularService.SavePersonal(Global.BASE_EmpInfoTabular_ENDPOINT, PersonalInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) this.FillPassingYear(PersonalInformation.EditEmployeeid, PersonalInformation.Editmode); } SaveEducation(EducationInformation: IEducationInformation) { this.lblError = ""; var School1 = $("#School1").val() var School2 = $("#School2").val() var School3 = $("#School3").val() var School4 = $("#School4").val() var School5 = $("#School5").val() var School6 = $("#School6").val() var School7 = $("#School7").val() var School8 = $("#School8").val() var Eduid = $("#Education").val() debugger; if (Eduid == "Select" || Eduid == "" || Eduid == null) { this.lblError = "Plese select Any Education type" } else { if (School1 != null && School1 != "") { if ($("#rbnHighesteducation1").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } var label = $('#Class1'); var month = label.attr('class'); EducationInformation.ClassDegree = month; EducationInformation.Schoolinstitute = School1; if ($("#Medium1").val() != null || $("#Medium1").val() != "") { EducationInformation.Medium = $("#Medium1").val(); } else { this.lblError = ""; this.lblError += "Please Enter Medium " } if ($("#Passingyear1").val() != null || $("#Passingyear1").val() != "") { EducationInformation.Passingyear = $("#Passingyear1").val(); } else { this.lblError = ""; this.lblError += "Please Enter Passingyear " } if ($("#Board1").val() != null || $("#Board1").val() != "") { EducationInformation.Boarduniversity = $("#Board1").val(); } else { this.lblError = ""; this.lblError += "Please Enter Board/University Name " } if ($("#Percentage1").val() != null || $("#Percentage1").val() != "") { EducationInformation.Percentage = $("#Percentage1").val(); } else { this.lblError = ""; this.lblError += "Please Enter Percentage" } this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError += "Please Enter School/Institute Name" } if (School2 != null && School2 != "") { if ($("#rbnHighesteducation2").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } var label = $('#Class2'); var classvalue = label.attr('class1'); EducationInformation.ClassDegree = classvalue; EducationInformation.Schoolinstitute = School2; EducationInformation.Medium = $("#Medium2").val(); EducationInformation.Passingyear = $("#Passingyear2").val(); EducationInformation.Boarduniversity = $("#Board2").val(); EducationInformation.Percentage = $("#Percentage2").val(); this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError = "Please Enter School/Institute Name" } if (School3 != null && School3 != "") { if ($("#rbnHighesteducation3").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } EducationInformation.ClassDegree = $("#Class3").val();; EducationInformation.Schoolinstitute = School2; EducationInformation.Medium = $("#Medium3").val(); EducationInformation.Passingyear = $("#Passingyear3").val(); EducationInformation.Boarduniversity = $("#Board3").val(); EducationInformation.Percentage = $("#Percentage3").val(); this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError = "Please Enter School/Institute Name" } if (School4 != null && School4 != "") { if ($("#rbnHighesteducation4").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } EducationInformation.ClassDegree = $("#Class4").val();; EducationInformation.Schoolinstitute = School2; EducationInformation.Medium = $("#Medium4").val(); EducationInformation.Passingyear = $("#Passingyear4").val(); EducationInformation.Boarduniversity = $("#Board4").val(); EducationInformation.Percentage = $("#Percentage4").val(); this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError = "Please Enter School/Institute Name" } if (School5 != null && School5 != "") { if ($("#rbnHighesteducation5").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } EducationInformation.ClassDegree = $("#Class5").val();; EducationInformation.Schoolinstitute = School2; EducationInformation.Medium = $("#Medium5").val(); EducationInformation.Passingyear = $("#Passingyear5").val(); EducationInformation.Boarduniversity = $("#Board5").val(); EducationInformation.Percentage = $("#Percentage5").val(); this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError = "Please Enter School/Institute Name" } if (School6 != null && School6 != "") { if ($("#rbnHighesteducation6").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } EducationInformation.ClassDegree = $("#Class6").val();; EducationInformation.Schoolinstitute = School2; EducationInformation.Medium = $("#Medium6").val(); EducationInformation.Passingyear = $("#Passingyear6").val(); EducationInformation.Boarduniversity = $("#Board6").val(); EducationInformation.Percentage = $("#Percentage6").val(); this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError = "Please Enter School/Institute Name" } if (School7 != null && School7 != "") { if ($("#rbnHighesteducation7").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } EducationInformation.ClassDegree = $("#Class7").val();; EducationInformation.Schoolinstitute = School2; EducationInformation.Medium = $("#Medium7").val(); EducationInformation.Passingyear = $("#Passingyear7").val(); EducationInformation.Boarduniversity = $("#Board7").val(); EducationInformation.Percentage = $("#Percentage7").val(); this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError = "Please Enter School/Institute Name" } if (School8 != null && School8 != "") { if ($("#rbnHighesteducation8").prop("checked")) { EducationInformation.HighestEducation = true; } else { EducationInformation.HighestEducation = false; } EducationInformation.ClassDegree = $("#Class8").val();; EducationInformation.Schoolinstitute = School2; EducationInformation.Medium = $("#Medium8").val(); EducationInformation.Passingyear = $("#Passingyear8").val(); EducationInformation.Boarduniversity = $("#Board8").val(); EducationInformation.Percentage = $("#Percentage8").val(); this._EmpInfoTabularService.SaveEducation(Global.BASE_EmpInfoTabular_ENDPOINT, EducationInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.lblError = ""; this.lblError = "Please Enter School/Institute Name" } } } SaveNextEducation() { alert('NexttabEducation') } SaveSalary(SalaryInformation: ISalaryInformation) { SalaryInformation.EditEmployeeid = this.EditEmployeeid; SalaryInformation.Editmode = this.Editmode; if (SalaryInformation.Accountno != null && SalaryInformation.Accountno != "") { this.indLoading = true this._EmpInfoTabularService.GetAccountNo(Global.BASE_EmpInfoTabular_ENDPOINT, SalaryInformation.Accountno, this.EditEmployeeid) .subscribe(data => { this.SalaryAccount = data this.Type = this.SalaryAccount[0].Type; alert(this.SalaryAccount) alert(this.Type) if (this.Type == "false") { debugger; var msg1 = "You have already linked Account Number to inactive User :- " + this.SalaryAccount[0].Employee_Name + "" if (confirm(msg1) == true) { if ($("#ISPFApplicable").prop("checked")) { SalaryInformation.ISPFApplicable = true; if (SalaryInformation.UANNumber != null && SalaryInformation.PFAccountNo != null) { SalaryInformation.UANNumber = $("#UANNumber").val(); SalaryInformation.PFAccountNo = $("#PFNumber").val(); SalaryInformation.AdharNumber = $("#AdharNumber").val(); } else { SalaryInformation.UANNumber = 0; SalaryInformation.PFAccountNo = null; SalaryInformation.AdharNumber = $("#AdharNumber").val(); alert("UANNumber Number is Empty && PFAccount Number is Empty."); } } else { $("#UANNumber").val(0); $("#PFNumber").val(0); SalaryInformation.ISPFApplicable = false; SalaryInformation.UANNumber = 0; SalaryInformation.PFAccountNo = null; } this._EmpInfoTabularService.SaveSalary(Global.BASE_EmpInfoTabular_ENDPOINT, SalaryInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { } } else if (this.Type == "NotAccount") { if ($("#ISPFApplicable").prop("checked")) { SalaryInformation.ISPFApplicable = true; if (SalaryInformation.UANNumber != null && SalaryInformation.PFAccountNo != null) { SalaryInformation.UANNumber = $("#UANNumber").val(); SalaryInformation.PFAccountNo = $("#PFNumber").val(); SalaryInformation.AdharNumber = $("#AdharNumber").val(); } else { SalaryInformation.UANNumber = 0; SalaryInformation.PFAccountNo = null; SalaryInformation.AdharNumber = $("#AdharNumber").val(); alert("UANNumber Number is Empty && PFAccount Number is Empty."); } } else { SalaryInformation.ISPFApplicable = false; } this._EmpInfoTabularService.SaveSalary(Global.BASE_EmpInfoTabular_ENDPOINT, SalaryInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { alert("Account Number is already linked."); } }) } //if ($("#ISPFApplicable").prop("checked")) { // SalaryInformation.ISPFApplicable = true; // if (SalaryInformation.UANNumber != null && SalaryInformation.PFAccountNo != null) { // SalaryInformation.UANNumber = $("#UANNumber").val(); // SalaryInformation.PFAccountNo = $("#PFNumber").val(); // SalaryInformation.AdharNumber = $("#AdharNumber").val(); // } // else { // SalaryInformation.UANNumber = 0; // SalaryInformation.PFAccountNo = null; // SalaryInformation.AdharNumber = $("#AdharNumber").val(); // alert("UANNumber Number is Empty && PFAccount Number is Empty."); // } //} //else { // SalaryInformation.ISPFApplicable = false; //} //this._EmpInfoTabularService.SaveSalary(Global.BASE_EmpInfoTabular_ENDPOINT, SalaryInformation).subscribe( // data => { // if (data.startsWith("Success: ")) //Success // { // this.msg = data // } // else { // alert(data) // } // }) } SaveAttendance(AttendanceInformation: IAttendanceInformation) { AttendanceInformation.EditEmployeeid = this.EditEmployeeid AttendanceInformation.Editmode = this.Editmode; AttendanceInformation.UserId = parseInt(this.EditEmployeeid); if (AttendanceInformation.AccessCardId == 0) { var selectedValues = $("#nwdday").val(); var commaSeparated = selectedValues.join(',') alert(commaSeparated) AttendanceInformation.Nwdday = commaSeparated; AttendanceInformation.Intime = $("#IntimeHH").val() + ':' + $("#IntimeMM").val(); AttendanceInformation.Outitme = $("#OutitmeHH").val() + ':' + $("#OutitmeMM").val(); AttendanceInformation.Intimesat = $("#IntimesatHH").val() + ':' + $("#IntimesatMM").val(); AttendanceInformation.Outtimesat = $("#OuttimesatHH").val() + ':' + $("#OuttimesatMM").val(); this._EmpInfoTabularService.SaveAttendance(Global.BASE_EmpInfoTabular_ENDPOINT, AttendanceInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { this.indLoading = true this._EmpInfoTabularService.GetAttendanceDetail(Global.BASE_EmpInfoTabular_ENDPOINT, AttendanceInformation.AccessCardId, AttendanceInformation.UserId) .subscribe(data => { this.GetAttendance = data this.indLoading = false this.Output = this.GetAttendance[0].Output; alert(this.Output) if (this.Output == "true") { alert("This access card id as already used.") } else if (this.Output == "Null") { alert("Something went wrong while adding details. <br> Please try again.") } else { var selectedValues = $("#nwdday").val(); var commaSeparated = selectedValues.join(',') alert(commaSeparated) AttendanceInformation.Nwdday = commaSeparated; AttendanceInformation.Intime = $("#IntimeHH").val() + ':' + $("#IntimeMM").val(); AttendanceInformation.Outitme = $("#OutitmeHH").val() + ':' + $("#OutitmeMM").val(); AttendanceInformation.Intimesat = $("#IntimesatHH").val() + ':' + $("#IntimesatMM").val(); AttendanceInformation.Outtimesat = $("#OuttimesatHH").val() + ':' + $("#OuttimesatMM").val(); this._EmpInfoTabularService.SaveAttendance(Global.BASE_EmpInfoTabular_ENDPOINT, AttendanceInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } } ) } } SaveJoining(JoiningInformation: IJoiningInformation) { JoiningInformation.EditEmployeeid = this.EditEmployeeid; JoiningInformation.Editmode = this.Editmode this.JoiningstrError = ""; if (JoiningInformation.Passportno == null || JoiningInformation.Placeofissue == null || JoiningInformation.Issuedate == null || JoiningInformation.Expirydate == null) { if (JoiningInformation.Passportno == "" || JoiningInformation.Passportno == null) { this.JoiningstrError += "Please enter passport no ! <br/>"; } if (JoiningInformation.Placeofissue == "" || JoiningInformation.Placeofissue == null) { this.JoiningstrError += "Please enter place of issue ! <br/>"; } if (JoiningInformation.Issuedate == null) { this.JoiningstrError += "Please enter issue date ! <br/>"; } if (JoiningInformation.Expirydate == null || JoiningInformation.Expirydate == null) { this.JoiningstrError += "Please enter expiry date ! <br/>"; } } else { if (this.Relieving != null) { JoiningInformation.RelievingLetterFileName = this.Relieving.item(0).name; } else { JoiningInformation.RelievingLetterFileName = null } if (this.Experience != null) { JoiningInformation.ExperienceLetterFileName = this.Experience.item(0).name; } else { JoiningInformation.ExperienceLetterFileName = null } if (this.LastSalarySlip != null) { JoiningInformation.LastSalarySlipFileName = this.LastSalarySlip.item(0).name; } else { JoiningInformation.LastSalarySlipFileName = null } if (this.DegreeCertificate != null) { JoiningInformation.DegreeCertificateFileName = this.DegreeCertificate.item(0).name; } else { JoiningInformation.DegreeCertificateFileName = null } if (this.LastMarksheet != null) { JoiningInformation.LastMarksheetFileName = this.LastMarksheet.item(0).name; } else { JoiningInformation.LastMarksheetFileName = null } if (this.Passport != null) { JoiningInformation.PassportFileName = this.Passport.item(0).name; } else { JoiningInformation.PassportFileName = null } if (this.DrivingLicense != null) { JoiningInformation.DrivingLicenseFileName = this.DrivingLicense.item(0).name; } else { JoiningInformation.DrivingLicenseFileName = null } if (this.PANCard != null) { JoiningInformation.PANCardFileName = this.PANCard.item(0).name; } else { JoiningInformation.PANCardFileName = null } if (this.CurriculamVitae != null) { JoiningInformation.CurriculamVitaeFilName = this.CurriculamVitae.item(0).name; } else { JoiningInformation.CurriculamVitaeFilName = null } if (this.Other != null) { JoiningInformation.OtherFileName = this.Other.item(0).name; } else { JoiningInformation.OtherFileName = null } if (this.Other0 != null) { JoiningInformation.OtherFileName0 = this.Other0.item(0).name; } else { JoiningInformation.OtherFileName0 = null } if (this.Other1 != null) { JoiningInformation.OtherFileName1 = this.Other1.item(0).name; } else { JoiningInformation.OtherFileName1 = null } this._EmpInfoTabularService.SaveJoining(Global.BASE_EmpInfoTabular_ENDPOINT, JoiningInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { if (this.Relieving != null) { if (this.Relieving.length > 0) { this.Relieving.item(0).name let file: File = this.Relieving[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.RelievingLetterFileName = null } if (this.Experience != null) { if (this.Experience.length > 0) { this.Experience.item(0).name let file: File = this.Experience[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.ExperienceLetterFileName = null } if (this.LastSalarySlip != null) { if (this.LastSalarySlip.length > 0) { this.LastSalarySlip.item(0).name let file: File = this.LastSalarySlip[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.LastSalarySlipFileName = null } if (this.DegreeCertificate != null) { if (this.DegreeCertificate.length > 0) { this.DegreeCertificate.item(0).name let file: File = this.DegreeCertificate[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.DegreeCertificateFileName = null } if (this.LastMarksheet != null) { if (this.LastMarksheet.length > 0) { this.LastMarksheet.item(0).name let file: File = this.LastMarksheet[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.LastMarksheetFileName = null } if (this.Passport != null) { if (this.Passport.length > 0) { this.Passport.item(0).name let file: File = this.Passport[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.PassportFileName = null } if (this.DrivingLicense != null) { if (this.DrivingLicense.length > 0) { this.DrivingLicense.item(0).name let file: File = this.DrivingLicense[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.DrivingLicenseFileName = null } if (this.PANCard != null) { if (this.PANCard.length > 0) { this.PANCard.item(0).name let file: File = this.PANCard[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.PANCardFileName = null } if (this.CurriculamVitae != null) { if (this.CurriculamVitae.length > 0) { this.CurriculamVitae.item(0).name let file: File = this.CurriculamVitae[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.CurriculamVitaeFilName = null } if (this.Other != null) { if (this.Other.length > 0) { this.Other.item(0).name let file: File = this.Other[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.OtherFileName = null } if (this.Other0 != null) { if (this.Other0.length > 0) { this.Other0.item(0).name let file: File = this.Other0[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.OtherFileName0 = null } if (this.Other1 != null) { if (this.Other1.length > 0) { this.Other1.item(0).name let file: File = this.Other1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/EmpInfoTabularAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { JoiningInformation.Other1 = null } this.msg = data } else { alert(data) } }) } } SaveIncrement(Incrementformation: IIncrementformation) { Incrementformation.EditEmployeeid = this.EditEmployeeid; Incrementformation.Editmode = this.Validation = ""; var joinigtype = $("#DesignationChange").val(); var incrmenttype = $("#incrmenttype").val(); var salarychange = $("#salarychange").val(); var salarychangebreakup = $("#salarychangebreakup").val(); Incrementformation.SalaryRangeId = salarychangebreakup; var currentTime = new Date() var displayDate = currentTime.getFullYear() if (Incrementformation.AppraisalDate != null) { var tt = $("#AppraisalDate").val(); var date = new Date(tt); var dd = date.getDate(); var mm = date.getMonth() + 1; var y = date.getFullYear(); var someFormattedDate = y; } Incrementformation.Designationchange = joinigtype; Incrementformation.Increment = incrmenttype; Incrementformation.Isfirst = false; Incrementformation.Salarychange = salarychange; if (Incrementformation.AppraisalDate == null || Incrementformation.Incrementdate == null || joinigtype == 0 || incrmenttype == 0 || salarychange == "") { if (Incrementformation.Incrementdate == null) { this.Validation = "Please Select Increment Date ! \n"; } if (joinigtype == 0) { this.Validation += "Please Select Designation Change ! \n"; } if (incrmenttype == 0) { this.Validation += "Please Select Increment Type ! \n"; } if (salarychange == "") { this.msg += "Please Enter Salary Change ! \n"; } if (salarychangebreakup == 0) { this.Validation += "Please Select Salary Slab ! \n"; } if (Incrementformation.AppraisalDate == null) { this.Validation += "Please Select Next Appraisal Date ! \n"; } } else if ((Incrementformation.AppraisalDate) <= (Incrementformation.Incrementdate)) { this.Validation = "Next Appraisal Date not Less than Increment Date ! \n "; } else if ((someFormattedDate) <= (displayDate)) { this.Validation = "Next Appraisal Date is not Past Date ! \n "; } if (this.Validation != "") { } else { this.Validation = "" if ($("#chkIncrementType").prop("checked") && $("#chkIncrementSalary").prop("checked")) { this.Validation = "Both Designation & Salary can't be unchanged !"; } else { this._EmpInfoTabularService.SaveIncrement(Global.BASE_EmpInfoTabular_ENDPOINT, Incrementformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } } } SaveOfficial(OfficialInformation: IOfficialInformation) { OfficialInformation.EditEmployeeid = this.EditEmployeeid, OfficialInformation.Editmode = this.Editmode, this.strError = ""; if (OfficialInformation.Verveemail == null && OfficialInformation.Vervepassword == null) { } else { if (OfficialInformation.Vervepassword == null) { this.strError = "Please enter Company email id's password ! </n>"; } if (OfficialInformation.Verveemail == null) { this.strError += "Please enter Company email id ! </n>"; } } if (OfficialInformation.Gmail == null && OfficialInformation.Gmailpassword == null) { } else { if (OfficialInformation.Gmailpassword == null) { this.strError += "Please enter Gmail id's password ! </n>"; } if (OfficialInformation.Gmail == null) { this.strError += "Please enter Gmail id ! </n>"; } } if (OfficialInformation.Yahoo == null && OfficialInformation.Yahoopassword == null) { } else if (OfficialInformation.Yahoo == "" && OfficialInformation.Yahoopassword == "") { } else { if (OfficialInformation.Yahoopassword == null) { this.strError += "Please enter yahoo id's password ! </n>"; } if (OfficialInformation.Yahoo == null) { this.strError += "Please enter yahoo id ! </n>"; } } if (OfficialInformation.Skype == null && OfficialInformation.Skypepassword == null) { } else if (OfficialInformation.Skype == "" && OfficialInformation.Skypepassword == "") { } else { if (OfficialInformation.Skypepassword == null) { this.strError += "Please enter skype id's password ! </n>"; } if (OfficialInformation.Skype == null) { this.strError += "Please enter skype id ! </n>"; } } if (OfficialInformation.Othersitename == null && OfficialInformation.Otherid == null && OfficialInformation.Othersitename == null) { } else if (OfficialInformation.Othersitename == "" && OfficialInformation.Otherid == "" && OfficialInformation.Othersitename == "") { } else { if (OfficialInformation.Othersitename == null) { this.strError += "Please enter Other site's name ! </n>"; } if (OfficialInformation.Otherid == null) { this.strError += "Please enter Other site's email id ! </n>"; } if (OfficialInformation.Othersitename == null) { this.strError += "Please enter Other site's password ! </n>"; } } if (this.strError == "") { this._EmpInfoTabularService.SaveOfficial(Global.BASE_EmpInfoTabular_ENDPOINT, OfficialInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } else { } } SavePastExperience(ExperienceInformation: IExperienceInformation) { ExperienceInformation.EditEmployeeid = this.EditEmployeeid; ExperienceInformation.Editmode = this.Editmode; var Totalexperience = $("#txtTotalexperience").val(); var ExperienceMonth = $("#txtExperienceMonth").val(); if (Totalexperience != "" && ExperienceMonth != "12") { if ((ExperienceMonth) < 9) { var expmonth = "0" + ExperienceMonth; ExperienceInformation.Totalexp = Totalexperience + "." + expmonth; } else { ExperienceInformation.Totalexp = Totalexperience + "." + ExperienceMonth; } } else { var year = Totalexperience; year = year + 1; ExperienceInformation.Totalexp = year; } this._EmpInfoTabularService.btnAddExp(Global.BASE_EmpInfoTabular_ENDPOINT, ExperienceInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } AddLeave(LeaveInfoFrm: ILeaveInfoFrm) { LeaveInfoFrm.EditEmployeeid = this.EditEmployeeid; LeaveInfoFrm.Editmode = this.Editmode; var intvalue = LeaveInfoFrm.AdjustedValue; var adjvalue = $("#txtAdjustLeave").val() if (intvalue == 0) { alert('0 Leave can not be adjusted.'); } else if (LeaveInfoFrm.Remarks == null) { this.leaveerror = "Remarks required !"; } else { if ($("#chkLeaveAdjust").prop("checked")) { if (intvalue != 0) { if (intvalue > 0) { LeaveInfoFrm.Transactiontype = "Credit"; } else { LeaveInfoFrm.Transactiontype = "Debit"; } LeaveInfoFrm.Isadjusted = true; LeaveInfoFrm.AdjustedValue = adjvalue; this._EmpInfoTabularService.AddLeave(Global.BASE_EmpInfoTabular_ENDPOINT, LeaveInfoFrm).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data this.GetAdustmentleave(parseInt(LeaveInfoFrm.EditEmployeeid)) } else { alert(data) } }) } } } } EmpInfoTabularFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.EmpInfoTabularFilter = value } EmpInfoTabularSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc this.column = property this.direction = this.isDesc ? 1 : -1 } } addEmpInfoTabular() { // this.SetControlsState(true) this.modalTitle = "Add New EmpInfoTabular" this.modalBtnTitle = "Add" this.EmpInfoTabularFrm.reset() this.modal.open() } editEmpInfoTabular(id: number) { this.dbops = DBOperation.update /// this.SetControlsState(true) this.modalTitle = "Edit News" this.modalBtnTitle = "Update" //his.EmpInfoTabular = this.EmpInfoTabulars.filter(x => x.Id == id)[0] this.EmpInfoTabularFrm.setValue(this.EmpInfoTabular) this.modal.open() } AddRole(ExperienceInformation: IExperienceInformation) { this.InLoading = true; this._EmpInfoTabularService.AddRole(Global.BASE_EmpInfoTabular_ENDPOINT, ExperienceInformation).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) this.indLoading = true } GetRoleAdd() { this.indLoading = true this._EmpInfoTabularService.GetRoleAdd(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.RoleAdds = data this.indLoading = false } ) } editRoles(ExpRoleId: number) { //this.SetControlsState(true) this.ExperienceInformation = this.RoleAdds.filter(x => x.ExpRoleId == ExpRoleId)[0] // this.ExperienceInfoFrm.setValue(this.ExperienceInformation) } deleteRoles(id: number) { this.indLoading = true; this._EmpInfoTabularService.delete(Global.BASE_EmpInfoTabular_ENDPOINT, id) .subscribe(Data => { if (Data.startsWith("Success: ")) //Success { this.msg = Data; this.GetRoleAdd() } else { alert(Data); } this.indLoading = false; } ); } OpenSkill() { alert('Skill') this.modal.open(); } GetSkill() { this.indLoading = true this._EmpInfoTabularService.GetSkill(Global.BASE_EmpInfoTabular_ENDPOINT) .subscribe(data => { this.MySkillFrms = data console.log(this.MySkillFrms) this.indLoading = false } ) } GetPopupSkill(event) { alert(event.target.value) this.indLoading = true this._EmpInfoTabularService.GetPopupSkill(Global.BASE_EmpInfoTabular_ENDPOINT, event.target.value) .subscribe(data => { this.Secondlists = data this.indLoading = false } ) } GetGridViewList(UserId:number) { this.indLoading = true this._EmpInfoTabularService.GetPopupSkill(Global.BASE_EmpInfoTabular_ENDPOINT, UserId) .subscribe(data => { this.Secondlists = data this.indLoading = false } ) } Saveskill(MySkillFrm: IMySkillFrm) { debugger; MySkillFrm.EditEmployeeid = this.EditEmployeeid; MySkillFrm.Editmode = this.Editmode; this._EmpInfoTabularService.Saveskill(Global.BASE_EmpInfoTabular_ENDPOINT, MySkillFrm).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data } else { alert(data) } }) } //SetControlsState(isEnable: boolean) { // isEnable ? this.ExperienceInfoFrm.enable() : this.ExperienceInfoFrm.disable() //} ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage if (RecordsPerPage >= 0) { this.JumpOnPage(1) } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.PendingTasks) this.pager = this.pagerService.pager this.pagedItems = this.pagerService.pagedItems alert(this.pagedItems) } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch } onSubmit(formData: any) { this.msg = "" switch (this.dbops) { case DBOperation.create: this._EmpInfoTabularService.post(Global.BASE_EmpInfoTabular_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data this.modal.dismiss() } else { alert(data) } }, error => { this.msg = error } ) break case DBOperation.update: this._EmpInfoTabularService.put(Global.BASE_EmpInfoTabular_ENDPOINT, formData.Id, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data this.modal.dismiss() } else { alert(data) } }, error => { this.msg = error } ) break case DBOperation.delete: this._EmpInfoTabularService.delete(Global.BASE_EmpInfoTabular_ENDPOINT, formData.Id).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data this.modal.dismiss() } else { alert(data) } }, error => { this.msg = error } ) break } } }<file_sep> import { Component, OnInit, ViewChild } from '@angular/core'; import { MyTicketService } from '../../service/Notification/MyTicket.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IMyTicket } from '../../Model/Notification/MyTicket'; import { IOraganization } from '../../Model/Notification/Organization'; import { FileDropDirective, FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-upload'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { DatePipe } from '@angular/common'; @Component({ providers: [MyTicketService], templateUrl: 'app/Components/Notification/MyTicket.component.html' }) export class MyTicketComponent implements OnInit { public uploaderF1: FileUploader; @ViewChild('modal') modal: ModalComponent; @ViewChild('modal1') modal1: ModalComponent; @ViewChild('modal3') modal3: ModalComponent; MyTickets: IMyTicket[]; MyTicket: IMyTicket; ViewHistory: IMyTicket[]; GetDetail: IMyTicket[]; GetDetails: IMyTicket; Oraganization: IOraganization[]; msg: string; indLoading: boolean = false; MyTicketFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; MyTicketFilter: string; isDesc: boolean = false; column: any = 'Subject'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchSubject: string; strSearchMessage: string; strSearchAddressToGroup: string; strSearchAssignTo: string; strSearchPriority: string; strSearchUpdatebyName: string; strSearchStatus: string; //File Add fileList1: FileList; fileList2: FileList; fileList3: FileList; constructor(private fb: FormBuilder, private _MyTicketService: MyTicketService, private pagerService: PagerService, private http: Http) { } //file upload event fileChange1(event) { this.fileList1 = event.target.files; } fileChange2(event) { this.fileList2 = event.target.files; } fileChange3(event) { this.fileList3 = event.target.files; } ngOnInit(): void { this.MyTicketFrm = this.fb.group({ CompanyId: [''], Id: 0, Subject: [''], Message: [''], Remarks :[''], AddressToGroup: [''], AssignTo: [''], CreatedByName: [''], UpdatedByName: [''], Priority: [''], Status: [''], CreatedId: 0, CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], RecordCreatedOn: [''], RecordCreatedBy: [''], HelpTicketId: [''], FileName: [''], FileName1: [''], FileName2: [''], DepartmentHelpTicketDll: [''], SuggestionAlie: [''], SuggestionId: [''], RoleType: [''], EntityMessage: [''] }); // this.LoadGetChildGroup(21); // this.LoadOpenTicket(21); } MyTicketFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.MyTicketFilter = value; } MyTicketSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } //LoadMyTickets(): void { // this.indLoading = true; // this._MyTicketService.get(Global.BASE_MyTicket_ENDPOINT) // .subscribe(MyTickets => { // this.MyTickets = MyTickets; // //Logic for searching - start // if (this.ShowHideSearch) { // this.strSearchMyTicket_Name = (<HTMLInputElement>document.getElementById("searchMyTicket_Name")).value; // if (this.strSearchMyTicket_Name != '') { // this.strSearchMyTicket_Name = this.strSearchMyTicket_Name.toLocaleLowerCase(); // this.MyTickets = this.MyTickets.filter( // x => x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(this.strSearchMyTicket_Name) != -1); // } // } // //Logic for searching - End // this.indLoading = false; // // initialize to page 1 // this.JumpOnPage(1); // } // //,error => this.msg = <any>error // ); //} LoadGetChildGroup(CreatedId: number): void { this.indLoading = true; this._MyTicketService.getchildgroup(Global.BASE_MyTicket_ENDPOINT, CreatedId) .subscribe(data => { this.MyTickets = data; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchSubject = (<HTMLInputElement>document.getElementById("searchSubject")).value; if (this.strSearchSubject != '') { this.strSearchSubject = this.strSearchSubject.toLocaleLowerCase(); this.MyTickets = this.MyTickets.filter( x => x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(this.strSearchSubject) != -1); } } if (this.ShowHideSearch) { this.strSearchAddressToGroup = (<HTMLInputElement>document.getElementById("searchAddressToGroup")).value; if (this.strSearchAddressToGroup != '') { this.strSearchAddressToGroup = this.strSearchAddressToGroup.toLocaleLowerCase(); this.MyTickets = this.MyTickets.filter( x => x.AddressToGroup != null && x.AddressToGroup.toLocaleLowerCase().indexOf(this.strSearchAddressToGroup) != -1); } } if (this.ShowHideSearch) { this.strSearchAssignTo = (<HTMLInputElement>document.getElementById("searchAssignTo")).value; if (this.strSearchAssignTo != '') { this.strSearchAssignTo = this.strSearchAssignTo.toLocaleLowerCase(); this.MyTickets = this.MyTickets.filter( x => x.AssignTo != null && x.AssignTo.toLocaleLowerCase().indexOf(this.strSearchAssignTo) != -1); } if (this.ShowHideSearch) { this.strSearchUpdatebyName = (<HTMLInputElement>document.getElementById("searchUpdatedByName")).value; if (this.strSearchUpdatebyName != '') { this.strSearchUpdatebyName = this.strSearchUpdatebyName.toLocaleLowerCase(); this.MyTickets = this.MyTickets.filter( x => x.UpdatedByName != null && x.UpdatedByName.toLocaleLowerCase().indexOf(this.strSearchUpdatebyName) != -1); } } if (this.ShowHideSearch) { this.strSearchPriority = (<HTMLInputElement>document.getElementById("searchPriority")).value; if (this.strSearchPriority != '') { this.strSearchPriority = this.strSearchPriority.toLocaleLowerCase(); this.MyTickets = this.MyTickets.filter( x => x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(this.strSearchPriority) != -1); } } if (this.ShowHideSearch) { this.strSearchStatus = (<HTMLInputElement>document.getElementById("searchStatus")).value; if (this.strSearchStatus != '') { this.strSearchStatus = this.strSearchStatus.toLocaleLowerCase(); this.MyTickets = this.MyTickets.filter( x => x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(this.strSearchStatus) != -1); } } } //Logic for searching - End this.indLoading = false; this.JumpOnPage(1); } ); } FilterByStatus(event) { if (event.target.value == 'Open') { this.MyTickets = this.MyTickets.filter(x => x.Status == 'Open') this.JumpOnPage(1); } else if (event.target.value == 'Closed') { this.MyTickets = this.MyTickets.filter(x => x.Status == 'Closed') this.JumpOnPage(1); } // this.LoadGetChildGroup(21); } LoadDp(): void { this.indLoading = true; this._MyTicketService.getDp(Global.BASE_MyTicket_ENDPOINT) .subscribe(DATADP => { this.Oraganization = DATADP; } ); } LoadViwHistory(id: number): void { this.indLoading = true; this._MyTicketService.getViewHistory(Global.BASE_MyTicket_ENDPOINT, id) .subscribe(DATADP => { this.ViewHistory = DATADP; } ); } LoadGetTicketDetail(id: number): void { this.indLoading = true; this._MyTicketService.getTicketDetail(Global.BASE_MyTicket_ENDPOINT, id) .subscribe(DATADP => { this.GetDetail = DATADP; } ); } addMyTicket() { this.LoadDp(); this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New MyTicket"; this.modalBtnTitle = "Add"; this.MyTicketFrm.reset(); this.modal.open(); } editMyTicket(Id: number) { this.LoadDp(); this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit MyTicket"; this.modalBtnTitle = "Update"; this.MyTicket = this.MyTickets.filter(x => x.Id == Id)[0]; this.MyTicketFrm.setValue(this.MyTicket); this.LoadGetTicketDetail(Id); this.modal3.open(); } ViewMyTicket(Id: number) { this.dbops = DBOperation.View; this.SetControlsState(true); this.modalTitle = "Conversation Ticket"; this.MyTicket = this.MyTickets.filter(x => x.Id == Id)[0]; this.MyTicketFrm.setValue(this.MyTicket); this.LoadViwHistory(Id); this.modal1.open(); this.modal3.dismiss(); } deleteMyTicket(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.MyTicket = this.MyTickets.filter(x => x.Id == id)[0]; this.MyTicketFrm.setValue(this.MyTicket); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.MyTicketFrm.enable() : this.MyTicketFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.MyTickets); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: if (this.fileList1 != null) { formData._value.FileName = this.fileList1.item(0).name; } else { formData._value.FileName = null } if (this.fileList2 != null) { formData._value.FileName1 = this.fileList2.item(0).name; } else { formData._value.FileName1 = null } if (this.fileList3 != null) { formData._value.FileName2 = this.fileList3.item(0).name; } else { formData._value.FileName2 = null } //formData._value.FileName = this.fileList2.item(0).name; //formData._value.FileName = this.fileList3.item(0).name; this._MyTicketService.post(Global.BASE_MyTicket_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { if (this.fileList1 != null) { if (this.fileList1.length > 0) { this.fileList1.item(0).name let file: File = this.fileList1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { formData._value.FileName = null } if (this.fileList2 != null) { if (this.fileList2.length > 0) { this.fileList2.item(0).name let file: File = this.fileList2[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { formData._value.FileName2 = null } if (this.fileList3 != null) { if (this.fileList3.length > 0) { this.fileList3.item(0).name let file: File = this.fileList3[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } } else { formData._value.FileName3 = null } this.msg = data; this.LoadGetChildGroup(21); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._MyTicketService.put(Global.BASE_MyTicket_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadGetChildGroup(21); // this.LoadMyTickets(); this.modal3.dismiss(); } else { //alert(data); this.msg = "Error has occurred while changing status of existing MyTicket!."; } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._MyTicketService.delete(Global.BASE_MyTicket_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "MyTicket status changed successfully."; this.LoadGetChildGroup(21); // this.LoadMyTickets(); } else { this.msg = "Error has occurred while changing status of existing MyTicket!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Masters.EmployeeLevels { public class EmployeeData { public long Id { get; set; } public string Employee_Name { get; set; } public string Email { get; set; } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { BankMasterService } from '../../../service/Masters/CompanyRelated/BankMaster.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IBankMaster } from '../../../Model/Masters/CompanyRelated/BankMaster'; import { ICompany } from '../../../Model/Masters/CompanyRelated/BankMaster'; import { ICurrency } from '../../../Model/Masters/CompanyRelated/BankMaster'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [BankMasterService], templateUrl: 'app/Components/Masters/CompanyRelated/BankMaster.component.html' }) export class BankMasterComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; bankmasters: IBankMaster[]; bankmaster: IBankMaster; company: ICompany[]; currency: ICurrency[]; msg: string; indLoading: boolean = false; BankMasterFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; BankMasterFilter: string; isDesc: boolean = false; column: any = 'BankName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchBankAlias: string; strSearchBankName: string; strSearchBranchName: string; strSearchBankAddress: string; constructor(private fb: FormBuilder, private _BankMasterService: BankMasterService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } Resetmodel() { this.bankmaster = { AccountNumber:'', BankAddress: '', BankAlias: '', BankDetail: '', BankName: '', BranchName: '', CompanyId: 0, CreatedBy: '', CreatedOn:null, CurrencyId: 0, Id: 0, IsActive: false, Status: false, UpdatedBy: '', UpdatedOn: null, EntityMessage: '', } } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.BankMasterFrm = this.fb.group ({ Id: [''], BankAlias: ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(50)])], BankName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], BranchName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], BankAddress: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], BankDetail: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], CreatedBy: [''], UpdatedBy: [''], AccountNumber: ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(50)])], Status:[''], CompanyId: ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(50)])], CurrencyId: ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(50)])], EntityMessage: [''] }); this.LoadBankMaster(); this.GetCompany(); this.GetCurrency(); } BankFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.BankMasterFilter = value; } BankMasterSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadBankMaster(): void { this.indLoading = true; this._BankMasterService.get(Global.BASE_BANKMASTER_ENDPOINT) .subscribe(bankmasters => { this.bankmasters = bankmasters; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchBankAlias = (<HTMLInputElement>document.getElementById("searchBankAlias")).value; if (this.strSearchBankAlias != '') { this.strSearchBankAlias = this.strSearchBankAlias.toLocaleLowerCase(); this.bankmasters = this.bankmasters.filter ( x => x.BankAlias != null && x.BankAlias.toLocaleLowerCase().indexOf(this.strSearchBankAlias) != -1); } this.strSearchBankName = (<HTMLInputElement>document.getElementById("searchBankName")).value; if (this.strSearchBankName != '') { this.strSearchBankName = this.strSearchBankName.toLocaleLowerCase(); this.bankmasters = this.bankmasters.filter ( x => x.BankName != null && x.BankName.toLocaleLowerCase().indexOf(this.strSearchBankName) != -1); } this.strSearchBranchName = (<HTMLInputElement>document.getElementById("searchBranchName")).value; if (this.strSearchBranchName != '') { this.strSearchBranchName = this.strSearchBranchName.toLocaleLowerCase(); this.bankmasters = this.bankmasters.filter ( x => x.BranchName != null && x.BranchName.toLocaleLowerCase().indexOf(this.strSearchBranchName) != -1); } this.strSearchBankAddress = (<HTMLInputElement>document.getElementById("searchBankAddress")).value; if (this.strSearchBankAddress != '') { this.strSearchBankAddress = this.strSearchBankAddress.toLocaleLowerCase(); this.bankmasters = this.bankmasters.filter ( x => x.BankAddress != null && x.BankAddress.toLocaleLowerCase().indexOf(this.strSearchBankAddress) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } AddBankMaster() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Bank"; this.modalBtnTitle = "Add"; this.Resetmodel(); this.BankMasterFrm.setValue(this.bankmaster); this.modal.open(); } editBankMaster(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Bank"; this.modalBtnTitle = "Update"; this.bankmaster = this.bankmasters.filter(x => x.Id == id)[0]; this.BankMasterFrm.setValue(this.bankmaster); this.modal.open(); } deleteBankMaster(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.bankmaster = this.bankmasters.filter(x => x.Id == id)[0]; this.BankMasterFrm.setValue(this.bankmaster); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.BankMasterFrm.enable() : this.BankMasterFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.bankmasters); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._BankMasterService.post(Global.BASE_BANKMASTER_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadBankMaster(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._BankMasterService.put(Global.BASE_BANKMASTER_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadBankMaster(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._BankMasterService.delete(Global.BASE_BANKMASTER_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Bank status changed successfully."; this.LoadBankMaster(); } else { this.msg = "Error has occurred while changing status of existing Bank!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } GetCompany(): void { this.indLoading = true; this._BankMasterService.getcompany(Global.BASE_BANKMASTER_ENDPOINT) .subscribe(companylist => { this.company = companylist; }); } GetCurrency(): void { this.indLoading = true; this._BankMasterService.getcurrency(Global.BASE_BANKMASTER_ENDPOINT) .subscribe(currencylist => { this.currency = currencylist; }); } }<file_sep>export interface IMyProfile { EmployeeName: string; LineManagerName: string; FirstName: string; MiddleName: string; LastName: string; Gender: string; PhotographFileName: string; CompanyName: string; EmailID: string; Designation: string; DepartmentName: string; FatherName: string; PermenantAddress: string; CommunicationAddress: string; LandlineNumber: string; MobileNumber: string; MotherName: string; BirthDate: string; BloodGroup: string; MaritalStatus: string; EmplopyeeGrade: string; }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { ILateEarlyReport } from '../../../Model/Report/Attendance/LateEarlyReport'; @Pipe ({ name: 'lateearlyreportFilter' }) export class LateEarlyReportFilterPipe implements PipeTransform { transform(value: ILateEarlyReport[], filter: string): ILateEarlyReport[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: ILateEarlyReport) => app.Employees_Name != null && app.Employees_Name.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Reports.Attendance { public class ProductivityTrackerReport:VISBaseEntity { } public class FillDP { public Int64 Id { get; set; } public string Department_Name { get; set; } } public class EmployeeList { public Int64 ID { get; set; } public string EmployeeName { get; set; } } public class LineManager { public Int64 Id { get; set; } public string EmployeeName { get; set; } } public class Lookup { public Int64 Id { get; set; } public string name { get; set; } } public class YearData { public Int64 Id { get; set; } public string Year { get; set; } } public class ProductivityTracker { public string EntryType { get; set; } public string Difference { get; set; } public string Employeename { get; set; } public string ForWhichDate { get; set; } public string OutTime { get; set; } public string InTime { get; set; } } public static class ProductivityTrackerReportConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Organization = "Organization"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Id = "Id"; public const string const_Field_DepartmentName = "Department_Name"; public const string const_Field_Mode = "mode"; public const string const_Field_Allow = "Allow"; public const string const_Field_empid = "empid"; public const string Const_Field_InActive = "isActive"; public const string Const_Field_UserId = "UserId"; public const string Const_Field_Allow = "Allow"; public const string Const_Field_sort = "sort"; public const string Const_Field_fromDate = "fromDate"; public const string Const_Field_toDate = "toDate"; public const string Const_Field_Duration = "Duration"; public const string Const_Field_Employeelist = "Employeelist"; public const string Const_Field_OutType = "OutType"; public const string Const_Field_Consolidate = "Consolidate"; public const string Const_Field_Out = "Out"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procAttendanceReportNew_SelectAll = "ProcAttendanceReportBindDropdown"; public const string const_procGetEmployeeForOutReport = "procGetEmployeeForOutReport"; public const string const_ProcAttendanceReportBindDropdown = "ProcAttendanceReportBindDropdown"; public const string const_Proc_productivityTracker = "Proc_productivityTracker"; } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { LookupService } from '../../../service/Masters/CompanyRelated/Lookup.service'; import { LookupTypeService } from '../../../service/Masters/CompanyRelated/LookupType.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ILookup } from '../../../Model/Masters/CompanyRelated/Lookup'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; //import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; import { LookupTypeComponent } from '../CompanyRelated/LookupType.component'; import { ILookupType } from '../../../Model/Masters/CompanyRelated/LookupType'; @Component ({ providers: [LookupService, LookupTypeService], templateUrl: 'app/Components/Masters/CompanyRelated/Lookup.component.html' }) export class LookupComponent { @ViewChild('modal') modal: ModalComponent; lookups: ILookup[]; lookup: ILookup; msg: string; indLoading: boolean = false; LookupFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; LookupFilter: string; isDesc: boolean = false; column: any = 'Name'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchName: string; strSearchType: string; strSearchValue: string; strSearchFullName: string; strSearchColorCode: string; LookupTyeList: ILookupType[]; constructor(private fb: FormBuilder, private _LookupService: LookupService, private pagerService: PagerService, private _LookupTypeService: LookupTypeService, private _CommonHelperService: CommonHelperService) { } //private lt: LookupTypeComponent = new LookupTypeComponent(this.fb, this._LookupTypeService, this.pagerService); Resetmodel() { this.lookup = { ColorCode: '', Country: '', CreatedBy: '', CreatedOn: '', FullName: '', Id: 0, IsActive: '', Name: '', Type: '0', UpdatedBy: '', UpdatedOn: null, Value: '', CompanyId: 0, EntityMessage: '' } } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.LookupFrm = this.fb.group ({ CompanyId: [''], Id: [''], Name: ['',Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], Type: ['',Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], Value: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], FullName: ['',Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], ColorCode: [''], Country:[''], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], EntityMessage: [''], }); this.LoadLookup(); this.LoadLookupType(); debugger; } LookupFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.LookupFilter = value; } LookupSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadLookup(): void { this.indLoading = true; this._LookupService.get(Global.BASE_LOOKUP_ENDPOINT) .subscribe(lookups => { this.lookups = lookups; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchName = (<HTMLInputElement>document.getElementById("searchName")).value; if (this.strSearchName != '') { this.strSearchName = this.strSearchName.toLocaleLowerCase(); this.lookups = this.lookups.filter ( x => x.Name != null && x.Name.toLocaleLowerCase().indexOf(this.strSearchName) != -1); } this.strSearchType = (<HTMLInputElement>document.getElementById("searchType")).value; if (this.strSearchType != '') { this.strSearchType = this.strSearchType.toLocaleLowerCase(); this.lookups = this.lookups.filter ( x => x.Type != null && x.Type.toLocaleLowerCase().indexOf(this.strSearchType) != -1); } //this.strSearchValue = (<HTMLInputElement>document.getElementById("searchValue")).value; //if (this.strSearchValue != '') //{ // this.strSearchValue = this.strSearchValue.toLocaleLowerCase(); // this.lookups = this.lookups.filter // ( // x => x.Value != null && x.Value.indexOf(this.strSearchValue) != -1); //} this.strSearchFullName = (<HTMLInputElement>document.getElementById("searchFullName")).value; if (this.strSearchFullName != '') { this.strSearchFullName = this.strSearchFullName.toLocaleLowerCase(); this.lookups = this.lookups.filter ( x => x.FullName != null && x.FullName.toLocaleLowerCase().indexOf(this.strSearchFullName) != -1); } this.strSearchColorCode = (<HTMLInputElement>document.getElementById("searchColorCode")).value; if (this.strSearchColorCode != '') { this.strSearchColorCode = this.strSearchColorCode.toLocaleLowerCase(); this.lookups = this.lookups.filter ( x => x.ColorCode != null && x.ColorCode.toLocaleLowerCase().indexOf(this.strSearchColorCode) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } LoadLookupType(): ILookupType[] { this.indLoading = true; this._LookupTypeService.get(Global.BASE_LOOKUPTYPE_ENDPOINT) .subscribe(lookuptype => { this.LookupTyeList = lookuptype; } ); return this.LookupTyeList; } AddLookup() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Lookup"; this.modalBtnTitle = "Add"; this.Resetmodel(); this.LookupFrm.setValue(this.lookup); $("#ColorCode").css("background-color", ""); this.modal.open(); } EditLookup(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Lookup"; this.modalBtnTitle = "Update"; this.lookup = this.lookups.filter(x => x.Id == id)[0]; this.LookupFrm.setValue(this.lookup); $("#ColorCode").css("background-color", this.lookup.ColorCode); this.modal.open(); } DeleteLookup(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.lookup = this.lookups.filter(x => x.Id == id)[0]; this.LookupFrm.setValue(this.lookup); $("#ColorCode").css("background-color", this.lookup.ColorCode); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.LookupFrm.enable() : this.LookupFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.lookups); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { formData.value.ColorCode = ($("#ColorCode").val()); this.msg = ""; debugger; switch (this.dbops) { case DBOperation.create: this._LookupService.post(Global.BASE_LOOKUP_ENDPOINT, formData.value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLookup(); this.modal.dismiss(); $("#ColorCode").val(null); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._LookupService.put(Global.BASE_LOOKUP_ENDPOINT, formData.value.Id, formData.value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadLookup(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._LookupService.delete(Global.BASE_LOOKUP_ENDPOINT, formData.value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Lookup status changed successfully."; this.LoadLookup(); } else { this.msg = "Error has occurred while changing status of existing Lookup!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } } <file_sep>export interface ILeaveType { Id: number; LeaveTypeName: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string; IsActive: boolean; }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var OutReport_service_1 = require("../../../Service/Report/Attendance/OutReport.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); ; ; var exportexcel_service_1 = require("../../../Shared/exportexcel.service"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var OutReportComponent = (function () { function OutReportComponent(fb, _OutReportService, _ExcelService, pagerService, _CommonHelperService) { this.fb = fb; this._OutReportService = _OutReportService; this._ExcelService = _ExcelService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.isDesc = false; this.column = 'EventName'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; } // Load Event Function OutReportComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.AttendanceDepart = [({ Id: 0, Department_Name: '', mode: '' })]; this.AttendanceEmployee = [({ Id: 0, Employee_Name: '', mode: '' })]; this.AttendanceCompany = [({ Id: 0, CompanyName: '', mode: '' })]; this.AttendanceLineManager = [({ Id: 0, LineManager: '', mode: '' })]; this.AttendancebindData = [({ EmployeeID: 0, EmployeeName: '', Date: '', ToDate: '', InTimeID: 0, InTIme: null, OutTimeID: 0, OutTIme: null, LunchOutTimeID: 0, LunchOutTIme: null, LunchInTimeID: 0, LunchInTIme: null, OtherTimeID: 0, TotalOtherTime: '', TotalOfficeTime: '', TotalLunchTime: '', TotalBreakTime: '', TotalWorkingTime: '', TotalWorksheetHours: 0, IsInOffice: false, IsInBreak: false, IsInLunch: false, IsInMeeting: false, IsInOfficeWork: false, Days: '', ImportRemarks: '', EmployeeCode: '', MMDDYYYY_DateFormat: '' })]; this.outreport = { EmployeeId: 0, Active: 0, AllDate: false, Consolidated: '', Employeelist: '', FromDate: new Date(), Minute: 0, OutType: '', Sort: '', ToDate: new Date() }; this.GetEmployee(); this.GetDepartment(); this.GetCompany(); this.GetLineManager(); }; // Hide & Show Element jQuery Function OutReportComponent.prototype.ToogleMyProfile = function () { $("#alltypeoutreportdata").slideToggle(300); }; OutReportComponent.prototype.CloseWidgetProfile = function () { $("#alltypeoutreport").hide(300); }; OutReportComponent.prototype.ViewStyleToogle = function () { if ($("#rbtconsolidated").prop('checked')) { $("#viewstyle").show(); } else { $("#viewstyle").hide(); } }; OutReportComponent.prototype.ToogleHideShowOption = function () { if ($("#rbtdepartment").prop('checked')) { $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); $("#ddldepartment").show(); } else if ($("#rbtcompany").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").show(); $("#ddllinemanager").hide(); } else if ($("#rbtlinemanager").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").show(); } else { $("#ddldepartment").hide(); $("#ddlemployee").show(); $("#chkallemployeediv").show(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); } }; OutReportComponent.prototype.ToogleAllDate = function () { if ($("#alldate").prop('checked')) { $("#fromdate").attr("disabled", "disabled"); $("#todate").attr("disabled", "disabled"); } else { $("#fromdate").removeAttr("disabled"); $("#todate").removeAttr("disabled"); } }; OutReportComponent.prototype.ToogleAllTypesofOut = function () { if ($("#rbtall").prop('checked')) { $("#chkall").attr("disabled", "disabled"); $("#chklunch").attr("disabled", "disabled"); $("#chkother").attr("disabled", "disabled"); $("#chkmeeting").attr("disabled", "disabled"); $("#chkofficeout").attr("disabled", "disabled"); $("#chkall").attr("checked", "checked"); $("#chklunch").prop("checked", false); $("#chkother").prop("checked", false); $("#chkmeeting").prop("checked", false); $("#chkofficeout").prop("checked", false); } else { $("#chkall").attr("disabled", "disabled"); $("#chkall").removeAttr("checked"); $("#chklunch").removeAttr("disabled"); $("#chkother").removeAttr("disabled"); $("#chkmeeting").removeAttr("disabled"); $("#chkofficeout").removeAttr("disabled"); } }; OutReportComponent.prototype.ToogleMinute = function () { if ($("#toogleminute").prop('checked')) { $("#txtminute").removeAttr("disabled"); } else { $("#txtminute").attr("disabled", "disabled"); } }; // Dropdown bind Function OutReportComponent.prototype.GetEmployee = function () { var _this = this; this._OutReportService.getemployee(global_1.Global.BASE_OutReportApi_ENDPOINT). subscribe(function (employee) { _this.AttendanceEmployee = employee; }); }; OutReportComponent.prototype.GetAllEmployee = function () { var _this = this; if ($("#chkallemployee").prop("checked")) { this._OutReportService.getallemployee(global_1.Global.BASE_OutReportApi_ENDPOINT). subscribe(function (allemployee) { _this.AttendanceEmployee = allemployee; }); } else { this.GetEmployee(); } }; OutReportComponent.prototype.GetDepartment = function () { var _this = this; this._OutReportService.getdepartment(global_1.Global.BASE_OutReportApi_ENDPOINT). subscribe(function (department) { _this.AttendanceDeparts = department; }); }; OutReportComponent.prototype.GetCompany = function () { var _this = this; this._OutReportService.getcompany(global_1.Global.BASE_OutReportApi_ENDPOINT). subscribe(function (companydata) { _this.AttendanceCompany = companydata; }); }; OutReportComponent.prototype.GetLineManager = function () { var _this = this; this._OutReportService.getlinemanager(global_1.Global.BASE_OutReportApi_ENDPOINT). subscribe(function (linemanagaer) { _this.AttendanceLineManager = linemanagaer; }); }; OutReportComponent.prototype.GetEmployeeIdByLM = function (LineManager) { var _this = this; if ($("#ddllinemanager").val() != '0') { this._OutReportService.getemployeeidbylm(global_1.Global.BASE_OutReportApi_ENDPOINT, LineManager). subscribe(function (emplist) { _this.EmployeeIdByLM = emplist; }); } }; OutReportComponent.prototype.GetEmployeeIdByCompany = function (Company) { var _this = this; if ($("#ddlcompany").val() != '0') { this._OutReportService.getemployeeidbycompany(global_1.Global.BASE_OutReportApi_ENDPOINT, Company). subscribe(function (emplist) { _this.EmployeeIdByLM = emplist; }); } }; OutReportComponent.prototype.GetEmployeeIdByDepartment = function (ParentId) { var _this = this; if ($("#ddldepartment").val() != '0') { this._OutReportService.getemployeeidbydepartment(global_1.Global.BASE_OutReportApi_ENDPOINT, ParentId). subscribe(function (emplist) { _this.EmployeeIdByLM = emplist; }); } }; // Post Report By Selected Category OutReportComponent.prototype.onSubmit = function (entityobject) { var _this = this; $("html, body").animate({ scrollTop: 590 }, 250); entityobject.Employeelist = ''; if ($("#rbtlinemanager").prop("checked") && $("#ddllinemanager").val() != '0' && $("#ddllinemanager").val() != '' && $("#ddllinemanager").val() != undefined) { for (var _i = 0, _a = this.EmployeeIdByLM; _i < _a.length; _i++) { var item = _a[_i]; entityobject.Employeelist += item.Id + ','; } } else if ($("#rbtcompany").prop("checked") && $("#ddlcompany").val() != '0' && $("#ddlcompany").val() != '' && $("#ddlcompany").val() != undefined) { for (var _b = 0, _c = this.EmployeeIdByLM; _b < _c.length; _b++) { var item = _c[_b]; entityobject.Employeelist += item.Id + ','; } } else if ($("#rbtdepartment").prop("checked") && $("#ddldepartment").val() != '0' && $("#ddldepartment").val() != '' && $("#ddldepartment").val() != undefined) { for (var _d = 0, _e = this.EmployeeIdByLM; _d < _e.length; _d++) { var item = _e[_d]; entityobject.Employeelist += item.Id + ','; } } else if ($("#ddlemployee").val() == '0' || $("#ddldepartment").val() == '0' || $("#ddlcompany").val() == '0' || $("#ddllinemanager").val() == '0') { entityobject.EmployeeId = 0; } else { entityobject.Employeelist = entityobject.EmployeeId.toString(); } if ($("#toogleminute").prop("checked")) { entityobject.Minute = $("#txtminute").val(); } else { entityobject.Minute = 0; } if ($("#chkallemployee").prop("checked")) { entityobject.Active = 1; } else { entityobject.Active = 0; } if ($("#alldate").prop("checked")) { entityobject.AllDate = true; } if ($("#rbtall").prop("checked")) { entityobject.OutType = 'All'; } else if ($("#rbtother").prop("checked")) { if ($("#chklunch").prop("checked") && $("#chkother").prop("checked") && $("#chkmeeting").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Other Breaks' + ',' + 'Meeting' + ',' + 'office Out'; } else if ($("#chklunch").prop("checked") && $("#chkother").prop("checked") && $("#chkmeeting").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Other Breaks' + ',' + 'Meeting'; } else if ($("#chkother").prop("checked") && $("#chkmeeting").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Other Breaks' + ',' + 'Meeting' + ',' + 'office Out'; } else if ($("#chklunch").prop("checked") && $("#chkother").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Other Breaks'; } else if ($("#chklunch").prop("checked") && $("#chkmeeting").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'Meeting'; } else if ($("#chklunch").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Lunch' + ',' + 'office Out'; } else if ($("#chkother").prop("checked") && $("#chkmeeting").prop("checked")) { entityobject.OutType = 'Other Breaks' + ',' + 'Meeting'; } else if ($("#chkother").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Other Breaks' + ',' + 'office Out'; } else if ($("#chkmeeting").prop("checked") && $("#chkofficeout").prop("checked")) { entityobject.OutType = 'Meeting' + ',' + 'office Out'; } else if ($("#chklunch").prop("checked")) { entityobject.OutType = 'Lunch'; } else if ($("#chkother").prop("checked")) { entityobject.OutType = 'Other Breaks'; } else if ($("#chkmeeting").prop("checked")) { entityobject.OutType = 'Meeting'; } else if ($("#chkofficeout").prop("checked")) { entityobject.OutType = 'office Out'; } } if (($("#toogleminute").prop("checked"))) { entityobject.Minute = ($("#txtminute").val()); entityobject.Consolidated = 'Date'; entityobject.Sort = 'Name'; } else { entityobject.Minute = 0; } if ($("#alldate").prop("checked")) { entityobject.AllDate = true; } else { entityobject.AllDate = false; } if ($("#rbtdetailed").prop("checked")) { entityobject.Consolidated = 'All'; } if ($("#rbtconsolidated").prop("checked")) { if ($("#rbtnone").prop("checked")) { entityobject.Consolidated = 'None'; } else if ($("#rbtname").prop("checked")) { entityobject.Consolidated = 'Name'; } else if ($("#rbttype").prop("checked")) { entityobject.Consolidated = 'Type'; } else { entityobject.Consolidated = 'Date'; } } if ($("#rbtsortname").prop("checked")) { entityobject.Sort = 'Name'; } else if ($("#rbtsortdate").prop("checked")) { entityobject.Sort = 'Date'; } else if ($("#rbtsorttype").prop("checked")) { entityobject.Sort = 'Type'; } else { entityobject.Sort = 'Duration'; } if ($("#toogleminute").prop("checked")) { entityobject.Consolidated = 'Date'; } this.InLoading = true; this._OutReportService.getoutreportdata(global_1.Global.BASE_OutReportApi_ENDPOINT, entityobject). subscribe(function (reportdata) { _this.outreports = reportdata; _this.JumpOnPage(1); $("html, body").animate({ scrollTop: 590 }, 250); _this.InLoading = false; }); if (entityobject.Consolidated == 'None' || entityobject.Consolidated == 'Name' || entityobject.Consolidated == 'Type' || entityobject.Consolidated == 'Date') { $("#headerstarttime").hide(); $("#headerendtime").hide(); $("#headerremarks").hide(); $("#col2starttime").hide(); $("#col2endtime").hide(); $("#col2remarks").hide(); } else { $("#headerstarttime").show(); $("#headerendtime").show(); $("#headerremarks").show(); $("#col2starttime").show(); $("#col2endtime").show(); $("#col2remarks").show(); } }; // pagination Function OutReportComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.outreports); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; this.pagedItemscount = this.pagerService.pagedItems; var total = 0; for (var _i = 0, _a = this.pagedItemscount; _i < _a.length; _i++) { var item = _a[_i]; total += item.Duration; this.cnttotal = total; } }; OutReportComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; OutReportComponent.prototype.ExportToExcel = function () { if (this.outreports != null && this.outreports.length > 0) { this._ExcelService.exportAsExcelFile(this.outreports, 'OutReport'); } else { alert("No Record Found !"); } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], OutReportComponent.prototype, "modal", void 0); OutReportComponent = __decorate([ core_1.Component({ providers: [OutReport_service_1.OutReportService], templateUrl: 'app/Components/Report/Attendance/OutReport.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, OutReport_service_1.OutReportService, exportexcel_service_1.ExcelService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], OutReportComponent); return OutReportComponent; }()); exports.OutReportComponent = OutReportComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.MyProfiles { public class MyProfiles : VISBaseEntity { public string Mode { get; set; } public Int64 UserId { get; set; } public string Employee_Name { get; set; } public string LineManagerName { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string Gender { get; set; } public string PhotographFileName { get; set; } public string CompanyName { get; set; } public string Email { get; set; } public string Designation { get; set; } public string DepartmentName { get; set; } public string FatherName { get; set; } public string MotherName { get; set; } public string PermenantAddress { get; set; } public string CommunicationAddress { get; set; } public string LandlineNumber { get; set; } public string MobileNumber { get; set; } public string BirthDate { get; set; } public string BloodGroup { get; set; } public string MaritalStatus { get; set; } public string EmplopyeeGrade { get; set; } ///<summary> ///Education Data /// </summary> public bool HighestEducation { get; set; } public string ClassDegree { get; set; } public string SchoolInstitute { get; set; } public string Medium { get; set; } public Int64 PassingYear { get; set; } public string BoardUniversity { get; set; } public string Percentage { get; set; } } public static class MyProfilesConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_EmployeeMaster = "Employee_Master"; /// <summary> /// Database table field Name Constants. /// </summary> /// public const string const_Field_Mode = "Mode"; public const string const_Field_UserId = "UserId"; public const string const_Field_Employee_Name = "Employee_Name"; public const string const_Field_LineManagerName = "LineManagerName"; public const string const_Field_FirstName = "FirstName"; public const string const_Field_MiddleName = "MiddleName"; public const string const_Field_LastName = " LastName"; public const string const_Field_Gender = " Gender"; public const string const_Field_PhotographFileName = "PhotographFileName "; public const string const_Field_CompanyName = "CompanyName "; public const string const_Field_Email = " Email"; public const string cons_Filed_Designation = " Designation"; public const string cons_Filed_DepartmentNam = " DepartmentName"; public const string cons_Filed_FatherName = " FatherName"; public const string cons_Filed_MotherName = " MotherName"; public const string cons_Filed_PermenantAddress = " PermenantAddress"; public const string cons_Filed_CommunicationAddress = "CommunicationAddress"; public const string cons_Filed_MobileNumber = " MobileNumber"; public const string cons_Filed_LandlineNumber = " LandlineNumber"; public const string cons_Filed_BirthDate = "BirthDate "; public const string cons_Filed_BloodGroup = " BloodGroup"; public const string cons_Filed_MaritalStatus = "MaritalStatus "; public const string cons_Filed_EmplopyeeGrade = "EmplopyeeGrade"; ///<summary> ///EducationFiles /// </summary> public const string cons_Filed_HighestEducation = "HighestEducation"; public const string cons_Filed_ClassDegree = "ClassDegree"; public const string cons_Filed_SchoolInstitute = "SchoolInstitute"; public const string cons_Filed_Medium = "Medium"; public const string cons_Filed_PassingYear = "PassingYear"; public const string cons_Filed_BoardUniversity = "BoardUniversity"; public const string cons_Filed_Percentage = "Percentage"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_procGetUserProfile = "procGetUserProfile"; public const string const_procGetEmployeeList = "procGetEmployeeList"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class BankMaster : VISBaseEntity { /// <summary> /// BankMaster Entity Fields. /// </summary> /// public string BankAlias { get; set; } public string BankName { get; set; } public string BranchName { get; set; } public string BankAddress { get; set; } public string BankDetail { get; set; } public string AccountNumber { get; set; } public int CurrencyId { get; set; } public bool Status { get; set; } } public static class BankMasterConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_BankMaster_Table = "BankMaster"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_BankAlias = "BankAlias"; public const string const_BankName = "BankName"; public const string const_BranchName = "BranchName"; public const string const_BankAddress = "BankAddress"; public const string const_BankDetail = "BankDetail"; public const string const_AccountNumber = "AccountNumber"; public const string const_CurrencyId = "CurrencyId"; public const string const_Status = "Status"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procBankMaster_Add = "procBankMaster_Add"; public const string const_procBankMaster_Update = "procBankMaster_Update"; public const string const_procBankMaster_ActiveInActive = "procBankMaster_ActiveInActive"; public const string const_procBankMaster_SelectAll = "procBankMaster_SelectAll"; public const string const_procBankMaster_SelectById = "procBankMaster_SelectById"; public const string const_procGetCompanyMaster = "procGetCompanyMaster"; public const string const_procGetCurrency = "procGetCurrency"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using VIS_Domain.Opinion; using System.Data.SqlClient; namespace VIS_Repository.Opinion { public class ConfigureServeyRepository : VISDbCommand { public ConfigureServeyRepository(string _connectionstring) : base(_connectionstring) { } public bool GetRollOfEmployee(int EmployeeId, string RoleType) { DataTable dt = new DataTable(); try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ConfigureSurveyConstant.Const_Proc_CheckUserRolesById; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_EmployeeID, EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_RoleName, RoleType); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); da.Fill(dt); } catch (Exception ex) { } if (Convert.ToInt32(dt.Rows[0][0]) == 1) { return true; } else { return false; } } public DataTable GetSurveyDetails(string SearchField, string searchValue, int EmployeeId, string RoleType, string ServeyType, string Approvetype) { DataTable dt = new DataTable(); try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = ConfigureSurveyConstant.const_ProcSurvey_GetAllSurvey_SelectAll; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_EmployeeID, EmployeeId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_SearchField, SearchField); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_SearchValue, searchValue); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_RoleType, RoleType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_SurveyType, ServeyType); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_ApproveType, Approvetype); objVISDbCommand.objSqlCommand.Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); da.Fill(dt); } catch (Exception ex) { } return dt; } public IEnumerable<SurveyType> BindSurveyType() { List<SurveyType> objListToReturn = new List<SurveyType>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureSurveyConstant.const_ProcEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_Mode, "SurveyType"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<SurveyType>(dt); } return objListToReturn; } public IEnumerable<GetUserListForOwnerSelection> BindUsersForOwnerSelection() { List<GetUserListForOwnerSelection> objListToReturn = new List<GetUserListForOwnerSelection>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ConfigureSurveyConstant.const_ProcEmployeeDropDown; base.objSqlCommand.Parameters.AddWithValue(ConfigureSurveyConstant.const_Field_Mode, "GetUsersForOwnerSelection"); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<GetUserListForOwnerSelection>(dt); } return objListToReturn; } } } <file_sep>export class LoginData { public VISUsername: string; public VISPassword: string; public UserFullName: string; public LastName: string; public Id: number; public Email: string; public UserType: string; public UserRoleTypeName: string; public ArrayUserType: string[]; public IsAdmin: boolean; public IsLineManager: boolean; public ArrayDepartmentId: number[]; public DepartmentId: string; public IsOnStypend: boolean; public IsFormerEmployee: boolean; public IsWebAccess: boolean; public validForLogin: boolean; public WebAccessURL: string; }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IMacIdConfiguration } from '../../../Model/Masters/Configuration/MacIdConfiguration'; @Pipe ({ name: 'macidconfigurationFilter' }) export class MacIdConfigurationFilterPipe implements PipeTransform { transform(value: IMacIdConfiguration[], filter: string): IMacIdConfiguration[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IMacIdConfiguration) => app.MacID != null && app.MacID.toLocaleLowerCase().indexOf(filter) != -1 || app.IPAddress != null && app.IPAddress.toLocaleLowerCase().indexOf(filter) != -1 || app.Version != null && app.Version.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>/** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { System.config({ paths: { // paths serve as alias 'npm:': 'node_modules/', 'underscore': 'node_modules/underscore/underscore.js' }, //map tells the System loader where to look for things map: { // our app is within the app folder app: 'app', // 'dist', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js', // other libraries 'rxjs': 'npm:rxjs', 'typescript': 'npm:[email protected]/lib/typescript.js', 'underscore': 'npm:underscore', 'ng2-bs3-modal': 'npm:/ng2-bs3-modal', 'ng2-file-upload': 'npm:ng2-file-upload', 'ng2-formly': 'npm:ng2-formly/bundles/ng2-formly.umd.js', "ng2-ckeditor": 'npm:ng2-ckeditor', 'angular2-color-picker': 'node_modules/angular2-color-picker', 'ng2-tab': 'node_modules/ng2-tab/dist', 'angular-2-dropdown-multiselect': 'node_modules/angular-2-dropdown-multiselect', 'ng2-datepicker': 'node_modules/ng2-datepicker', 'file-saver': 'node_modules/file-saver', 'xlsx': 'node_modules/xlsx', 'xlsx-style': 'node_modules/xlsx-style', 'ng2-tree': 'node_modules/ng2-tree' }, // packages tells the System loader how to load when no filename and/or no extension packages: { app: { main: 'main.js', defaultExtension: 'js' }, rxjs: { defaultExtension: 'js' }, 'ng2-bs3-modal': { main: '/bundles/ng2-bs3-modal.js', defaultExtension: 'js' }, 'ng2-file-upload': { main: 'index.js', defaultExtension: 'js' }, 'ng2-ckeditor': { main: 'lib/index.js', defaultExtension: 'js' }, 'underscore': { main: 'underscore.js', defaultExtension: 'js' }, 'angular2-color-picker': { main: 'index.js', defaultExtension: 'js' }, 'ng2-tab': { main: 'ng2-tab.umd.js', defaultExtension: 'js' }, 'angular-2-dropdown-multiselect': { main: 'bundles/dropdown.umd', defaultExtension: 'js' }, 'ng2-datepicker': { main: 'bundles/ng2-datepicker.umd', defaultExtension: 'js' }, 'file-saver': { format: 'global', main: 'FileSaver.js', defaultExtension: 'js' }, 'xlsx': { format: 'global', main: 'xlsx.js', defaultExtension: 'js' }, 'xlsx-style': { format: 'global', main: 'xlsx.js', defaultExtension: 'js' }, 'ng2-tree': { main: '/bundles/ng2-tree.umd.min', defaultExtension: 'js' } } }); })(this);<file_sep>export interface IEmployee { Id: number; Employee_Name: string; } export interface IYear { CurrentYear: string; } export interface IEmployeeAccessCardComparision { EmployeeCode: string; Employee_Name: string; Date: Date; LineManager: string; Grace: number; Grade: string; Status: string; PunchInVIS: Date; PunchInAC: Date; MAC: string; IP: string; TimeofFirstScreenShot: string; TimeofLastScreenShot: string; PunchInIssue: string; PunchOutIssue: string; } export interface IParameterModel { EmployeeId: number; FromDate: string; ToDate: string; IssueOnly: string; Search: string; OrderBy: string; LoginUserId: number; FromMonth: string; FromYear: string; ToMonth: string; ToYear: string; MonthWise: boolean; } <file_sep>export interface ILevels { levelnumber: number; Name: String; Icon: String; startpoint: number; endpoint: number; }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.VacancyRelated; using VIS_Repository; using VIS_Repository.Masters.VacancyRelated; namespace VIS_App.Controllers.Masters.VacancyRelated { public class PositionAPIController : BaseAPIController { PositionRepository objPositionRepository = null; public PositionAPIController() { objPositionRepository = new PositionRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/PositionAPI/Get")] public HttpResponseMessage Get() { return ToJson(objPositionRepository.GetEntityList()); } [Route("api/PositionAPI/Post")] public HttpResponseMessage Post([FromBody]Position value) { return ToJson(objPositionRepository.AddEntity(value)); } [Route("api/PositionAPI/UpdateEntity")] [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]Position value) { return ToJson(objPositionRepository.UpdateEntity(value)); } [Route("api/PositionAPI/DeleteEntity")] [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(objPositionRepository.DeleteEntity(Id)); } [Route("api/PositionAPI/GetSkills")] public HttpResponseMessage GetSkills() { return ToJson(objPositionRepository.GetSkills()); } } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Router } from '@angular/router'; import { Global } from '../../../Shared/global'; @Injectable() export class ChangePSWService { constructor(private _http: Http, private router: Router) { } get(url: string): Observable<any> { return this._http.get(url) .map((response: Response) => <any>response.json()); } public ChangePassword(url:string,Id: number, model:any): Observable<any> { //let urltohit = Global.BASE_ChhangePassword_ENDPOINT + 'GetChangePassword?Id=' + 3; let urltohit = Global.BASE_ChhangePassword_ENDPOINT + 'GetChangePassword?Id='; let body = JSON.stringify(model); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this._http.post(urltohit + Id, body, options) .map((response: Response) => <any>response.json()) } }<file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var FinancialYear_service_1 = require("../../../service/Masters/CompanyRelated/FinancialYear.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); //import * as _ from 'underscore'; var pager_index_1 = require("../../../Shared/pager.index"); var FinancialYearComponent = (function () { function FinancialYearComponent(fb, _FinancialYearService, pagerService) { this.fb = fb; this._FinancialYearService = _FinancialYearService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'Full_Name'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; this.ArrayYear = new Array(); } FinancialYearComponent.prototype.ngOnInit = function () { this.FinancialYear = ({ Id: 0, FromMonth: '', ToMonth: '', CurrentYear: '', Nextyear: '', FinancialYear: '', CreatedOn: null, CreatedBy: 0, UpdatedOn: null, UpdatedBy: 0, IsActive: false, EntityMessage: '' }); this.LoadFinancialYearsCM(); this.LoadFinancialYears(); }; FinancialYearComponent.prototype.LoadFinancialYearsCM = function () { }; FinancialYearComponent.prototype.GetNextYear = function () { this.ArrayYear = []; var displayDate = (new Date()).getFullYear(); var EndDate = displayDate + 1; var j = 10; for (var i = 0; i < j; i++) { this.ArrayYear.push(EndDate); EndDate = EndDate - 1; } }; FinancialYearComponent.prototype.FinancialYearFilterCriteriaChange = function (value) { if (value != '[object Event]') this.FinancialYearFilter = value; }; FinancialYearComponent.prototype.FinancialYearSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; FinancialYearComponent.prototype.ResetInputControls = function () { this.FinancialYear.FinancialYear = null; this.FinancialYear.FromMonth = null; this.FinancialYear.Nextyear = null; this.FinancialYear.ToMonth = null; }; FinancialYearComponent.prototype.LoadFinancialYears = function () { var _this = this; this.indLoading = true; this._FinancialYearService.get(global_1.Global.BASE_FINANCIALYEAR_ENDPOINT) .subscribe(function (FinancialYears) { _this.FinancialYears = FinancialYears; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchFromMonth = document.getElementById("searchFromMonth").value; if (_this.strSearchFromMonth != '') { _this.strSearchFromMonth = _this.strSearchFromMonth.toLocaleLowerCase(); _this.FinancialYears = _this.FinancialYears.filter(function (x) { return x.FromMonth != null && x.FromMonth.toLocaleLowerCase().indexOf(_this.strSearchFromMonth) != -1; }); } _this.strSearchToMonth = document.getElementById("searchToMonth").value; if (_this.strSearchToMonth != '') { _this.strSearchToMonth = _this.strSearchToMonth.toLocaleLowerCase(); _this.FinancialYears = _this.FinancialYears.filter(function (x) { return x.ToMonth != null && x.ToMonth.toLocaleLowerCase().indexOf(_this.strSearchToMonth) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; FinancialYearComponent.prototype.addFinancialYear = function () { // this.ResetInputControls(); $(function () { var year = $("#lblYear").val((new Date()).getFullYear()); }); this.GetNextYear(); this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Financial Year"; this.modalBtnTitle = "Add"; //this.FinancialYearFrm.reset(); this.modal.open(); }; FinancialYearComponent.prototype.editFinancialYear = function (id) { this.GetNextYear(); this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Financial Year"; this.modalBtnTitle = "Update"; this.FinancialYear = this.FinancialYears.filter(function (x) { return x.Id == id; })[0]; //this.FinancialYearFrm.setValue(this.FinancialYear); this.modal.open(); }; FinancialYearComponent.prototype.deleteFinancialYear = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.FinancialYear = this.FinancialYears.filter(function (x) { return x.Id == id; })[0]; //this.FinancialYearFrm.setValue(this.FinancialYear); this.modal.open(); }; FinancialYearComponent.prototype.SetControlsState = function (isEnable) { // isEnable ? this.FinancialYearFrm.enable() : this.FinancialYearFrm.disable(); }; FinancialYearComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; FinancialYearComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.FinancialYears); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; FinancialYearComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; FinancialYearComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._FinancialYearService.post(global_1.Global.BASE_FINANCIALYEAR_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadFinancialYears(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._FinancialYearService.put(global_1.Global.BASE_FINANCIALYEAR_ENDPOINT, formData.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadFinancialYears(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._FinancialYearService.delete(global_1.Global.BASE_FINANCIALYEAR_ENDPOINT, formData.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "Financial Year status changed successfully."; _this.LoadFinancialYears(); } else { _this.msg = "Error has occurred while changing status of existing FinancialYear!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], FinancialYearComponent.prototype, "modal", void 0); FinancialYearComponent = __decorate([ core_1.Component({ providers: [FinancialYear_service_1.FinancialYearService], templateUrl: 'app/Components/Masters/CompanyRelated/FinancialYear.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, FinancialYear_service_1.FinancialYearService, pager_index_1.PagerService]) ], FinancialYearComponent); return FinancialYearComponent; }()); exports.FinancialYearComponent = FinancialYearComponent; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Master.CompanyRelated; using VIS_Repository; namespace VIS_App.Controllers.Masters.CompanyRelated { public class LeaveTypeAPIController : BaseAPIController { VISIBaseRepository<LeaveType> LeaveTypeRepository; List<LeaveType> EntityList = new List<LeaveType>(); public LeaveTypeAPIController(VISIBaseRepository<LeaveType> _LeaveTypeRepositiory) { LeaveTypeRepository = _LeaveTypeRepositiory; } public HttpResponseMessage Get() { return ToJson(LeaveTypeRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]LeaveType value) { return ToJson(LeaveTypeRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]LeaveType value) { return ToJson(LeaveTypeRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(LeaveTypeRepository.DeleteEntity(Id)); } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { Global } from '../../../../app/Shared/global'; import { PagerService } from '../../../../app/Shared/pager.service'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; import { SalaryGrievancePEService } from '../../../Service/HumanResource/Grievance/SalaryGrievancePE.service'; @Component({ providers: [SalaryGrievancePEService], templateUrl: 'app/Components/HumanResource/Grievance/SalaryGrievancePE.component.html' }) export class SalaryGrievancePEComponent implements OnInit { constructor(private fb: FormBuilder, private _SalaryGrievancePEService: SalaryGrievancePEService, public http: Http, private router: Router, private pagerService: PagerService) { } ngOnInit(): void { } } <file_sep>export interface ICommonConfiguration { Id: number; URLLocal: string; URLLive: string; MinimumLunchBreak: number; MinimumOtherBreak: number; MouseMinutes: number; PlusMouseMinutes: number; MouseTracking: number; ProductivityTracker: number; WorksheetPrompt: number; MinimumPunchoutInterval: number; InTimeMondayToFridayHH: number; InTimeMondayToFridayMM: number; OutTimeMondayToFridayHH: number; OutTimeMondayToFridayMM: number; InTimeSaturdayHH: number; InTimeSaturdayMM: number; OutTimeSaturdayHH: number; OutTimeSaturdayMM: number; ShiftDurationHH: number; ShiftDurationMM: number; TDSMenuHideOrShow:string; RoleMenu: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.Configuration { public class MacIdConfiguration : VISBaseEntity { /// <summary> /// MacIdConfiguration Entity Fields. /// </summary> /// public int EmployeeId { get; set; } public string Employee_Name { get; set; } public string MacID { get; set; } public string IPAddress { get; set; } public DateTime RequestedDate { get; set; } public DateTime ApprovalDate { get; set; } public string ApprovedBy { get; set; } public string Version { get; set; } public bool Active { get; set; } public bool OfficeMacId { get; set; } public string Description { get; set; } } public static class MacIdConfigurationConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_Employee_MACRegister_Table = "Employee_MACRegister"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_EmployeeId = "EmployeeId"; public const string const_Employee_Name = "Employee_Name"; public const string const_MacID = "MacID"; public const string const_IPAddress = "IPAddress"; public const string const_RequestedDate = "RequestedDate"; public const string const_ApprovalDate = "ApprovalDate"; public const string const_ApprovedBy = "ApprovedBy"; public const string const_Version = "Version"; public const string const_Active = "Active"; public const string const_OfficeMacId = "OfficeMacId"; public const string const_Description = "Description"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procEmployee_MacRegisteration_Add = "procEmployee_MacRegisteration_Add"; public const string const_procEmployee_MacRegisteration_Update = "procEmployee_MacRegisteration_Update"; public const string const_procEmployee_MacRegisteration_ActiveInActive = "procEmployee_MacRegisteration_ActiveInActive"; public const string const_procEmployee_MACRegister_SelectAll = "procEmployee_MacRegisteration_SelectAll"; public const string const_procEmployee_MACRegister_SelectById = "procEmployee_MacRegisteration_SelectById"; public const string const_procEmployee_Master_SelectAll = "procEmployee_Master_SelectAll"; public const string const_procEmployee_MacRegisteration_ActivateDeactivate = "procEmployee_MacRegisteration_ActivateDeactivate"; } } <file_sep> import { Component, OnInit, ViewChild } from '@angular/core'; import { Levels_AchievementService } from '../../../service/Masters/EmployeeLevels/Levels_Achievement.service'; import { LevelCriteriaSetupService } from '../../../service/Masters/EmployeeLevels/LevelCriteriaSetup.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ILevels_Achievement, IForIsCriteria } from '../../../Model/Masters/EmployeeLevels/Levels_Achievement'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { ILevelCriteriaSetup } from '../../../Model/Masters/EmployeeLevels/LevelCriteriaSetup'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; @Component({ providers: [Levels_AchievementService, LevelCriteriaSetupService], templateUrl: 'app/Components/Masters/EmployeeLevels/Levels_Achievement.component.html' }) export class Levels_AchievementComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; Levels_Achievements: ILevels_Achievement[]; Levels_AchievementsForImage: ILevels_Achievement; Levels_AchievementEdit: ILevels_Achievement; Levels_Achievement: ILevels_Achievement; LevelCriteriaSetupForDll: ILevelCriteriaSetup[]; IsCriteriaList: IForIsCriteria[]; ForSetupId: ILevels_Achievement; SetupId: number; msg: string; indLoading: boolean = false; Levels_AchievementFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; Levels_AchievementFilter: string; isDesc: boolean = false; column: any = 'LevelName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchAchievementName: string; strSearchCriteriaName: string; strSearchCalculatedIn: string; strSearchSelectActive: string; fileList1: FileList; imagePath: string; VisibleCriteria: boolean; ImgGlobalPath: string; ImageEdit: File; constructor(private fb: FormBuilder, private _Levels_AchievementService: Levels_AchievementService, private _LevelCriteriaSetupService: LevelCriteriaSetupService, private pagerService: PagerService, private http: Http) { } fileChange1(event) { this.fileList1 = event.target.files; } ngOnInit(): void { this.Levels_AchievementFrm = this.fb.group({ Id: [''], CompanyId: [''], Range:[''], CriteriaId:[''], CriteriaName: [''], CalculatedIn: [''], SelectActive:[''], AchievementName: [''], SetUpID: [''], IsCriteria: [''], AndAbove: [''], Description: [''], Help: [''], Calculated: [''], AchievedIn: [''], Points: [''], Image: [''], Active: [''], IsActive: [''], LevelSetupId: [''], CreatedBy: [''], CreatedOn: [''], UpdatedBy: [''], UpdatedOn: [''], EntityMessage:[''] }); this.LoadLevels_Achievements(); this.LoadCriteria() } Levels_AchievementSearchCriteriaChange(value: string): void { if (value != '[object Event]') this.Levels_AchievementFilter = value; } Levels_AchievementSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } LoadCriteria(): void { this.indLoading = true; this._LevelCriteriaSetupService.getCriteria(Global.BASE_LEVELCRITERIASETUP_ENDPOINT) .subscribe(DATA => { this.LevelCriteriaSetupForDll = DATA; } //,error => this.msg = <any>error ); } LoadLevels_Achievements(): void { this.VisibleCriteria = false; this.indLoading = true; this._Levels_AchievementService.get(Global.BASE_Levels_Achievement_ENDPOINT) .subscribe(Levels_Achievements => { debugger; this.Levels_Achievements = Levels_Achievements; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchAchievementName = (<HTMLInputElement>document.getElementById("searchAchievementName")).value; if (this.strSearchAchievementName != '') { this.strSearchAchievementName = this.strSearchAchievementName.toLocaleLowerCase(); this.Levels_Achievements = this.Levels_Achievements.filter( x => x.AchievementName != null && x.AchievementName.toLocaleLowerCase().indexOf(this.strSearchAchievementName) != -1); } this.strSearchCriteriaName = (<HTMLInputElement>document.getElementById("searchCriteriaName")).value; if (this.strSearchCriteriaName != '') { this.strSearchCriteriaName = this.strSearchCriteriaName.toLocaleLowerCase(); this.Levels_Achievements = this.Levels_Achievements.filter( x => x.CriteriaName != null && x.CriteriaName.toLocaleLowerCase().indexOf(this.strSearchCriteriaName) != -1); } this.strSearchCalculatedIn = (<HTMLInputElement>document.getElementById("searchCalculatedIn")).value; if (this.strSearchCalculatedIn != '') { this.strSearchCalculatedIn = this.strSearchCalculatedIn.toLocaleLowerCase(); this.Levels_Achievements = this.Levels_Achievements.filter( x => x.CalculatedIn != null && x.CalculatedIn.toLocaleLowerCase().indexOf(this.strSearchCalculatedIn) != -1); } this.strSearchSelectActive = (<HTMLInputElement>document.getElementById("searchActive")).value; if (this.strSearchSelectActive != '') { this.strSearchSelectActive = this.strSearchSelectActive.toLocaleLowerCase(); this.Levels_Achievements = this.Levels_Achievements.filter( x => x.SelectActive != null && x.SelectActive.toLocaleLowerCase().indexOf(this.strSearchSelectActive) != -1); } } this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } ChangeCriteria(value:number) { this.VisibleCriteria = false; this.indLoading = true; this._Levels_AchievementService.getIsCriteria(Global.BASE_Levels_Achievement_ENDPOINT, value) .subscribe(Data => { this.IsCriteriaList = Data; if (this.IsCriteriaList.length > 1) { this.VisibleCriteria = true; } else { this.VisibleCriteria = false; } } //,error => this.msg = <any>error ); } addLevels_Achievement() { this.imagePath = null; this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Achievement"; this.modalBtnTitle = "Add"; this.Levels_AchievementFrm.reset(); this.modal.open(); } editLevels_Achievement(id: number) { this.ImgGlobalPath = Global.WebAccessURL; this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Achievement"; this.modalBtnTitle = "Update"; this.Levels_Achievement = this.Levels_Achievements.filter(x => x.Id == id)[0]; this._Levels_AchievementService.GetDataOnEdit(Global.BASE_Levels_Achievement_ENDPOINT, this.Levels_Achievement.Id) .subscribe(Levels_Achieve => { this.Levels_AchievementEdit = Levels_Achieve[0]; this.Levels_AchievementsForImage = this.Levels_AchievementEdit; this.imagePath = this.Levels_AchievementEdit.Image; this.Levels_AchievementEdit.Image = null; if (this.Levels_AchievementEdit.IsCriteria) { this.Levels_AchievementEdit.CriteriaId = this.Levels_AchievementEdit.SetUpID; this.VisibleCriteria = false; } else { this.VisibleCriteria = true; this.ChangeCriteria(this.Levels_AchievementEdit.CriteriaId) this.Levels_AchievementEdit.Range = this.Levels_AchievementEdit.SetUpID; } this.Levels_AchievementFrm.setValue(this.Levels_AchievementEdit); this.modal.open(); this.indLoading = false; } //,*error => this.msg = <any>error*/ ); // this.Levels_Achievement.Id = this.Levels_Achievement.AchievementID; } deleteLevels_Achievement(id: number, status: any) { debugger; this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == "Yes") { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.Levels_Achievement = this.Levels_Achievements.filter(x => x.Id == id)[0]; this.Levels_AchievementFrm.setValue(this.Levels_Achievement); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.Levels_AchievementFrm.enable() : this.Levels_AchievementFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.Levels_Achievements); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } GetSetupIdFromCriteriaId(CriteriaId):number { this._LevelCriteriaSetupService.getLevelSetupId(Global.BASE_LEVELCRITERIASETUP_ENDPOINT, CriteriaId) .subscribe(Data => { this.SetupId = Data; }, //,error => this.msg = <any>error ); return this.SetupId; } onSubmit(formData: any) { this.msg = ""; ///// switch (this.dbops) { case DBOperation.create: if (this.fileList1 != null) { formData._value.Image = "/Upload/EmployeeLevels/" + this.fileList1.item(0).name; if (this.VisibleCriteria == true) { if (formData._value.Range > 0) { formData._value.IsCriteria = false; formData._value.SetUpID = formData._value.Range; formData._value.AndAbove = true; formData._value.LevelSetupId = formData._value.Range; } else { formData._value.IsCriteria = true; formData._value.SetUpID = formData._value.CriteriaId; formData._value.AndAbove = false; formData._value.LevelSetupId = this.GetSetupIdFromCriteriaId(formData._value.CriteriaId); } } else { formData._value.IsCriteria = true; formData._value.SetUpID = formData._value.CriteriaId; formData._value.AndAbove = false; formData._value.LevelSetupId = this.GetSetupIdFromCriteriaId(formData._value.CriteriaId); } this._Levels_AchievementService.post(Global.BASE_Levels_Achievement_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { if (this.fileList1 != null) { if (this.fileList1.length > 0) { this.fileList1.item(0).name let file: File = this.fileList1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/Levels_AchievementAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) this.fileList1 = null; } } this.msg = data; this.LoadLevels_Achievements(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); } else { alert('Please select Image file'); } break; case DBOperation.update: if (this.fileList1 != null) { formData._value.Image = "/Upload/EmployeeLevels/" + this.fileList1.item(0).name; } if (this.VisibleCriteria == true) { if (formData._value.Range > 0) { formData._value.IsCriteria = false; formData._value.SetUpID = formData._value.Range; formData._value.AndAbove = true; formData._value.LevelSetupId = formData._value.Range; } else { formData._value.IsCriteria = true; formData._value.SetUpID = formData._value.CriteriaId; formData._value.AndAbove = false; formData._value.LevelSetupId = this.GetSetupIdFromCriteriaId(formData._value.CriteriaId); } } else { formData._value.IsCriteria = true; formData._value.SetUpID = formData._value.CriteriaId; formData._value.AndAbove = false; formData._value.LevelSetupId = this.GetSetupIdFromCriteriaId(formData._value.CriteriaId); } this._Levels_AchievementService.put(Global.BASE_Levels_Achievement_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { if (this.fileList1 != null) { if (this.fileList1.length > 0) { this.fileList1.item(0).name let file: File = this.fileList1[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/Levels_AchievementAPI/UploadJsonFile"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) this.fileList1 = null; } } this.msg = data; this.LoadLevels_Achievements(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._Levels_AchievementService.delete(Global.BASE_Levels_Achievement_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "Levels_Achievement status changed successfully."; this.LoadLevels_Achievements(); } else { this.msg = "Error has occurred while changing status of existing Levels_Achievement!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; using VIS_Repository.Reports.Attendance; using VIS_Repository.Dashboard; using VIS_Repository.Reports; namespace VIS_App.Controllers.Masters.Configuration { public class DailyEntrysheetAPIController : BaseAPIController { DailyEntrySheetRepository objDailyEntrySheetRepository = null; public DailyEntrysheetAPIController() { objDailyEntrySheetRepository = new DailyEntrySheetRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [Route("api/DailyEntrysheetAPI/GetDailyEntryRecord")] [HttpGet] public HttpResponseMessage GetDailyEntryRecord(Int64 Id,string Date) { return ToJson(objDailyEntrySheetRepository.GetDailyEntrySheetData(Id, Date)); } [Route("api/DailyEntrysheetAPI/GetDailyEntryTime")] [HttpGet] public HttpResponseMessage GetDailyEntryTime(Int64 Id, string Date) { return ToJson(objDailyEntrySheetRepository.GetDailyEntrySheetTime(Id, Date)); } [Route("api/DailyEntrysheetAPI/GetDailyEntryTimeAllEmp")] [HttpGet] public HttpResponseMessage GetDailyEntryTimeAllEmp(string Date) { return ToJson(objDailyEntrySheetRepository.GetDailyEntrySheetTimeAllEmployee(Date)); } [Route("api/DailyEntrysheetAPI/GetAllEmployee")] [HttpGet] public HttpResponseMessage GetAllEmployee() { return ToJson(objDailyEntrySheetRepository.GetAllEmployees()); } [Route("api/DailyEntrysheetAPI/UpdateReportDeatil")] [HttpPut] public HttpResponseMessage UpdateReportDeatil(DailyEntrysheetEmployee entityObject) { return ToJson(objDailyEntrySheetRepository.UpdateReportDetail(entityObject)); } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { EmployeeScreenCaptureReportService } from '../../../Service/Report/Attendance/EmployeeScreenCaptureReport.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { IEmployee } from '../../../Model/Report/Attendance/EmployeeScreenCaptureReport'; import { IEmployeeScreenCapture } from '../../../Model/Report/Attendance/EmployeeScreenCaptureReport'; import { IParameterModel } from '../../../Model/Report/Attendance/EmployeeScreenCaptureReport'; import { IYear } from '../../../Model/Report/Attendance/EmployeeScreenCaptureReport'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [EmployeeScreenCaptureReportService], templateUrl: 'app/Components/Report/Attendance/EmployeeScreenCapture.component.html' }) export class EmployeeScreenCaptureReportComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; constructor(private fb: FormBuilder, private _EmployeeScreenCaptureReportService: EmployeeScreenCaptureReportService, private pagerService: PagerService, private _CommonHelperService : CommonHelperService) { } pager: any = {}; pagedItems: any[]; CurrentRecordsPerPage: number = 10; Employee: IEmployee[]; EmployeeScreenCapture:IEmployeeScreenCapture; EmployeeScreenCaptures: IEmployeeScreenCapture[]; ParameterModel: IParameterModel; Year: IYear[]; modalTitle: string; InLoading: boolean; frommonth: number = new Date().getMonth() + 1; fromyear: number = new Date().getFullYear(); tomonth: number = new Date().getMonth() + 1; toyear: number = new Date().getFullYear(); fromdate: string; todate: string; ngOnInit() { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.ParameterModel = ({ EmployeeId: 0, FromDate:'', LoginUserId: 0, OrderBy: '', ToDate: '', FromMonth: '', FromYear: '', ToMonth: '', ToYear: '', MonthWise: false }) this.Year = [({ CurrentYear:'' })] this.GetEmployee(); this.GetYear(); } HideShowPanel() { if ($("#rbtdate").prop("checked")) { $("#paneldatewise").show(); $("#panelmonthwise").hide(); $("#panelmonthwise2").hide(); $("#panelmonthwise3").hide(); $("#panelmonthwise4").hide(); } else { $("#paneldatewise").hide(); $("#panelmonthwise").show(); $("#panelmonthwise2").show(); $("#panelmonthwise3").show(); $("#panelmonthwise4").show(); } } ToogleMyProfile() { $("#alltypeoutreportdata").slideToggle(300); } CloseWidgetProfile() { $("#alltypeoutreport").hide(300); } GetEmployee() { this._EmployeeScreenCaptureReportService.getemployee(Global.BASE_EmployeeScreenCaptureReportAPI_ENDPOINT). subscribe(employee => { this.Employee = employee }, ); } GetYear() { this._EmployeeScreenCaptureReportService.getyear(Global.BASE_EmployeeScreenCaptureReportAPI_ENDPOINT). subscribe(year => { debugger; this.Year = year }, ); } onSubmit(ParameterModel: IParameterModel) { if ($("#rbtdate").prop("checked")) { ParameterModel.OrderBy = 'Name'; ParameterModel.MonthWise = false; } else { ParameterModel.MonthWise = true; ParameterModel.FromMonth = this.frommonth.toString(); ParameterModel.FromYear = this.fromyear.toString() ParameterModel.ToMonth = this.tomonth.toString(); ParameterModel.ToYear = this.toyear.toString(); if ($("#rbtsortdate").prop("checked")) { ParameterModel.OrderBy = 'Date'; } else { ParameterModel.OrderBy = 'Name' } } ParameterModel.LoginUserId = 158; this.EmployeeScreenCaptures = null; this.InLoading = true; this._EmployeeScreenCaptureReportService.getoutreportdata(Global.BASE_EmployeeScreenCaptureReportAPI_ENDPOINT, ParameterModel). subscribe(employeescreencapture => { this.EmployeeScreenCaptures = employeescreencapture; this.JumpOnPage(1); $("html, body").animate({ scrollTop: 310 }, 150); this.InLoading = false; }, ); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeScreenCaptures); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ShowPopup() { this.modal.open(); this.modalTitle = 'Screen Capture Images'; } }<file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IConfigureWorkSheet } from '../../../Model/Masters/Configuration/ConfigureWorksheet'; @Pipe ({ name: 'configureworksheetFilter' }) export class ConfigureWorkSheetFilterPipe implements PipeTransform { transform(value: IConfigureWorkSheet[], filter: string): IConfigureWorkSheet[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IConfigureWorkSheet) => app.Fromm != null && app.Fromm.toLocaleString().indexOf(filter) != -1 ) : value; } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master.Configuration; namespace VIS_Repository.Reports { public class EmployeeDashboardHeartBeatReportRepository : VISDbCommand { int intAffectedRecords; public EmployeeDashboardHeartBeatReportRepository(string _connectionstring) : base(_connectionstring) { } public DataTable GetEmployee() { string mode = "Employee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetYear() { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeDashboardHeartBeatReportParameterModelConstant.const_procFinancialYear_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetEmployeeDashboardHeartBeatReporytByEmployeeId(EmployeeDashboardHeartBeatReportParameterModel entityobject) { DataTable dt = new DataTable(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = EmployeeDashboardHeartBeatReportParameterModelConstant.const_procEmployee_DashboardHeartBeatReport; objSqlCommand.Parameters.AddWithValue(EmployeeDashboardHeartBeatReportParameterModelConstant.const_EmployeeId, entityobject.EmployeeId); objSqlCommand.Parameters.AddWithValue(EmployeeDashboardHeartBeatReportParameterModelConstant.const_FromDate, entityobject.FromDate); objSqlCommand.Parameters.AddWithValue(EmployeeDashboardHeartBeatReportParameterModelConstant.const_ToDate, entityobject.ToDate); objSqlCommand.Parameters.AddWithValue(EmployeeDashboardHeartBeatReportParameterModelConstant.const_ViewBy, entityobject.ViewBy); objSqlCommand.Parameters.AddWithValue(EmployeeDashboardHeartBeatReportParameterModelConstant.const_ConsolidateBy, entityobject.ConsolidateBy); objSqlCommand.Parameters.AddWithValue(EmployeeDashboardHeartBeatReportParameterModelConstant.const_OrderBy, entityobject.OrderBy); objSqlCommand.Parameters.AddWithValue(EmployeeDashboardHeartBeatReportParameterModelConstant.const_LoginUserId, entityobject.LoginUserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch (Exception) { } return dt; } } }<file_sep>export class IMyLeaveDetails { ID: number; EmployeeID: number; ToDate: Date; FromDate: Date; Reason: String; ContactDetail: String; AppliedTo: number; LeaveType: number; Status: number; GHID: number; EnteredDate: Date; ResponsiblePersonID: number; Remarks: String; IsFullDay: boolean; IsFirstHalf: boolean; IsSecondHalf: boolean; CreatedDate: Date; contact: string; CallOnDate: Date; CallOnTime: string; EmergencyLeave: boolean; LongleaveEntry: boolean; } export class INwdHistory { id: number; employeeId: number; date: Date; leaveType: string; nwdId: number; } export class ICalTotalAttendance { EmployeeID: number; EmployeeName: String; Date: String; InTimeID: number; InTime: Date; OutTimeID: number; OutTime: Date; LunchOutTimeID: number; LunchOutTime: Date; LunchInTimeID: number; LunchInTime: Date; OtherTimeID: number; TotalOtherTime: String; TotalOfficeTime: String; TotalLunchTime: String; TotalBreakTime: String; TotalWorkingTime: String; TotalWorksheetHour: number; IsInOffice: boolean; IsInBreak: boolean; IsInLunch: boolean; IsInMeeting: boolean; IsInOfficeWork: boolean; Days: String; ImportRemarks: String; EmployeeCode: String; MMDDYYYY_DateFormate: String; } export class IActualEntryTimeAndGraceForPunchInId { actualEntryTime: string; grace: number; } export class IEmpLeaveLedgerForDate { leaveDuration: String; leaveType: String; approveType: String; shortLeaveType: String; } export class ILeaveDetailsByDate { ID: number; LeaveType: string; LeaveStatus: string; EmployeeId: number; FromDate: Date; ToDate: Date; CalendarDays: Date; IsFullDay: boolean; IsFirstHalf: boolean; IsSecondhalf: boolean; } export class IEmpHolidayListForDate { id: number; holidayName: String; fromDate: Date; toDate: Date; remarks: String; active: boolean; noOfDays: number; } export class IHolidayForDate { id: number; holidayName: String; fromDate: Date; toDate: Date; remarks: String; active: boolean; noOfDays: number; } export interface MyDate { year: number; month: number; day: number; } export interface mymonth { monthTxt: string; monthNbr: number; year: number; } export class IMyCalender { private myDatePickeroption = { todaybtnTxt: 'Today', dateFormat: 'yyyy-mm-dd', firstdayofweek: 'mo', sunHighlights: true, height: '150px', width: '300px', background: '#3BAFDA', ShowTextBox: false, }; SelectedDate: string = ''; } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Web.Http; using VIS_Domain.Notification; using VIS_Repository; using VIS_Repository.Notification; namespace VIS_App.Controllers.Notification { public class NewsAPIController : BaseAPIController { //VISIBaseRepository<News> NewsRepository; //List<News> EntityList = new List<News>(); NewsRepository ObjNewsRepository = null; public NewsAPIController() { ObjNewsRepository = new NewsRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjNewsRepository.GetEntityList().AsEnumerable()); } [Route("api/Newsapi/GetViewNewsList")] [HttpGet] public HttpResponseMessage GetViewNewsList(int id) { return ToJson(ObjNewsRepository.GetViewNews(id)); } public HttpResponseMessage Post([FromBody]News value) { return ToJson(ObjNewsRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]News value) { return ToJson(ObjNewsRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjNewsRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain { public static class VISCommonConstants { } } <file_sep>export interface IConfigureWorkSheet { Id: number; SrNo: string; Fromm: number; Too: number; HexadecimalValue: string; CreatedOn: Date; CreatedBy: string; UpdatedOn: Date; UpdatedBy: string IsActive: boolean; }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Masters.EmployeeLevels; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.Masters; using VIS_Domain; using System.Configuration; using VIS_Domain.Master.EmployeeManualPointEntry; namespace VIS_Repository.Masters.EmployeeLevels { public class LevelCriteriaRepository : VISDbCommand { public Int32 intAffectedRecords { get; set; } public LevelCriteriaRepository(string _connectionstring) : base(_connectionstring) { } public string AddEntity(LevelCriteria levelCriteria) { try { if (base.DatabaseConnection.ConnectionString == "") { base.DatabaseConnection.ConnectionString= ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaConstants.const_procLevelCriteria_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_Name, levelCriteria.Name); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_AliasName, levelCriteria.AliasName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_calculatedOnID, levelCriteria.calculatedOnID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_CategoryID, levelCriteria.CategoryID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_IsAutomatic, levelCriteria.IsAutomatic); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_Active, levelCriteria.Active); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_reference, levelCriteria.reference); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, levelCriteria.CreatedBy); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_IsPerformanceBadge, levelCriteria.IsPerformanceBased); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_IsPercentage, levelCriteria.IsPercentage); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_Point, levelCriteria.Point); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_Active, levelCriteria.Active); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_IsProgressive, levelCriteria.IsProgressive); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_ProgressiveDays, levelCriteria.ProgressiveDays); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_ProgressivePoints, levelCriteria.ProgressivePoints); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, levelCriteria.CreatedBy); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_AliasName, levelCriteria.AliasName); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_Name, levelCriteria.Name); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_CategoryID, levelCriteria.CategoryID); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_IsAutomatic, levelCriteria.IsAutomatic); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaConstants.const_Field_reference, levelCriteria.reference); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public LevelCriteria GetCriteriaDetails(long CriteriaId) { LevelCriteria objEntityToReturn = new LevelCriteria(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_GetLevelCriteriaCriteriaId; base.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_CriteriaId, CriteriaId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<LevelCriteria>(dt.Rows[0]); } return objEntityToReturn; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } //void IDisposable.Dispose() //{ // throw new NotImplementedException(); //} // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~LevelCriteriaRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Masters.EmployeeLevels { public class LevelConfiguration : VISBaseEntity { public int Period { get; set; } public string PeriodName { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public Boolean Active { get; set; } public Boolean IsCurrentPeriod { get; set; } public Int32 StartYear { get; set; } public Int32 StartMonth { get; set; } } public static class LevelConfigurationConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_LevelConfiguration = "LevelConfiguration"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Period = "Period"; public const string const_Field_PeriodName = "PeriodName"; public const string const_Field_StartDate = "StartDate"; public const string const_Field_EndDate = "EndDate"; public const string const_Field_Active = "Active"; public const string const_Field_IsCurrentPeriod = "IsCurrentPeriod"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procLevelConfigurations_Add = "procLevelConfigurations_Add"; public const string const_procLevelConfigurations_Update = "procLevelConfigurations_Update"; public const string const_procLevelConfigurations_ActiveInActive = "procLevelConfiguration_ActiveInActive"; public const string const_procLevelConfigurations_SelectAll = "procLevelConfigurations_SelectAll"; public const string const_procLevelConfigurations_SelectBaseNonBase = "procLevelConfigurations_SelectBaseNonBase"; public const string const_procLevelConfigurations_SelectById = "procLevelConfigurations_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.ContactManagement { public class Reports_ContactManagementRepository : VISDbCommand { private static Reports_ContactManagementRepository instance = new Reports_ContactManagementRepository(string.Empty); private Reports_ContactManagementRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_ContactManagementRepository getInstance() { return instance; } } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IRatingType } from '../../../Model/Masters/VacancyRelated/RatingType'; @Pipe ({ name: 'RatingtypeFilter' }) export class RatingTypeFilterPipe implements PipeTransform { transform(value: IRatingType[], filter: string): IRatingType[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IRatingType) => app.TypeName != null && app.TypeName.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var Skill_service_1 = require("../../../service/Masters/VacancyRelated/Skill.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var SkillComponent = (function () { function SkillComponent(fb, _SkillService, pagerService, _CommonHelperService) { this.fb = fb; this._SkillService = _SkillService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.indLoading = false; this.isDesc = false; this.column = 'SkillName'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; } SkillComponent.prototype.ResetModel = function () { this.skill = { CreatedBy: '', CreatedOn: null, Description: '', Id: 0, IsActive: false, Level: [], RatingGroup: '', SkillGroupID: 0, SkillGroupName: '', SkillName: '', Status: false, UpdatedBy: '', UpdatedOn: null, }; this.IMultiSelectOption = [ { id: 0, name: '0' }, { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, { id: 5, name: '5' }, { id: 6, name: '6' }, { id: 7, name: '7' }, { id: 8, name: '8' }, { id: 9, name: '9' }, { id: 10, name: '10' }, ]; }; SkillComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.LoadSkill(); this.LoadSkillGroup(); this.ResetModel(); }; SkillComponent.prototype.SkillFilterCriteriaChange = function (value) { if (value != '[object Event]') this.SkillFilter = value; }; SkillComponent.prototype.SkillSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; SkillComponent.prototype.LoadSkill = function () { var _this = this; this.indLoading = true; this._SkillService.get(global_1.Global.BASE_SKILL_ENDPOINT) .subscribe(function (skills) { _this.skills = skills; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchSkillName = document.getElementById("searchSkillName").value; if (_this.strSearchSkillName != '') { _this.strSearchSkillName = _this.strSearchSkillName.toLocaleLowerCase(); _this.skills = _this.skills.filter(function (x) { return x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(_this.strSearchSkillName) != -1; }); } _this.strSearchSkillGroupName = document.getElementById("searchSkillGroupName").value; if (_this.strSearchSkillGroupName != '') { _this.strSearchSkillGroupName = _this.strSearchSkillGroupName.toLocaleLowerCase(); _this.skills = _this.skills.filter(function (x) { return x.SkillGroupName != null && x.SkillGroupName.toLocaleLowerCase().indexOf(_this.strSearchSkillGroupName) != -1; }); } _this.strSearchDescription = document.getElementById("searchDescription").value; if (_this.strSearchDescription != '') { _this.strSearchDescription = _this.strSearchDescription.toLocaleLowerCase(); _this.skills = _this.skills.filter(function (x) { return x.Description != null && x.Description.toLocaleLowerCase().indexOf(_this.strSearchDescription) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); this.indLoading = true; this._SkillService.get(global_1.Global.BASE_SKILLGROUP_ENDPOINT) .subscribe(function (skillgroups) { _this.skillgroups = skillgroups; _this.indLoading = false; } //,error => this.msg = <any>error ); }; SkillComponent.prototype.AddSkill = function () { this.skill.SkillName = ''; this.skill.SkillGroupID = 0; this.skill.Description = ''; this.skill.Level = []; this.skill.Status = false; this.dbops = enum_1.DBOperation.create; this.modalTitle = "Add New Skill"; this.modalBtnTitle = "Add"; this.SetControlsState(false); this.modal.open(); }; SkillComponent.prototype.EditSkill = function (id) { this.dbops = enum_1.DBOperation.update; this.modalTitle = "Edit Skill"; this.modalBtnTitle = "Update"; this.skill.Id = id; this.skill.SkillName = this.skills.filter(function (x) { return x.Id == id; })[0].SkillName; this.skill.SkillGroupID = this.skills.filter(function (x) { return x.Id == id; })[0].SkillGroupID; this.skill.Description = this.skills.filter(function (x) { return x.Id == id; })[0].Description; this.skill.Status = this.skills.filter(function (x) { return x.Id == id; })[0].Status; this.TempLevel = this.skills.filter(function (x) { return x.Id == id; })[0].Level.toString().split(','); this.skill.Level = []; for (var _i = 0, _a = this.TempLevel; _i < _a.length; _i++) { var item = _a[_i]; this.skill.Level.push(Number(item)); } this.modal.open(); }; SkillComponent.prototype.DeleteSkill = function (id, status) { this.dbops = enum_1.DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.skill.Id = id; this.skill.SkillName = this.skills.filter(function (x) { return x.Id == id; })[0].SkillName; this.skill.SkillGroupID = this.skills.filter(function (x) { return x.Id == id; })[0].SkillGroupID; this.skill.Description = this.skills.filter(function (x) { return x.Id == id; })[0].Description; this.skill.Status = this.skills.filter(function (x) { return x.Id == id; })[0].Status; this.TempLevel = this.skills.filter(function (x) { return x.Id == id; })[0].Level.toString().split(','); this.skill.Level = []; for (var _i = 0, _a = this.TempLevel; _i < _a.length; _i++) { var item = _a[_i]; this.skill.Level.push(Number(item)); } this.SetControlsState(true); this.modal.open(); }; SkillComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.ControlIsDisable = true : this.ControlIsDisable = false; }; SkillComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; SkillComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.skills); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; SkillComponent.prototype.LoadSkillGroup = function () { var _this = this; this.indLoading = true; this._SkillService.get(global_1.Global.BASE_SKILLGROUP_ENDPOINT) .subscribe(function (skillgroups) { _this.skillgroups = skillgroups; _this.indLoading = false; // set items to json response // initialize to page 1 //this.JumpOnPage(1); //this.pager = this.pagerService.pager; //this.pagedItems = this.pagerService.pagedItems; } //,error => this.msg = <any>error ); }; SkillComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; SkillComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; if (formData.SkillGroupID != 0 && formData.Level.length > 0) { switch (this.dbops) { case enum_1.DBOperation.create: this._SkillService.post(global_1.Global.BASE_SKILL_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.ResetModel(); _this.LoadSkill(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._SkillService.put(global_1.Global.BASE_SKILL_ENDPOINT, formData.Id, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadSkill(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._SkillService.delete(global_1.Global.BASE_SKILL_ENDPOINT, formData.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.LoadSkill(); _this.msg = "Skill status changed successfully."; } else { _this.msg = "Error has occurred while changing status of existing Skill!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], SkillComponent.prototype, "modal", void 0); SkillComponent = __decorate([ core_1.Component({ providers: [Skill_service_1.SkillService], templateUrl: 'app/Components/Masters/VacancyRelated/Skill.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, Skill_service_1.SkillService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], SkillComponent); return SkillComponent; }()); exports.SkillComponent = SkillComponent; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { NewsService } from '../../service/Notification/News.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { INews } from '../../Model/Notification/News'; import { DBOperation } from '../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { DatePipe } from '@angular/common'; @Component({ providers: [NewsService], templateUrl: 'app/Components/Notification/News.component.html' }) export class NewsComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; @ViewChild('modal1') modal1: ModalComponent; Newss: INews[]; News: INews; ViewNew: INews[]; msg: string; indLoading: boolean = false; NewsFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; NewsFilter: string; isDesc: boolean = false; column: any = 'News_Name'; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchNews_Name: string; strSearchDescription: string; constructor(private fb: FormBuilder, private _NewsService: NewsService, private pagerService: PagerService) { } ngOnInit(): void { this.NewsFrm = this.fb.group({ CompanyId: [''], Id: [''], News_Name: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])], Description: ['', Validators.required], IsNew: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); this.LoadNewss() } NewsFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.NewsFilter = value; } NewsSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } LoadNewss(): void { this.indLoading = true; this._NewsService.get(Global.BASE_News_ENDPOINT) .subscribe(Newss => { this.Newss = Newss; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchNews_Name = (<HTMLInputElement>document.getElementById("searchNews_Name")).value; if (this.strSearchNews_Name != '') { this.strSearchNews_Name = this.strSearchNews_Name.toLocaleLowerCase(); this.Newss = this.Newss.filter( x => x.News_Name != null && x.News_Name.toLocaleLowerCase().indexOf(this.strSearchNews_Name) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } addNews() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New News"; this.modalBtnTitle = "Add"; this.NewsFrm.reset(); this.modal.open(); } editNews(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit News"; this.modalBtnTitle = "Update"; this.News = this.Newss.filter(x => x.Id == id)[0]; this.NewsFrm.setValue(this.News); this.modal.open(); } deleteNews(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.News = this.Newss.filter(x => x.Id == id)[0]; this.NewsFrm.setValue(this.News); this.modal.open(); } ViewNews(id: number) { this.dbops = DBOperation.View; this.SetControlsState(false); this.modalTitle = "View News"; this.modalBtnTitle = "Back"; this.News = this.Newss.filter(x => x.Id == id)[0]; this.NewsFrm.setValue(this.News); this.modal1.open(); this.LoadViewNews(id); } LoadViewNews(id: number): void { this.indLoading = true; this._NewsService.getViewNews(Global.BASE_News_ENDPOINT, id) .subscribe(DATADP => { this.ViewNew = DATADP; } ); } SetControlsState(isEnable: boolean) { isEnable ? this.NewsFrm.enable() : this.NewsFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.Newss); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._NewsService.post(Global.BASE_News_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadNewss(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._NewsService.put(Global.BASE_News_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadNewss(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._NewsService.delete(Global.BASE_News_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "News status changed successfully."; this.LoadNewss(); } else { this.msg = "Error has occurred while changing status of existing News!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { OfficialWorkReportService } from '../../../Service/Report/Attendance/OfficialWorkReport.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { IEmployee } from '../../../Model/Report/Attendance/OfficialWorkReport'; import { IYear } from '../../../Model/Report/Attendance/OfficialWorkReport'; import { IParameterModel } from '../../../Model/Report/Attendance/OfficialWorkReport'; import { IOfficialWorkReportBind } from '../../../Model/Report/Attendance/OfficialWorkReport'; import { Pipe } from '@angular/core'; import { DatepickerOptions } from 'ng2-datepicker'; import * as frLocale from 'date-fns/locale/fr'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [OfficialWorkReportService], templateUrl: 'app/Components/Report/Attendance/OfficialWorkReport.component.html' }) export class OfficialWorkReportComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; constructor(private fb: FormBuilder, private _OfficialWorkReportService: OfficialWorkReportService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } pager: any = {}; pagedItems: any[]; CurrentRecordsPerPage: number = 10; isDesc: boolean = false; column: any = 'Employee_Name'; direction: number; Employee: IEmployee[]; Year: IYear[]; ShowHideSearch: boolean = false; ParameterModel: IParameterModel; OfficialWorkReportBindList: IOfficialWorkReportBind[]; EmployeeId: number = 0; modalTitle: string; InLoading: boolean; frommonth: number = new Date().getMonth()+1; fromyear: number = new Date().getFullYear(); fromdate: string; todate: string; ngOnInit() { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.Year = [({ CurrentYear: '' })] this.ParameterModel = { EmployeeId: 0, FromDate: new Date(), ToDate: new Date(), ReportSort: '', Sort: 0, UserId: 0, UserType:'', FromMonth: '', FromYear: '', ToMonth: '', ToYear: '', MonthWise: false } this.GetEmployee(); this.GetYear(); } ToogleMyProfile() { $("#alltypeoutreportdata").slideToggle(300); } CloseWidgetProfile() { $("#alltypeoutreport").hide(300); } ViewStyleToogle() { if ($("#rbtconsolidated").prop('checked')) { $("#viewstyle").show(); } else { $("#viewstyle").hide(); } } ToogleHideShowOption() { if ($("#rbtdepartment").prop('checked')) { $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); $("#ddldepartment").show(); } else if ($("#rbtcompany").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").show(); $("#ddllinemanager").hide(); } else if ($("#rbtlinemanager").prop('checked')) { $("#ddldepartment").hide(); $("#ddlemployee").hide(); $("#chkallemployeediv").hide(); $("#ddlcompany").hide(); $("#ddllinemanager").show(); } else { $("#ddldepartment").hide(); $("#ddlemployee").show(); $("#chkallemployeediv").show(); $("#ddlcompany").hide(); $("#ddllinemanager").hide(); } } ToogleDateOption() { if ($("#rbtdate").prop("checked")) { $("#searchbydate").show(); $("#searchbymonth").hide(); } else { $("#searchbydate").hide(); $("#searchbymonth").show(); } } // function for bind dropdownlist GetEmployee() { this._OfficialWorkReportService.getemployee(Global.BASE_OfficialWorkReportAPI_ENDPOINT). subscribe(employee => { this.Employee = employee }, ); } GetYear() { this._OfficialWorkReportService.getyear(Global.BASE_OfficialWorkReportAPI_ENDPOINT). subscribe(year => { this.Year = year }, ); } GetOfficialWorkReport(entityobject : IParameterModel) { this._OfficialWorkReportService.getofficialworkreportdata(Global.BASE_OfficialWorkReportAPI_ENDPOINT, entityobject). subscribe(data => { this.OfficialWorkReportBindList = data this.JumpOnPage(1); }, ); } onSubmit(entityobject : IParameterModel) { debugger; entityobject.UserId = 21; entityobject.UserType = 'Admin'; // check search date wise or monthwise if ($("#rbtdate").prop("checked")) { entityobject.MonthWise = false; } else { entityobject.MonthWise = true; entityobject.FromMonth = this.frommonth.toString(); entityobject.FromYear = this.fromyear.toString(); } // check sorting date wise or name if ($("#rbtdatesort").prop("checked")) { entityobject.ReportSort = 'Date'; } else { entityobject.ReportSort = 'Name'; } // check approve status if ($("#rbtall").prop("checked")) { entityobject.Sort = 3; } else if ($("#rbtapproved").prop("checked")) { entityobject.Sort = 1; } else if ($("#rbtunapproved").prop("checked")) { entityobject.Sort = 0; } else { entityobject.Sort = 2; } this.GetOfficialWorkReport(entityobject); $("html, body").animate({ scrollTop: 500 }, 150); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.OfficialWorkReportBindList); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.HumanResource.EmployeeManagement; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.HumanResource.EmployeeManagement; using VIS_Repository.Masters.CompanyRelated; namespace VIS_App.Controllers.HumanResource.EmployeeManagement { public class SalaryBreakupTypeAPIController : BaseAPIController { SalaryBreakupTypeRepository ObjSalaryBreakupTypeRepository = null; public SalaryBreakupTypeAPIController() { ObjSalaryBreakupTypeRepository = new SalaryBreakupTypeRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjSalaryBreakupTypeRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]SalaryBreakupType value) { return ToJson(ObjSalaryBreakupTypeRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]SalaryBreakupType value) { return ToJson(ObjSalaryBreakupTypeRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 id) { return ToJson(ObjSalaryBreakupTypeRepository.DeleteEntity(id)); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var DocumentTemplate_service_1 = require("../../Service/DocCenter/DocumentTemplate.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../Shared/enum"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); var pager_index_1 = require("../../Shared/pager.index"); var CommonHelper_service_1 = require("../../Shared/CommonHelper.service"); var http_1 = require("@angular/http"); require("rxjs/add/operator/map"); require("rxjs/add/operator/do"); require("rxjs/add/operator/catch"); var DocumentTemplateComponent = (function () { function DocumentTemplateComponent(fb, _DocumentTemplateService, pagerService, _CommonHelperService, http) { this.fb = fb; this._DocumentTemplateService = _DocumentTemplateService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.http = http; this.strImgpath = '../../../Upload/DocumentCenter/DocumentTemplateImages/'; this.strTableField = ''; this.string = ''; this.IsStep1Completed = false; this.indLoading = false; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; this.step2Option = 'Text'; this.IsEditStep2 = false; this.lstContainerField = []; this.ShowHideSearch = false; this.isDesc = false; this.column = 'Employee_Name'; this.DocTempId = 0; this.TodayDate = new Date(); this.ResetModal(); } // Step 1 & Step 2 Related Function DocumentTemplateComponent.prototype.ResetModal = function () { this.objIDocumentTemplateModel = ({ AddRecurrenceType: false, AllowFooter: false, AllowHeader: false, ApprovedOn: null, ContributorsId: '', DateFormat: 'Date(dd/mm/yyyy)', DocRightsId: 0, DocTemplateId: 0, DocTemplateInProgressId: 0, EmployeeId: 0, EmployeeName: '', FooterContent: '', HeaderContent: '', IsApproved: false, IsBehalf: false, IsDMSPdf: false, IsDMSWord: false, IsDownloadPdf: false, IsDownloadWord: false, IsEmailPdf: false, IsEmailWord: false, IsFinalSubmited: false, IsPortrait: true, IsRecurrence: false, IsSelf: true, ModuleId: '', ModuleName: '', OwnerId: Number(sessionStorage.getItem('Id')), PublishDate: '', SharingVariableType: '', StartingVariableRole: '', stringDate: null, TemplateDescription: '', TemplateName: '', TemplateRightsData: '', CreatedBy: 0 }); this.objIDocMasterFieldDataContract = ({ AttachmentList: '', CreatedBy: 0, CreatedOn: null, DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: 0, FieldDescription: '', FieldId: '', FieldName: '', FieldType: 'Text', Id: 0, ImageName: '', ImageAlign: 'left', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.listIListItem = null; this.listIListItemRole = null; }; DocumentTemplateComponent.prototype.ngOnInit = function () { this.lstIDropdownTableField = [ { FieldName: '', IsActive: false, ModuleId: 0, VariableId: 0, VarName: '', TableName: '' } ]; this.lstIDropdownCustomField = [ { MasterFieldId: 0, TokenName: '', TokenValue: '' } ]; this._CommonHelperService.ToogleMenu(); this.GetApprovedDocumentData(); }; DocumentTemplateComponent.prototype.BindTableFieldDropDown = function (TableName) { var _this = this; this._DocumentTemplateService.bindtablefielddropdown(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, TableName). subscribe(function (data) { _this.lstIDropdownTableField = data; }); }; DocumentTemplateComponent.prototype.BindCustomFieldDropDown = function (DocTempId) { var _this = this; this._DocumentTemplateService.bindcustomfielddropdown(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, DocTempId). subscribe(function (data) { _this.lstIDropdownCustomField = data; }); }; DocumentTemplateComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; DocumentTemplateComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.listIDocumentTemplateViewModel); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; DocumentTemplateComponent.prototype.DocumentTemplateSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; DocumentTemplateComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; DocumentTemplateComponent.prototype.GetApprovedDocumentData = function () { var _this = this; // get id this.EmployeeId = Number(sessionStorage.getItem('Id')); // get role if (JSON.parse(sessionStorage.getItem('IsAdmin'))) { this.EmployeeRole = 'Admin'; } else if (JSON.parse(sessionStorage.getItem('IsLineManager')) && this.EmployeeRole != 'Admin') { this.EmployeeRole = 'LM'; } // get status if ($("#rbtapproved").prop("checked")) { this.ApprovedStatus = 'Approved'; } else if ($("#rbtpending").prop("checked")) { this.ApprovedStatus = 'Pending'; } else if ($("#rbtreject").prop("checked")) { this.ApprovedStatus = 'Reject'; } if (this.EmployeeRole == 'Admin' || this.EmployeeRole == 'LM') { this.strPageHeader = 'Document Template'; } else { this.strPageHeader = 'My Suggestion'; } this._DocumentTemplateService.getapprovedrecord(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, this.EmployeeId, this.EmployeeRole, this.ApprovedStatus). subscribe(function (data) { _this.indLoading = true; _this.listIDocumentTemplateViewModel = data; //Logic for searching - start if (_this.ShowHideSearch) { _this.strTemplateName = document.getElementById("searchTemplateName").value; if (_this.strTemplateName != '') { _this.strTemplateName = _this.strTemplateName.toLocaleLowerCase(); _this.listIDocumentTemplateViewModel = _this.listIDocumentTemplateViewModel.filter(function (x) { return x.TemplateName != null && x.TemplateName.toLocaleLowerCase().indexOf(_this.strTemplateName) != -1; }); } _this.strOwnerName = document.getElementById("searchOwnerName").value; if (_this.strOwnerName != '') { _this.strOwnerName = _this.strOwnerName.toLocaleLowerCase(); _this.listIDocumentTemplateViewModel = _this.listIDocumentTemplateViewModel.filter(function (x) { return x.OwnerName != null && x.OwnerName.toLocaleLowerCase().indexOf(_this.strOwnerName) != -1; }); } _this.strModuleName = document.getElementById("searchModuleName").value; if (_this.strModuleName != '') { _this.strModuleName = _this.strModuleName.toLocaleLowerCase(); _this.listIDocumentTemplateViewModel = _this.listIDocumentTemplateViewModel.filter(function (x) { return x.ModuleName != null && x.ModuleName.toLocaleLowerCase().indexOf(_this.strModuleName) != -1; }); } } //Logic for searching - End _this.indLoading = false; _this.JumpOnPage(1); }); }; DocumentTemplateComponent.prototype.AddNewTemplate = function () { this.DisableAllSteps(); this.BindModuleDropDown(); this.modalTitle = 'Document Template'; this.modalBtnTitle = 'Save & Next'; this.dbops = enum_1.DBOperation.create; this.ResetModal(); this.GetDocumentFieldByDocId(0); this.DocTempId = 0; this.IsStep1Completed = false; this.modal.open(); }; DocumentTemplateComponent.prototype.EditTempalte = function (id) { var _this = this; this.DisableAllSteps(); this.BindModuleDropDown(); this.modalTitle = 'Document Template'; this.modalBtnTitle = 'Save & Next'; this.dbops = enum_1.DBOperation.update; this._DocumentTemplateService.getbyid(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, id). subscribe(function (data) { _this.objentitybyid = data; _this.BindStartingVariableNameDropdown(_this.objentitybyid.ModuleId); _this.objIDocumentTemplateModel = _this.objentitybyid; _this.DocTempId = _this.objentitybyid.DocTemplateId; _this.GetDocumentFieldByDocId(_this.DocTempId); _this.BindContainerField(); _this.BindMasterField(); _this.IsStep1Completed = true; }); this.modal.open(); }; DocumentTemplateComponent.prototype.DeleteTemplate = function (id, status) { this.objIDocumentTemplateModel.DocTemplateId = this.listIDocumentTemplateViewModel.filter(function (x) { return x.DocTemplateId == id; })[0].DocTemplateId; this.objIDocumentTemplateModel.TemplateName = this.listIDocumentTemplateViewModel.filter(function (x) { return x.DocTemplateId == id; })[0].TemplateName; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.dbops = enum_1.DBOperation.delete; this.modaldelete.open(); }; DocumentTemplateComponent.prototype.CopyTemplate = function () { }; DocumentTemplateComponent.prototype.ActivateDeactivateStatus = function (id) { alert(id); }; DocumentTemplateComponent.prototype.EnableDisableApproveButton = function () { if (this.listIDocumentTemplateViewModel[0].ApprovedStatus == 'Approved') { var styles = { 'filter': 'grayscale(100%)', 'cursor': 'not-allowed' }; $(".btnstatus").prop('disabled', true); return styles; } else { var styles = { 'filter': 'grayscale(0%)', 'cursor': 'allowed' }; $(".btnstatus").prop('disabled', false); return styles; } }; DocumentTemplateComponent.prototype.BindModuleDropDown = function () { var _this = this; this._DocumentTemplateService.getallmodule(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT). subscribe(function (data) { _this.listIDocTemplateModule = data; }); }; DocumentTemplateComponent.prototype.BindStartingVariableNameDropdown = function (modulevalue) { if (modulevalue == 'DocTemplateModuleVariables') { this.listIListItem = [{ text: '<NAME>', value: '' }, { text: '<NAME>', value: 'interviewsheetmaster' }]; $("#rbtself").prop('disabled', false); $("#rbtself").prop('checked', true); $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', false); } else if (modulevalue == 'Other') { this.listIListItem = [{ text: 'Employee Name', value: 'Employee_Master' }, { text: '<NAME>', value: 'interviewsheetmaster' }]; $("#rbtself").prop('disabled', false); $("#rbtself").prop('checked', false); $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', true); } else if (modulevalue == "ProjectMaster") { this.listIListItem = [{ text: 'Project Name', value: 'ProjectMaster' }]; $("#rbtself").prop('checked', false); $("#rbtself").prop('disabled', true); $("#rbtbehalf").prop('checked', true); $("#rbtbehalf").prop('disabled', false); } else if (modulevalue == "RFQ_Initial") { this.listIListItem = [{ text: 'RFQ Initial', value: 'RFQ_Initial' }]; $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', true); $("#rbtself").prop('checked', false); $("#rbtself").prop('disabled', true); } else if (modulevalue == "ManageProjectMaster") { this.listIListItem = [{ text: 'BD Project Name', value: 'ManageProjectMaster' }]; $("#rbtbehalf").prop('disabled', false); $("#rbtbehalf").prop('checked', true); $("#rbtself").prop('checked', false); $("#rbtself").prop('disabled', true); } this.objIDocumentTemplateModel.SharingVariableType = this.listIListItem[0].value; this.BindStartingVariableTypeDropdown(modulevalue); }; DocumentTemplateComponent.prototype.BindStartingVariableTypeDropdown = function (modulevalue) { if (modulevalue == 'DocTemplateModuleVariables') { this.listIListItemRole = [{ text: 'None', value: 'none' }, { text: 'Admin', value: 'admin' }, { text: 'HR', value: 'hr' }, { text: 'HRH', value: 'hrh' }, { text: 'LM', value: 'lm' }]; } else if (modulevalue == 'Other') { this.listIListItemRole = [{ text: 'None', value: 'none' }, { text: 'Admin', value: 'admin' }, { text: 'HR', value: 'hr' }, { text: 'HRH', value: 'hrh' }, { text: 'LM', value: 'lm' }]; } else if (modulevalue == "ProjectMaster") { this.listIListItemRole = [{ text: 'None', value: 'none' }, { text: 'Admin', value: 'admin' }, { text: 'AManager', value: 'amanager' }, { text: 'AMG', value: 'amg' }, { text: 'BH', value: 'bh' }, { text: 'BM', value: 'bm' }, { text: 'DH', value: 'dh' }, { text: 'PM', value: 'pm' }, { text: 'RMG', value: 'rmg' }, { text: 'SH', value: 'sh' }]; } else if (modulevalue == "RFQ_Initial") { this.listIListItemRole = [{ text: 'None', value: 'none' }, { text: 'Admin', value: 'admin' }, { text: 'BH', value: 'bh' }, { text: 'BM', value: 'bm' }, { text: 'SH', value: 'sh' }]; } else if (modulevalue == "ManageProjectMaster") { this.listIListItemRole = [{ text: 'None', value: 'none' }, { text: 'Admin', value: 'admin' }, { text: 'BH', value: 'bh' }, { text: 'BM', value: 'bm' }, { text: 'SH', value: 'sh' }]; } this.objIDocumentTemplateModel.StartingVariableRole = this.listIListItemRole[0].value; }; DocumentTemplateComponent.prototype.onSubmitStep1 = function (formData) { var _this = this; formData.OwnerId = Number(sessionStorage.getItem('Id')); formData.CreatedBy = Number(sessionStorage.getItem('Id')); if ($("#rbtself").prop("checked")) { formData.IsSelf = true; formData.IsBehalf = false; } else { formData.IsSelf = false; formData.IsBehalf = true; } if (JSON.parse(sessionStorage.getItem('IsAdmin')) || JSON.parse(sessionStorage.getItem('IsLineManager'))) { formData.ApprovedOn = new Date(); formData.IsApproved = true; formData.IsFinalSubmited = true; } switch (this.dbops) { case enum_1.DBOperation.create: this._DocumentTemplateService.addnewdocument(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { alert('Document Template Saved sucessfully...'); _this.ResetModal(); _this._DocumentTemplateService.getmaxid(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT). subscribe(function (id) { _this.DocTempId = id; if (_this.DocTempId > 0) { _this.IsStep1Completed = true; _this.NextStep1(); } }); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._DocumentTemplateService.updatedocument(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { alert('Document Template Saved sucessfully...'); _this.ResetModal(); _this.NextStep1(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._DocumentTemplateService.deletedocument(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, formData.DocTemplateId).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.GetApprovedDocumentData(); _this.modaldelete.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); } }; DocumentTemplateComponent.prototype.onSubmitStep2 = function (formData) { var _this = this; if (formData.DataSourceColumn == '' && formData.DataSourceColumnForCustom == '') { alert('Select Table Field or Custom Control Field'); } else { if (formData.DataSourceColumn == '') { formData.DataSourceColumn = '0'; } if (this.fileList1 != null) { if (this.fileList1.length > 0) { formData.ImageName = this.fileList1.item(0).name; formData.ImageHeight = 100; formData.ImageWidth = 100; } } else { formData.ImageName = this.objIDocMasterFieldDataContract.ImageName; } if (this.IsEditStep2 == false) { formData.DocTemplateId = this.DocTempId; formData.CreatedBy = Number(sessionStorage.getItem('Id')); this._DocumentTemplateService.addnewdocumentfield(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { alert('Field saved Successfully...'); _this.GetDocumentFieldByDocId(_this.DocTempId); _this.BindContainerField(); _this.BindMasterField(); _this.ResetModal(); } else { alert(data); } }, function (error) { _this.msg = error; }); } else { formData.UpdatedBy = Number(sessionStorage.getItem('Id')); this._DocumentTemplateService.updatedocumentfield(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { alert('Field saved Successfully...'); _this.GetDocumentFieldByDocId(_this.DocTempId); _this.BindContainerField(); _this.BindMasterField(); _this.ResetModal(); } else { alert(data); } }, function (error) { _this.msg = error; }); } } }; DocumentTemplateComponent.prototype.CheckEnableDisableOption = function () { if ($("#rbtself").prop('checked')) { $("#SharingVariableType").prop('disabled', true); $("#StartingVariableRole").prop('disabled', true); } else { $("#SharingVariableType").prop('disabled', false); $("#StartingVariableRole").prop('disabled', false); } }; DocumentTemplateComponent.prototype.EditField = function (id) { this.IsEditStep2 = true; this.objIDocMasterFieldDataContract = this.lstIDocMasterFieldDataContract.filter(function (x) { return x.Id == id; })[0]; this.strImgpath = '../../../Upload/DocumentCenter/DocumentTemplateImages/' + this.objIDocMasterFieldDataContract.ImageName; }; DocumentTemplateComponent.prototype.DeleteField = function (id) { var _this = this; var confirmation = confirm('Are you sure want to delete User Input?'); if (confirmation == true) { this._DocumentTemplateService.deletedocumentfield(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, id, Number(sessionStorage.getItem('Id'))).subscribe(function (data) { if (data.startsWith("Success: ")) { alert('Field deleted Successfully...'); _this.GetDocumentFieldByDocId(_this.DocTempId); _this.ResetModal(); } else { alert(data); } }, function (error) { _this.msg = error; }); } }; DocumentTemplateComponent.prototype.CopyField = function (id) { this.IsEditStep2 = false; this.objIDocMasterFieldDataContract = this.lstIDocMasterFieldDataContract.filter(function (x) { return x.Id == id; })[0]; this.objIDocMasterFieldDataContract.FieldName = ''; }; DocumentTemplateComponent.prototype.GetDocumentFieldByDocId = function (doctempid) { var _this = this; this._DocumentTemplateService.getbydoctempid(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, doctempid). subscribe(function (data) { _this.lstIDocMasterFieldDataContract = data; _this.lstIDocMasterFieldDataContract = _this.lstIDocMasterFieldDataContract.filter(function (x) { return x.FieldType == 'Text' || x.FieldType == 'Image' || x.FieldType == 'TokenText'; }); }); }; DocumentTemplateComponent.prototype.EnableDisableSteps = function () { if (this.IsStep1Completed == true) { var styles = { 'pointer-events': 'auto', 'color': '#337ab7' }; return styles; } else { var styles = { 'pointer-events': 'none', 'color': '#dce2e8' }; return styles; } }; DocumentTemplateComponent.prototype.GetImageFile = function (event) { this.fileList1 = event.target.files; }; DocumentTemplateComponent.prototype.UploadImage = function () { if (this.fileList1 != null) { if (this.fileList1.length > 0) { this.fileList1.item(0).name; var file = this.fileList1[0]; var formData = new FormData(); formData.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); this.http.post(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT + 'UploadImage', formData, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { }, function (error) { console.log(error); }); this.strImgpath = '../../../Upload/DocumentCenter/DocumentTemplateImages/' + this.fileList1.item(0).name; } } else { alert('Please Select Image'); } }; DocumentTemplateComponent.prototype.BindDropDownTableField = function () { this.IsEditStep2 = false; this.objIDocMasterFieldDataContract.AttachmentList = ''; this.objIDocMasterFieldDataContract.DataSourceColumn = ''; this.objIDocMasterFieldDataContract.DataSourceColumnForCustom = ''; this.objIDocMasterFieldDataContract.DataSourceTable = ''; this.objIDocMasterFieldDataContract.FieldDescription = ''; this.objIDocMasterFieldDataContract.FieldName = ''; this.objIDocMasterFieldDataContract.ImageAlign = 'left'; this.objIDocMasterFieldDataContract.ImageHeight = 0; this.objIDocMasterFieldDataContract.ImageWidth = 0; this.objIDocMasterFieldDataContract.PageContent = ''; this.strImgpath = ''; this.GetDocumentFieldByDocId(this.DocTempId); if (this.DocTempId > 0) { this.BindCustomFieldDropDown(this.DocTempId); } if (this.objIDocumentTemplateModel.ModuleName != '') { this.BindTableFieldDropDown(this.objIDocumentTemplateModel.ModuleId); } }; DocumentTemplateComponent.prototype.ChangeTableFieldDropDown = function (value) { this.strTableField = '<p>' + value + '</p>'; }; DocumentTemplateComponent.prototype.AddTableFieldToTextEditor = function () { if (this.strTableField != '') { this.objIDocMasterFieldDataContract.PageContent += this.strTableField; } else { alert("Select Table Field."); } }; DocumentTemplateComponent.prototype.AddCustomFieldToTextEditor = function (value) { if (value != '') { var todayDate = new Date(), day = todayDate.getDate(), month = todayDate.getMonth(), year = todayDate.getFullYear(), hour = todayDate.getHours(), minute = todayDate.getMinutes(), second = todayDate.getSeconds(), miSecond = todayDate.getMilliseconds(); if (value == "{Textbox}") { value = "{Textbox_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{TextArea}") { value = "{TextArea_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{CKEditor}") { value = "{CKEditor_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{SingleDate}") { value = "{SingleDate_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{Time}") { value = "{Time_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "{DateRange}") { value = "{DateRange_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "DropDownList") { value = "{DropDownList_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "ListBox") { value = "{ListBox_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "CheckBoxList") { value = "{CheckBoxList_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } else if (value == "RadioButtonList") { value = "{RadioButtonList_" + day + "_" + month + "_" + year + "_" + hour + "_" + minute + "_" + second + "_" + miSecond + "}"; } this.strCustomField = '<p>' + value + '</p>'; this.objIDocMasterFieldDataContract.PageContent += this.strCustomField; } else { alert("Select Custom Field."); } }; DocumentTemplateComponent.prototype.NextStep1 = function () { $("#Step1Content").hide(); $("#Step2Content").show(); $("#Step2Content").scrollTop(0); }; DocumentTemplateComponent.prototype.CancelStep2 = function () { this.IsEditStep2 = false; this.strImgpath = ''; this.strTableField = ''; this.strCustomField = ''; this.fileList1 = null; var FieldType = this.objIDocMasterFieldDataContract.FieldType; this.objIDocMasterFieldDataContract = ({ AttachmentList: '', CreatedBy: 0, CreatedOn: null, DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: 0, FieldDescription: '', FieldId: '', FieldName: '', FieldType: 'Text', Id: 0, ImageName: '', ImageAlign: 'left', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.objIDocMasterFieldDataContract.FieldType = FieldType; $("#Step2Content").scrollTop(0); }; DocumentTemplateComponent.prototype.PreviousStep2 = function () { $("#Step2Content").hide(); $("#Step1Content").show(); $("#Step1Content").scrollTop(0); }; DocumentTemplateComponent.prototype.NextStep2 = function () { $("#Step2Content").hide(); $("#Step3Content").show(); $("#Step3Content").scrollTop(0); }; DocumentTemplateComponent.prototype.DisableAllSteps = function () { $("#Step1Content").hide(); $("#Step2Content").hide(); $("#Step3Content").hide(); $("#Step4Content").hide(); $("#Step5Content").hide(); $("#Step6Content").hide(); $("#Step7Content").hide(); $("#Step8Content").hide(); $("#Step1Content").show(); $("#Step1Content").scrollTop(0); }; // Step 3 Related Function DocumentTemplateComponent.prototype.BindContainerField = function () { var _this = this; this._DocumentTemplateService.GetDocumentContainer(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, this.DocTempId). subscribe(function (data) { _this.lstContainerField = []; _this.lstContainerField = data; }); }; DocumentTemplateComponent.prototype.BindMasterField = function () { var _this = this; this._DocumentTemplateService.getbydoctempid(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, this.DocTempId). subscribe(function (data) { _this.lstMasterField = data; }); }; DocumentTemplateComponent.prototype.AddAllField = function () { if (this.lstMasterField.length > 0) { for (var _i = 0, _a = this.lstMasterField; _i < _a.length; _i++) { var item = _a[_i]; this.lstContainerField.push(item); } this.lstMasterField = this.lstIDocMasterFieldDataContract.filter(function (x) { return x.FieldType == 'Text' || x.FieldType == 'Image'; }); } }; DocumentTemplateComponent.prototype.RemoveAllField = function () { if (this.lstContainerField.length > 0) { for (var _i = 0, _a = this.lstContainerField; _i < _a.length; _i++) { var item = _a[_i]; if (item.FieldType != 'Text' && item.FieldType != 'Image') { this.lstMasterField.push(item); } } this.lstContainerField = []; } }; DocumentTemplateComponent.prototype.AddLineBreak = function () { this.objContainerField = ({ AttachmentList: '', CreatedBy: Number(sessionStorage.getItem('Id')), CreatedOn: new Date(), DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: this.DocTempId, FieldDescription: '', FieldId: '', FieldName: 'Line Break', FieldType: '<BR>', Id: 0, ImageName: '', ImageAlign: '', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.lstContainerField.push(this.objContainerField); }; DocumentTemplateComponent.prototype.AddPageBreak = function () { this.objContainerField = ({ AttachmentList: '', CreatedBy: Number(sessionStorage.getItem('Id')), CreatedOn: new Date(), DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: this.DocTempId, FieldDescription: '', FieldId: '', FieldName: 'Page Break', FieldType: '<PageBreak>', Id: 0, ImageName: '', ImageAlign: '', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.lstContainerField.push(this.objContainerField); this.lstContainerField = this.lstContainerField; }; DocumentTemplateComponent.prototype.NextStep3 = function () { $("#Step3Content").hide(); $("#Step4Content").show(); $("#Step4Content").scrollTop(0); }; DocumentTemplateComponent.prototype.CancelStep3 = function () { this.BindContainerField(); this.BindMasterField(); $("#Step3Content").scrollTop(0); $(".contentscrollermasterfield").scrollTop(0); }; DocumentTemplateComponent.prototype.PreviousStep3 = function () { $("#Step3Content").hide(); $("#Step2Content").show(); $("#Step2Content").scrollTop(0); }; DocumentTemplateComponent.prototype.onSubmitStep3 = function () { var _this = this; if (this.lstContainerField.length == 0) { this.objContainerField = ({ AttachmentList: '', CreatedBy: 0, CreatedOn: null, DataSourceColumn: '', DataSourceColumnForCustom: '', DataSourceTable: '', DocTemplateId: this.DocTempId, FieldDescription: '', FieldId: '', FieldName: '', FieldType: '', Id: 0, ImageName: '', ImageAlign: '', ImageHeight: 0, ImageWidth: 0, IsActive: false, IsCustomField: false, IsDelete: false, IsNew: false, ListType: '', PageContent: '', UpdatedBy: 0, UpdatedOn: null }); this.lstContainerField.push(this.objContainerField); } this._DocumentTemplateService.AddDocumentContainerField(global_1.Global.BASE_DocumentTemplateAPI_ENDPOINT, this.lstContainerField). subscribe(function (data) { _this.BindContainerField(); alert('My Document Container Saved Successfully...'); }); }; DocumentTemplateComponent.prototype.RemoveLineBreakPageBreak = function (CreatedOn) { this.objContainerField = this.lstContainerField.filter(function (x) { return x.CreatedOn == CreatedOn; })[0]; var index = this.lstContainerField.indexOf(this.objContainerField); if (index !== -1) { this.lstContainerField.splice(index, 1); } }; DocumentTemplateComponent.prototype.RemoveLineBreakPageBreakMaster = function (CreatedOn) { this.objContainerField = this.lstMasterField.filter(function (x) { return x.CreatedOn == CreatedOn; })[0]; var index = this.lstMasterField.indexOf(this.objContainerField); if (index !== -1) { this.lstMasterField.splice(index, 1); } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], DocumentTemplateComponent.prototype, "modal", void 0); __decorate([ core_1.ViewChild('modaldelete'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], DocumentTemplateComponent.prototype, "modaldelete", void 0); DocumentTemplateComponent = __decorate([ core_1.Component({ providers: [DocumentTemplate_service_1.DocumentTemplateService], templateUrl: 'app/Components/DocCenter/DocumentTemplate.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, DocumentTemplate_service_1.DocumentTemplateService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService, http_1.Http]) ], DocumentTemplateComponent); return DocumentTemplateComponent; }()); exports.DocumentTemplateComponent = DocumentTemplateComponent; <file_sep>using System; using System.Collections.Generic; using System.Reflection; using System.Data; namespace VIS_Repository { public static class VISAutoMapper { public static List<T> ConvertDataTable<T>(DataTable dt) { try { List<T> ListOfClass = new List<T>(); foreach (DataRow row in dt.Rows) { T itemobject = GetItem<T>(row); ListOfClass.Add(itemobject); } return ListOfClass; } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); throw; } } public static T GetItem<T>(DataRow dr) { string strColumnHavingProblem = string.Empty; try { Type classType = typeof(T); T classobject = Activator.CreateInstance<T>(); foreach (DataColumn column in dr.Table.Columns) { foreach (PropertyInfo pro in classType.GetProperties()) { strColumnHavingProblem = pro.Name; if (pro.Name.ToLower() == column.ColumnName.ToLower()) pro.SetValue(classobject, dr[column.ColumnName.ToLower()] != DBNull.Value ? dr[column.ColumnName.ToLower()] : (pro.PropertyType.IsValueType == true ? Activator.CreateInstance(pro.PropertyType) : String.Empty)); else continue; } } return classobject; } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); throw; } } public static T ConvertDataRow<T>(DataRow row) { try { T ListOfClass = GetItem<T>(row); return ListOfClass; } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); throw; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; using VIS_Domain.Masters.EmployeeLevels; using VIS_Repository; namespace VIS_App.Controllers.Masters.EmployeeLevels { public class LevelConfigurationAPIController : BaseAPIController { VISIBaseRepository<LevelConfiguration> LevelConfigurationRepository; List<LevelConfiguration> EntityList = new List<LevelConfiguration>(); public LevelConfigurationAPIController(VISIBaseRepository<LevelConfiguration> _levelsRepository) { LevelConfigurationRepository = _levelsRepository; } public HttpResponseMessage Get() { return ToJson(LevelConfigurationRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]LevelConfiguration value) { return ToJson(LevelConfigurationRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 id, [FromBody]LevelConfiguration value) { return ToJson(LevelConfigurationRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(LevelConfigurationRepository.DeleteEntity(Id)); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var Subject_1 = require("rxjs/Subject"); var SharedContents = (function () { function SharedContents() { this.PageWrapper = new Subject_1.Subject(); this.ShowDashboard = new Subject_1.Subject(); this.loader = new Subject_1.Subject(); this.pageWrapper$ = this.PageWrapper.asObservable(); this.showDashboard$ = this.ShowDashboard.asObservable(); this.loader$ = this.loader.asObservable(); } SharedContents.prototype.setData = function (pWrapper, showDashboard) { this.PageWrapper.next(pWrapper); this.ShowDashboard.next(showDashboard); }; SharedContents.prototype.setLoader = function (loader) { this.loader.next(loader); }; SharedContents = __decorate([ core_1.Injectable() ], SharedContents); return SharedContents; }()); exports.SharedContents = SharedContents; <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain.Notification; using VIS_Repository.Notification; namespace VIS_App.Controllers.Notification { public class TicketListClosedAPIController : BaseAPIController { TicketListClosedRepository ObjTicketListClosedRepository = null; public TicketListClosedAPIController() { // TicketListClosedRepository = _TicketListClosedRepository; ObjTicketListClosedRepository = new TicketListClosedRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(ObjTicketListClosedRepository.GetEntityList().AsEnumerable()); } [Route("api/TicketListClosedapi/GetDetailTicket")] [HttpGet] public HttpResponseMessage GetDetailTicket(int UserId) { return ToJson(ObjTicketListClosedRepository.GetTicketByUserOpen(UserId)); } [Route("api/TicketListClosedapi/GetViewHistoryTicket")] [HttpGet] public HttpResponseMessage GetViewHistoryTicket(int id) { return ToJson(ObjTicketListClosedRepository.GetViewHistory(id)); } [Route("api/TicketListClosedapi/GetDetailTicketByID")] [HttpGet] public HttpResponseMessage GetDetailTicketByID(int id) { return ToJson(ObjTicketListClosedRepository.GetTicketDetail(id)); } public HttpResponseMessage Post([FromBody]TicketListClosed value) { return ToJson(ObjTicketListClosedRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]TicketListClosed value) { return ToJson(ObjTicketListClosedRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(ObjTicketListClosedRepository.DeleteEntity(Id)); } } } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; import { IFinancialYear } from '../../../Model/Masters/CompanyRelated/FinancialYear'; @Pipe({ name: 'financialyearFilter' }) export class FinancialYearFilterPipe implements PipeTransform { transform(value: IFinancialYear[], filter: string): IFinancialYear[] { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter((app: IFinancialYear) => app.FromMonth != null && app.FromMonth.toLocaleLowerCase().indexOf(filter) != -1 || app.ToMonth != null && app.ToMonth.toLocaleLowerCase().indexOf(filter) != -1 || app.CurrentYear != null && app.CurrentYear.toLocaleLowerCase().indexOf(filter) != -1 || app.Nextyear != null && app.Nextyear.toLocaleLowerCase().indexOf(filter) != -1 //|| app.ProspectId != null && app.ProspectId.toLocaleLowerCase().indexOf(filter) != -1 ) : value; } } /* 1. In the first line, we are importing the PipeTransform and Pipe interfaces that we are implementing to achieve filtering functionality. 2. In the second line, we are importing the IFinancialYear interface that we created in first part to hold the list of currencys. Over here, we are also using it to hold the list of currencys that is the source data for filtering. 3. In next line, we are specifying the pipe selector/name currencyFilter through which we will use the pipe (you will find in future steps, how). 4. Next, we are creating the FinancialYearFilterPipe class that is implementing the PipeTransform interface (implementing interface means providing the body to all methods mentioned in the interface). 5. Right click on PipeTransform and select the option Go To Definition: 6. You will be landed to the pipe_transform_d.ts file where you will find the nice brief description how to use the pipe with an example and transform method that we must need to implement: 7. So let’s go back to currency.pipe.ts where can see we have transform method with first argument as IFinancialYear array and second is named as filter that is the input string to be searched in the IFinancialYear array. 8. In transform method, the first line is only to check if the filter is not null. 9. The next statement is the actual implementation of search, if you are C# developer, you can compare it to the LINQ to Object. We are calling Array’s filter method, checking through conditional operator that if any of IFinancialYear member (FirstName, LastName or Gender) is matching with currency input search string and if YES, returning the filtered result. toLocaleLowerCase method is converting string to lower case, to read more about it, click here. If there is no matching record in User list, we are returning the all rows.Now that we have our filter ready, let’s add it to */<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using VIS_Domain; using VIS_Domain.Notification; using System.Net; using System.Text.RegularExpressions; namespace VIS_Repository.Notification { public class NewsRepository : VISDbCommand, VISIBaseRepository<News> { public Int32 intAffectedRecords { get; set; } public NewsRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = NewsConstants.const_procNews_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public News GetEntityByID(Int64 entityId) { News objEntityToReturn = new News(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = NewsConstants.const_procNews_SelectById; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<News>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<News> GetEntityList() { List<News> objListToReturn = new List<News>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = NewsConstants.const_procNews_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<News>(dt); } return objListToReturn; } public string AddEntity(News entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = NewsConstants.const_procNews_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(NewsConstants.const_Field_News_Name, entityObject.News_Name); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(NewsConstants.const_Field_Description, entityObject.Description); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(NewsConstants.const_Field_IsNew, entityObject.IsNew); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(News entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = NewsConstants.const_procNews_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(NewsConstants.const_Field_News_Name, entityObject.News_Name); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(NewsConstants.const_Field_Description, entityObject.Description); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(NewsConstants.const_Field_IsNew, entityObject.IsNew); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<News> GetViewNews(Int64 Id) { List<News> objListToReturn = new List<News>(); List<News> objListToReturn1 = new List<News>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = NewsConstants.const_procNews_View; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<News>(dt); foreach (var item in objListToReturn) { System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>"); string str = rx.Replace(item.Description, ""); System.Text.RegularExpressions.Regex rx1 = new System.Text.RegularExpressions.Regex("&nbsp;"); string str1 = rx1.Replace(str, ""); objListToReturn1.Add(new News { Description = str1, News_Name = item.News_Name }); } } return objListToReturn1; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~NewsRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var OfficialWorkReporFilterPipe = (function () { function OfficialWorkReporFilterPipe() { } OfficialWorkReporFilterPipe.prototype.transform = function (value, filter) { filter = filter ? filter.toLocaleLowerCase() : null; return filter ? value.filter(function (app) { return app.Employee_Name != null && app.Employee_Name.toLocaleLowerCase().indexOf(filter) != -1 || app.Date != null && app.Date.toLocaleLowerCase().indexOf(filter) != -1 || app.OutTime != null && app.OutTime.toLocaleLowerCase().indexOf(filter) != -1 || app.InTime != null && app.InTime.toLocaleLowerCase().indexOf(filter) != -1 || app.Total_Time != null && app.Total_Time.toLocaleLowerCase().indexOf(filter) != -1 || app.Out_Remark != null && app.OutTime.toLocaleLowerCase().indexOf(filter) != -1 || app.In_Remark != null && app.In_Remark.toLocaleLowerCase().indexOf(filter) != -1 || app.Line_Manager != null && app.Line_Manager.toLocaleLowerCase().indexOf(filter) != -1 || app.ApprovalSentTo != null && app.ApprovalSentTo.toLocaleLowerCase().indexOf(filter) != -1 || app.Status != null && app.Status.toLocaleLowerCase().indexOf(filter) != -1 || app.ActionBy != null && app.ActionBy.toLocaleLowerCase().indexOf(filter) != -1 || app.Action_DateTime != null && app.Action_DateTime.toString().indexOf(filter) != -1; }) : value; }; OfficialWorkReporFilterPipe = __decorate([ core_1.Pipe({ name: 'officialworkreportFilter' }) ], OfficialWorkReporFilterPipe); return OfficialWorkReporFilterPipe; }()); exports.OfficialWorkReporFilterPipe = OfficialWorkReporFilterPipe; <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var SecurityKey_service_1 = require("../../../service/Masters/Configuration/SecurityKey.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var CommonHelper_service_1 = require("../../../Shared/CommonHelper.service"); var SecurityKeyComponent = (function () { function SecurityKeyComponent(fb, _SecurityKeyService, pagerService, _CommonHelperService) { this.fb = fb; this._SecurityKeyService = _SecurityKeyService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.indLoading = false; this.isDesc = false; this.column = 'Key1'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; } SecurityKeyComponent.prototype.ngOnInit = function () { this._CommonHelperService.ToogleMenu(); this.securitykey = ({ Id: 0, Key1: '', Key2: '', Key3: '', Key4: '', Key5: '', UniqueKey: '', Active: false, IsActive: false, CreatedOn: null, UpdatedOn: null, CreatedBy: '', UpdatedBy: '', }); this.LoadSecurityKey(); this.InputNavigator(); }; SecurityKeyComponent.prototype.CancelModel = function () { this.modal.dismiss(); this.securitykey = ({ Id: 0, Key1: '', Key2: '', Key3: '', Key4: '', Key5: '', UniqueKey: '', Active: false, IsActive: false, CreatedOn: null, UpdatedOn: null, CreatedBy: '', UpdatedBy: '', }); }; SecurityKeyComponent.prototype.InputNavigator = function () { $(function () { $("#Key1").keyup(function () { if ($("#Key1").val().length == 4) { $("#Key2").focus(); } }); $("#Key2").keyup(function () { if ($("#Key2").val().length == 4) { $("#Key3").focus(); } }); $("#Key3").keyup(function () { if ($("#Key3").val().length == 4) { $("#Key4").focus(); } }); $("#Key4").keyup(function () { if ($("#Key4").val().length == 4) { $("#Key5").focus(); } }); }); }; SecurityKeyComponent.prototype.SecurityKeyFilterCriteriaChange = function (value) { if (value != '[object Event]') this.SecurityKeyFilter = value; }; SecurityKeyComponent.prototype.SecurityKeySort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; SecurityKeyComponent.prototype.GenrateUniqueKey = function (formData) { var _this = this; if (formData.Key1.length == 4 && formData.Key2.length == 4 && formData.Key3.length == 4 && formData.Key4.length == 4 && formData.Key5.length == 4) { this._SecurityKeyService.GenrateSecurityKey(global_1.Global.BASE_SECURITYKEY_ENDPOINT, formData).subscribe(function (securitykeyunique) { _this.securitykey.UniqueKey = securitykeyunique; }, function (error) { _this.msg = error; }); } }; SecurityKeyComponent.prototype.LoadSecurityKey = function () { var _this = this; this.indLoading = true; this._SecurityKeyService.get(global_1.Global.BASE_SECURITYKEY_ENDPOINT) .subscribe(function (securitykeys) { _this.securitykeys = securitykeys; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchKey1 = document.getElementById("searchKey1").value; if (_this.strSearchKey1 != '') { _this.strSearchKey1 = _this.strSearchKey1.toLocaleLowerCase(); _this.securitykeys = _this.securitykeys.filter(function (x) { return x.Key1 != null && x.Key1.toLocaleLowerCase().indexOf(_this.strSearchKey1) != -1; }); } _this.strSearchKey2 = document.getElementById("searchKey2").value; if (_this.strSearchKey2 != '') { _this.strSearchKey2 = _this.strSearchKey2.toLocaleLowerCase(); _this.securitykeys = _this.securitykeys.filter(function (x) { return x.Key2 != null && x.Key2.toLocaleLowerCase().indexOf(_this.strSearchKey2) != -1; }); } _this.strSearchKey3 = document.getElementById("searchKey3").value; if (_this.strSearchKey3 != '') { _this.strSearchKey3 = _this.strSearchKey3.toLocaleLowerCase(); _this.securitykeys = _this.securitykeys.filter(function (x) { return x.Key3 != null && x.Key3.toLocaleLowerCase().indexOf(_this.strSearchKey3) != -1; }); } _this.strSearchKey4 = document.getElementById("searchKey4").value; if (_this.strSearchKey4 != '') { _this.strSearchKey4 = _this.strSearchKey4.toLocaleLowerCase(); _this.securitykeys = _this.securitykeys.filter(function (x) { return x.Key4 != null && x.Key4.toLocaleLowerCase().indexOf(_this.strSearchKey4) != -1; }); } _this.strSearchKey5 = document.getElementById("searchKey5").value; if (_this.strSearchKey5 != '') { _this.strSearchKey5 = _this.strSearchKey5.toLocaleLowerCase(); _this.securitykeys = _this.securitykeys.filter(function (x) { return x.Key5 != null && x.Key5.toLocaleLowerCase().indexOf(_this.strSearchKey5) != -1; }); } } //Logic for searching - End _this.indLoading = false; _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; SecurityKeyComponent.prototype.AddSecurityKey = function () { this.dbops = enum_1.DBOperation.create; //this.SetControlsState(true); this.modalTitle = "Add New SecurityKey"; this.modalBtnTitle = "Add"; //this.SecurityKeyFrm.reset(); this.modal.open(); }; SecurityKeyComponent.prototype.EditSecurityKey = function (id) { this.dbops = enum_1.DBOperation.update; //this.SetControlsState(true); this.modalTitle = "Edit SecurityKey"; this.modalBtnTitle = "Update"; this.securitykey = this.securitykeys.filter(function (x) { return x.Id == id; })[0]; this.modal.open(); }; SecurityKeyComponent.prototype.DeleteSecurityKey = function (id, status) { this.dbops = enum_1.DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.securitykey = this.securitykeys.filter(function (x) { return x.Id == id; })[0]; //this.SecurityKeyFrm.setValue(this.securitykey); this.modal.open(); }; SecurityKeyComponent.prototype.SetControlsState = function () { }; SecurityKeyComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; SecurityKeyComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.securitykeys); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; SecurityKeyComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; SecurityKeyComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._SecurityKeyService.post(global_1.Global.BASE_SECURITYKEY_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.CancelModel(); _this.msg = data; _this.LoadSecurityKey(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._SecurityKeyService.put(global_1.Global.BASE_SECURITYKEY_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.CancelModel(); _this.msg = data; _this.LoadSecurityKey(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._SecurityKeyService.delete(global_1.Global.BASE_SECURITYKEY_ENDPOINT, formData).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.CancelModel(); _this.msg = "SecurityKey status changed successfully."; _this.LoadSecurityKey(); } else { _this.msg = "Error has occurred while changing status of existing SecurityKey!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], SecurityKeyComponent.prototype, "modal", void 0); SecurityKeyComponent = __decorate([ core_1.Component({ providers: [SecurityKey_service_1.SecurityKeyService], templateUrl: 'app/Components/Masters/Configuration/SecurityKey.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, SecurityKey_service_1.SecurityKeyService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], SecurityKeyComponent); return SecurityKeyComponent; }()); exports.SecurityKeyComponent = SecurityKeyComponent; <file_sep>export interface IManualPointEntry { Id: number; GroupID: number; EmpName: string; Criteria: string; Points: number; Point: number; Month: Date; Remarks: string; EntityMessage: string; ForDate: Date; Type: string; Category: string; CategoryId: number; IsPerformanceBadge: boolean; CriteriaId: number; CreatedOn: Date; CreatedBy: number; UpdatedOn: Date; UpdatedBy: number; IsActive: boolean; } export interface IEmployeeTag { id: number; name: string; }<file_sep>export interface IDepartment { Id: number; Department_Name: string; } export interface IEmployee { ID: number; EmployeeName: string; } export interface ILineManager { Id: number; EmployeeName: string; } export interface ILookup { Id: number; name: string; } export interface IProductivityTracker { EntryType: string; Difference: string; Employeename: string; ForWhichDate: string; OutTime: string; InTime: string; }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using VIS_Domain.Master.Configuration; namespace VIS_Repository.Reports.Attendance { public class AttendanceAccessCardComparisionReportRepository : VISDbCommand { int intAffectedRecords; public AttendanceAccessCardComparisionReportRepository(string _connectionstring) : base(_connectionstring) { } public DataTable GetEmployee() { string mode = "Employee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = OutReportConstant.const_procAttendanceReport_SelectAll; base.objSqlCommand.Parameters.AddWithValue(OutReportConstant.const_Field_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetYear() { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceAccessCardComparisionReportConstant.const_procFinancialYear_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetAttendanceAccessCardEntryComparisionEmployeeId(AttendanceAccessCardComparisionReportParameterModel entityobject) { DataTable dt = new DataTable(); try { using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = AttendanceAccessCardComparisionReportConstant.const_procAccessCardEntry_Report; base.objSqlCommand.Parameters.AddWithValue(AttendanceAccessCardComparisionReportConstant.const_EmployeeId, entityobject.EmployeeId); base.objSqlCommand.Parameters.AddWithValue(AttendanceAccessCardComparisionReportConstant.const_FromDate, entityobject.FromDate); base.objSqlCommand.Parameters.AddWithValue(AttendanceAccessCardComparisionReportConstant.const_ToDate, entityobject.ToDate); base.objSqlCommand.Parameters.AddWithValue(AttendanceAccessCardComparisionReportConstant.const_IssueOnly, entityobject.IssueOnly); base.objSqlCommand.Parameters.AddWithValue(AttendanceAccessCardComparisionReportConstant.const_Search, entityobject.Search); base.objSqlCommand.Parameters.AddWithValue(AttendanceAccessCardComparisionReportConstant.const_LoginUserId, entityobject.LoginUserId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } } catch (Exception) { } return dt; } } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { SkillService } from '../../../service/Masters/VacancyRelated/Skill.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ISkill } from '../../../Model/Masters/VacancyRelated/Skill'; import { ISkillViewModel } from '../../../Model/Masters/VacancyRelated/Skill'; import { ISkillGroup } from '../../../Model/Masters/VacancyRelated/SkillGroup'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { IMultiSelectOption } from 'angular-2-dropdown-multiselect'; import { ISkillList } from '../../../Model/Masters/VacancyRelated/Skill'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [SkillService], templateUrl: 'app/Components/Masters/VacancyRelated/Skill.component.html' }) export class SkillComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; skills: ISkillViewModel[]; skill: ISkill; skillgroups: ISkillGroup[]; skillgroup: ISkillGroup; msg: string; indLoading: boolean = false; SkillFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; SkillFilter: string; isDesc: boolean = false; column: any = 'SkillName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; //Variables for Filter ShowHideSearch: boolean = false; strSearchSkillName: string; strSearchDescription: string; strSearchSkillGroupName: string; myOptions: IMultiSelectOption[]; IMultiSelectOption: ISkillList[]; TempLevel: string[]; ControlIsDisable: boolean; constructor(private fb: FormBuilder, private _SkillService: SkillService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } ResetModel() { this.skill = { CreatedBy: '', CreatedOn: null, Description: '', Id: 0, IsActive: false, Level: [], RatingGroup: '', SkillGroupID: 0, SkillGroupName: '', SkillName: '', Status: false, UpdatedBy: '', UpdatedOn: null, } this.IMultiSelectOption = [ { id: 0, name: '0' }, { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, { id: 5, name: '5' }, { id: 6, name: '6' }, { id: 7, name: '7' }, { id: 8, name: '8' }, { id: 9, name: '9' }, { id: 10, name: '10' }, ] } ngOnInit(): void { this._CommonHelperService.ToogleMenu(); this.LoadSkill(); this.LoadSkillGroup(); this.ResetModel(); } SkillFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.SkillFilter = value; } SkillSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadSkill(): void { this.indLoading = true; this._SkillService.get(Global.BASE_SKILL_ENDPOINT) .subscribe(skills => { this.skills = skills; //Logic for searching - start if (this.ShowHideSearch) { this.strSearchSkillName = (<HTMLInputElement>document.getElementById("searchSkillName")).value; if (this.strSearchSkillName != '') { this.strSearchSkillName = this.strSearchSkillName.toLocaleLowerCase(); this.skills = this.skills.filter ( x => x.SkillName != null && x.SkillName.toLocaleLowerCase().indexOf(this.strSearchSkillName) != -1); } this.strSearchSkillGroupName = (<HTMLInputElement>document.getElementById("searchSkillGroupName")).value; if (this.strSearchSkillGroupName != '') { this.strSearchSkillGroupName = this.strSearchSkillGroupName.toLocaleLowerCase(); this.skills = this.skills.filter ( x => x.SkillGroupName != null && x.SkillGroupName.toLocaleLowerCase().indexOf(this.strSearchSkillGroupName) != -1); } this.strSearchDescription = (<HTMLInputElement>document.getElementById("searchDescription")).value; if (this.strSearchDescription != '') { this.strSearchDescription = this.strSearchDescription.toLocaleLowerCase(); this.skills = this.skills.filter ( x => x.Description != null && x.Description.toLocaleLowerCase().indexOf(this.strSearchDescription) != -1); } } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); this.indLoading = true; this._SkillService.get(Global.BASE_SKILLGROUP_ENDPOINT) .subscribe(skillgroups => { this.skillgroups = skillgroups; this.indLoading = false; } //,error => this.msg = <any>error ); } AddSkill() { this.skill.SkillName = ''; this.skill.SkillGroupID = 0; this.skill.Description =''; this.skill.Level = []; this.skill.Status = false; this.dbops = DBOperation.create; this.modalTitle = "Add New Skill"; this.modalBtnTitle = "Add"; this.SetControlsState(false); this.modal.open(); } EditSkill(id: number) { this.dbops = DBOperation.update; this.modalTitle = "Edit Skill"; this.modalBtnTitle = "Update"; this.skill.Id = id; this.skill.SkillName = this.skills.filter(x => x.Id == id)[0].SkillName; this.skill.SkillGroupID = this.skills.filter(x => x.Id == id)[0].SkillGroupID; this.skill.Description = this.skills.filter(x => x.Id == id)[0].Description; this.skill.Status = this.skills.filter(x => x.Id == id)[0].Status; this.TempLevel = this.skills.filter(x => x.Id == id)[0].Level.toString().split(','); this.skill.Level = []; for (let item of this.TempLevel) { this.skill.Level.push(Number(item)); } this.modal.open(); } DeleteSkill(id: number, status: boolean) { this.dbops = DBOperation.delete; if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.skill.Id = id; this.skill.SkillName = this.skills.filter(x => x.Id == id)[0].SkillName; this.skill.SkillGroupID = this.skills.filter(x => x.Id == id)[0].SkillGroupID; this.skill.Description = this.skills.filter(x => x.Id == id)[0].Description; this.skill.Status = this.skills.filter(x => x.Id == id)[0].Status; this.TempLevel = this.skills.filter(x => x.Id == id)[0].Level.toString().split(','); this.skill.Level = []; for (let item of this.TempLevel) { this.skill.Level.push(Number(item)); } this.SetControlsState(true); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.ControlIsDisable = true : this.ControlIsDisable = false; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.skills); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } LoadSkillGroup() { this.indLoading = true; this._SkillService.get(Global.BASE_SKILLGROUP_ENDPOINT) .subscribe(skillgroups => { this.skillgroups = skillgroups; this.indLoading = false; // set items to json response // initialize to page 1 //this.JumpOnPage(1); //this.pager = this.pagerService.pager; //this.pagedItems = this.pagerService.pagedItems; } //,error => this.msg = <any>error ); } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: ISkill) { this.msg = ""; if (formData.SkillGroupID != 0 && formData.Level.length > 0 ) { switch (this.dbops) { case DBOperation.create: this._SkillService.post(Global.BASE_SKILL_ENDPOINT, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.ResetModel(); this.LoadSkill(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._SkillService.put(Global.BASE_SKILL_ENDPOINT, formData.Id, formData).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadSkill(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._SkillService.delete(Global.BASE_SKILL_ENDPOINT, formData.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.LoadSkill(); this.msg = "Skill status changed successfully."; } else { this.msg = "Error has occurred while changing status of existing Skill!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Masters.EmployeeLevelCriteriaSetup { public class LevelCriteriaSetup : VISBaseEntity { public long CriteriaID { get; set; } public string AliasName { get; set; } public int CalculatedOnID { get; set; } public int CategoryID { get; set; } public Boolean IsAutomatic { get; set; } public Boolean Active { get; set; } public string reference { get; set; } public Boolean IsRange { get; set; } public decimal FromLimit { get; set; } public decimal ToLimit { get; set; } public Boolean IsRepeated { get; set; } public decimal Units { get; set; } public Boolean IsOnce { get; set; } public Boolean IsPerformanceBased { get; set; } public Boolean IsPercentage { get; set; } public int Point { get; set; } public Boolean IsProgressive { get; set; } public int ProgressiveDays { get; set; } public int ProgressivePoints { get; set; } public string Category { get; set; } public string Name { get; set; } public string CriteriaType { get; set; } public string CalculatedOn { get; set; } public int SelectPoint { get; set; } public Boolean rbAutomatic { get; set; } public Boolean rbManual { get; set; } public Boolean rbRange { get; set; } public Boolean rbRepeated { get; set; } public Boolean rbOnce { get; set; } public Boolean rbPerformanceBasedType { get; set; } public Boolean rbManualType { get; set; } public Boolean rbEnabledYes { get; set; } public Boolean rbEnabledNo { get; set; } public Boolean rbProgressiveYes { get; set; } public Boolean rbProgressiveNo { get; set; } public Boolean rbCSYes { get; set; } public Boolean rbCSNo { get; set; } public string ArbCriteriaType { get; set; } public string ArbSubType { get; set; } public string ArbManualType { get; set; } public string ArbIsProgressive { get; set; } public string ArbCascading { get; set; } public DateTime dtFromDate { get; set; } public DateTime dtToDate { get; set; } public Boolean bBothYes { get; set; } public Boolean bBothNo { get; set; } public Boolean bFromYes { get; set; } public Boolean bToYes { get; set; } public long CriteriaId { get; set; }//for manual point entry //public string ArbAutomatic { get; set; } //public string ArbManual { get; set; } //public string ArbRange { get; set; } //public string ArbRepeated { get; set; } //public string ArbOnce { get; set; } //public string ArbPerformanceBasedType { get; set; } //public string ArbManualType { get; set; } //public string ArbEnabledYes { get; set; } //public string ArbEnabledNo { get; set; } //public string ArbProgressiveYes { get; set; } //public string ArbProgressiveNo { get; set; } } public static class LevelCriteriaSetupConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_LevelCriteriaSetup = "LevelCriteriaSetup"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_CriteriaID = "CriteriaID"; public const string const_Field_IsRange = "IsRange"; public const string const_Field_FromLimit = "FromLimit"; public const string const_Field_ToLimit = "ToLimit"; public const string const_Field_IsRepeated = "IsRepeated"; public const string const_Field_Units = "Units"; public const string const_Field_IsOnce = "IsOnce"; public const string const_Field_IsPerformanceBadge = "IsPerformanceBadge"; public const string const_Field_IsPercentage = "IsPercentage"; public const string const_Field_Point = "Point"; public const string const_Field_Active = "Active"; public const string const_Field_IsProgressive = "IsProgressive"; public const string const_Field_ProgressiveDays = "ProgressiveDays"; public const string const_Field_ProgressivePoints = "ProgressivePoints"; public const string const_Field_CalculatedOn = "CalculatedOn"; public const string const_Field_FromDate = "dtFromDate"; public const string const_Field_ToDate = "dtToDate"; public const string const_Field_bBothYes = "bBothYes"; public const string const_Field_bBothNo = "bBothNo"; public const string const_Field_bFromYes = "bFromYes"; public const string const_Field_bToYes = "bToYes"; public const string const_Field_CriteriaId = "CriteriaId";//for manual point entry /// <summary> /// Database table name constant. /// </summary> public const string const_Table_LevelCriteria = "LevelCriteria"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Name = "Name"; public const string const_Field_AliasName = "AliasName"; public const string const_Field_CalculatedOnID = "CalculatedOnID"; public const string const_Field_CategoryID = "CategoryID"; public const string const_Field_IsAutomatic = "IsAutomatic"; public const string const_Field_reference = "reference"; public const string const_Field_iSetupID = "iSetupID"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procLevelCriteriaSetup_Add = "procLevelCriteriaSetup_Add"; public const string const_procLevelCriteriaSetup_Update = "procLevelCriteriaSetup_Update"; public const string const_procLevelCriteriaSetup_ActiveInActive = "procLevelCriteriaSetup_ActiveInActive"; public const string const_procLevelCriteriaSetup_SelectAll = "procLevelCriteriaSetup_SelectAll"; public const string const_procLevelCriteriaSetup_SelectById = "procLevelCriteriaSetup_SelectById"; public const string const_procLevelCriteriaSetup_ForSelectCriteria = "procSelectCriteria"; public const string const_procLevelCriteriaSetup_ForSelectCalculatedOn = "procSelectCalculatedOn"; public const string const_procLevelCriteriaSetup_ForSelectCategory = "procSelectCategory"; public const string const_procLevelCriteriaSetup_LogEntry = "Levels_CascadingChange"; public const string const_procLevelCriteriaSetup_GetSetupDetails = "procGetSetupDetails"; public const string const_procLevelCriteriaSetup_GetCriteriaDetails = "procGetCriteriaDetails"; public const string const_procLevelCriteriaSetup_AddCriteriaLevel = "proc_AddCriteriaLevel"; public const string const_procManualPointEntry_GetDataByCriteriaId = "procGetDataByCriteriaId";//for manual point entry } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Repository.Reports.BusinessManagement { public class Reports_BusinessManagementRepository : VISDbCommand { public string ConnectionString { get; set; } private static Reports_BusinessManagementRepository instance = new Reports_BusinessManagementRepository(string.Empty); private Reports_BusinessManagementRepository(string _connectionstring) : base(_connectionstring) { } public static Reports_BusinessManagementRepository getInstance() { return instance; } } } <file_sep>export interface IMyTeam { EmployeeId: number; ProjectId: number; ProjectName: string; EmployeeName: string; }<file_sep>export interface IDepartment { Id: number; Department_Name: string; mode: string; } export interface IEmployee { Id: number; Employee_Name: string; mode: string; } export interface ICompany { Id: number; CompanyName: string; mode: string; } export interface ILineManager { Id: number; LineManager: string; mode: string; } export interface ICalTotalAttendance { Employee_Id: number; EmployeeCode: string; Employee_Name: string; Date: string; MMDDYYYY_DateFormat: string; Days: string; ImportRemarks: string; HoverImportRemarks: string; InId: number; In_Time: Date; OutId: number; Out_Time: Date; LunchOutId: number; LunchOut_Time: Date; LunchInId: number; LunchIn_Time: Date; OtherId: number; Other_Time: Date; TotalWorksheet_Hr: number; status: string; Total_W_Hr: string; Total_Hrs: string; diff: string; TotalId: string; ActualEntryTime: string; Grace: number; EntryType: string; } export interface IAttendanceParam { cbDeduction: false; cbMissingEntry: false; rdbmonth: false; rdbDate: false; } export interface IYear { Id: number; Month: string; Year: string; } export interface SaveDailyEntryTime { In_Mon_Fri: string; Out_Mon_Fri: string; In_Sat: string; Out_Sat: string; } export interface IEmpId { id: number; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.Notification { public class HelpTicketAdd : VISBaseEntity { /// <summary> /// HelpTicketAdd Entity Fields. /// </summary> /// public string Subject { get; set; } public string Message { get; set; } public string Remarks { get; set; } public int AssignTo { get; set; } public int AddressToGroup { get; set; } public string Priority { get; set; } public string Status { get; set; } public string FileName { get; set; } public string FileName1 { get; set; } public string FileName2 { get; set; } // for dropdown in add company master public string DepartmentHelpTicketDll { get; set; } public string SuggestionAlie { get; set; } } public static class HelpTicketAddConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_HelpTicketAdd = "HelpTicketMaster"; /// <summary> /// Database table field Name Constants." /// </summary> public const string const_Field_Subject = "Subject"; public const string const_Field_Message = "Message"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_AssignTo = "AssignTo"; public const string const_Field_AddressToGroup = "AddressToGroup"; public const string const_Field_Priority = "Priority"; public const string const_Field_Status = "Status"; public const string cons_Filed_FileName = "FileName"; public const string cons_Filed_FileName1 = "FileName"; public const string cons_Filed_FileName2 = "FileName"; public const string const_Field_SuggestionAlie = "SuggestionAlie"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procHelpTicketMaster_Add = "procHelpTicketMaster_Add"; public const string const_procHelpTicketMaster_DepartmentHelpTicketDll = "procSelectDepartmentHelpTicket"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.EmployeeLevels { public class Levels : VISBaseEntity { /// <summary> /// Levels Entity Fields. /// </summary> public int LevelNumber { get; set; } public string LevelName { get; set; } public string LevelIcon { get; set; } public int StartPoint { get; set; } public int EndPoint { get; set; } } public static class LevelsConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Levels = "Levels"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_LevelNumber = "LevelNumber"; public const string const_Field_LevelName = "LevelName"; public const string const_Field_LevelIcon = "LevelIcon"; public const string const_Field_StartPoint = "StartPoint"; public const string const_Field_EndPoint = "EndPoint"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procLevels_Add = "procLevels_Add"; public const string const_procLevels_Update = "procLevels_Update"; public const string const_procLevels_ActiveInActive = "procLevels_ActiveInActive"; public const string const_procLevels_SelectAll = "procLevels_SelectAll"; public const string const_procLevels_SelectById = "procLevels_SelectById"; } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.RFQ; namespace VIS_Repository.RFQ { public class RFQResponseRepository :VISDbCommand { public RFQResponseRepository(string _connectionstring) : base(_connectionstring) { } public List<ActionTakenBy> GetActionTaken(string UserId, bool Access) { List<ActionTakenBy> objListToReturn = new List<ActionTakenBy>(); if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ActionTakenByConstatnt.const_Field_GetActionTaken; base.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Access, Access); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<ActionTakenBy>(dt); } return objListToReturn; } public HiddenValue GetOnLoadData(string UserId, long RFQId) { HiddenValue hdnValue = new HiddenValue(); try { string str = string.Empty; long Id; if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQResponseConstant.const_Field_GetEmployeeActionId; base.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_UserId, UserId); base.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_RFQId, RFQId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); Id = Convert.ToInt64(dt.Rows[0][0].ToString()); hdnValue.hdnEmployeeId = Id; } if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } using (base.objSqlCommand.Connection) { base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQResponseConstant.const_Field_GetEmployeeNameById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); str = dt.Rows[0][0].ToString(); hdnValue.hdnEmployee = str; } return hdnValue; } catch (Exception ex) { throw; } } public void SaveAddResponse(RFQResponse RFQRes, SessionData sessionValue, long RFQId) { RFQRes.RFQ_InitialID = RFQId; if (RFQRes.IsEstimateReady == false) { RFQRes.Technology = GetTechnology(RFQRes.TechnologyIdList).ToString(); RFQRes.Timeline_Unit = RFQRes.Timeline_Unit.Substring(0, 1); RFQRes.Leadtime_Unit = RFQRes.Leadtime_Unit.Substring(0, 1); } if (RFQRes.IsChangeToAction == true) { RFQRes.ActionRequestedBy = Convert.ToInt64(RFQRes.hdnEmployeeId); RFQRes.ActionByDate = DateTime.ParseExact(RFQRes.ActionByDate.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture); } else { RFQRes.ActionRequestedBy = Convert.ToInt32(RFQRes.EmpId); RFQRes.ActionByDate = DateTime.Now; //DateTime.ParseExact(txtCurrentActionDate.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture); } RFQRes.CreatedBy = sessionValue.SessionId; InsertResponse(RFQRes); AddToPoints(RFQRes.RFQ_InitialID, RFQRes.IsEstimateReady, RFQRes.CreatedBy, GetMaxResponse()); } public void InsertResponse(RFQResponse entityObject) { try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } int intAffectedRecords; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = RFQResponseConstant.const_Field_RFQResponse_Add; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_RFQ_InitialID, entityObject.RFQ_InitialID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_IsEstimateReady, entityObject.IsEstimateReady); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Hours, entityObject.Hours); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Timeline, entityObject.Timeline); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Timeline_Unit, entityObject.Timeline_Unit); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Leadtime, entityObject.Leadtime); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Leadtime_Unit, entityObject.Leadtime_Unit); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Technology, entityObject.Technology); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_Description, entityObject.Description); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_ActionRequestedBy, entityObject.ActionRequestedBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(RFQResponseConstant.const_Field_ActionByDate, entityObject.ActionByDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (objVISDbCommand.objSqlCommand.Connection.State == ConnectionState.Closed) { objVISDbCommand.objSqlCommand.Connection.Open(); } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } catch (Exception ex) { } } //////Helper Method public string GetTechnology(List<long> tech) { string ReturnObj = string.Empty; foreach (var item in tech) { if (item != 0) { ReturnObj = ReturnObj + item.ToString() + ','; } } return ReturnObj; } public void AddToPoints(long iRFQ_InitialID, bool bIsEstimateReady, long iCreatedBy, long iResponeId) { try { // EmployeeLevelsBAL levelsBAL = new EmployeeLevelsBAL(); if (!bIsEstimateReady) { AddCriteria(iCreatedBy, "RFQ Response with Estimate", iResponeId.ToString()); } RFQInitialBase rfqInitial = GetRFQDetail(iRFQ_InitialID); if (rfqInitial != null) { if (DateTime.Now.Date <= rfqInitial.SubmittedOn.Date) { AddCriteria(iCreatedBy, "RFQ Response within Time", iResponeId.ToString()); } } } catch (Exception ex) { } } public void AddCriteria(long iEmpId, string sCriteria, string sData, decimal iRange = 0, bool isTodo = false) { try { // EmployeeLevelsBAL levelsBAL = new EmployeeLevelsBAL(); if (iRange > 0) { InsertAutomaticPoints(iEmpId, sCriteria, sData, iRange, false); } else { if (isTodo) { InsertAutomaticPoints(iEmpId, sCriteria, sData, iRange, true); } else { InsertAutomaticPoints(iEmpId, sCriteria, sData, 0, false); } } } catch (Exception ex) { } finally { } } public void InsertAutomaticPoints(long empId ,string criteria ,string forWhichData , decimal rangeCount,bool isTodo ) { try { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } int intAffectedRecords; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = AutoPointAddConstant.const_Field_Levels_AutomaticPointsEntry; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AutoPointAddConstant.const_Field_empId, empId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AutoPointAddConstant.const_Field_criteria, criteria); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AutoPointAddConstant.const_Field_forWhichData, forWhichData); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AutoPointAddConstant.const_Field_rangeCount, rangeCount); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(AutoPointAddConstant.const_Field_isTodo, isTodo); if (objVISDbCommand.objSqlCommand.Connection.State == ConnectionState.Closed) { objVISDbCommand.objSqlCommand.Connection.Open(); } intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } catch (Exception ex) { } } public long GetMaxResponse() { try { long objEntityToReturn; using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQResponseConstant.const_Field_GetMaxResponseId; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); dt.Clear(); da.Fill(dt); objEntityToReturn = Convert.ToInt64(dt.Rows[0][0].ToString()); } return objEntityToReturn; } catch (Exception exc) { throw; } } public RFQInitialBase GetRFQDetail(long Id) { try { RFQInitialBase objEntityToReturn = new RFQInitialBase(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQResponseConstant.const_Field_GetRFQDetailByRFQInitialId; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); dt.Clear(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataTable<RFQInitialBase>(dt)[0]; } return objEntityToReturn; } catch (Exception exc) { throw; } } public RFQResponse GetViewRFQResponseById(long Id) { RFQHelperRepository helper = new RFQHelperRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); try { RFQResponse objEntityToReturn = new RFQResponse(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = RFQResponseConstant.const_Field_GetRFQResponseByResponseId; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); dt.Clear(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataTable<RFQResponse>(dt)[0]; } objEntityToReturn.EmployeeName = helper.GetEmployeeNameById(objEntityToReturn.ActionRequestedBy); string[] str = objEntityToReturn.Technology.Split(','); objEntityToReturn.Technology = string.Empty; foreach (var item in str) { objEntityToReturn.Technology = objEntityToReturn.Technology+ ',' + helper.GetTechnology(item); } objEntityToReturn.Technology.Remove(0, 1); // objEntityToReturn.Technology = helper.GetTechnology(str); return objEntityToReturn; } catch (Exception exc) { throw; } } } } <file_sep>export interface IFinancialYear { Id: number; FromMonth: string; ToMonth: string; CurrentYear: string; Nextyear: string; FinancialYear: string; CreatedOn: Date; CreatedBy: number; UpdatedOn: Date; UpdatedBy: number; IsActive: boolean; EntityMessage: string; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CurrencyRelated { public class CurrencyHistory : VISBaseEntity { /// <summary> /// CurrencyHistory Entity Fields. /// </summary> public Int64 Currency_Id { get; set; } public double Default_Exch_Rate { get; set; } public double Current_Exch_Rate { get; set; } public int Month_Entered { get; set; } public int Year_Entered { get; set; } public DateTime Date_Entered { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } } public static class CurrencyHistoryConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_Currency = "CurrencyHistory"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_Currency_Id = "Currency_Id"; public const string const_Field_Default_Exch_Rate = "Default_Exch_Rate"; public const string const_Field_Current_Exch_Rate = "Current_Exch_Rate"; public const string const_Field_Month_Entered = "Month_Entered"; public const string const_Field_Year_Entered = "Year_Entered"; public const string const_Field_Date_Entered = "Date_Entered"; public const string const_Field_FromDate = "FromDate"; public const string const_Field_ToDate = "ToDate"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procCurrencyHistory_Add = "procCurrencyHistory_Add"; public const string const_procCurrencyHistory_Update = "procCurrencyHistory_Update"; public const string const_procCurrencyHistory_ActiveInActive = "procCurrencyHistory_ActiveInActive"; public const string procCurrencyHistory_SelectAll = "procCurrencyHistory_SelectAll"; public const string procCurrencyHistory_SelectById = "procCurrencyHistory_SelectById"; } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var MyTicket_service_1 = require("../../service/Notification/MyTicket.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var http_1 = require("@angular/http"); var enum_1 = require("../../Shared/enum"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); var pager_index_1 = require("../../Shared/pager.index"); var MyTicketComponent = (function () { function MyTicketComponent(fb, _MyTicketService, pagerService, http) { this.fb = fb; this._MyTicketService = _MyTicketService; this.pagerService = pagerService; this.http = http; this.indLoading = false; this.isDesc = false; this.column = 'Subject'; this.CurrentRecordsPerPage = 10; // pager object this.pager = {}; //Variables for Filter this.ShowHideSearch = false; } //file upload event MyTicketComponent.prototype.fileChange1 = function (event) { this.fileList1 = event.target.files; }; MyTicketComponent.prototype.fileChange2 = function (event) { this.fileList2 = event.target.files; }; MyTicketComponent.prototype.fileChange3 = function (event) { this.fileList3 = event.target.files; }; MyTicketComponent.prototype.ngOnInit = function () { this.MyTicketFrm = this.fb.group({ CompanyId: [''], Id: 0, Subject: [''], Message: [''], Remarks: [''], AddressToGroup: [''], AssignTo: [''], CreatedByName: [''], UpdatedByName: [''], Priority: [''], Status: [''], CreatedId: 0, CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], RecordCreatedOn: [''], RecordCreatedBy: [''], HelpTicketId: [''], FileName: [''], FileName1: [''], FileName2: [''], DepartmentHelpTicketDll: [''], SuggestionAlie: [''], SuggestionId: [''], RoleType: [''], EntityMessage: [''] }); // this.LoadGetChildGroup(21); // this.LoadOpenTicket(21); }; MyTicketComponent.prototype.MyTicketFilterCriteriaChange = function (value) { if (value != '[object Event]') this.MyTicketFilter = value; }; MyTicketComponent.prototype.MyTicketSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; //LoadMyTickets(): void { // this.indLoading = true; // this._MyTicketService.get(Global.BASE_MyTicket_ENDPOINT) // .subscribe(MyTickets => { // this.MyTickets = MyTickets; // //Logic for searching - start // if (this.ShowHideSearch) { // this.strSearchMyTicket_Name = (<HTMLInputElement>document.getElementById("searchMyTicket_Name")).value; // if (this.strSearchMyTicket_Name != '') { // this.strSearchMyTicket_Name = this.strSearchMyTicket_Name.toLocaleLowerCase(); // this.MyTickets = this.MyTickets.filter( // x => x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(this.strSearchMyTicket_Name) != -1); // } // } // //Logic for searching - End // this.indLoading = false; // // initialize to page 1 // this.JumpOnPage(1); // } // //,error => this.msg = <any>error // ); //} MyTicketComponent.prototype.LoadGetChildGroup = function (CreatedId) { var _this = this; this.indLoading = true; this._MyTicketService.getchildgroup(global_1.Global.BASE_MyTicket_ENDPOINT, CreatedId) .subscribe(function (data) { _this.MyTickets = data; //Logic for searching - start if (_this.ShowHideSearch) { _this.strSearchSubject = document.getElementById("searchSubject").value; if (_this.strSearchSubject != '') { _this.strSearchSubject = _this.strSearchSubject.toLocaleLowerCase(); _this.MyTickets = _this.MyTickets.filter(function (x) { return x.Subject != null && x.Subject.toLocaleLowerCase().indexOf(_this.strSearchSubject) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchAddressToGroup = document.getElementById("searchAddressToGroup").value; if (_this.strSearchAddressToGroup != '') { _this.strSearchAddressToGroup = _this.strSearchAddressToGroup.toLocaleLowerCase(); _this.MyTickets = _this.MyTickets.filter(function (x) { return x.AddressToGroup != null && x.AddressToGroup.toLocaleLowerCase().indexOf(_this.strSearchAddressToGroup) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchAssignTo = document.getElementById("searchAssignTo").value; if (_this.strSearchAssignTo != '') { _this.strSearchAssignTo = _this.strSearchAssignTo.toLocaleLowerCase(); _this.MyTickets = _this.MyTickets.filter(function (x) { return x.AssignTo != null && x.AssignTo.toLocaleLowerCase().indexOf(_this.strSearchAssignTo) != -1; }); } if (_this.ShowHideSearch) { _this.strSearchUpdatebyName = document.getElementById("searchUpdatedByName").value; if (_this.strSearchUpdatebyName != '') { _this.strSearchUpdatebyName = _this.strSearchUpdatebyName.toLocaleLowerCase(); _this.MyTickets = _this.MyTickets.filter(function (x) { return x.UpdatedByName != null && x.UpdatedByName.toLocaleLowerCase().indexOf(_this.strSearchUpdatebyName) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchPriority = document.getElementById("searchPriority").value; if (_this.strSearchPriority != '') { _this.strSearchPriority = _this.strSearchPriority.toLocaleLowerCase(); _this.MyTickets = _this.MyTickets.filter(function (x) { return x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(_this.strSearchPriority) != -1; }); } } if (_this.ShowHideSearch) { _this.strSearchStatus = document.getElementById("searchStatus").value; if (_this.strSearchStatus != '') { _this.strSearchStatus = _this.strSearchStatus.toLocaleLowerCase(); _this.MyTickets = _this.MyTickets.filter(function (x) { return x.Priority != null && x.Priority.toLocaleLowerCase().indexOf(_this.strSearchStatus) != -1; }); } } } //Logic for searching - End _this.indLoading = false; _this.JumpOnPage(1); }); }; MyTicketComponent.prototype.FilterByStatus = function (event) { if (event.target.value == 'Open') { this.MyTickets = this.MyTickets.filter(function (x) { return x.Status == 'Open'; }); this.JumpOnPage(1); } else if (event.target.value == 'Closed') { this.MyTickets = this.MyTickets.filter(function (x) { return x.Status == 'Closed'; }); this.JumpOnPage(1); } // this.LoadGetChildGroup(21); }; MyTicketComponent.prototype.LoadDp = function () { var _this = this; this.indLoading = true; this._MyTicketService.getDp(global_1.Global.BASE_MyTicket_ENDPOINT) .subscribe(function (DATADP) { _this.Oraganization = DATADP; }); }; MyTicketComponent.prototype.LoadViwHistory = function (id) { var _this = this; this.indLoading = true; this._MyTicketService.getViewHistory(global_1.Global.BASE_MyTicket_ENDPOINT, id) .subscribe(function (DATADP) { _this.ViewHistory = DATADP; }); }; MyTicketComponent.prototype.LoadGetTicketDetail = function (id) { var _this = this; this.indLoading = true; this._MyTicketService.getTicketDetail(global_1.Global.BASE_MyTicket_ENDPOINT, id) .subscribe(function (DATADP) { _this.GetDetail = DATADP; }); }; MyTicketComponent.prototype.addMyTicket = function () { this.LoadDp(); this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New MyTicket"; this.modalBtnTitle = "Add"; this.MyTicketFrm.reset(); this.modal.open(); }; MyTicketComponent.prototype.editMyTicket = function (Id) { this.LoadDp(); this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit MyTicket"; this.modalBtnTitle = "Update"; this.MyTicket = this.MyTickets.filter(function (x) { return x.Id == Id; })[0]; this.MyTicketFrm.setValue(this.MyTicket); this.LoadGetTicketDetail(Id); this.modal3.open(); }; MyTicketComponent.prototype.ViewMyTicket = function (Id) { this.dbops = enum_1.DBOperation.View; this.SetControlsState(true); this.modalTitle = "Conversation Ticket"; this.MyTicket = this.MyTickets.filter(function (x) { return x.Id == Id; })[0]; this.MyTicketFrm.setValue(this.MyTicket); this.LoadViwHistory(Id); this.modal1.open(); this.modal3.dismiss(); }; MyTicketComponent.prototype.deleteMyTicket = function (id, status) { this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.MyTicket = this.MyTickets.filter(function (x) { return x.Id == id; })[0]; this.MyTicketFrm.setValue(this.MyTicket); this.modal.open(); }; MyTicketComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.MyTicketFrm.enable() : this.MyTicketFrm.disable(); }; MyTicketComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; MyTicketComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.MyTickets); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; MyTicketComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; MyTicketComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: if (this.fileList1 != null) { formData._value.FileName = this.fileList1.item(0).name; } else { formData._value.FileName = null; } if (this.fileList2 != null) { formData._value.FileName1 = this.fileList2.item(0).name; } else { formData._value.FileName1 = null; } if (this.fileList3 != null) { formData._value.FileName2 = this.fileList3.item(0).name; } else { formData._value.FileName2 = null; } //formData._value.FileName = this.fileList2.item(0).name; //formData._value.FileName = this.fileList3.item(0).name; this._MyTicketService.post(global_1.Global.BASE_MyTicket_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { if (_this.fileList1 != null) { if (_this.fileList1.length > 0) { _this.fileList1.item(0).name; var file = _this.fileList1[0]; var formData_1 = new FormData(); formData_1.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; _this.http.post(apiUrl1, formData_1, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); } } else { formData._value.FileName = null; } if (_this.fileList2 != null) { if (_this.fileList2.length > 0) { _this.fileList2.item(0).name; var file = _this.fileList2[0]; var formData_2 = new FormData(); formData_2.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; _this.http.post(apiUrl1, formData_2, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); } } else { formData._value.FileName2 = null; } if (_this.fileList3 != null) { if (_this.fileList3.length > 0) { _this.fileList3.item(0).name; var file = _this.fileList3[0]; var formData_3 = new FormData(); formData_3.append('uploadFile', file, file.name); var headers = new http_1.Headers(); var options = new http_1.RequestOptions({ headers: headers }); var apiUrl1 = "/api/MyTicketapi/UploadJsonFile"; _this.http.post(apiUrl1, formData_3, options) .map(function (res) { return res.json(); }) .catch(function (error) { return Rx_1.Observable.throw(error); }) .subscribe(function (data) { return console.log('success'); }, function (error) { return console.log(error); }); } } else { formData._value.FileName3 = null; } _this.msg = data; _this.LoadGetChildGroup(21); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._MyTicketService.put(global_1.Global.BASE_MyTicket_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadGetChildGroup(21); // this.LoadMyTickets(); _this.modal3.dismiss(); } else { //alert(data); _this.msg = "Error has occurred while changing status of existing MyTicket!."; } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._MyTicketService.delete(global_1.Global.BASE_MyTicket_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "MyTicket status changed successfully."; _this.LoadGetChildGroup(21); // this.LoadMyTickets(); } else { _this.msg = "Error has occurred while changing status of existing MyTicket!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], MyTicketComponent.prototype, "modal", void 0); __decorate([ core_1.ViewChild('modal1'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], MyTicketComponent.prototype, "modal1", void 0); __decorate([ core_1.ViewChild('modal3'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], MyTicketComponent.prototype, "modal3", void 0); MyTicketComponent = __decorate([ core_1.Component({ providers: [MyTicket_service_1.MyTicketService], templateUrl: 'app/Components/Notification/MyTicket.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, MyTicket_service_1.MyTicketService, pager_index_1.PagerService, http_1.Http]) ], MyTicketComponent); return MyTicketComponent; }()); exports.MyTicketComponent = MyTicketComponent; <file_sep>export interface IEmployee { Id: number; Employee_Name: string; } export interface IBindEmployeeDetails { Id: number; Employee_Name: string; Transaction_Id: number; Entry_Type: string; Remarks: string; Entry_Time: string; forWhichDate: string; actualEntryTime: string; grace: number; } export interface IBindEmployeeAttendance { EmployeeID: number; EmployeeName: string; Date: string; InTimeID: number; InTIme: Date; OutTimeID: number; OutTIme: Date; LunchOutTimeID: number; LunchOutTIme: Date; LunchInTimeID: number; LunchInTIme: Date; OtherTimeID: number; TotalOtherTime: Date; TotalOfficeTime: Date; TotalLunchTime: Date; TotalBreakTime: Date; TotalWorkingTime: Date; TotalWorksheetHours: Date; IsInOffice: boolean; IsInBreak: boolean; IsInLunch: boolean; IsInMeeting: boolean; IsInOfficeWork: boolean; Days: string; ImportRemarks:string; EmployeeCode: string; MMDDYYYY_DateFormat: Date; CalTotalAttendance:string; } export interface IHRAttendance { HRInTime: string; HROutTime: string; Grace: number; Grade: string; } export interface IAttendance { Id: number; Employee_Id: number; Entry_Type: number; Remarks: string; Entry_Time: string; Date: string; actualEntryTime: string; grace: number; macID: string; forWhichDate: Date; IsActive: boolean; ipAddress: string; source: string; isApprove: boolean; groupId: number; attendancePolicy: string; Grade: number; ImportRemarks: string; Days: string; forWhichEntryType: number; CreatedOn: Date; UpdatedOn: Date; CreatedBy: number; UpdatedBy: number; }<file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Global = (function () { function Global() { } Global.BASE_CURRENCY_ENDPOINT = 'api/currencyapi/'; Global.BASE_VISUSER_ENDPOINT = 'api/visuserapi/'; Global.BASE_LEVELS_ENDPOINT = 'api/levelsapi/'; Global.BASE_CONTACTMASTER_ENDPOINT = 'api/contactmasterapi/'; Global.BASE_BANKMASTER_ENDPOINT = 'api/bankmasterapi/'; Global.BASE_RATINGTYPE_ENDPOINT = 'api/RatingTypeAPI/'; Global.BASE_LOOKUPTYPE_ENDPOINT = 'api/LookupTypeAPI/'; Global.BASE_LOOKUP_ENDPOINT = 'api/lookupapi/'; Global.BASE_SKILLGROUP_ENDPOINT = 'api/skillgroupapi/'; Global.BASE_FORGOTPASSWORD_ENDPOINT = 'api/VISUserAPI/'; Global.BASE_SKILL_ENDPOINT = 'api/skillapi/'; Global.BASE_POSITION_ENDPOINT = 'api/positionapi/'; Global.BASE_TECHNOLOGYMASTER_ENDPOINT = 'api/technologymasterapi/'; Global.BASE_COMPANYMASTER_ENDPOINT = 'api/companymasterapi/'; Global.BASE_MACIDCONFIGURATION_ENDPOINT = 'api/macidconfigurationapi/'; Global.BASE_SECURITYKEY_ENDPOINT = 'api/securitykeyapi/'; Global.BASE_FINANCIALYEAR_ENDPOINT = 'api/financialyearapi/'; Global.BASE_EVENTCOUNTDOWN_ENDPOINT = 'api/eventcountdownapi/'; Global.BASE_DASHBOARD_ENDPOINT = 'api/dashboardapi/'; Global.BASE_COMMONCONFIGURATION_ENDPOINT = 'api/commonconfigurationapi/'; Global.BASE_LEVELCONFIGURATION_ENDPOINT = 'api/levelconfigurationapi/'; Global.BASE_POLICY_ENDPOINT = 'api/policyapi/'; Global.BASE_CONFIGUREWORKSHEET_ENDPOINT = 'api/configureworksheetapi/'; Global.BASE_News_ENDPOINT = 'api/Newsapi/'; Global.BASE_LEVELCRITERIASETUP_ENDPOINT = 'api/levelcriteriasetupapi/'; Global.BASE_CONFIGURETICKET_ENDPOINT = 'api/configureticketapi/'; Global.BASE_HelpTicketAdd_ENDPOINT = 'api/HelpTicketAddAPI/'; Global.BASE_MyTicket_ENDPOINT = 'api/MyTicketapi/'; Global.BASE_HOMEPAGEIMAGE_ENDPOINT = 'api/homepageimageapi/'; Global.BASE_ChhangePassword_ENDPOINT = 'api/ProfileAttendanceAPI/'; Global.BASE_MyTicketListOpen_ENDPOINT = 'api/TicketListOpenapi/'; Global.BASE_MyTicketListClosed_ENDPOINT = 'api/TicketListClosedapi/'; Global.BASE_MyProfiles_ENDPOINT = 'api/MyProfilesAPI/'; Global.BASE_LeaveType_ENDPOINT = 'api/LeaveTypeapi/'; Global.BASE_GroupName_ENDPOINT = 'api/GroupNameapi/'; Global.BASE_DailyEntrysheet_ENDPOINT = 'api/DailyEntrysheetAPI/'; Global.BASE_AttendanceReport_ENDPOINT = 'api/AttendanceReportAPI/'; Global.BASE_OutReportApi_ENDPOINT = 'api/OutReportAPI/'; Global.BASE_WorkSheet_ENDPOINT = 'api/WorkSheetAPI/'; Global.BASE_MySkill_ENDPOINT = 'api/MySkillAPI/'; Global.BASE_MyTeam_ENDPOINT = 'api/MyTeamAPI/'; Global.BASE_EmployeeFeedback_ENDPOINT = 'api/EmployeeFeedbackAPI/'; Global.BASE_Levels_Achievement_ENDPOINT = 'api/Levels_AchievementAPI/'; Global.BASE_AttendanceEntry_ENDPOINT = 'api/AttendanceEntryApi/'; Global.BASE_EmployeeScreenCaptureReportAPI_ENDPOINT = 'api/EmployeeScreenCaptureReportAPI/'; Global.BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT = 'api/EmployeeDashboarHeartBeatAPI/'; Global.BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT = 'api/AttendanceAccessCardComparisionReportAPI/'; Global.BASE_EmployeeList_ENDPOINT = 'api/EmployeeListAPI/'; Global.BASE_EmpInfoTabular_ENDPOINT = 'api/EmpInfoTabularAPI/'; Global.BASE_ManualPointEntry_ENDPOINT = 'api/ManualPointEntryAPI/'; Global.BASE_LateEarlyReport_ENDPOINT = 'api/LateEarlyReportAPI/'; Global.BASE_UserRole_ENDPOINT = 'api/UserRoleAPI/'; Global.BASE_EducationType_ENDPOINT = 'api/EducationTypeAPI/'; Global.BASE_SalaryBreakupType_ENDPOINT = 'api/SalaryBreakupTypeAPI/'; Global.BASE_AddEmployeeRecord_ENDPOINT = 'api/AddEmployeeRecordAPI/'; Global.BASE_AttendanceReportNew_ENDPOINT = 'api/AttendanceReportNewAPI/'; Global.BASE_OfficialWorkReportAPI_ENDPOINT = 'api/OfficialWorkReportAPI/'; Global.BASE_ProductivityTrackerAPI_ENDPOINT = 'api/ProductivityTrackerReportAPI/'; Global.BASE_ConfigureSurveyAPI_ENDPOINT = 'api/ConfigureSurveyAPI/'; Global.BASE_RFQ_ENDPOINT = 'api/RFQAPI/'; Global.BASE_RFQResponse_ENDPOINT = 'api/RFQResponseAPI/'; Global.BASE_CurrencyHistoryAPI_ENDPOINT = 'api/CurrencyHistoryAPI/'; Global.BASE_SalaryGrievanceAPI_ENDPOINT = 'api/SalaryGrievanceAPI/'; Global.BASE_DocumentTemplateAPI_ENDPOINT = 'api/DocumentTemplateAPI/'; Global.WebAccessURL = 'http://localhost:53349'; return Global; }()); exports.Global = Global; <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var dashboard_service_1 = require("../../Service/Dashboard/dashboard.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); var pager_index_1 = require("../../Shared/pager.index"); var CommonHelper_service_1 = require("../../Shared/CommonHelper.service"); var DashboardComponent = (function () { function DashboardComponent(fb, _DashboardService, pagerService, _CommonHelperService) { this.fb = fb; this._DashboardService = _DashboardService; this.pagerService = pagerService; this._CommonHelperService = _CommonHelperService; this.indLoading = false; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; } DashboardComponent.prototype.ngOnInit = function () { this.dashboard = ({ UserProfileData: { EmployeeName: '', LineManagerName: '', FirstName: '', MiddleName: '', LastName: '', Gender: '', PhotographFileName: '', CompanyName: '', EmailID: '', Designation: '', DepartmentName: '', FatherName: '', PermenantAddress: '', CommunicationAddress: '', LandlineNumber: '', MobileNumber: '', MotherName: '', BirthDate: '', BloodGroup: '', MaritalStatus: '', EmplopyeeGrade: '' }, UserSkillData: [ { Level_Text: '', SkillName: '' }, ], MyAttendanceData: [ { Date: null, InTime: null, OutTime: null, Status: '', TotalWorksheetHours: null }, ], UserAllocationData: [ { FromDate: '', ToDate: '', AllocatedHr: 0, TotalHr: 0, ProjectName: '' }, ], UserAlertData: [ { Name: '', Status: '', Type: '' }, ], UserTeamData: [ { EmployeeId: 0, ProjectId: 0, ProjectName: '', EmployeeName: '' }, ], WorksheetLeaveDeta: { ID: 0, EmployeeID: 0, ToDate: null, FromDate: null, Reason: '', ContactDetail: '', AppliedTo: 0, LeaveType: 0, Status: 0, GHID: 0, EnteredDate: null, ResponsiblePersonID: 0, Remarks: '', IsFullDay: false, IsFirstHalf: false, IsSecondHalf: false, CreatedDate: null, contact: '', CallOnDate: null, CallOnTime: '', EmergencyLeave: false, LongleaveEntry: false }, WorksheetNwdHistoryData: [ { id: 0, employeeId: 0, date: null, leaveType: '', nwdId: 0 }, ], WorksheetCalTotalAttendanceData: { EmployeeID: 0, EmployeeName: '', Date: '', InTimeID: 0, InTime: null, OutTimeID: 0, OutTime: null, LunchOutTimeID: 0, LunchOutTime: null, LunchInTimeID: 0, LunchInTime: null, OtherTimeID: 0, TotalOtherTime: '', TotalOfficeTime: '', TotalLunchTime: '', TotalBreakTime: '', TotalWorkingTime: '', TotalWorksheetHour: 0, IsInOffice: false, IsInBreak: false, IsInLunch: false, IsInMeeting: false, IsInOfficeWork: false, Days: '', ImportRemarks: '', EmployeeCode: '', MMDDYYYY_DateFormate: '' }, WorksheetGetActualEntryTimeAndGraceData: { actualEntryTime: '', grace: 0 }, WorksheetGetEmpLeaveLedgerData: [ { leaveDuration: '', leaveType: '', approveType: '', shortLeaveType: '' }, ], WorksheetGetLeaveDetailsByDateData: [ { ID: 0, LeaveType: '', LeaveStatus: '', EmployeeId: 0, FromDate: null, ToDate: null, CalendarDays: null, IsFullDay: false, IsFirstHalf: false, IsSecondhalf: false }, ], WorksheetGetEmpHolidayListData: [ { id: 0, holidayName: '', fromDate: null, toDate: null, remarks: '', active: false, noOfDays: 0 }, ], WorksheetGetHolidayForDateData: [ { id: 0, holidayName: '', fromDate: null, toDate: null, remarks: '', active: false, noOfDays: 0 }, ], ProfileGetLevelsListData: [ { levelnumber: 0, Name: '', Icon: '', startpoint: 0, endpoint: 0 }, ], ProfileGetPointsLegendData: [ { Criteria: '', CalculatedOn: '', From: 0, To: 0, Points: 0 }, ], ProfileGetPointsDeta: [ { EventName: '', Type: false, CalculatedOn: '', PointsGained: 0, Date: '' }, ], }); this.LoadDashboards(); this.GetAttendanceDetail(); }; DashboardComponent.prototype.LoadDashboards = function () { var _this = this; this.indLoading = true; this._DashboardService.get(global_1.Global.BASE_DASHBOARD_ENDPOINT + 'GetDashboardDataSets?UserId=158&IsApproved=true&FromDate=2014-01-01&ToDate=2017-09-06&IsLineManager=true&date=2014-01-01&PunchInId=158&IsAdmin=true') .subscribe(function (dashboarddata) { debugger; _this.dashboard = dashboarddata; }); this.indLoading = false; }; DashboardComponent.prototype.GetAttendanceDetail = function () { var _this = this; this.indLoading = true; this._DashboardService.get(global_1.Global.BASE_DASHBOARD_ENDPOINT + 'GetMyAttendance?Id=158&&Date=01/01/2015') .subscribe(function (attendancedata) { _this.attendancedata = attendancedata; }); this.indLoading = false; }; DashboardComponent.prototype.ProgressiveData = function () { this.modal.open(); //this.dbops = DBOperation.create; //this.SetControlsState(true); this.modalTitle = "Progressive Point Details"; //this.modalBtnTitle = "Add"; //this.ContactMasterFrm.reset(); }; DashboardComponent.prototype.AchievementsData = function () { this.modalAchievements.open(); this.modalTitle = "Achievements Details"; }; DashboardComponent.prototype.PointsData = function () { this.modalPoints.open(); this.modalTitle = "Points Details"; }; DashboardComponent.prototype.LegendData = function () { this.modalLegend.open(); this.modalTitle = "Points Details"; }; DashboardComponent.prototype.LevelsData = function () { this.modalLevels.open(); this.modalTitle = "Employee Levels Details"; }; DashboardComponent.prototype.onSubmit = function (formData) { this.msg = ""; }; DashboardComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; DashboardComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.dashboards); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; // Function For Close Widget DashboardComponent.prototype.CloseWidgetProfile = function () { $("#adminProfile").hide(1000); }; DashboardComponent.prototype.CloseWidgetWorkSheet = function () { $("#worksheetwidget").hide(1000); }; DashboardComponent.prototype.CloseWidgetAttendance = function () { $("#MyAttendance").hide(1000); }; DashboardComponent.prototype.CloseWidgetLeave = function () { $("#MyLeave").hide(1000); }; DashboardComponent.prototype.CloseWidgetAllocation = function () { $("#MyAllocation").hide(1000); }; DashboardComponent.prototype.CloseWidgetTeam = function () { $("#MyTeam").hide(1000); }; DashboardComponent.prototype.CloseWidgetAlert = function () { $("#MyAlert").hide(1000); }; DashboardComponent.prototype.CloseWidgetSkill = function () { $("#MySkill").hide(1000); }; // Function For Collapse & Expand Widget DashboardComponent.prototype.ToogleMyProfile = function () { $("#myprofiledata").slideToggle(1000); }; DashboardComponent.prototype.ToogleWorkSheet = function () { $("#myworksheetdata").slideToggle(1000); }; DashboardComponent.prototype.ToogleAttendance = function () { $("#myattendancedata").slideToggle(1000); }; DashboardComponent.prototype.ToogleLeave = function () { $("#myleavedata").slideToggle(1000); }; DashboardComponent.prototype.ToogleAllocation = function () { $("#myallocationdata").slideToggle(1000); }; DashboardComponent.prototype.ToogleTeam = function () { $("#myteamdata").slideToggle(1000); }; DashboardComponent.prototype.ToogleAlert = function () { $("#myalertdata").slideToggle(1000); }; DashboardComponent.prototype.ToogleSkill = function () { $("#myskilldata").slideToggle(1000); }; // Function For Full Screen & Actual Size Widget DashboardComponent.prototype.MyProfileFullScreen = function () { if ($("#adminProfile").hasClass("widgetfullscreen")) { $("#adminProfile").removeClass("widgetfullscreen"); $("#myprofiledata").removeClass("widgetfullscreen"); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#adminProfile").addClass("widgetfullscreen"); $("#myprofiledata").addClass("widgetfullscreen"); $("#worksheetwidget").hide(1000); $("#MyAttendance").hide(1000); $("#MyLeave").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); } }; DashboardComponent.prototype.WorkSheetFullScreen = function () { if ($("#worksheetwidget").hasClass("widgetfullscreen")) { $("#worksheetwidget").removeClass("widgetfullscreen"); $("#myworksheetdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#worksheetwidget").addClass("widgetfullscreen"); $("#myworksheetdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyLeave").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); } }; DashboardComponent.prototype.AttendanceFullScreen = function () { if ($("#MyAttendance").hasClass("widgetfullscreen")) { $("#MyAttendance").removeClass("widgetfullscreen"); $("#myattendancedata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyAttendance").addClass("widgetfullscreen"); $("#myattendancedata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyLeave").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); } }; DashboardComponent.prototype.MyLeaveFullScreen = function () { if ($("#MyLeave").hasClass("widgetfullscreen")) { $("#MyLeave").removeClass("widgetfullscreen"); $("#myleavedata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyLeave").addClass("widgetfullscreen"); $("#myleavedata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); } }; DashboardComponent.prototype.MyAllocationFullScreen = function () { if ($("#MyAllocation").hasClass("widgetfullscreen")) { $("#MyAllocation").removeClass("widgetfullscreen"); $("#myallocationdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyAllocation").addClass("widgetfullscreen"); $("#myallocationdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } }; DashboardComponent.prototype.MyTeamFullScreen = function () { if ($("#MyTeam").hasClass("widgetfullscreen")) { $("#MyTeam").removeClass("widgetfullscreen"); $("#myteamdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyAlert").show(1000); $("#MySkill").show(1000); } else { $("#MyTeam").addClass("widgetfullscreen"); $("#myteamdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyAlert").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } }; DashboardComponent.prototype.MyAlertFullScreen = function () { if ($("#MyAlert").hasClass("widgetfullscreen")) { $("#MyAlert").removeClass("widgetfullscreen"); $("#myalertdata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MySkill").show(1000); } else { $("#MyAlert").addClass("widgetfullscreen"); $("#myalertdata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MySkill").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } }; DashboardComponent.prototype.MySkillFullScreen = function () { if ($("#MySkill").hasClass("widgetfullscreen")) { $("#MySkill").removeClass("widgetfullscreen"); $("#myskilldata").removeClass("widgetfullscreen"); $("#adminProfile").show(1000); $("#worksheetwidget").show(1000); $("#MyAttendance").show(1000); $("#MyLeave").show(1000); $("#MyAllocation").show(1000); $("#MyTeam").show(1000); $("#MyAlert").show(1000); } else { $("#MySkill").addClass("widgetfullscreen"); $("#myskilldata").addClass("widgetfullscreen"); $("#adminProfile").hide(1000); $("#MyAttendance").hide(1000); $("#MyAllocation").hide(1000); $("#MyTeam").hide(1000); $("#MyAlert").hide(1000); $("#worksheetwidget").hide(1000); $("#MyLeave").hide(1000); } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], DashboardComponent.prototype, "modal", void 0); __decorate([ core_1.ViewChild('modalAchievements'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], DashboardComponent.prototype, "modalAchievements", void 0); __decorate([ core_1.ViewChild('modalPoints'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], DashboardComponent.prototype, "modalPoints", void 0); __decorate([ core_1.ViewChild('modalLegend'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], DashboardComponent.prototype, "modalLegend", void 0); __decorate([ core_1.ViewChild('modalLevels'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], DashboardComponent.prototype, "modalLevels", void 0); DashboardComponent = __decorate([ core_1.Component({ providers: [dashboard_service_1.DashboardService], templateUrl: 'app/Components/Dashboard/dashboard.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, dashboard_service_1.DashboardService, pager_index_1.PagerService, CommonHelper_service_1.CommonHelperService]) ], DashboardComponent); return DashboardComponent; }()); exports.DashboardComponent = DashboardComponent; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { EmployeeDashboardHeartBeatReportService } from '../../../Service/Report/Attendance/EmployeeDashboardHeartBeat.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { IEmployee } from '../../../Model/Report/Attendance/EmployeeDashboardHeartBeatReport'; import { IEmployeeDashboardHeartBeat } from '../../../Model/Report/Attendance/EmployeeDashboardHeartBeatReport'; import { IParameterModel } from '../../../Model/Report/Attendance/EmployeeDashboardHeartBeatReport'; import { IYear } from '../../../Model/Report/Attendance/EmployeeDashboardHeartBeatReport'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [EmployeeDashboardHeartBeatReportService], templateUrl: 'app/Components/Report/Attendance/EmployeeDashboardHeartBeatReport.component.html' }) export class EmployeeDashboardHeartBeatReportComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; constructor(private fb: FormBuilder, private _EmployeeDashboardHeartBeatReportService: EmployeeDashboardHeartBeatReportService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } pager: any = {}; pagedItems: any[]; CurrentRecordsPerPage: number = 10; Employee: IEmployee[]; EmployeeDashboardHeartBeat: IEmployeeDashboardHeartBeat; EmployeeDashboardHeartBeats: IEmployeeDashboardHeartBeat[]; ParameterModel: IParameterModel; Year: IYear[]; modalTitle: string; InLoading: boolean; frommonth: number = new Date().getMonth() + 1; fromyear: number = new Date().getFullYear(); tomonth: number = new Date().getMonth() + 1; toyear: number = new Date().getFullYear(); fromdate: string; todate: string; ngOnInit() { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.ParameterModel = ({ EmployeeId: 0, FromDate: '', LoginUserId: 0, OrderBy: '', ToDate: '', FromMonth: '', FromYear: '', ToMonth: '', ConsolidateBy: '', ViewBy:'', ToYear: '', MonthWise: false }) this.Year = [({ CurrentYear: '' })] this.GetEmployee(); this.GetYear(); } HideShowPanel() { if ($("#rbtdate").prop("checked")) { $("#paneldatewise").show(); $("#panelmonthwise").hide(); $("#panelmonthwise2").hide(); $("#panelmonthwise3").hide(); $("#panelmonthwise4").hide(); } else { $("#paneldatewise").hide(); $("#panelmonthwise").show(); $("#panelmonthwise2").show(); $("#panelmonthwise3").show(); $("#panelmonthwise4").show(); } if ($("#rbtconsolidated").prop("checked")) { $("#panelconsolidate").show(); } else { $("#panelconsolidate").hide(); } } ToogleMyProfile() { $("#alltypeoutreportdata").slideToggle(300); } CloseWidgetProfile() { $("#alltypeoutreport").hide(300); } GetEmployee() { this._EmployeeDashboardHeartBeatReportService.getemployee(Global.BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT). subscribe(employee => { this.Employee = employee }, ); } GetYear() { this._EmployeeDashboardHeartBeatReportService.getyear(Global.BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT). subscribe(year => { this.Year = year }, ); } onSubmit(ParameterModel: IParameterModel) { if ($("#rbtconsolidated").prop("checked")) { $("#headerouttype").hide(); $("#headerstarttime").hide(); $(".inputcentetext").hide(); } else { $("#headerouttype").show(); $("#headerstarttime").show(); $(".inputcentetext").show(); } if ($("#rbtdate").prop("checked")) { ParameterModel.MonthWise = false; } else { ParameterModel.MonthWise = true; } if ($("#rbtdeatil").prop("checked")) { ParameterModel.ViewBy = 'detail'; } else { ParameterModel.ViewBy = ''; if ($("#rbtnone").prop("checked")) { ParameterModel.ConsolidateBy = 'None' } else if ($("#rbtname").prop("checked")) { ParameterModel.ConsolidateBy = 'Name' } else { ParameterModel.ConsolidateBy = 'Date' } } if ($("#rbtsortdate").prop("checked")) { ParameterModel.OrderBy = 'Date'; } else { ParameterModel.OrderBy = 'Name'; } ParameterModel.LoginUserId = 158; this.InLoading = true; this._EmployeeDashboardHeartBeatReportService.getemployeedashboardheartbeatreport(Global.BASE_EmployeeDashboarHeartBeatAPI_ENDPOINT, ParameterModel). subscribe(empdashboardheartbeat => { this.EmployeeDashboardHeartBeats = empdashboardheartbeat; this.JumpOnPage(1); $("html, body").animate({ scrollTop: 500 }, 150); this.InLoading = false; }, ); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeDashboardHeartBeats); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } }<file_sep>export interface IMyAttendance { Date: Date; Status: string; InTime: Date; OutTime: Date; TotalWorksheetHours: Date; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.Masters.CompanyRelated; using System.Web; namespace VIS_App.Controllers.Masters.CompanyRelated { public class CompanyMasterAPIController : BaseAPIController { CompanyMasterRepository objCompanyMasterRepository = null; VISIBaseRepository<CompanyMaster> CompanyMasterRepository; List<CompanyMaster> EntityList = new List<CompanyMaster>(); public CompanyMasterAPIController(VISIBaseRepository<CompanyMaster> _CompanyMasterRepository) { CompanyMasterRepository = _CompanyMasterRepository; objCompanyMasterRepository = new CompanyMasterRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } public HttpResponseMessage Get() { return ToJson(CompanyMasterRepository.GetEntityList().AsEnumerable()); } [HttpGet] [Route("api/CompanyMasterAPI/GetDesignationdllData")] public HttpResponseMessage GetDesignationdllData() { return ToJson(objCompanyMasterRepository.GetDesignation().AsEnumerable()); } [HttpGet] [Route("api/CompanyMasterAPI/GetCountrydllData")] public HttpResponseMessage GetCountrydllData() { return ToJson(objCompanyMasterRepository.GetCountry().AsEnumerable()); } [HttpGet] [Route("api/CompanyMasterAPI/GetFYdllData")] public HttpResponseMessage GetFYdllData() { return ToJson(objCompanyMasterRepository.GetFinancialYear().AsEnumerable()); } [HttpGet] [Route("api/CompanyMasterAPI/SelectHead")] public HttpResponseMessage SelectHead() { return ToJson(objCompanyMasterRepository.GetHeaddll().AsEnumerable()); } [HttpPost] [Route("api/CompanyMasterAPI/UploadJsonFile")] public HttpResponseMessage UploadJsonFile() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/Upload/CompanyMaster/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } //[HttpPost] //[Route("api/CompanyMasterAPI/FileUpload")] //public void FileUpload() //{ // var httpRequest = HttpContext.Current.Request; // if (httpRequest.Files.Count > 0) // { // } // // return ToJson(CompanyMasterRepository.AddEntity(value)); //} //[Route("api/CompanyMasterAPI/FileUpload")] //public HttpResponseMessage UploadJsonFile() //{ // HttpResponseMessage response = new HttpResponseMessage(); // var httpRequest = HttpContext.Current.Request; // if (httpRequest.Files.Count > 0) // { // foreach (string file in httpRequest.Files) // { // var postedFile = httpRequest.Files[file]; // var filePath = HttpContext.Current.Server.MapPath("~/Upload/" + postedFile.FileName); // postedFile.SaveAs(filePath); // } // } // return response; //} public HttpResponseMessage Post([FromBody]CompanyMaster value) { return ToJson(CompanyMasterRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]CompanyMaster value) { return ToJson(CompanyMasterRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(CompanyMasterRepository.DeleteEntity(Id)); } //public HttpResponseMessage GetDropdownData() //{ // return ToJson(CompanyMasterRepository.GetAllDropdownData().AsEnumerable()); //} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; using VIS_Repository.Masters.CompanyRelated; using System.Web; namespace VIS_App.Controllers.Masters.Configuration { public class HomePageImageAPIController : BaseAPIController { HomePageImageRepository objHomePageImageRepository = null; public HomePageImageAPIController() { objHomePageImageRepository = new HomePageImageRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [HttpGet] public HttpResponseMessage GetAllImage() { return ToJson(objHomePageImageRepository.GetEntityList()); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(objHomePageImageRepository.DeleteEntity(Id)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]HomePageImage value) { value.Id = Id; return ToJson(objHomePageImageRepository.UpdateEntity(value)); } [HttpGet] [Route("api/HomePageImageAPI/GetActivatHomePageImage")] public HttpResponseMessage GetActivatHomePageImage() { return ToJson(objHomePageImageRepository.GetActiveImage()); } public HttpResponseMessage Post([FromBody]HomePageImage value) { return ToJson(objHomePageImageRepository.AddEntity(value)); } [HttpPost] [Route("api/HomePageImageAPI/UploadJsonFile")] public HttpResponseMessage UploadJsonFile() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/Upload/HomePageImage/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.CompanyRelated { public class LookupType : VISBaseEntity { /// <summary> /// Lookuptype Entity Fields. /// </summary> /// public string TypeName { get; set; } } public static class LookupTypeConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_LookupType_Table = "LookupType"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_TypeName = "TypeName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procLookupType_Add = "procLookupType_Add"; public const string const_procLookupType_Update = "procLookupType_Update"; public const string const_procLookupType_ActiveInActive = "procLookupType_ActiveInActive"; public const string const_procLookupType_SelectAll = "procLookupType_SelectAll"; public const string const_procLookupType_SelectById = "procLookupType_SelectById"; } } <file_sep>export interface IEmployee { Id: number; Employee_Name: string; } export interface IYear { CurrentYear: string; } export interface IParameterModel { EmployeeId: number; FromDate: Date; ToDate: Date; ReportSort: string; Sort: number; UserId: number; UserType: string; FromMonth: string; FromYear: string; ToMonth: string; ToYear: string; MonthWise: boolean; } export interface IOfficialWorkReportBind { Employee_Name: string; Date: string; OutTime: string; InTime: string; Total_Time: string; Out_Remark: string; In_Remark: string; Line_Manager: string; ApprovalSentTo: string; Status: string; ActionBy: string; Action_DateTime: string; } <file_sep> import { Component, OnInit, ViewChild, Directive, forwardRef } from '@angular/core'; import { RFQService } from '../../Service/RFQ/RFQ.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule, FormControl, NG_VALIDATORS } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { ProspectClient,SessionValues,IRFQ, IRFQInitial, IRFQDoc, IRFQLink, ITechnology, ITechMultiCheckBox, IEmployee,IRFQDocEntity, ForSessionData} from '../../Model/RFQ/RFQEstimateListing'; import { DBOperation } from '../../Shared/enum'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../Shared/pager.index'; import { IMultiSelectOption } from 'angular-2-dropdown-multiselect'; import { DatepickerOptions } from 'ng2-datepicker'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; @Component({ providers: [RFQService], templateUrl: 'app/Components/RFQ/AddRFQ.component.html' }) export class AddRFQComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; forSessionData: ForSessionData; prospectClient: ProspectClient; prospectClientList: ProspectClient[]; sessionValues: SessionValues; RFQs: IRFQInitial; MultiTechnology: any=[]; myOptions: ITechMultiCheckBox[]; myOptionsEmp: ITechMultiCheckBox[]; MultiTechnologys: ITechMultiCheckBox; Technology: ITechnology[] = []; Employee: IEmployee[] = []; RFQDocList: IRFQDoc[] = []; RFQDoc: IRFQDoc; RFQDocEntity: IRFQDocEntity; RFQDocEntityList: IRFQDocEntity[] = []; RFQLinkList: IRFQLink[] = []; RFQLink: IRFQLink; RFQLinkEntityList: IRFQLink[] = []; RFQLinkEntity: IRFQLink; BusinessHeadDDL: IRFQInitial; BusinessManagerDDL: IRFQInitial; BusinessTypeDDL: IRFQInitial; ProjectTypeDDL: IRFQInitial; IndustriesDDL: IRFQInitial; SolutionDDL: IRFQInitial; ServiceOfferingDDL: IRFQInitial; AuthorDDL: IRFQDoc; RFQStatusDDL: IRFQInitial; FileTypeDDL: IRFQInitial; fileList: FileList fileListForAPI: FileList[] = []; msg: string; i: number; indLoading: boolean = false; ProspectHelper: boolean; sessionvar: string; ProspectClientFilter: string; CurrentRecordsPerPage: number = 10; pager: any = {}; pagedItems: any[]; CPFrm: FormGroup; SourceVal: boolean; constructor(private fb: FormBuilder, private _RFQService: RFQService, private router: Router, private pagerService: PagerService, private http: Http) { this.MultiTechnology.id = null; this.MultiTechnology.name = null; this.i = 0; } fileChangeDoc(event) { this.fileList = event.target.files; this.fileListForAPI[this.i] = this.fileList; this.i = this.i + 1; } addClient() { debugger; this.modal.open(); this.ProspectHelper = false; } ngOnInit(): void { this.CPFrm = this.fb.group({ Id: [''], CompanyName: [''], Country: [''], FilterRadioButton: [''] }); this.RFQs = ({ Id: 0, BusinessHeadId: 0, BusinessManagerId:0, Employee_Name: '', BusinessTypeId: 0, BusinessType: '', ProjectTypeId: 0, ProjectType: '', IndustryId: 0, Industries: '', SolutionId: 0, Solution: '', ServiceOfferingId: 0, ServiceOffering: '', TechnologyIdList : 0, TechnologyId: 0, TechnologyName: '', Remark: '', ResponseRequiredBy: null, SupportedBy: '', ConfidenceLevel: 0, OpportunityStatus: '', StatusId :0, RFQStatus: '', ExpectedClosureDate: null, Source: '', Title: '', ProspectClient: '', DateOfInitiation: null, UserIdList : 0, UserId: 0, ResponseRequiredFrom: 0, CreatedOn: null, CreatedBy: 0, UpdatedBy: 0, UpdatedDate: null, }); this.RFQDoc = ({ FileTypeID : 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQDocEntity = ({ FileTypeId: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQLink = ({ RemarkLink: '', UserId: 0, Password: '', URL: '' }) this.forSessionData = ({ SessionId : 0 }); this.prospectClient = ({ Id: 0, CompanyName: "", Country : "", FilterRadioButton: "" }); this.sessionValues = ({ UserType: "", UserId: 0 }) this.GetEmployee(); this.GetTechnology(); this.LoadFillBusinessHead(); this.GetBusinessManager(); this.GetBusinessType(); this.GetProjectType(); this.GetIndustries(); this.GetSolution(); this.GetServiceOffering(); this.GetFileType(); this.GetAuthor(); this.GetRFQStatus(); this.GetProspectClient(); this.ProspectHelper = true; this.SourceVal = false; } LoadFillBusinessHead(): void { this.indLoading = true; this._RFQService.FillBusinessHead(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.BusinessHeadDDL = RFQs; this.indLoading = false; }); } GetBusinessManager(): void { var UserName = sessionStorage.getItem('VISUsername'); var UserType = sessionStorage.getItem('UserType'); this.indLoading = true; this._RFQService.GetBusinessManager(Global.BASE_RFQ_ENDPOINT, UserName) .subscribe(RFQs => { this.BusinessManagerDDL = RFQs; this.indLoading = false; }); } GetBusinessType(): void { this.indLoading = true; this._RFQService.GetBusinessType(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.BusinessTypeDDL = RFQs; this.indLoading = false; }); } GetProjectType(): void { this.indLoading = true; this._RFQService.GetProjectType(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.ProjectTypeDDL = RFQs; this.indLoading = false; }); } GetIndustries(): void { this.indLoading = true; this._RFQService.GetIndustries(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.IndustriesDDL = RFQs; this.indLoading = false; }); } GetSolution(): void { this.indLoading = true; this._RFQService.GetSolution(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.SolutionDDL = RFQs; this.indLoading = false; }); } GetServiceOffering(): void { this.indLoading = true; this._RFQService.GetServiceOffering(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.ServiceOfferingDDL = RFQs; this.indLoading = false; }); } GetFileType(): void { this.indLoading = true; this._RFQService.GetFileType(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.FileTypeDDL = RFQs; this.indLoading = false; }); } GetAuthor(): void { this.indLoading = true; this._RFQService.GetAuthor(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.AuthorDDL = RFQs; this.indLoading = false; }); } GetRFQStatus(): void { this.indLoading = true; this._RFQService.GetRFQStatus(Global.BASE_RFQ_ENDPOINT) .subscribe(RFQs => { this.RFQStatusDDL = RFQs; this.indLoading = false; }); } GetTechnology(): void { this.indLoading = true; this._RFQService.GetTechnology(Global.BASE_RFQ_ENDPOINT) .subscribe(Technology => { this.Technology = Technology; this.myOptions = []; for (let item of this.Technology) { this.myOptions.push({ id: item.TechnologyId, name: item.TechnologyName }); } this.indLoading = false; }); } GetEmployee(): void { this.indLoading = true; this._RFQService.GetEmployee(Global.BASE_RFQ_ENDPOINT) .subscribe(Emp => { this.Employee = Emp; debugger this.myOptionsEmp = []; for (let item of this.Employee) { this.myOptionsEmp.push({ id : item.UserId , name: item.Employee_Name}); } debugger; this.indLoading = false; }); } GetProspectClient() { this.sessionvar = sessionStorage.getItem('IsAdmin'); this.sessionValues.UserId = +sessionStorage.getItem('Id'); // + is used for casting string to number if (this.sessionvar == "true") { this.sessionValues.UserType = "admin"; } this.sessionValues.UserType = "admin"; this.prospectClient.FilterRadioButton = "Client" var SuperProspectClient = { ProspectClient : this.prospectClient, SessionValues : this.sessionValues } this._RFQService.GetProspectClient(Global.BASE_RFQ_ENDPOINT, SuperProspectClient).subscribe( data => { this.prospectClientList = data; debugger; // initialize to page 1 this.JumpOnPage(1); }, error => { this.msg = error; } ); } onRFQInitialSubmit(formData: any) { if (this.ProspectHelper == true) { this.forSessionData.SessionId = +sessionStorage.getItem('Id'); // + is used for casting string to number var MainRFQInitial = { SessionData: this.forSessionData, RFQInitial: formData, RFQDoc: this.RFQDocEntityList, RFQLink: this.RFQLinkEntityList // RFQDoc: this.RFQDocList, //RFQLink: this.RFQLinkList } this._RFQService.post(Global.BASE_RFQ_ENDPOINT, MainRFQInitial).subscribe( data => { if (data.startsWith("Success:"))//Success { this.msg = data; if (this.fileListForAPI.length > 0) { var k = 0; for (let fileToBeUpload of this.fileListForAPI) { let file: File = fileToBeUpload[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/RFQAPI/UploadRFQDoc"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) file = null; formData = null; headers = null; options = null; k = k + 1; } this.fileListForAPI = null; } this.router.navigate(['/MyRFQ']); } else { alert(data); } }, error => { this.msg = error; } ); } else { this.ProspectHelper = true; } } onDocSubmit(formDocData: any) { if (this.fileList != null) { this.RFQDocEntity = formDocData; this.RFQDocEntity.FileName = this.fileList.item(0).name; this.RFQDocEntityList.push(this.RFQDocEntity); this.clearDoc(); } else { alert('please select Any document file') } } deleteRFQDoc(FileName: any) { var elementPos = this.RFQDocList.map(function (x) { return x.FileName; }).indexOf(FileName); this.RFQDocEntityList.splice(elementPos, 1); } onLinkSubmit(formLinkData: any) { this.RFQLinkEntity = formLinkData; this.RFQLinkEntityList.push(this.RFQLinkEntity); this.clearLink(); } deleteRFQLink(UserId: any) { var elementPos = this.RFQLinkList.map(function (x) { return x.UserId; }).indexOf(UserId); this.RFQLinkEntityList.splice(elementPos, 1); } clearDoc() { this.RFQDoc.Author = ""; this.RFQDoc.AuthorId = 0; this.RFQDoc.FileName = ""; this.RFQDoc.FileType = ""; this.RFQDoc.RemarkDoc = ""; } clearLink() { this.RFQLink.Password = ""; this.RFQLink.RemarkLink = ""; this.RFQLink.URL = ""; this.RFQLink.UserId = 0; } ProspectClientFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.ProspectClientFilter = value; } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.prospectClientList); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } addClientInForm(Id: number, CompanyName: string, Country:string) { this.RFQs.ProspectClient = CompanyName; this.SourceVal = true; this.modal.dismiss(); } ClearClient() { this.RFQs.ProspectClient = ""; this.ProspectHelper = false; this.SourceVal = false; } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { EventCountDownService } from '../../../service/Masters/Configuration/EventCountDown.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IEventCountDown } from '../../../Model/Masters/Configuration/EventCountDown'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import * as _ from 'underscore'; import { PagerService } from '../../../Shared/pager.index'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; import { DatePipe } from '@angular/common'; @Component ({ providers: [EventCountDownService], templateUrl: 'app/Components/Masters/Configuration/EventCountDown.component.html' }) export class EventCountDownComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; eventcountdowns: IEventCountDown[]; eventcountdown: IEventCountDown; msg: string; indLoading: boolean = false; EventCountDownFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; EventCountDownFilter: string; isDesc: boolean = false; column: any = 'EventName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; nums: number[]; //Variables for Filter ShowHideSearch: boolean = false; strEventName: string; strCountDownText: string; //Vaiable for For Loop No of Day //noday: number[] = new Array(200) constructor(private fb: FormBuilder, private _EventCountDownService: EventCountDownService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } Resetmodel() { this.eventcountdown = { Active: false, CountDownDate: '', CountDownDateTime: null, CountDownText: '', CountDownTime: '0', CreatedBy: '', CreatedOn: null, EventName: '', Id: 0, IsActive: false, NoOfDay: 0, UpdatedBy: '', UpdatedOn: null, CompanyId: 0, EntityMessage:'' } } ngOnInit(): void { //for (var i = 1; i < this.noday.length ; i++) //{ // //this.noday.push(i); //} this._CommonHelperService.ToogleMenu(); this.EventCountDownFrm = this.fb.group ({ Id: [''], EventName: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], CountDownText: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], CountDownDate: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], CountDownTime: ['',Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(100)])], CountDownDateTime: [''], NoOfDay: [0, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(100)])], Active: [''], IsActive: [''], CreatedOn: [''], UpdatedOn: [''], CreatedBy: [''], UpdatedBy: [''], CompanyId: [''], EntityMessage:[''] }); this.LoadEventCountDown(); } EventCountDownFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.EventCountDownFilter = value; } EventCountDownSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; LoadEventCountDown(): void { this.indLoading = true; this._EventCountDownService.get(Global.BASE_EVENTCOUNTDOWN_ENDPOINT) .subscribe(eventcountdown => { this.eventcountdowns = eventcountdown; //Logic for searching - start if (this.ShowHideSearch) { this.strEventName = (<HTMLInputElement>document.getElementById("searchEventName")).value; if (this.strEventName != '') { this.strEventName = this.strEventName.toLocaleLowerCase(); this.eventcountdowns = this.eventcountdowns.filter ( x => x.EventName != null && x.EventName.toLocaleLowerCase().indexOf(this.strEventName) != -1); } this.strCountDownText = (<HTMLInputElement>document.getElementById("searchCountDownText")).value; if (this.strCountDownText != '') { this.strCountDownText = this.strCountDownText.toLocaleLowerCase(); this.eventcountdowns = this.eventcountdowns.filter ( x => x.CountDownText != null && x.CountDownText.toLocaleLowerCase().indexOf(this.strCountDownText) != -1); } } //Logic for searching - End this.indLoading = false; this.JumpOnPage(1); } //,error => this.msg = <any>error ); } AddEventCountDown() { this.dbops = DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New Event Count Down"; this.modalBtnTitle = "Add"; this.Resetmodel(); this.EventCountDownFrm.setValue(this.eventcountdown); this.modal.open(); } EditEventCountDown(id: number) { this.dbops = DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit Event Count Down"; this.modalBtnTitle = "Update"; this.eventcountdown = this.eventcountdowns.filter(x => x.Id == id)[0]; this.eventcountdown.CountDownTime = this.eventcountdown.CountDownDateTime.substr(11, 9); this.eventcountdown.CountDownDate = this.eventcountdown.CountDownDateTime.substr(0, 10); this.EventCountDownFrm.setValue(this.eventcountdown); this.modal.open(); } DeleteEventCountDown(id: number, status: boolean) { this.dbops = DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.eventcountdown = this.eventcountdowns.filter(x => x.Id == id)[0]; this.eventcountdown.CountDownTime = this.eventcountdown.CountDownDateTime.substr(11, 9); this.eventcountdown.CountDownDate = this.eventcountdown.CountDownDateTime.substr(0, 10); this.EventCountDownFrm.setValue(this.eventcountdown); this.modal.open(); } SetControlsState(isEnable: boolean) { isEnable ? this.EventCountDownFrm.enable() : this.EventCountDownFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.eventcountdowns); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { //this.eventcountdown.CountDownDateTime = this.eventcountdown.CountDownDate + this.eventcountdown.CountDownTime; console.log(formData); // this.msg = ""; switch (this.dbops) { case DBOperation.create: this._EventCountDownService.post(Global.BASE_EVENTCOUNTDOWN_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadEventCountDown(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: this._EventCountDownService.put(Global.BASE_EVENTCOUNTDOWN_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = data; this.LoadEventCountDown(); this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._EventCountDownService.delete(Global.BASE_EVENTCOUNTDOWN_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: "))//Success { this.msg = "EventCountDown status changed successfully."; this.LoadEventCountDown(); } else { this.msg = "Error has occurred while changing status of existing EventCountDown!" } this.modal.dismiss(); }, error => { this.msg = error; } ); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain.Masters.EmployeeLevels; using VIS_Domain.Master; using VIS_Domain.Master.CompanyRelated; using VIS_Repository.Masters; using VIS_Domain; using VIS_Domain.Masters.EmployeeLevelCriteriaSetup; using System.Configuration; using VIS_Domain.Master.EmployeeManualPointEntry; namespace VIS_Repository.Masters.EmployeeLevels { public class LevelCriteriaSetupRepository : VISDbCommand, VISIBaseRepository<LevelCriteriaSetup> { public int iSetupID = 0; public Int32 intAffectedRecords { get; set; } public LevelCriteriaSetupRepository(string _connectionstring) : base(_connectionstring) { } public IEnumerable<LevelCriteriaSetup> GetCriteria() { List<LevelCriteriaSetup> objListToReturn = new List<LevelCriteriaSetup>(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); using (objVISDbCommand.objSqlCommand.Connection) { objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_ForSelectCriteria; if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<LevelCriteriaSetup>(dt); } return objListToReturn; } // public string GetSetupIdForAchievement(int CriteriaId) { string i; List<Levels_Achievement> objListToReturn = new List<Levels_Achievement>(); using (base.objSqlCommand.Connection) { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = Levels_AchievementConstants.const_procLevels_Achievement_GetLevelSetupId; base.objSqlCommand.Parameters.AddWithValue(Levels_AchievementConstants.const_Field_CriteriaId, CriteriaId); SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); i=dt.Rows[0][0].ToString(); } return i; } public IEnumerable<LevelCriteriaSetup> GetCalculatedOn() { List<LevelCriteriaSetup> objListToReturn = new List<LevelCriteriaSetup>(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); using (objVISDbCommand.objSqlCommand.Connection) { objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_ForSelectCalculatedOn; if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<LevelCriteriaSetup>(dt); } return objListToReturn; } public IEnumerable<LevelCriteriaSetup> GetCategory() { List<LevelCriteriaSetup> objListToReturn = new List<LevelCriteriaSetup>(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); using (objVISDbCommand.objSqlCommand.Connection) { objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_ForSelectCategory; if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<LevelCriteriaSetup>(dt); } return objListToReturn; } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } //try //{ // string UpdatedBy = string.Empty; // VISDbCommand objVISDbCommand.objSqlCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); // objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetups_ActiveInActive; // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); // objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); // if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) // { // objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); // } // objVISDbCommand.objSqlCommand.Connection.Open(); // intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); // objSqlCommand.Connection.Close(); // string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; // return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); //} //catch (Exception ex) //{ // return ex.Message + Environment.NewLine + ex.StackTrace; //} } public LevelCriteriaSetup GetEntityByID(Int64 entityId) { LevelCriteriaSetup objEntityToReturn = new LevelCriteriaSetup(); //using (objVISDbCommand.objSqlCommand.Connection) //{ // objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; // objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetups_SelectById; // if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) // { // objVISDbCommand.objSqlCommand.Connection.Open(); // } // SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); // DataTable dt = new DataTable(); // da.Fill(dt); // objEntityToReturn = VISAutoMapper.ConvertDataRow<LevelCriteriaSetup>(dt.Rows[0]); //} //return objEntityToReturn; return objEntityToReturn; } public IEnumerable<LevelCriteriaSetup> GetEntityList() { List<LevelCriteriaSetup> objListToReturn = new List<LevelCriteriaSetup>(); VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); using (objVISDbCommand.objSqlCommand.Connection) { objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_SelectAll; if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<LevelCriteriaSetup>(dt); } return objListToReturn; } public string AddEntity(LevelCriteriaSetup levelcriteriasetup) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_CriteriaID, levelcriteriasetup.CriteriaID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsRange, levelcriteriasetup.IsRange); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_FromLimit, levelcriteriasetup.FromLimit); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_ToLimit, levelcriteriasetup.ToLimit); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsRepeated, levelcriteriasetup.IsRepeated); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Units, levelcriteriasetup.Units); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsOnce, levelcriteriasetup.IsOnce); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsPerformanceBadge, levelcriteriasetup.IsPerformanceBased); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsPercentage, levelcriteriasetup.IsPercentage); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Point, levelcriteriasetup.Point); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Active, levelcriteriasetup.Active); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsProgressive, levelcriteriasetup.IsProgressive); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_ProgressiveDays, levelcriteriasetup.ProgressiveDays); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_ProgressivePoints, levelcriteriasetup.ProgressivePoints); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, levelcriteriasetup.CreatedBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_AliasName, levelcriteriasetup.AliasName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Name, levelcriteriasetup.Name); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_CategoryID, levelcriteriasetup.CategoryID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsAutomatic, levelcriteriasetup.IsAutomatic); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_reference, levelcriteriasetup.reference); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { // return ex.Message + Environment.NewLine + ex.StackTrace; } //SaveLevelCerteriaSetUp(entityObject); //if (entityObject.rbCSYes == "") //{ // //bool bFromYes = false, bToYes = false, bBothYes = false, bBothNo = false; // //DateTime dtFromDate = DateTime.Now.Date; // //DateTime dtToDate = DateTime.Now.Date; // //if (txtFromDate.Text != "") // //{ // // dtFromDate = DateTime.Parse(txtFromDate.Text); // //} // //if (txtToDate.Text != "") // //{ // // dtToDate = DateTime.Parse(txtToDate.Text); // //} // //if (txtFromDate.Text != "" && txtToDate.Text != "") // //{ // // bBothYes = true; // //} // //else if (txtFromDate.Text == "" && txtToDate.Text != "") // //{ // // bToYes = true; // //} // //else if (txtFromDate.Text != "" && txtToDate.Text == "") // //{ // // bFromYes = true; // //} // //else // //{ // // bBothNo = true; // //} // //levelsBAL.CascadingEffect(Convert.ToInt32(ddlCriteria.SelectedItem.Value), Convert.ToInt32(txtPoints.Text), dtFromDate, dtToDate, bBothYes, bBothNo, bFromYes, bToYes); //} return "1"; } public void LevelsPointLogEntry(LevelCriteriaSetup levelcriteriasetup) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_LogEntry; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_CriteriaID, levelcriteriasetup.CriteriaID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Point, levelcriteriasetup.Point); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_FromDate, levelcriteriasetup.dtFromDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_ToDate, levelcriteriasetup.dtToDate); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_bBothYes, levelcriteriasetup.bBothYes); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_bBothNo, levelcriteriasetup.bBothNo); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_bFromYes, levelcriteriasetup.bFromYes); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_bToYes, levelcriteriasetup.bToYes); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); } catch (Exception Ex) { } } public string UpdateEntity(LevelCriteriaSetup levelcriteriasetup) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, levelcriteriasetup.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_CriteriaID, levelcriteriasetup.CriteriaID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsRange, levelcriteriasetup.IsRange); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_FromLimit, levelcriteriasetup.FromLimit); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_ToLimit, levelcriteriasetup.ToLimit); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsRepeated, levelcriteriasetup.IsRepeated); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Units, levelcriteriasetup.Units); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsOnce, levelcriteriasetup.IsOnce); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsPerformanceBadge, levelcriteriasetup.IsPerformanceBased); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsPercentage, levelcriteriasetup.IsPercentage); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Point, levelcriteriasetup.Point); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Active, levelcriteriasetup.Active); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsProgressive, levelcriteriasetup.IsProgressive); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_ProgressiveDays, levelcriteriasetup.ProgressiveDays); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_ProgressivePoints, levelcriteriasetup.ProgressivePoints); //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, levelcriteriasetup.CreatedBy); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_AliasName, levelcriteriasetup.AliasName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_Name, levelcriteriasetup.Name); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_CategoryID, levelcriteriasetup.CategoryID); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_IsAutomatic, levelcriteriasetup.IsAutomatic); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_reference, levelcriteriasetup.reference); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, levelcriteriasetup.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return "error"; } } public LevelCriteriaSetup GetLevelCriteriaSetupByCriteriaId(int CriteriaId) { LevelCriteriaSetup objEntityToReturn = new LevelCriteriaSetup(); using (base.objSqlCommand.Connection) { if (objSqlCommand.Connection.ConnectionString == null || objSqlCommand.Connection.ConnectionString == "") { base.objSqlCommand.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString; } base.objSqlCommand.Parameters.Clear(); base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = ManualPointEntryConstants.const_procManualPointEntry_GetLevelCriteriaSetupByCriteriaId; base.objSqlCommand.Parameters.AddWithValue(ManualPointEntryConstants.const_Field_CriteriaId, CriteriaId); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<LevelCriteriaSetup>(dt.Rows[0]); } return objEntityToReturn; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~LevelCriteriaSetupRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion #region supporting methods LevelCriteriaSetup GetSetupDetails(int iSetupID) { LevelCriteriaSetup objEntityToReturn = new LevelCriteriaSetup(); try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); using (objVISDbCommand.objSqlCommand.Connection) { objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelCriteriaSetupConstants.const_procLevelCriteriaSetup_GetSetupDetails; //objVISDbCommand.objSqlCommand.Parameters.AddWithValue(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelCriteriaSetupConstants.const_Field_iSetupID, iSetupID); if (objVISDbCommand.objSqlCommand.Connection.State != ConnectionState.Open) { objVISDbCommand.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); if (dt != null) { if (dt.Rows.Count > 0) { objEntityToReturn = VISAutoMapper.ConvertDataRow<LevelCriteriaSetup>(dt.Rows[0]); } else { objEntityToReturn = null; } } //if (dt != null) //{ // objEntityToReturn = VISAutoMapper.ConvertDataRow<LevelCriteriaSetup>(dt.Rows[0]); //} //else //{ // objEntityToReturn = null; //} } //return objEntityToReturn; } catch (Exception Ex) { string error = Ex.ToString(); } return objEntityToReturn; //return db.LevelCriteriaSetups.Where(x => x.SetupID == iSetupID && x.IsActive == true).FirstOrDefault(); } #endregion } } <file_sep>export interface IMySkill { id: number; SkillID: number; mode: string; UserID: number; SkillName: string; SkillGroup: string; Skilltext: number; lookupSkilId: number; Name: string; status: string; IsApproved: boolean; }<file_sep>"use strict"; //Saurabh var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var RFQResponse_service_1 = require("../../Service/RFQ/RFQResponse.service"); var RFQ_service_1 = require("../../Service/RFQ/RFQ.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var router_1 = require("@angular/router"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../Shared/global"); //import * as _ from 'underscore'; var pager_index_1 = require("../../Shared/pager.index"); var http_1 = require("@angular/http"); var ViewRFQResponsecomponent = (function () { function ViewRFQResponsecomponent(fb, _RFQResponseService, _RFQService, router, pagerService, route, http) { this.fb = fb; this._RFQResponseService = _RFQResponseService; this._RFQService = _RFQService; this.router = router; this.pagerService = pagerService; this.route = route; this.http = http; this.indLoading = false; this.isDesc = false; this.Technology = []; this.Access = true; this.RFQDocList = []; this.RFQDocEntityList = []; this.RFQLinkList = []; this.RFQLinkEntityList = []; this.fileListForAPI = []; } ViewRFQResponsecomponent.prototype.ngOnInit = function () { this.addRFQResponse = ({ RFQ_InitialID: 0, IsEstimateReady: false, IsChangeToAction: false, Hours: 0, Timeline: 0, Timeline_Unit: '', Leadtime: 0, Leadtime_Unit: '', Technology: '', TechnologyIdList: 0, Description: '', ActionRequestedBy: 0, ActionByDate: null, EmployeeName: '', hdnEmployee: '', CurruntDate: null, hdnEmployeeId: 0, EmpId: 0 }); this.forRFQId = ({ RFQId: 0 }); this.forSessionData = ({ SessionId: 0 }); this.actionTakenBy = ({ EmpId: 0, Employee_Name: '' }); this.RFQDoc = ({ FileTypeID: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQDocEntity = ({ FileTypeId: 0, FileType: '', FileName: '', AuthorId: 0, Author: '', RemarkDoc: '' }); this.RFQLink = ({ RemarkLink: '', UserId: '', Password: '', URL: '' }); this.forSessionData.SessionId = +sessionStorage.getItem('Id'); this.LoadActionTaken(); this.GetTechnology(); this.LoadData(); this.GetRFQLink(); this.GetRFQDocument(); }; ViewRFQResponsecomponent.prototype.GetRFQLink = function () { var _this = this; this._RFQResponseService.GetRFQLink(global_1.Global.BASE_RFQResponse_ENDPOINT) .subscribe(function (RFQs) { _this.RFQLink = RFQs; }); }; ViewRFQResponsecomponent.prototype.GetRFQDocument = function () { var _this = this; this._RFQResponseService.GetRFQDocument(global_1.Global.BASE_RFQResponse_ENDPOINT) .subscribe(function (RFQs) { _this.RFQDoc = RFQs; }); }; ViewRFQResponsecomponent.prototype.LoadActionTaken = function () { var _this = this; this.indLoading = true; this._RFQResponseService.GetActionTaken(global_1.Global.BASE_RFQResponse_ENDPOINT, this.forSessionData.SessionId, this.Access) .subscribe(function (RFQs) { _this.actionTakenByList = RFQs; } //,error => this.msg = <any>error ); }; ViewRFQResponsecomponent.prototype.LoadData = function () { var _this = this; this._RFQResponseService.GetViewRFQResponseById(global_1.Global.BASE_RFQResponse_ENDPOINT, 68) //68==rfqid .subscribe(function (RFQs) { _this.addRFQResponse = RFQs; debugger; if (_this.addRFQResponse.Timeline_Unit = 'D') { _this.addRFQResponse.Timeline_Unit = 'Days'; } else if (_this.addRFQResponse.Timeline_Unit = 'W') { _this.addRFQResponse.Timeline_Unit = 'Week'; } else if (_this.addRFQResponse.Timeline_Unit = 'M') { _this.addRFQResponse.Timeline_Unit = 'Month'; } else { _this.addRFQResponse.Timeline_Unit = 'Year'; } if (_this.addRFQResponse.Leadtime_Unit = 'D') { _this.addRFQResponse.Leadtime_Unit = 'Days'; } else if (_this.addRFQResponse.Leadtime_Unit = 'W') { _this.addRFQResponse.Leadtime_Unit = 'Week'; } else if (_this.addRFQResponse.Leadtime_Unit = 'M') { _this.addRFQResponse.Leadtime_Unit = 'Month'; } else { _this.addRFQResponse.Timeline_Unit = 'Year'; } debugger; } //,error => this.msg = <any>error ); }; ViewRFQResponsecomponent.prototype.GetTechnology = function () { var _this = this; this.indLoading = true; this._RFQResponseService.GetTechnology(global_1.Global.BASE_RFQ_ENDPOINT) .subscribe(function (Technology) { _this.Technology = Technology; _this.myOptions = []; for (var _i = 0, _a = _this.Technology; _i < _a.length; _i++) { var item = _a[_i]; _this.myOptions.push({ id: item.TechnologyId, name: item.TechnologyName }); } _this.indLoading = false; }); }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], ViewRFQResponsecomponent.prototype, "modal", void 0); ViewRFQResponsecomponent = __decorate([ core_1.Component({ providers: [RFQResponse_service_1.RFQResponseService, RFQ_service_1.RFQService], templateUrl: 'app/Components/RFQ/ViewResponse.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, RFQResponse_service_1.RFQResponseService, RFQ_service_1.RFQService, router_1.Router, pager_index_1.PagerService, router_1.ActivatedRoute, http_1.Http]) ], ViewRFQResponsecomponent); return ViewRFQResponsecomponent; }()); exports.ViewRFQResponsecomponent = ViewRFQResponsecomponent; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { AttendanceAccessCardComparisionReportService } from '../../../Service/Report/Attendance/AttendanceAccessCardComparisionReport.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { IEmployee } from '../../../Model/Report/Attendance/AttendanceAccessCardComparisionReport'; import { IEmployeeAccessCardComparision } from '../../../Model/Report/Attendance/AttendanceAccessCardComparisionReport'; import { IParameterModel } from '../../../Model/Report/Attendance/AttendanceAccessCardComparisionReport'; import { IYear } from '../../../Model/Report/Attendance/AttendanceAccessCardComparisionReport'; import { CommonHelperService } from '../../../Shared/CommonHelper.service'; @Component ({ providers: [AttendanceAccessCardComparisionReportService], templateUrl: 'app/Components/Report/Attendance/AttendanceAccessCardReportComparisionReport.component.html' }) export class AttendanceAccessCardComparisionReportComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; constructor(private fb: FormBuilder, private _AttendanceAccessCardComparisionReportService: AttendanceAccessCardComparisionReportService, private pagerService: PagerService, private _CommonHelperService: CommonHelperService) { } pager: any = {}; pagedItems: any[]; CurrentRecordsPerPage: number = 10; Employee: IEmployee[]; EmployeeAccessCardComparision: IEmployeeAccessCardComparision; EmployeeAccessCardComparisions: IEmployeeAccessCardComparision[]; ParameterModel: IParameterModel; Year: IYear[]; modalTitle: string; InLoading: boolean; frommonth: number = new Date().getMonth() + 1; fromyear: number = new Date().getFullYear(); tomonth: number = new Date().getMonth() + 1; toyear: number = new Date().getFullYear(); fromdate: string; todate: string; ngOnInit() { this._CommonHelperService.ToogleMenu(); this.InLoading = false; this.Employee = [({ Id: 0, Employee_Name: '' })]; this.ParameterModel = ({ EmployeeId: 0, FromDate: '', LoginUserId: 0, OrderBy: '', ToDate: '', FromMonth: '', FromYear: '', ToMonth: '', IssueOnly: '', Search: '', ToYear: '', MonthWise: false }) this.Year = [({ CurrentYear: '' })] this.GetEmployee(); this.GetYear(); } HideShowPanel() { if ($("#rbtdate").prop("checked")) { $("#paneldatewise").show(); $("#panelmonthwise").hide(); $("#panelmonthwise2").hide(); $("#panelmonthwise3").hide(); $("#panelmonthwise4").hide(); } else { $("#paneldatewise").hide(); $("#panelmonthwise").show(); $("#panelmonthwise2").show(); $("#panelmonthwise3").show(); $("#panelmonthwise4").show(); } if ($("#rbtconsolidated").prop("checked")) { $("#panelconsolidate").show(); } else { $("#panelconsolidate").hide(); } } ToogleMyProfile() { $("#alltypeoutreportdata").slideToggle(300); } CloseWidgetProfile() { $("#alltypeoutreport").hide(300); } GetEmployee() { this._AttendanceAccessCardComparisionReportService.getemployee(Global.BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT). subscribe(employee => { this.Employee = employee }, ); } GetYear() { this._AttendanceAccessCardComparisionReportService.getyear(Global.BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT). subscribe(year => { this.Year = year }, ); } onSubmit(ParameterModel: IParameterModel) { ParameterModel.Search = ''; if ($("#rbtdate").prop("checked")) { ParameterModel.MonthWise = false; } else { ParameterModel.MonthWise = true; ParameterModel.FromMonth = this.frommonth.toString(); ParameterModel.FromYear = this.fromyear.toString(); ParameterModel.ToMonth = this.tomonth.toString(); ParameterModel.ToYear = this.toyear.toString(); } if ($("#chkissueonly").prop("checked")) { ParameterModel.IssueOnly = '1'; } else { ParameterModel.IssueOnly = '0'; } ParameterModel.LoginUserId = 158; this.EmployeeAccessCardComparisions = null; this.InLoading = true; this._AttendanceAccessCardComparisionReportService.getoutreportdata(Global.BASE_AttendanceAccessCardComparisionReportAPI_ENDPOINT, ParameterModel). subscribe(employeescreencapture => { this.EmployeeAccessCardComparisions = employeescreencapture; this.JumpOnPage(1); $("html, body").animate({ scrollTop: 310 }, 150); this.InLoading = false; }, ); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeAccessCardComparisions); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } ImportAccessCardDetail() { alert("Import Access Card Detail"); } ExportAccessCardDetail() { alert("Export Access Card Detail"); } DownloadSampleAccessCardDetail() { alert("Download Sample Access Card Detail"); } } <file_sep>export interface IEmployee { Id: number; Employee_Name: string; } export interface IYear { CurrentYear: string; } export interface IEmployeeDashboardHeartBeat { Employee_Name: string; Date: Date; OutTime: string; InTime: string; TotalTime: string; Duration: number; } export interface IParameterModel { EmployeeId: number; FromDate: string; ToDate: string; ViewBy: string; ConsolidateBy: string; OrderBy: string; LoginUserId: number; FromMonth: string; FromYear: string; ToMonth: string; ToYear: string; MonthWise: boolean; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; namespace VIS_App.Controllers.Masters.Configuration { public class MacIdConfigurationAPIController : BaseAPIController { MacIdConfigurationRepository objMacIdConfigurationRepository = null; VISIBaseRepository<MacIdConfiguration> MacIdConfigurationRepository; List<MacIdConfiguration> EntityList = new List<MacIdConfiguration>(); public MacIdConfigurationAPIController() { objMacIdConfigurationRepository = new MacIdConfigurationRepository(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); } [HttpGet] [Route("api/MacIdConfigurationAPI/Get")] public HttpResponseMessage Get() { return ToJson(objMacIdConfigurationRepository.GetEntityList().AsEnumerable()); } [HttpGet] [Route("api/MacIdConfigurationAPI/GetAllEmployees")] public HttpResponseMessage GetAllEmployees() { return ToJson(objMacIdConfigurationRepository.GetAllEmployees().AsEnumerable()); } [HttpPost] [Route("api/MacIdConfigurationAPI/Post")] public HttpResponseMessage Post([FromBody]MacIdConfiguration value) { return ToJson(objMacIdConfigurationRepository.AddEntity(value)); } [HttpPut] [Route("api/MacIdConfigurationAPI/UpdateEntity")] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]MacIdConfiguration value) { return ToJson(objMacIdConfigurationRepository.UpdateEntity(value)); } [HttpDelete] [Route("api/MacIdConfigurationAPI/DeleteEntity")] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(objMacIdConfigurationRepository.DeleteEntity(Id)); } [Route("api/MacIdConfigurationAPI/ActivateDeactivateStatus")] [HttpPost] public HttpResponseMessage ActivateDeactivateStatus(Int64 Id) { return ToJson(objMacIdConfigurationRepository.ActivateDeactivateStatus(Id)); } } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var LevelConfiguration_service_1 = require("../../../service/Masters/EmployeeLevels/LevelConfiguration.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); var enum_1 = require("../../../Shared/enum"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var LevelConfigurationComponent = (function () { function LevelConfigurationComponent(fb, _LevelConfigurationService, pagerService) { this.fb = fb; this._LevelConfigurationService = _LevelConfigurationService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'Full_Name'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; //Variables for Filter this.ShowHideSearch = false; this.ArrayYear = new Array(); } LevelConfigurationComponent.prototype.ngOnInit = function () { this.LevelConfigurationFrm = this.fb.group({ Id: [''], Period: [''], PeriodName: [''], StartDate: [''], EndDate: [''], Active: [''], IsCurrentPeriod: [''], StartYear: [''], StartMonth: [''], CompanyId: [''], CreatedOn: [''], CreatedBy: [''], UpdatedOn: [''], UpdatedBy: [''], IsActive: [''], EntityMessage: [''] }); this.LoadLevelConfigurations(); this.YearforEdit = ((new Date()).getFullYear()) - 1; }; LevelConfigurationComponent.prototype.LevelConfigurationFilterCriteriaChange = function (value) { if (value != '[object Event]') this.LevelConfigurationFilter = value; }; LevelConfigurationComponent.prototype.LevelConfigurationSort = function (property) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } }; ; LevelConfigurationComponent.prototype.LoadLevelConfigurations = function () { var _this = this; debugger; this.indLoading = true; this._LevelConfigurationService.get(global_1.Global.BASE_LEVELCONFIGURATION_ENDPOINT) .subscribe(function (LevelConfigurations) { debugger; _this.LevelConfigurations = LevelConfigurations; //Logic for searching - start if (_this.ShowHideSearch) { _this.strsearchPeriodName = document.getElementById("searchPeriodName").value; if (_this.strsearchPeriodName != '') { _this.strsearchPeriodName = _this.strsearchPeriodName.toLocaleLowerCase(); _this.LevelConfigurations = _this.LevelConfigurations.filter(function (x) { return x.PeriodName != null && x.PeriodName.toLocaleLowerCase().indexOf(_this.strsearchPeriodName) != -1; }); } } //Logic for searching - End _this.indLoading = false; // initialize to page 1 _this.JumpOnPage(1); } //,error => this.msg = <any>error ); }; LevelConfigurationComponent.prototype.FillYear = function () { this.ArrayYear = []; var displayDate = (new Date()).getFullYear(); var EndDate = displayDate; var j = 6; for (var i = 0; i < j; i++) { this.ArrayYear.push(EndDate); EndDate = EndDate + 1; } }; LevelConfigurationComponent.prototype.addLevelConfiguration = function () { this.FillYear(); this.dbops = enum_1.DBOperation.create; this.SetControlsState(true); this.modalTitle = "Add New LevelConfiguration"; this.modalBtnTitle = "Add"; this.LevelConfigurationFrm.reset(); this.modal.open(); }; LevelConfigurationComponent.prototype.editLevelConfiguration = function (id) { debugger; this.FillYear(); this.dbops = enum_1.DBOperation.update; this.SetControlsState(true); this.modalTitle = "Edit LevelConfiguration"; this.modalBtnTitle = "Update"; this.LevelConfiguration = this.LevelConfigurations.filter(function (x) { return x.Id == id; })[0]; this.LevelConfigurationFrm.setValue(this.LevelConfiguration); this.modal.open(); }; LevelConfigurationComponent.prototype.deleteLevelConfiguration = function (id, status) { this.FillYear(); this.dbops = enum_1.DBOperation.delete; this.SetControlsState(false); if (status == true) { this.modalTitle = "Confirm to Delete?"; this.modalBtnTitle = "Delete"; } else { this.modalTitle = "Confirm to Undo Delete?"; this.modalBtnTitle = "Undo Delete"; } this.LevelConfiguration = this.LevelConfigurations.filter(function (x) { return x.Id == id; })[0]; this.LevelConfigurationFrm.setValue(this.LevelConfiguration); this.modal.open(); }; LevelConfigurationComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.LevelConfigurationFrm.enable() : this.LevelConfigurationFrm.disable(); }; LevelConfigurationComponent.prototype.ChangeRecordsPerPage = function (RecordsPerPage) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } }; LevelConfigurationComponent.prototype.JumpOnPage = function (PageNumber) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.LevelConfigurations); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; }; LevelConfigurationComponent.prototype.ShowHideSearchControls = function () { this.ShowHideSearch = !this.ShowHideSearch; }; LevelConfigurationComponent.prototype.onSubmit = function (formData) { var _this = this; this.msg = ""; switch (this.dbops) { case enum_1.DBOperation.create: this._LevelConfigurationService.post(global_1.Global.BASE_LEVELCONFIGURATION_ENDPOINT, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadLevelConfigurations(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.update: this._LevelConfigurationService.put(global_1.Global.BASE_LEVELCONFIGURATION_ENDPOINT, formData._value.Id, formData._value).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = data; _this.LoadLevelConfigurations(); _this.modal.dismiss(); } else { alert(data); } }, function (error) { _this.msg = error; }); break; case enum_1.DBOperation.delete: this._LevelConfigurationService.delete(global_1.Global.BASE_LEVELCONFIGURATION_ENDPOINT, formData._value.Id).subscribe(function (data) { if (data.startsWith("Success: ")) { _this.msg = "LevelConfiguration status changed successfully."; _this.LoadLevelConfigurations(); } else { _this.msg = "Error has occurred while changing status of existing LevelConfiguration!"; } _this.modal.dismiss(); }, function (error) { _this.msg = error; }); break; } }; __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], LevelConfigurationComponent.prototype, "modal", void 0); LevelConfigurationComponent = __decorate([ core_1.Component({ providers: [LevelConfiguration_service_1.LevelConfigurationService], templateUrl: 'app/Components/Masters/EmployeeLevels/LevelConfiguration.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, LevelConfiguration_service_1.LevelConfigurationService, pager_index_1.PagerService]) ], LevelConfigurationComponent); return LevelConfigurationComponent; }()); exports.LevelConfigurationComponent = LevelConfigurationComponent; <file_sep>import { Component, OnInit, ViewChild, Directive, DirectiveDecorator } from '@angular/core'; import { ConfigureTicketService } from '../../../service/Masters/Configuration/ConfigureTicket.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IConfigureTicket } from '../../../Model/Masters/Configuration/ConfigureTicket'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { TreeModel, NodeEvent } from 'ng2-tree'; @Component ({ providers: [ConfigureTicketService], templateUrl: 'app/Components/Masters/Configuration/ConfigureTicket.component.html' }) export class ConfigureTicketComponent implements OnInit { @ViewChild('treeComponent') treeComponent; public tree: TreeModel; @ViewChild('modal') modal: ModalComponent; ticketselectedemployee: IConfigureTicket[]; ticketseeperson: IConfigureTicket[]; parentgrouplists: IConfigureTicket[]; parentgrouplist: IConfigureTicket; childgrouplist: IConfigureTicket[]; employeeheadlist: IConfigureTicket[]; configureticket: IConfigureTicket; handleSelected(event: NodeEvent) { const oopNodeController = this.treeComponent.getControllerByNodeId(2); } msg: string; indLoading: boolean = false; ConfigureTicketFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; ConfigureTicketFilter: string; isDesc: boolean = false; column: any = 'EventName'; direction: number; // pager object pager: any = {}; CurrentRecordsPerPage: number = 10; // paged items pagedItems: any[]; PagerInformation: string; nums: number[]; toStr = JSON.stringify; constructor(private fb: FormBuilder, private _ConfigureTicketService: ConfigureTicketService, private pagerService: PagerService) { } ngOnInit() { this.ticketseeperson = [({ Id: 0, CreatedOn: null, CreatedBy: '', UpdatedOn: null, UpdatedBy: '', IsActive: false, Parent_Id: 0, User_Id: 0, Department_Name: '', Position_Id: 0, IsActiveSuggestion: false, SuggestionAlie: '', Employee_Name: '', Employee_Id: 0, Flag: false, Organization_Id: 0, Suggestion_Dep_Emp_Id: 0 })]; this.configureticket = ({ Id: 0, CreatedOn: null, CreatedBy: '', UpdatedOn: null, UpdatedBy: '', IsActive: false, Parent_Id: 0, User_Id: 0, Department_Name: '', Position_Id: 0, IsActiveSuggestion: false, SuggestionAlie: '', Employee_Name: '', Employee_Id: 0, Flag: false, Organization_Id: 0, Suggestion_Dep_Emp_Id: 0 }); this.parentgrouplists = [({ CreatedBy: '', CreatedOn: null, Department_Name: '', Employee_Id: 0, Employee_Name: '', Flag: false, Id: 0, IsActive: false, IsActiveSuggestion: false, Organization_Id: 0, Parent_Id: 0, Position_Id: 0, SuggestionAlie: '', Suggestion_Dep_Emp_Id: 0, UpdatedBy: '', UpdatedOn: null, User_Id: 0 })] this.LoadEmployeeHead(); this.LoadParentGroup(); } moveItems(origin, dest) { $(origin).find(':selected').appendTo(dest); } moveAllItems(origin, dest) { $(origin).children().appendTo(dest); } moveRightAll(origin, dest) { this.moveAllItems("#ddlticket1", "#ddlticket2"); } moveLeftAll(origin, dest) { this.moveAllItems("#ddlticket2", "#ddlticket1"); } moveRight(origin, dest) { this.moveItems("#ddlticket1", "#ddlticket2"); } moveLeft(origin, dest) { this.moveItems("#ddlticket2", "#ddlticket1"); } LoadChildGroup(event) { this.indLoading = true; this._ConfigureTicketService.getchildgroup(Global.BASE_CONFIGURETICKET_ENDPOINT,event.target.value) .subscribe(data => { this.childgrouplist = data; this.indLoading = false; } ); } TicketDetail(event) { this.configureticket = this.childgrouplist.filter(x => x.Id == event.target.value)[0]; this._ConfigureTicketService.getticketdisplay(Global.BASE_CONFIGURETICKET_ENDPOINT, event.target.value) .subscribe(data => { this.ticketseeperson = data; this.indLoading = false; } ); } LoadEmployeeHead() { this.indLoading = true; this._ConfigureTicketService.getemployeehead(Global.BASE_CONFIGURETICKET_ENDPOINT) .subscribe(data => { this.employeeheadlist = data; this.indLoading = false; } ); } LoadParentGroup(): IConfigureTicket[] { this._ConfigureTicketService.getparantgroup(Global.BASE_CONFIGURETICKET_ENDPOINT) .subscribe(data => { this.parentgrouplists = data; //Static Data this.tree = { value: 'Parent value', children: [ { value: 'Child value', children: [ { value: 'child 1' }, { value: 'child 2' }, { value: 'child 3' } ] } ] }; // dynamic Data //debugger; //for (let item of this.parentgrouplists) //{ // for (let itemchild of this.parentgrouplists) // { // this.tree = // { // value: item.Department_Name, // children: // [{ // value: this.parentgrouplists[0].Department_Name, // children: // [{ // value: this.parentgrouplists[0].Department_Name // }] // }] // }; // } //} } ); return this.parentgrouplists; } SetControlsState(isEnable: boolean) { isEnable ? this.ConfigureTicketFrm.enable() : this.ConfigureTicketFrm.disable(); } onSubmit(formData: IConfigureTicket) { var id = this.configureticket.Id; this.msg = ""; this._ConfigureTicketService.put(Global.BASE_CONFIGURETICKET_ENDPOINT, id, formData).subscribe( data => { debugger; if (data.startsWith("Success: "))//Success { this.msg = "Configure ticket details updated successfully."; } else { this.msg = "Error has occurred while modifying existing Configure Ticket"; } }, error => { this.msg = error; } ); this._ConfigureTicketService.saveemployeeid(Global.BASE_CONFIGURETICKET_ENDPOINT, this.ticketseeperson).subscribe( data => { debugger; if (data.startsWith("Success: "))//Success { this.msg = "Configure ticket saved successfully."; } else { this.msg = "error has occurred while modifying existing configuration"; } }, error => { this.msg = error; } ); } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.EmployeeLevels; using VIS_Repository.Masters; namespace VIS_Repository.Masters.EmployeeLevels { public class LevelsRepository : VISDbCommand, VISIBaseRepository<Levels> { public Int32 intAffectedRecords { get; set; } public LevelsRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelsConstants.const_procLevels_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public Levels GetEntityByID(Int64 entityId) { Levels objEntityToReturn = new Levels(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LevelsConstants.const_procLevels_SelectById; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<Levels>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<Levels> GetEntityList() { List<Levels> objListToReturn = new List<Levels>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LevelsConstants.const_procLevels_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<Levels>(dt); } return objListToReturn; } public string AddEntity(Levels entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelsConstants.const_procLevels_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_EndPoint, entityObject.EndPoint); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_LevelIcon, entityObject.LevelIcon); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_LevelName, entityObject.LevelName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_LevelNumber, entityObject.LevelNumber); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_StartPoint, entityObject.StartPoint); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_CreatedBy, entityObject.CreatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(Levels entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LevelsConstants.const_procLevels_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_EndPoint, entityObject.EndPoint); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_LevelIcon, entityObject.LevelIcon); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_LevelName, entityObject.LevelName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_LevelNumber, entityObject.LevelNumber); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LevelsConstants.const_Field_StartPoint, entityObject.StartPoint); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_UpdatedBy, entityObject.UpdatedBy); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } void IDisposable.Dispose() { throw new NotImplementedException(); } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~LevelsRepository() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. //void IDisposable.Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} #endregion } } <file_sep>"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var ConfigureTicket_service_1 = require("../../../service/Masters/Configuration/ConfigureTicket.service"); var forms_1 = require("@angular/forms"); var ng2_bs3_modal_1 = require("ng2-bs3-modal/ng2-bs3-modal"); require("rxjs/add/operator/map"); require("rxjs/add/operator/catch"); require("rxjs/add/observable/throw"); // fixed typo var global_1 = require("../../../Shared/global"); var pager_index_1 = require("../../../Shared/pager.index"); var ConfigureTicketComponent = (function () { function ConfigureTicketComponent(fb, _ConfigureTicketService, pagerService) { this.fb = fb; this._ConfigureTicketService = _ConfigureTicketService; this.pagerService = pagerService; this.indLoading = false; this.isDesc = false; this.column = 'EventName'; // pager object this.pager = {}; this.CurrentRecordsPerPage = 10; this.toStr = JSON.stringify; } ConfigureTicketComponent.prototype.handleSelected = function (event) { var oopNodeController = this.treeComponent.getControllerByNodeId(2); }; ConfigureTicketComponent.prototype.ngOnInit = function () { this.ticketseeperson = [({ Id: 0, CreatedOn: null, CreatedBy: '', UpdatedOn: null, UpdatedBy: '', IsActive: false, Parent_Id: 0, User_Id: 0, Department_Name: '', Position_Id: 0, IsActiveSuggestion: false, SuggestionAlie: '', Employee_Name: '', Employee_Id: 0, Flag: false, Organization_Id: 0, Suggestion_Dep_Emp_Id: 0 })]; this.configureticket = ({ Id: 0, CreatedOn: null, CreatedBy: '', UpdatedOn: null, UpdatedBy: '', IsActive: false, Parent_Id: 0, User_Id: 0, Department_Name: '', Position_Id: 0, IsActiveSuggestion: false, SuggestionAlie: '', Employee_Name: '', Employee_Id: 0, Flag: false, Organization_Id: 0, Suggestion_Dep_Emp_Id: 0 }); this.parentgrouplists = [({ CreatedBy: '', CreatedOn: null, Department_Name: '', Employee_Id: 0, Employee_Name: '', Flag: false, Id: 0, IsActive: false, IsActiveSuggestion: false, Organization_Id: 0, Parent_Id: 0, Position_Id: 0, SuggestionAlie: '', Suggestion_Dep_Emp_Id: 0, UpdatedBy: '', UpdatedOn: null, User_Id: 0 })]; this.LoadEmployeeHead(); this.LoadParentGroup(); }; ConfigureTicketComponent.prototype.moveItems = function (origin, dest) { $(origin).find(':selected').appendTo(dest); }; ConfigureTicketComponent.prototype.moveAllItems = function (origin, dest) { $(origin).children().appendTo(dest); }; ConfigureTicketComponent.prototype.moveRightAll = function (origin, dest) { this.moveAllItems("#ddlticket1", "#ddlticket2"); }; ConfigureTicketComponent.prototype.moveLeftAll = function (origin, dest) { this.moveAllItems("#ddlticket2", "#ddlticket1"); }; ConfigureTicketComponent.prototype.moveRight = function (origin, dest) { this.moveItems("#ddlticket1", "#ddlticket2"); }; ConfigureTicketComponent.prototype.moveLeft = function (origin, dest) { this.moveItems("#ddlticket2", "#ddlticket1"); }; ConfigureTicketComponent.prototype.LoadChildGroup = function (event) { var _this = this; this.indLoading = true; this._ConfigureTicketService.getchildgroup(global_1.Global.BASE_CONFIGURETICKET_ENDPOINT, event.target.value) .subscribe(function (data) { _this.childgrouplist = data; _this.indLoading = false; }); }; ConfigureTicketComponent.prototype.TicketDetail = function (event) { var _this = this; this.configureticket = this.childgrouplist.filter(function (x) { return x.Id == event.target.value; })[0]; this._ConfigureTicketService.getticketdisplay(global_1.Global.BASE_CONFIGURETICKET_ENDPOINT, event.target.value) .subscribe(function (data) { _this.ticketseeperson = data; _this.indLoading = false; }); }; ConfigureTicketComponent.prototype.LoadEmployeeHead = function () { var _this = this; this.indLoading = true; this._ConfigureTicketService.getemployeehead(global_1.Global.BASE_CONFIGURETICKET_ENDPOINT) .subscribe(function (data) { _this.employeeheadlist = data; _this.indLoading = false; }); }; ConfigureTicketComponent.prototype.LoadParentGroup = function () { var _this = this; this._ConfigureTicketService.getparantgroup(global_1.Global.BASE_CONFIGURETICKET_ENDPOINT) .subscribe(function (data) { _this.parentgrouplists = data; //Static Data _this.tree = { value: 'Parent value', children: [ { value: 'Child value', children: [ { value: 'child 1' }, { value: 'child 2' }, { value: 'child 3' } ] } ] }; // dynamic Data //debugger; //for (let item of this.parentgrouplists) //{ // for (let itemchild of this.parentgrouplists) // { // this.tree = // { // value: item.Department_Name, // children: // [{ // value: this.parentgrouplists[0].Department_Name, // children: // [{ // value: this.parentgrouplists[0].Department_Name // }] // }] // }; // } //} }); return this.parentgrouplists; }; ConfigureTicketComponent.prototype.SetControlsState = function (isEnable) { isEnable ? this.ConfigureTicketFrm.enable() : this.ConfigureTicketFrm.disable(); }; ConfigureTicketComponent.prototype.onSubmit = function (formData) { var _this = this; var id = this.configureticket.Id; this.msg = ""; this._ConfigureTicketService.put(global_1.Global.BASE_CONFIGURETICKET_ENDPOINT, id, formData).subscribe(function (data) { debugger; if (data.startsWith("Success: ")) { _this.msg = "Configure ticket details updated successfully."; } else { _this.msg = "Error has occurred while modifying existing Configure Ticket"; } }, function (error) { _this.msg = error; }); this._ConfigureTicketService.saveemployeeid(global_1.Global.BASE_CONFIGURETICKET_ENDPOINT, this.ticketseeperson).subscribe(function (data) { debugger; if (data.startsWith("Success: ")) { _this.msg = "Configure ticket saved successfully."; } else { _this.msg = "error has occurred while modifying existing configuration"; } }, function (error) { _this.msg = error; }); }; __decorate([ core_1.ViewChild('treeComponent'), __metadata("design:type", Object) ], ConfigureTicketComponent.prototype, "treeComponent", void 0); __decorate([ core_1.ViewChild('modal'), __metadata("design:type", ng2_bs3_modal_1.ModalComponent) ], ConfigureTicketComponent.prototype, "modal", void 0); ConfigureTicketComponent = __decorate([ core_1.Component({ providers: [ConfigureTicket_service_1.ConfigureTicketService], templateUrl: 'app/Components/Masters/Configuration/ConfigureTicket.component.html' }), __metadata("design:paramtypes", [forms_1.FormBuilder, ConfigureTicket_service_1.ConfigureTicketService, pager_index_1.PagerService]) ], ConfigureTicketComponent); return ConfigureTicketComponent; }()); exports.ConfigureTicketComponent = ConfigureTicketComponent; <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { EmployeeListService } from '../../../Service/HumanResource/EmployeeManagement/EmployeeList.service'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms'; import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; import { IEmployeeList } from '../../../Model/HumanResource/EmployeeManagement/EmployeeList'; import { IEmpInfoTabular } from '../../../Model/HumanResource/EmployeeManagement/EmpInfoTabular'; import { DBOperation } from '../../../Shared/enum'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; // fixed typo import { Global } from '../../../Shared/global'; import { PagerService } from '../../../Shared/pager.index'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; @Component({ providers: [EmployeeListService], templateUrl: 'app/Components/HumanResource/EmployeeManagement/EmployeeList.component.html' }) export class EmployeeListComponent implements OnInit { @ViewChild('modal') modal: ModalComponent; EmployeeLists: IEmployeeList[]; EmployeeList: IEmployeeList; EmpInfoTabulars: IEmpInfoTabular[] EmpInfoTabular: IEmpInfoTabular MyTeamFeedbacks: IEmployeeList[]; MyTeamFeedback: IEmployeeList; msg: string; indLoading: boolean = false; EmployeeListFrm: FormGroup; dbops: DBOperation; modalTitle: string; modalBtnTitle: string; EmployeeListFilter: string; isDesc: boolean = false; column: any = ''; direction: number; CurrentRecordsPerPage: number = 10; // pager object pager: any = {}; // paged items pagedItems: any[]; PagerInformation: string; Status: string; //Variables for Filter ShowHideSearch: boolean = false; ShowHideSearchNew: boolean = false; //second table searchID: string; searchCompanyName: string; searchEmployeeName: string; searchEmail: string; searchDepartment: string; searchTotalExp: string; searchJoiningDate: string; searchRelevingDate: string; searchGrace: string; searchSL_CL: string; someValue: string; //declare id tempUserId: number = 21; tempUSertype: string = "Admin" constructor(private fb: FormBuilder, private _EmployeeListService: EmployeeListService, private pagerService: PagerService, private router: Router) { this.Status = "Active" this.someValue = "hey"; } ngOnInit(): void { this.EmployeeListFrm = this.fb.group({ CompanyId: [''], UserId: [''], Usertype: [''], Id: [''], EmployeeCode: [''], CompanyName: [''], Employee_Name: [''], Email: [''], Department: [''], TotalExp: [''], JoiningDate: [''], RelevingDate: [''], Grace: [''], SL_CL: [''], }); this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, "%"); } SaveEmployee() { alert('Fristtab'); } EmployeeListFilterCriteriaChange(value: string): void { if (value != '[object Event]') this.EmployeeListFilter = value; } EmployeeListSort(property: any) { if (!this.ShowHideSearch) { this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } LoadValue(event) { debugger; var x = ($('input[name="Status"]:checked').val()); if (x == "InActive") { if (event.target.value =="E%") { this.LoadEmployeeModeInActive(this.tempUSertype, this.tempUserId); } else { this.LoadEmployeeListInActive(this.tempUSertype, this.tempUserId, event.target.value); } } else if (x == "ALL") { if (event.target.value == "E%") { this.LoadEmployeeModeAll(this.tempUSertype, this.tempUserId); } else { this.LoadEmployeeListAll(this.tempUSertype, this.tempUserId, event.target.value); } } else { if (event.target.value == "E%") { this.LoadEmployeeModeActive(this.tempUSertype, this.tempUserId); } else { this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, event.target.value); } } } FilterByStatus(event) { if (event.target.value == "InActive") { this.LoadEmployeeListInActive(this.tempUSertype, this.tempUserId, "%"); } if (event.target.value == "ALL") { this.LoadEmployeeListAll(this.tempUSertype, this.tempUserId, "%"); } else { this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, "%"); } } LoadEmployeelistActive(Usertype: string, UserId: number, EmployeeCode: string): void { this.indLoading = true; this._EmployeeListService.GetEmployeeListActive(Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId, EmployeeCode) .subscribe(EmployeeLists => { this.EmployeeLists = EmployeeLists; if (this.ShowHideSearch) { this.searchID = (<HTMLInputElement>document.getElementById("searchID")).value; if (this.searchID != '') { this.searchID = this.searchID.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(this.searchID) != -1); } } if (this.ShowHideSearch) { this.searchCompanyName = (<HTMLInputElement>document.getElementById("searchCompanyName")).value; if (this.searchCompanyName != '') { this.searchCompanyName = this.searchCompanyName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(this.searchCompanyName) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } if (this.ShowHideSearch) { this.searchEmail = (<HTMLInputElement>document.getElementById("searchEmail")).value; if (this.searchEmail != '') { this.searchEmail = this.searchEmail.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Email != null && x.Email.toLocaleLowerCase().indexOf(this.searchEmail) != -1); } } if (this.ShowHideSearch) { this.searchDepartment = (<HTMLInputElement>document.getElementById("searchDepartment")).value; if (this.searchDepartment != '') { this.searchDepartment = this.searchDepartment.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Department != null && x.Department.toLocaleLowerCase().indexOf(this.searchDepartment) != -1); } if (this.ShowHideSearch) { this.searchTotalExp = (<HTMLInputElement>document.getElementById("searchTotalExp")).value; if (this.searchTotalExp != '') { this.searchTotalExp = this.searchTotalExp.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(this.searchTotalExp) != -1); } } } this.indLoading = false; this.JumpOnPage(1); } ); } LoadEmployeeListAll(Usertype: string, UserId: number, EmployeeCode: string): void { debugger; this.indLoading = true; this._EmployeeListService.GetEmployeeListAll(Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId, EmployeeCode) .subscribe(EmployeeLists => { this.EmployeeLists = EmployeeLists; console.log(this.EmployeeLists) if (this.ShowHideSearch) { this.searchID = (<HTMLInputElement>document.getElementById("searchID")).value; if (this.searchID != '') { this.searchID = this.searchID.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(this.searchID) != -1); } } if (this.ShowHideSearch) { this.searchCompanyName = (<HTMLInputElement>document.getElementById("searchCompanyName")).value; if (this.searchCompanyName != '') { this.searchCompanyName = this.searchCompanyName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(this.searchCompanyName) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } if (this.ShowHideSearch) { this.searchEmail = (<HTMLInputElement>document.getElementById("searchEmail")).value; if (this.searchEmail != '') { this.searchEmail = this.searchEmail.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Email != null && x.Email.toLocaleLowerCase().indexOf(this.searchEmail) != -1); } } if (this.ShowHideSearch) { this.searchDepartment = (<HTMLInputElement>document.getElementById("searchDepartment")).value; if (this.searchDepartment != '') { this.searchDepartment = this.searchDepartment.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Department != null && x.Department.toLocaleLowerCase().indexOf(this.searchDepartment) != -1); } if (this.ShowHideSearch) { this.searchTotalExp = (<HTMLInputElement>document.getElementById("searchTotalExp")).value; if (this.searchTotalExp != '') { this.searchTotalExp = this.searchTotalExp.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(this.searchTotalExp) != -1); } } } this.indLoading = false; this.JumpOnPage(1); } ); } LoadEmployeeListInActive(Usertype: string, UserId: number, EmployeeCode: string): void { debugger; this.indLoading = true; this._EmployeeListService.GetEmployeeListInActive(Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId, EmployeeCode) .subscribe(EmployeeLists => { this.EmployeeLists = EmployeeLists; console.log(this.EmployeeLists) if (this.ShowHideSearch) { this.searchID = (<HTMLInputElement>document.getElementById("searchID")).value; if (this.searchID != '') { this.searchID = this.searchID.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(this.searchID) != -1); } } if (this.ShowHideSearch) { this.searchCompanyName = (<HTMLInputElement>document.getElementById("searchCompanyName")).value; if (this.searchCompanyName != '') { this.searchCompanyName = this.searchCompanyName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(this.searchCompanyName) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } if (this.ShowHideSearch) { this.searchEmail = (<HTMLInputElement>document.getElementById("searchEmail")).value; if (this.searchEmail != '') { this.searchEmail = this.searchEmail.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Email != null && x.Email.toLocaleLowerCase().indexOf(this.searchEmail) != -1); } } if (this.ShowHideSearch) { this.searchDepartment = (<HTMLInputElement>document.getElementById("searchDepartment")).value; if (this.searchDepartment != '') { this.searchDepartment = this.searchDepartment.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Department != null && x.Department.toLocaleLowerCase().indexOf(this.searchDepartment) != -1); } if (this.ShowHideSearch) { this.searchTotalExp = (<HTMLInputElement>document.getElementById("searchTotalExp")).value; if (this.searchTotalExp != '') { this.searchTotalExp = this.searchTotalExp.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(this.searchTotalExp) != -1); } } } this.indLoading = false; this.JumpOnPage(1); } ); } LoadEmployeeModeActive(Usertype: string, UserId: number): void { this.indLoading = true; this._EmployeeListService.GetEmployeeModeActive(Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId) .subscribe(EmployeeLists => { this.EmployeeLists = EmployeeLists; console.log(this.EmployeeLists) if (this.ShowHideSearch) { this.searchID = (<HTMLInputElement>document.getElementById("searchID")).value; if (this.searchID != '') { this.searchID = this.searchID.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(this.searchID) != -1); } } if (this.ShowHideSearch) { this.searchCompanyName = (<HTMLInputElement>document.getElementById("searchCompanyName")).value; if (this.searchCompanyName != '') { this.searchCompanyName = this.searchCompanyName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(this.searchCompanyName) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } if (this.ShowHideSearch) { this.searchEmail = (<HTMLInputElement>document.getElementById("searchEmail")).value; if (this.searchEmail != '') { this.searchEmail = this.searchEmail.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Email != null && x.Email.toLocaleLowerCase().indexOf(this.searchEmail) != -1); } } if (this.ShowHideSearch) { this.searchDepartment = (<HTMLInputElement>document.getElementById("searchDepartment")).value; if (this.searchDepartment != '') { this.searchDepartment = this.searchDepartment.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Department != null && x.Department.toLocaleLowerCase().indexOf(this.searchDepartment) != -1); } if (this.ShowHideSearch) { this.searchTotalExp = (<HTMLInputElement>document.getElementById("searchTotalExp")).value; if (this.searchTotalExp != '') { this.searchTotalExp = this.searchTotalExp.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(this.searchTotalExp) != -1); } } } this.indLoading = false; this.JumpOnPage(1); } ); } LoadEmployeeModeAll(Usertype: string, UserId: number): void { debugger; this.indLoading = true; this._EmployeeListService.GetEmployeeModeAll(Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId) .subscribe(EmployeeLists => { this.EmployeeLists = EmployeeLists; console.log(this.EmployeeLists) if (this.ShowHideSearch) { this.searchID = (<HTMLInputElement>document.getElementById("searchID")).value; if (this.searchID != '') { this.searchID = this.searchID.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(this.searchID) != -1); } } if (this.ShowHideSearch) { this.searchCompanyName = (<HTMLInputElement>document.getElementById("searchCompanyName")).value; if (this.searchCompanyName != '') { this.searchCompanyName = this.searchCompanyName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(this.searchCompanyName) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } if (this.ShowHideSearch) { this.searchEmail = (<HTMLInputElement>document.getElementById("searchEmail")).value; if (this.searchEmail != '') { this.searchEmail = this.searchEmail.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Email != null && x.Email.toLocaleLowerCase().indexOf(this.searchEmail) != -1); } } if (this.ShowHideSearch) { this.searchDepartment = (<HTMLInputElement>document.getElementById("searchDepartment")).value; if (this.searchDepartment != '') { this.searchDepartment = this.searchDepartment.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Department != null && x.Department.toLocaleLowerCase().indexOf(this.searchDepartment) != -1); } if (this.ShowHideSearch) { this.searchTotalExp = (<HTMLInputElement>document.getElementById("searchTotalExp")).value; if (this.searchTotalExp != '') { this.searchTotalExp = this.searchTotalExp.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(this.searchTotalExp) != -1); } } } this.indLoading = false; this.JumpOnPage(1); } ); } LoadEmployeeModeInActive(Usertype: string, UserId: number): void { this.indLoading = true; this._EmployeeListService.GetEmployeeModeInActive(Global.BASE_EmployeeList_ENDPOINT, Usertype, UserId) .subscribe(EmployeeLists => { this.EmployeeLists = EmployeeLists; console.log(this.EmployeeLists) if (this.ShowHideSearch) { this.searchID = (<HTMLInputElement>document.getElementById("searchID")).value; if (this.searchID != '') { this.searchID = this.searchID.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.EmployeeCode != null && x.EmployeeCode.toLocaleLowerCase().indexOf(this.searchID) != -1); } } if (this.ShowHideSearch) { this.searchCompanyName = (<HTMLInputElement>document.getElementById("searchCompanyName")).value; if (this.searchCompanyName != '') { this.searchCompanyName = this.searchCompanyName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.CompanyName != null && x.CompanyName.toLocaleLowerCase().indexOf(this.searchCompanyName) != -1); } } if (this.ShowHideSearch) { this.searchEmployeeName = (<HTMLInputElement>document.getElementById("searchEmployeeName")).value; if (this.searchEmployeeName != '') { this.searchEmployeeName = this.searchEmployeeName.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Employee_Name != null && x.Employee_Name.toLocaleLowerCase().indexOf(this.searchEmployeeName) != -1); } } if (this.ShowHideSearch) { this.searchEmail = (<HTMLInputElement>document.getElementById("searchEmail")).value; if (this.searchEmail != '') { this.searchEmail = this.searchEmail.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Email != null && x.Email.toLocaleLowerCase().indexOf(this.searchEmail) != -1); } } if (this.ShowHideSearch) { this.searchDepartment = (<HTMLInputElement>document.getElementById("searchDepartment")).value; if (this.searchDepartment != '') { this.searchDepartment = this.searchDepartment.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.Department != null && x.Department.toLocaleLowerCase().indexOf(this.searchDepartment) != -1); } if (this.ShowHideSearch) { this.searchTotalExp = (<HTMLInputElement>document.getElementById("searchTotalExp")).value; if (this.searchTotalExp != '') { this.searchTotalExp = this.searchTotalExp.toLocaleLowerCase(); this.EmployeeLists = this.EmployeeLists.filter( x => x.TotalExp != null && x.TotalExp.toLocaleLowerCase().indexOf(this.searchTotalExp) != -1); } } } this.indLoading = false; this.JumpOnPage(1); } ); } addEmployeeList() { this.router.navigate(['/EmpInfoTabular']); // this.SetControlsState(true); this.modalTitle = "Add New EmployeeList"; this.modalBtnTitle = "Add"; } editEmployeeList(id: number) { debugger; // this.EmployeeList = this.EmployeeLists.filter(x => x.Id == id)[0]; this.router.navigate(['/EmpInfoTabular'], { queryParams: { UserId: id,mode:"e" } }); } deleteEmployee(id: number) { var msg1 = "Are you sure you want to Delete this Employee?"; if (confirm(msg1) == true) { this.deleteEmployeeId(id); } else { this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, "%"); } } deleteEmployeeId(id: number): void { this.indLoading = true; this._EmployeeListService.delete(Global.BASE_EmployeeList_ENDPOINT, id) .subscribe(Data => { if (Data.startsWith("Success: ")) //Success { this.msg = Data; this.LoadEmployeelistActive(this.tempUSertype, this.tempUserId, "%"); } else { alert(Data); } //Logic for searching - End this.indLoading = false; // initialize to page 1 this.JumpOnPage(1); } //,error => this.msg = <any>error ); } SetControlsState(isEnable: boolean) { isEnable ? this.EmployeeListFrm.enable() : this.EmployeeListFrm.disable(); } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.EmployeeLists); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ShowHideSearchControls() { this.ShowHideSearch = !this.ShowHideSearch; } onSubmit(formData: any) { this.msg = ""; switch (this.dbops) { case DBOperation.create: this._EmployeeListService.post(Global.BASE_EmployeeList_ENDPOINT, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.update: debugger; this._EmployeeListService.put(Global.BASE_EmployeeList_ENDPOINT, formData._value.Id, formData._value).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; case DBOperation.delete: this._EmployeeListService.delete(Global.BASE_EmployeeList_ENDPOINT, formData._value.Id).subscribe( data => { if (data.startsWith("Success: ")) //Success { this.msg = data; this.modal.dismiss(); } else { alert(data); } }, error => { this.msg = error; } ); break; } } }<file_sep>export interface IDepartment { Id: number; Department_name: string; } export interface IEmployee { Id: number; Employee_Name: string; } export interface ICompany { Id: number; CompanyName: string; } export interface ILineManager { Id: number; EmployeeName: string; } export interface IUserType { Id: number; UserType: string; } export interface IYear { Id: number; Year: string; } export interface IAttendanceReport { EmployeeId: number; EmployeeCode: number; EmployeeName: string; Date: string; forWhichDate: Date; LineManager: string; Grace: number; Grade: string; attendancePolicy: string; HR_In_Time: string; PunchIntime: Date; PunchInRemark: number; PunchInBackColor: string; PunchOuttime: Date; PunchOutRemark: number; PunchOutBackColor: string; LunchOutTime: Date; LunchOutRemark: number; LunchInTime: Date; LunchInRemark: number; OtherWork: Date; OtherWorkRemark: number; TotalOtherWork: string; WorkingHour: string; WorkingHourBackColor: string; WorkingHourFontColor: string; TotalOfficeTime: string; WorksheetHour: string; WorksheetHourBackColor: string; IsAdmin: boolean; Diff: string; Status: string; GU_BU: number; GU_BUBackColor: string; WNE: string; PC: string; PC_Remarks: string; AUPL: string; UUPL: string; CL_H: string; CL_F: string; SL_H: string; SL_F: string; In_Remarks: string; Out_Remarks: string; Lunch_Out_Remarks: string; Lunch_In_Remarks: string; Other_Out_Remarks: string; Days: string; l1: string; l2: string; l3: string; l4: string; l5: string; l6: string; l7: string; l8: string; l9: string; l10: string; Total: string; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.DocCentre { public class DocumentTemplateModel : VISBaseEntity { public Int64 DocTemplateId { get; set; } public string TemplateName { get; set; } public bool AddRecurrenceType { get; set; } public bool IsRecurrence { get; set; } public string DateFormat { get; set; } public string TemplateDescription { get; set; } public bool IsDownloadWord { get; set; } public bool IsDownloadPdf { get; set; } public bool IsDMSPdf { get; set; } public bool IsDMSWord { get; set; } public bool IsEmailPdf { get; set; } public bool IsEmailWord { get; set; } public string TemplateRightsData { get; set; } public bool IsPortrait { get; set; } public bool IsSelf { get; set; } public bool IsBehalf { get; set; } public string SharingVariableType { get; set; } public string StartingVariableRole { get; set; } public bool AllowHeader { get; set; } public bool AllowFooter { get; set; } public string HeaderContent { get; set; } public string FooterContent { get; set; } public Int64 OwnerId { get; set; } public string ContributorsId { get; set; } public bool IsApproved { get; set; } public DateTime? ApprovedOn { get; set; } public bool IsFinalSubmited { get; set; } public string ModuleId { get; set; } public string PublishDate { get; set; } public DateTime? stringDate { get; set; } public Int64 DocRightsId { get; set; } public string ModuleName { get; set; } public string EmployeeName { get; set; } public Int64 DocTemplateInProgressId { get; set; } public int EmployeeId { get; set; } } public class DocMasterFieldDataContract : VISBaseEntity { public string FieldName { get; set; } public string FieldDescription { get; set; } public string FieldType { get; set; } public string ListType { get; set; } public string DataSourceTable { get; set; } public string DataSourceColumn { get; set; } public string PageContent { get; set; } public string ImageName { get; set; } public Int32? ImageHeight { get; set; } public Int32? ImageWidth { get; set; } public string ImageAlign { get; set; } public string FieldId { get; set; } public bool? IsCustomField { get; set; } public Int64? DocTemplateId { get; set; } public string AttachmentList { get; set; } public bool? IsNew { get; set; } public bool? IsDelete { get; set; } } public class DocumentTemplateViewModel : VISBaseEntity { public Int64 DocTemplateId { get; set; } public string TemplateName { get; set; } public string OwnerName { get; set; } public string ModuleName { get; set; } public bool IsRecurrence { get; set; } public bool IsSelf { get; set; } public bool IsBehalf { get; set; } public string PublishDate { get; set; } public string ApprovedStatus { get; set; } } public class DocTemplateModule : VISBaseEntity { public Int64 ModuleId { get; set; } public string ModuleName { get; set; } public string ModuleValue { get; set; } } public static class DocumentTemplateViewModelConstant { /// <summary> /// Database table name constant. /// </summary> public const string const_DocTemplate_Table = "DocTemplate"; public const string const_DocTemplateModule = "DocTemplateModule"; //Constant For Add & Edit Paramter Step 1 public const string const_Id = "Id"; public const string const_mode = "mode"; public const string const_DocTemplateId = "DocTemplateId"; public const string const_TemplateName = "TemplateName"; public const string const_TemplateDescription = "TemplateDescription"; public const string const_ModuleId = "ModuleId"; public const string const_IsRecurrence = "IsRecurrence"; public const string const_IsSelf = "IsSelf"; public const string const_IsBehalf = "IsBehalf"; public const string const_SharingVariableType = "SharingVariableType"; public const string const_StartingVariableRole = "StartingVariableRole"; public const string const_IsDownloadWord = "IsDownloadWord"; public const string const_IsDownloadPdf = "IsDownloadPdf"; public const string const_IsDMSPdf = "IsDMSPdf"; public const string const_IsDMSWord = "IsDMSWord"; public const string const_IsEmailPdf = "IsEmailPdf"; public const string const_IsEmailWord = "IsEmailWord"; public const string const_DateFormat = "DateFormat"; public const string const_IsPortrait = "IsPortrait"; public const string const_IsApproved = "IsApproved"; public const string const_ApprovedOn = "ApprovedOn"; public const string const_IsFinalSubmited = "IsFinalSubmited"; public const string const_OwnerId = "OwnerId"; public const string const_CreatedBy = "CreatedBy"; public const string const_UpdatedBy = "UpdatedBy"; /// <summary> /// Store procedure Parameter Name Constants. /// </summary> /// public const string const_PageIndex = "PageIndex"; public const string const_PageSize = "PageSize"; public const string const_SortBy = "SortBy"; public const string const_SortOrder = "SortOrder"; public const string const_SearchField = "SearchField"; public const string const_SearchText = "SearchText"; public const string const_IsShowAll = "IsShowAll"; public const string const_EmployeeId = "EmployeeId"; public const string const_EmployeeRole = "EmployeeRole"; public const string const_ApprovedStatus = "ApprovedStatus"; //Constant For Add & Edit Paramter Step 2 public const string const_TableName = "TableName"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procDOC_GetAllDocumentTemplate = "procDOC_GetAllDocumentTemplate"; public const string const_procGetAllModule = "procGetAllModule"; public const string const_procDocumentTemplateAddEditStep1 = "procDocumentTemplateAddEditStep1"; public const string const_procDocumentTemplateGetById = "procDocumentTemplateGetById"; public const string const_procDocumentTemplateActiveInActive = "procDocumentTemplateActiveInActive"; // Step 2 Store Procedures public const string const_procDocMasterFieldAddEdit = "procDocMasterFieldAddEdit"; public const string const_procDocMasterFieldActiveInActive = "procDocMasterFieldActiveInActive"; public const string const_procDocMasterFieldSelectByDocTempId = "procDocMasterFieldSelectByDocTempId"; public const string const_procDocMasterFieldSelectById = "procDocMasterFieldSelectById"; public const string const_procGetMaxDocId = "procGetMaxDocId"; public const string const_procDOC_GetCustomTokenList = "procDOC_GetCustomTokenList"; public const string const_procGetDocTemplateModuleVariables = "procGetDocTemplateModuleVariables"; // Step 2 Constant Parameter public const string const_FieldName = "FieldName"; public const string const_FieldDescription = "FieldDescription"; public const string const_FieldType = "FieldType"; public const string const_ListType = "ListType"; public const string const_DataSourceTable = "DataSourceTable"; public const string const_DataSourceColumn = "DataSourceColumn"; public const string const_PageContent = "PageContent"; public const string const_ImageName = "ImageName"; public const string const_ImageHeight = "ImageHeight"; public const string const_ImageWidth = "ImageWidth"; public const string const_ImageAlign = "ImageAlign"; public const string const_FieldId = "FieldId"; public const string const_IsCustomField = "IsCustomField"; public const string const_AttachmentList = "AttachmentList"; // Step 3 Constant For Parameter public const string const_MasterFieldId = "MasterFieldId"; // Step 3 Store Proecedure public const string const_procDeleteDocMasterFieldByDocTempId = "procDeleteDocMasterFieldByDocTempId"; public const string const_procDeleteDocFormBuilder = "procDeleteDocFormBuilder"; public const string const_procDocFormBuilderAdd = "procDocFormBuilderAdd"; public const string const_procDocMasterFieldPageLineBreakAdd = "procDocMasterFieldPageLineBreakAdd"; public const string const_procBindDocumentContainer = "procBindDocumentContainer"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; namespace VIS_Domain.Master.EmployeeManualPointEntry { public class ManualPointEntry : VISBaseEntity { /// <summary> /// ManualPointEntry Entity Fields. /// </summary> public int GroupID { get; set; } public string EmpName { get; set; } public string Criteria { get; set; } public string Category { get; set; } public int Points { get; set; } public DateTime Month { get; set; } public string Remarks { get; set; } public long CriteriaId { get; set; } public Boolean IsPerformanceBadge{ get; set; } public long CategoryId { get; set; } public int Point { get; set; } public long EmpId { get; set; } public string Employee_name { get; set; } public string Type { get; set; } public DateTime ForDate { get; set; } public int Max { get; set; } } public static class ManualPointEntryConstants { /// <summary> /// Database table name constant. /// </summary> public const string const_Table_ManualPointEntry = "ManualPointEntry"; /// <summary> /// Database table field Name Constants. /// </summary> public const string const_Field_GroupID = "GroupID"; public const string const_Field_EmpName = "EmpName"; public const string const_Field_Criteria = "Criteria"; public const string const_Field_Points = "Points"; public const string const_Field_Month = "Month"; public const string const_Field_Remarks = "Remarks"; public const string const_Field_CriteriaId = "CriteriaId"; public const string const_Field_Max = "Max"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> public const string const_procManualPointEntry_Add = "procManualPointEntry_Add"; public const string const_procManualPointEntry_Update = "procManualPointEntry_Update"; public const string const_procManualPointEntry_ActiveInActive = "procManualPointEntry_ActiveInActive"; public const string const_procManualPointEntry_SelectAll = "procManualPointEntry_SelectAll"; public const string const_procManualPointEntry_SelectById = "procManualPointEntry_SelectById"; public const string const_procManualPointEntry_GetCriteria = "procGetCriteria"; public const string const_procManualPointEntry_GetCategory = "procGetCategory"; public const string const_procManualPointEntry_GetDataByCriteriaId = "procGetDataByCriteriaId"; public const string const_procManualPointEntry_GetEmployeeById = "procGetEmployeeById"; public const string const_procManualPointEntry_SelectEmployee = "procSelectMultipleEmployee"; public const string const_procManualPointEntry_GetLevelCriteriaSetupByCriteriaId = "procGetLevelCriteriaSetupByCriteriaId"; public const string const_procManualPointEntry_GetLevelCriteriaCriteriaId = "procGetLevelCriteriaByCriteriaId"; public const string const_procSaveLevelsPointLog = "procSaveLevelsPointLog"; public const string const_procGetMaxGroupId = "procGetMaxGroupId"; public const string const_GetCriteriaFromSetupId = "procGetCriteriaFromSetupId"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using VIS_Domain; using VIS_Domain.Master; using VIS_Repository; using VIS_Repository.Masters; using System.Configuration; using VIS_Domain.Master.Configuration; using VIS_Repository.Masters.Configuration; namespace VIS_App.Controllers.Masters.Configuration { public class EventCountDownAPIController : BaseAPIController { VISIBaseRepository<EventCountDown> EventCountDownRepository; List<EventCountDown> EntityList = new List<EventCountDown>(); public EventCountDownAPIController(VISIBaseRepository<EventCountDown> _EventCountDownRepository) { EventCountDownRepository = _EventCountDownRepository; } public HttpResponseMessage Get() { return ToJson(EventCountDownRepository.GetEntityList().AsEnumerable()); } public HttpResponseMessage Post([FromBody]EventCountDown value) { return ToJson(EventCountDownRepository.AddEntity(value)); } [HttpPut] public HttpResponseMessage UpdateEntity(Int64 Id, [FromBody]EventCountDown value) { return ToJson(EventCountDownRepository.UpdateEntity(value)); } [HttpDelete] public HttpResponseMessage DeleteEntity(Int64 Id) { return ToJson(EventCountDownRepository.DeleteEntity(Id)); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using VIS_Domain; using VIS_Domain.Master.Configuration; using VIS_Domain.Reports.Attendance; namespace VIS_Repository.Reports.Attendance { public class LateEarlyReportRepository : VISDbCommand { int LateComing = 0; int EarlyLeaving = 0; DataTable dtlatecome = new DataTable(); DataTable dtlatecount = new DataTable(); public LateEarlyReportRepository(string _connectionstring) : base(_connectionstring) { } public DataTable GetEmployee() { string mode = "Employee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode,mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetAllEmployee() { string mode = "AllEmployee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetDepartment() { string mode = "Department"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetCompany() { string mode = "Company"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_ProcAttendanceReportBindDropdown; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetYear() { DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_procFinancialYear_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } return dt; } public DataTable GetEmployeeIdByDepartment(Int64 Id, DateTime Fromdate, DateTime Todate) { string mode = "Department"; DataTable dt = new DataTable(); DataTable dtLate = new DataTable(); DataRow drLate; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_procGetEmployeeId; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Id, Id); base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } dtLate.Columns.Add("Employees_Name", Type.GetType("System.String")); dtLate.Columns.Add("LateComing", Type.GetType("System.String")); dtLate.Columns.Add("EarlyLeaving", Type.GetType("System.String")); dtLate.Columns.Add("LessTime", Type.GetType("System.String")); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; GetLateComingReport(Convert.ToInt16(dr[0]), Fromdate, Todate); GetEarlyLeavingReport(Convert.ToInt16(dr[0]), Fromdate, Todate); DataColumn dcLate = new DataColumn(); drLate = dtLate.NewRow(); drLate["Employees_Name"] = dr[1]; drLate["LateComing"] = LateComing; drLate["EarlyLeaving"] = EarlyLeaving; drLate["LessTime"] = ""; dtLate.Rows.Add(drLate); //if (dtlatecount.Rows.Count < 1) //{ // dtLate.Clear(); //} } return dtLate; } public DataTable GetEmployeeIdByEmployee(Int64 Id,DateTime Fromdate,DateTime Todate) { try { string mode = "Employee"; DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_procGetEmployeeId; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Id, Id); base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); base.objSqlCommand.Connection.Close(); } //GetLateComingReport(Id, Fromdate, Todate); //GetEarlyLeavingReport(Id, Fromdate, Todate); DataTable dtLate = new DataTable(); DataRow drLate; DataColumn dcLate = new DataColumn(); dtLate.Columns.Add("Employees_Name", Type.GetType("System.String")); dtLate.Columns.Add("LateComing", Type.GetType("System.String")); dtLate.Columns.Add("EarlyLeaving", Type.GetType("System.String")); dtLate.Columns.Add("LessTime", Type.GetType("System.String")); drLate = dtLate.NewRow(); drLate["Employees_Name"] = dt.Rows[0]["Employee_Name"].ToString(); drLate["LateComing"] = GetLateComingReport(Id, Fromdate, Todate); drLate["EarlyLeaving"] = GetEarlyLeavingReport(Id, Fromdate, Todate); drLate["LessTime"] = ""; dtLate.Rows.Add(drLate); if (dtlatecount.Rows.Count < 1) { dtLate.Clear(); } return dtLate; } catch (Exception ex) { throw ex; } } public DataTable GetEmployeeIdByCompany(Int64 Id, DateTime Fromdate, DateTime Todate) { string mode = "Company"; DataTable dt = new DataTable(); DataTable dtLate = new DataTable(); DataRow drLate; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_procGetEmployeeId; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Id, Id); base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } dtLate.Columns.Add("Employees_Name", Type.GetType("System.String")); dtLate.Columns.Add("LateComing", Type.GetType("System.String")); dtLate.Columns.Add("EarlyLeaving", Type.GetType("System.String")); dtLate.Columns.Add("LessTime", Type.GetType("System.String")); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; GetLateComingReport(Convert.ToInt16(dr[0]), Fromdate, Todate); GetEarlyLeavingReport(Convert.ToInt16(dr[0]), Fromdate, Todate); DataColumn dcLate = new DataColumn(); drLate = dtLate.NewRow(); drLate["Employees_Name"] = dr[1]; drLate["LateComing"] = LateComing; drLate["EarlyLeaving"] = EarlyLeaving; drLate["LessTime"] = ""; dtLate.Rows.Add(drLate); //if (dtlatecount.Rows.Count < 1) //{ // dtLate.Clear(); //} } return dtLate; } public DataTable GetEmployeeIdSelectAll(Int64 Id, DateTime Fromdate, DateTime Todate) { string mode = "SelectAll"; DataTable dt = new DataTable(); DataTable dtLate = new DataTable(); DataRow drLate; using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = LateEarlyReportConstant.const_procGetEmployeeId; base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Id, Id); base.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_mode, mode); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); } dtLate.Columns.Add("Employees_Name", Type.GetType("System.String")); dtLate.Columns.Add("LateComing", Type.GetType("System.String")); dtLate.Columns.Add("EarlyLeaving", Type.GetType("System.String")); dtLate.Columns.Add("LessTime", Type.GetType("System.String")); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; GetLateComingReport(Convert.ToInt16(dr[0]), Fromdate, Todate); GetEarlyLeavingReport(Convert.ToInt16(dr[0]), Fromdate, Todate); DataColumn dcLate = new DataColumn(); drLate = dtLate.NewRow(); drLate["Employees_Name"] = dr[1]; drLate["LateComing"] = LateComing; drLate["EarlyLeaving"] = EarlyLeaving; drLate["LessTime"] = ""; dtLate.Rows.Add(drLate); //if (dtlatecount.Rows.Count < 1) //{ // dtLate.Clear(); //} } return dtLate; } public int GetLateComingReport(Int64 Id, DateTime Fromdate, DateTime Todate) { LateComing = 0; VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); DateTime DtTodayDate = Convert.ToDateTime(DateTime.Today.Date.ToShortDateString()); TimeSpan diff = Todate - Fromdate; int numdays = diff.Days; numdays = numdays + 1; DateTime tempFromDt; tempFromDt = Fromdate; for (int i = 0; i < numdays; i++) { string TempFromDateNew = tempFromDt.ToString(); string[] ArrayTempFromDateNew = TempFromDateNew.Split(' '); string newformdate = ArrayTempFromDateNew[0]; string[] DateFormat = newformdate.Split('/'); string dd, mm, yyyy, finaldate; dd = DateFormat[1]; mm = DateFormat[0]; yyyy = DateFormat[2]; if (dd.Length == 1) { dd = "0" + dd; } if (mm.Length == 1) { mm = "0" + mm; } finaldate = dd + "/" + mm + "/" + yyyy; objVISDbCommand.objSqlCommand.Connection.Open(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LateEarlyReportConstant.const_ProcLevels_GetAttendanceForLateComing; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Employee_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Date, finaldate); SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); dtlatecome.Clear(); da.Fill(dtlatecome); dtlatecount = dtlatecome; objVISDbCommand.objSqlCommand.Connection.Close(); objVISDbCommand.objSqlCommand.Parameters.Clear(); if (dtlatecome.Rows.Count > 0 && dtlatecome.Rows!=null) { int EntryType = Convert.ToInt16(dtlatecome.Rows[0]["Entry_Type"]); DateTime EntryTime = DateTime.Parse(dtlatecome.Rows[0]["Entry_Time"].ToString()); string ActualEntryTime = dtlatecome.Rows[0]["actualEntryTime"].ToString(); string[] tempactualentrytime = ActualEntryTime.Split(':'); string TemptempactualentrytimeHH = tempactualentrytime[0]; string TemptempactualentrytimeMM = tempactualentrytime[1]; int TemptempactualentrytimeHHnew = Convert.ToInt16(TemptempactualentrytimeHH.ToString()); int TemptempactualentrytimeMMNew = Convert.ToInt16(TemptempactualentrytimeMM.ToString()); float finalactualtime = Convert.ToSingle(TemptempactualentrytimeHHnew + "." + TemptempactualentrytimeMMNew); // string[] tempentrytime = EntryTime.ToString().Split(' '); string[] tempentrytimenew = tempentrytime[1].Split(':'); string timehh, timemm; timehh = tempentrytimenew[0]; timemm = tempentrytimenew[1]; int temptimehh = Convert.ToInt16(timehh.ToString()); int temptimemm = Convert.ToInt16(timemm.ToString()); float finlentrytime = Convert.ToSingle(temptimehh + "." + temptimemm); if (EntryType == 1 && finalactualtime < finlentrytime) { LateComing++; } } else { LateComing = LateComing + 0; } tempFromDt = tempFromDt.AddDays(1); } return LateComing; } public int GetEarlyLeavingReport(Int64 Id, DateTime Fromdate, DateTime Todate) { EarlyLeaving = 0; VISDbCommand objVISDbCommand = new VISDbCommand(ConfigurationManager.ConnectionStrings["VISConnection"].ConnectionString); DateTime DtTodayDate = Convert.ToDateTime(DateTime.Today.Date.ToShortDateString()); TimeSpan diff = Todate - Fromdate; int numdays = diff.Days; numdays = numdays + 1; DateTime tempFromDt; tempFromDt = Fromdate; DataTable dt = new DataTable(); for (int i = 0; i < numdays; i++) { objVISDbCommand.objSqlCommand.Connection.Open(); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = LateEarlyReportConstant.const_ProcLevels_GetAttendance; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Employee_Id, Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(LateEarlyReportConstant.const_Date, tempFromDt); objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); SqlDataAdapter da = new SqlDataAdapter(objVISDbCommand.objSqlCommand); dt.Clear(); da.Fill(dt); objVISDbCommand.objSqlCommand.Connection.Close(); objVISDbCommand.objSqlCommand.Parameters.Clear(); string punchtime = dt.Rows[0][1].ToString(); string wktime = dt.Rows[0][3].ToString(); if (dt.Rows.Count > 0 && punchtime != "" && wktime != "") { string TempTotalPunchingTimeHH; string TempTotalPunchingTimeMM; string TempTotalWorkingTimeHH; string TempTotalWorkingTimeMM; TempTotalPunchingTimeHH = dt.Rows[0]["TotalPunchInHours"].ToString(); TempTotalWorkingTimeHH = dt.Rows[0]["TotalWorkingTime"].ToString(); string[] temptotaltime = TempTotalPunchingTimeHH.Split(':'); string[] tempworking = TempTotalWorkingTimeHH.Split(':'); TempTotalPunchingTimeHH = temptotaltime[0]; TempTotalPunchingTimeMM = temptotaltime[1]; TempTotalWorkingTimeHH = tempworking[0]; TempTotalWorkingTimeMM = tempworking[1]; int TempTotalPunchingHHNew = Convert.ToInt32(TempTotalPunchingTimeHH.ToString()); int TempTotalPunchingMMNew = Convert.ToInt32(TempTotalPunchingTimeMM.ToString()); int TempTotalWorkingHHNew = Convert.ToInt32(TempTotalWorkingTimeHH.ToString()); int TempTotalWorkingMMNew = Convert.ToInt32(TempTotalWorkingTimeMM.ToString()); string restotal = TempTotalPunchingHHNew.ToString() + "." + TempTotalPunchingMMNew.ToString(); string resworking = TempTotalWorkingHHNew.ToString() + "." + TempTotalWorkingMMNew.ToString(); float finalrestotal = Convert.ToSingle(restotal); float finalresworking = Convert.ToSingle(resworking); if (finalrestotal < 9.30 & finalresworking < 9) { EarlyLeaving++; } else { EarlyLeaving = EarlyLeaving + 0; } } else { } tempFromDt = tempFromDt.AddDays(1); } return EarlyLeaving; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using VIS_Domain; using VIS_Domain.Master; using VIS_Domain.Master.VacancyRelated; using VIS_Repository.Masters; namespace VIS_Repository.Masters.VacancyRelated { public class PositionRepository : VISDbCommand { public Int32 intAffectedRecords { get; set; } public PositionRepository(string _connectionstring) : base(_connectionstring) { } public string DeleteEntity(Int64 Id) { try { string UpdatedBy = string.Empty; VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = PositionConstant.const_procPositionMaster_ActiveInActive; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public Position GetEntityByID(Int64 Id) { Position objEntityToReturn = new Position(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = PositionConstant.const_procPositionMaster_SelectById; base.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, Id); if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objEntityToReturn = VISAutoMapper.ConvertDataRow<Position>(dt.Rows[0]); } return objEntityToReturn; } public IEnumerable<PositionViewModel> GetEntityList() { List<PositionViewModel> objListToReturn = new List<PositionViewModel>(); DataTable dt = new DataTable(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = PositionConstant.const_procPositionMaster_SelectAll; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<PositionViewModel>(dt); } return objListToReturn; } public string AddEntity(Position entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = PositionConstant.const_procPositionMaster_Add; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_PositionName, entityObject.PositionName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_Remarks, entityObject.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_Status, entityObject.Status); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); if (intAffectedRecords > 0) { if(entityObject.SkillId.Length > 0) { foreach (Int64 SkillId in entityObject.SkillId) { AddPositionSkill(0,SkillId); } } } string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public string UpdateEntity(Position entityObject) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = PositionConstant.const_procPositionMaster_Update; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(VISBaseEntityConstants.const_Field_Id, entityObject.Id); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_PositionName, entityObject.PositionName); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_Remarks, entityObject.Remarks); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_Status, entityObject.Status); if (!objVISDbCommand.objSqlCommand.Parameters.Contains(VISBaseEntityConstants.const_Field_EntityMessage)) { objVISDbCommand.objSqlCommand.Parameters.Add(AddEntityMessageParameter()); } objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); DeletePositionSkill(entityObject.Id); if (entityObject.SkillId.Length > 0) { foreach (Int64 SkillId in entityObject.SkillId) { AddPositionSkill(entityObject.Id,SkillId); } } string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; return strRetValue + objVISDbCommand.objSqlCommand.Parameters[VISBaseEntityConstants.const_Field_EntityMessage].Value.ToString(); } catch (Exception ex) { return ex.Message + Environment.NewLine + ex.StackTrace; } } public IEnumerable<SkillList> GetSkills() { List<SkillList> objListToReturn = new List<SkillList>(); using (base.objSqlCommand.Connection) { base.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; base.objSqlCommand.CommandText = SkillConstant.const_procGetSkill; if (base.objSqlCommand.Connection.State != ConnectionState.Open) { base.objSqlCommand.Connection.Open(); } SqlDataAdapter da = new SqlDataAdapter(base.objSqlCommand); DataTable dt = new DataTable(); da.Fill(dt); objListToReturn = VISAutoMapper.ConvertDataTable<SkillList>(dt); } return objListToReturn; } public void AddPositionSkill(Int64 PositionId,Int64 SkillId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = PositionConstant.const_procPositionSkill_Add; objVISDbCommand.objSqlCommand.Parameters.Clear(); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_SkillId,SkillId); objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_PositionId, PositionId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { } } public void DeletePositionSkill(Int64 PositionId) { try { VISDbCommand objVISDbCommand = new VISDbCommand(base.DatabaseConnection.ConnectionString); objVISDbCommand.objSqlCommand.CommandType = System.Data.CommandType.StoredProcedure; objVISDbCommand.objSqlCommand.CommandText = PositionConstant.const_procPositionSkill_Delete; objVISDbCommand.objSqlCommand.Parameters.AddWithValue(PositionConstant.const_PositionId, PositionId); objVISDbCommand.objSqlCommand.Connection.Open(); intAffectedRecords = objVISDbCommand.objSqlCommand.ExecuteNonQuery(); objSqlCommand.Connection.Close(); string strRetValue = intAffectedRecords >= 1 ? VISBaseEntityConstants.const_Result_Success : VISBaseEntityConstants.const_Result_Failure; } catch (Exception ex) { } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VIS_Domain.HumanResource.EmployeeManagement { public class EmployeeList : VISBaseEntity { public string mode { get; set; } public Int64 UserId { get; set; } public string Usertype { get; set; } public string EmployeeCode { get; set; } public string CompanyName { get; set; } public string Employee_Name { get; set; } public string Email { get; set; } public string Department { get; set; } public string TotalExp { get; set; } public DateTime JoiningDate { get; set; } public DateTime RelevingDate { get; set; } public Int64 Grace { get; set; } public string SL_CL { get; set; } } public static class EmployeeListConstants { public const string const_Table_EmployeeFeedback = "Employee_Master"; public const string const_Field_mode = "mode"; public const string const_Field_UserId = "UserId"; public const string const_Field_Usertype = "Usertype"; public const string const_Field_EmployeeCode = "EmployeeCode"; public const string const_Field_CompanyName = "CompanyName"; public const string const_Field_Employee_Name = "Employee_Name"; public const string const_Field_Email = "Email"; public const string const_Field_Department = "Department"; public const string const_Field_TotalExp = "TotalExp"; public const string const_Field_joiningDate = "JoiningDate"; public const string const_Field_RelevingDate = "RelevingDate"; public const string const_Field_Grace = "Grace"; public const string const_Field_SL_CL = "SL_CL"; /// <summary> /// Database Procedure and fucntion constants. /// </summary> /// public const string const_procgetEmployeeRecordActive = "procgetEmployeeRecordActive"; public const string const_procgetEmployeeRecordAll = "procgetEmployeeRecordAll"; public const string const_procgetEmployeeRecorInActive = "procgetEmployeeRecorInActive"; public const string const_procSelectListDeleteEmployeelist = "procSelectListDeleteEmployeelist"; public const string const_procDeleteEmployeelist = "procDeleteEmployeelist"; public const string const_procEmployeemodeActive = "procEmployeemodeActive"; public const string const_procEmployeemodeAll = "procEmployeemodeAll"; public const string const_procEmployeemodeInActive = "procEmployeemodeInActive"; } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core' import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms' import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal' import { SalaryGrievanceService } from '../../../Service/HumanResource/Grievance/SalaryGrievance.service' import { Global } from '../../../../app/Shared/global'; import { PagerService } from '../../../../app/Shared/pager.service'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { HttpModule, Http, Headers } from '@angular/http'; import { DBOperation } from '../../../Shared/enum'; import { ISalaryGrievance, IGrievanceDate, IAttendance, IDailyEntry } from '../../../Model/HumanResource/Grievance/SalaryGrievance'; @Component({ providers: [SalaryGrievanceService], templateUrl: 'app/Components/HumanResource/Grievance/SalaryGrievance.component.html' }) export class SalaryGrievanceComponent implements OnInit { @ViewChild('modalAddGrievance') modal: ModalComponent; msg: string; dbops: DBOperation; indLoading: boolean = false; Id: number; PayCutAmt: string; PayCutAmtRemark: string; RemarkBy: string; EmployeeId: number; SalaryGrievanceForm: FormGroup; CurrentRecordsPerPage: number = 10; pager: any = {}; pagedItems: any[]; objeditGrievance: ISalaryGrievance[]; objGrievance: ISalaryGrievance; Grievance: ISalaryGrievance[]; GrievanceDate: IGrievanceDate[]; GrievanceDeductionDate: IGrievanceDate[]; Attendance: IAttendance; DailyEntry: IDailyEntry; modalTitle: string; modalButton: string; constructor(private fb: FormBuilder, private _SalaryGrievanceService: SalaryGrievanceService, public http: Http, private router: Router, private pagerService: PagerService) { } ngOnInit(): void { this.objGrievance = ({ Id: 0, Employee_Id: 0, Employee_Name: '', Deduction_Date: null, Grievance_Remarks: '', PaycutAmount: '', GrievanceType_PE: '', GrievanceType_PH: '', PE_Status: 0, PE_Remarks: '', PE_UpdatedBy: 0, PE_UpdatedDate: null, PH_Status: 0, PH_Remarks: '', PH_UpdatedBy: 0, PH_UpdatedDate: null, CreatedBy: 0, CreatedOn: null, UpdatedBy: 0, UpdatedOn: null, Active: false, verified_By: 0, }) $("#txtDeductDate").hide(); this.objGrievance.Employee_Id = Number(sessionStorage.getItem('Id')); this.objGrievance.Employee_Name = sessionStorage.getItem('UserFullName'); this.LoadGrievanceDetails(); // Add Grievance Method.. $("#AttendanceData").hide(); $("#DailyEntryData").hide(); $("#txtempname").prop('disabled', true); $("#txtDeductionDate").prop('disabled', true); $("#txtpcremark").prop('disabled', true); $("#txtPCAmt").prop('disabled', true); $("#txtremark_by").prop('disabled', true); this.FillDeductionDate() } LoadGrievanceDetails(): void { this.indLoading = true; this._SalaryGrievanceService.GetGrievance(Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "Pending") .subscribe(Grievance => { this.Grievance = Grievance; this.indLoading = false; this.JumpOnPage(1); }); } GetPendingGrievance(event): void { this.LoadGrievanceDetails(); } GetCompletedGrievance(event): void { this._SalaryGrievanceService.GetGrievance(Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "Completed") .subscribe(Grievance => { this.Grievance = Grievance; this.indLoading = false; this.JumpOnPage(1); }); } JumpOnPage(PageNumber: number) { this.pagerService.setPage(PageNumber, this.CurrentRecordsPerPage, this.Grievance); this.pager = this.pagerService.pager; this.pagedItems = this.pagerService.pagedItems; } ChangeRecordsPerPage(RecordsPerPage: number) { this.CurrentRecordsPerPage = RecordsPerPage; if (RecordsPerPage >= 0) { this.JumpOnPage(1); } } //SetControlsState(isEnable: boolean) { // isEnable ? this.SalaryGrievanceForm.enable() : this.SalaryGrievanceForm.disable(); //} ResetModal(): void { this.objGrievance = ({ Id: 0, Employee_Id: 0, Employee_Name: '', Deduction_Date: null, Grievance_Remarks: '', PaycutAmount: '', GrievanceType_PE: '', GrievanceType_PH: '', PE_Status: 0, PE_Remarks: '', PE_UpdatedBy: 0, PE_UpdatedDate: null, PH_Status: 0, PH_Remarks: '', PH_UpdatedBy: 0, PH_UpdatedDate: null, CreatedBy: 0, CreatedOn: null, UpdatedBy: 0, UpdatedOn: null, Active: false, verified_By: 0, }); } GoToAddGrievance(): void { this.ResetModal(); this.modalTitle = 'Add Grievance'; this.modalButton = 'Save'; this.dbops = DBOperation.create; this.modal.open(); } // Add Grievance Functions... FillDeductionDate(): void { this._SalaryGrievanceService.FillDeductionDate(Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "GetDeductDate") .subscribe(GetDeductionDate => { this.indLoading = false; this.GrievanceDate = GetDeductionDate; }, error => { this.msg = error; }); } LoadEmployeeAttendance(EmployeeId: number, DeductionDate: string): void { this._SalaryGrievanceService.LoadEmployeeAttendance(Global.BASE_SalaryGrievanceAPI_ENDPOINT, EmployeeId, DeductionDate) .subscribe(GetAttendance => { this.indLoading = false; this.Attendance = GetAttendance; }, error => { this.msg = error; }); } LoadEmployeeDailyEntry(EmployeeId: number, DeductionDate: string): void { this._SalaryGrievanceService.LoadEmployeeDailyEntry(Global.BASE_SalaryGrievanceAPI_ENDPOINT, EmployeeId, DeductionDate) .subscribe(GetDailyEntry => { debugger; this.indLoading = false; this.DailyEntry = GetDailyEntry; }, error => { this.msg = error; }); } GetAttendanceDetailOfEmployee(event): void { this._SalaryGrievanceService.FillDeductionDate(Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.objGrievance.Employee_Id, "GetDeductDate") .subscribe(GetDeduction => { this.GrievanceDeductionDate = GetDeduction; if (this.GrievanceDeductionDate != null) { $("#AttendanceData").show(); $("#DailyEntryData").show(); this.Id = event.target.value; if (this.Id == 0) { this.objGrievance.PaycutAmount = ""; this.PayCutAmtRemark = ""; this.RemarkBy = ""; } else { for (let item of this.GrievanceDeductionDate.filter(x => x.Id == this.Id)) { this.objGrievance.PaycutAmount = item.PayrollCut; this.PayCutAmtRemark = item.PayrollRemarks; this.RemarkBy = item.LineManagerName; this.LoadEmployeeAttendance(item.EmployeeId, item.Deduction_Date); this.LoadEmployeeDailyEntry(item.EmployeeId, item.Deduction_Date); } } } }); } EditGrievance(Id: number): void { $("#ddDeductDate").hide(); $("#txtDeductDate").show(); this.modalTitle = 'Edit Grievance'; this.modalButton = 'Update'; this.dbops = DBOperation.update; //this.SetControlsState(true); this.objGrievance = this.Grievance.filter(x => x.Id == Id)[0]; this.modal.open(); } onSubmit(objGrievance: ISalaryGrievance) { this.msg = ""; debugger; var dateval = $("#ddlDeductDate option:selected").text() var Pc_AMT = $("#txtPCAmt").val(); var GrievanceRemark = $("#txtGrievanceremark").val(); this.EmployeeId = Number(sessionStorage.getItem('Id')); switch (this.dbops) { case DBOperation.create: this._SalaryGrievanceService.AddGrievance(Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.EmployeeId, dateval, Pc_AMT, GrievanceRemark) .subscribe(Success => { this.modal.close(); }, error => { this.msg = error; }); break; case DBOperation.update: this._SalaryGrievanceService.put(Global.BASE_SalaryGrievanceAPI_ENDPOINT, this.EmployeeId, objGrievance) .subscribe(Success => { this.modal.close(); }, error => { this.msg = error; }); } } }
4ea224122917df0b83441b4e0c52c656ce7c5e43
[ "JavaScript", "C#", "TypeScript" ]
434
C#
Saurabh98241/WebAPI2-Angular6
a89f27a58b9c59ade7823522f47e3a807dc314f6
71172d8d4e018cf73ce7929de2b3151b4872849a
refs/heads/master
<repo_name>TerminalTesting/yml_yandex_SB<file_sep>/yml_test.py #! /usr/bin/python # -*- coding: utf8 -*- #import pytest import unittest import sys from lxml import etree import codecs import urllib2 import os from yml_models import * from string import split from urlparse import urlparse def get_domain(url): """ найти домен региона """ url_tuple=urlparse(url) netloc=split( url_tuple[1], '.') return unicode(netloc[0]) XSD_LIST={ 'YML Yandex TYPICAL':'shops.xsd', 'YML Yandex CONTEXT':'shops-context.xsd', 'YML Yandex CPA':'shops-cpa.xsd', 'SERIES & BRANDS':'series-brands.xsd' } DTD_LIST={ 'YML Yandex TYPICAL':'shops.dtd', 'YML Yandex CONTEXT':'shops-context.dtd', 'YML Yandex CPA':'shops-cpa.dtd', 'SERIES & BRANDS':'series-brands.dtd' } class YMLTest(unittest.TestCase): """Тесты ядекс выгрузки""" WAIT_TIME = 60 SLEEP_TIME=1 XSD_DTD_CATALOG='./xsd_dtd/' DTD_FILE_NAME=XSD_DTD_CATALOG+DTD_LIST[ os.getenv('TYPE')] XSD_FILE_NAME=XSD_DTD_CATALOG+XSD_LIST[ os.getenv('TYPE')] YML_FILE_NAME='XML_FILE_NAME' # домен региона для которого проверяется выгрузка CITY_DOMAIN='nsk' #соединение с БД HOST = os.getenv('HOST') PORT = os.getenv('PORT') SCHEMA = os.getenv('SCHEMA') USER = os.getenv('USER') PSWD = os.getenv('PSWD') def setUp(self): """Инициализация переменных для всех тестов""" pass self.parser = etree.XMLParser(huge_tree=True) print os.getenv('TYPE') print self.DTD_FILE_NAME print self.XSD_FILE_NAME self.CONNECT_STRING=('mysql://%s:%s@%s:%s/%s?charset=utf8')%(self.USER, self.PSWD, self.HOST, self.PORT, self.SCHEMA ) def tearDown(self): """Удаление переменных для всех тестов. Остановка приложения""" if sys.exc_info()[0]: print sys.exc_info()[0] def test_yml_0(self): """ верификация по dtd описанию shops.dtd """ xml=etree.parse(self.YML_FILE_NAME, parser=self.parser ) dtd=etree.DTD(codecs.open(self.DTD_FILE_NAME)) result= dtd.validate(xml) error_msg=dtd.error_log.filter_from_errors() try: dtd.assertValid(xml) except: print '\nОШИБКА ВАЛИДАЦИИ XML ФАЙЛА' print '-'*80 print ('File: %s last error line: %s\n')%(self.YML_FILE_NAME, error_msg.last_error.line) msg = error_msg.last_error.message.replace('Element offer content does not follow the DTD, expecting', 'Контент элемента <offer> не соответствует DTD. Ожидалось:\n'.decode('utf-8')).replace(', got', '\n\nПолучено:\n'.decode('utf-8')) print 'Сообщение об ошибке:\n' print msg raise AssertionError print ('YML:%s\nDTD:%s\nDTD Validation successful.')%(self.YML_FILE_NAME, self.DTD_FILE_NAME ) def test_yml_1(self): """ верификация по xsd описанию shops.xsd """ xml=etree.parse(self.YML_FILE_NAME, parser=self.parser, base_url=None) xsd=etree.XMLSchema(file=self.XSD_FILE_NAME) stat=xsd.validate(xml) error_msg=xsd.error_log.filter_from_errors() try: xsd.assertValid(xml) except: print '\nОШИБКА ВАЛИДАЦИИ XML ФАЙЛА' print '-'*80 print ('File:%s\nLine:%s\n\nError message:\n%s')%(self.YML_FILE_NAME, error_msg.last_error.line, error_msg.last_error.message ) raise AssertionError print ('YML:%s\nXSD:%s\nXSD Validation successful.')%(self.YML_FILE_NAME, self.XSD_FILE_NAME ) def test_yml_2(self): """ проверка тегов на соответствие с базой """ db = create_engine(self.CONNECT_STRING) #, convert_unicode=False db.echo = False # Try changing this to True and see what happens metadata = MetaData(db) session=create_session(bind=db) xml=etree.parse(self.YML_FILE_NAME, parser=self.parser ) xml_tree=xml.getiterator('offer') shop_url_element=xml.find('shop').find('url') DOMAIN = get_domain(shop_url_element.text) cnt=1 stat=0 # возможность доставки для региона delivery=session.query( Region, Goods_delivery, Goods_price).\ join(Goods_delivery, (Region.id==Goods_delivery.city_id) ).\ join(Goods_price, (Goods_delivery.goods_id==Goods_price.goods_id) ).\ filter(Region.domain==DOMAIN).\ filter( (Region.id==Goods_stat.city_id ) & (Goods_price.price_type_guid==Region.price_type_guid) ).\ all() #если возможности доставки нет то тег delivery=False delivery_flag=len(delivery)>0 # список цен на доставку в зависимости от габаритности товара if delivery_flag==True: delivery_price_1=[ float(element[2].price) for element in delivery if element[1].delivery_type==1 ] delivery_price_2=[ float(element[2].price) for element in delivery if element[1].delivery_type==2 ] delivery_price={1:delivery_price_1, 2:delivery_price_2} pass else: delivery_price={1:0.00, 2:0.00} print ('YML:%s\nDomain:%s\nDeliveries flag:%s')%(self.YML_FILE_NAME, DOMAIN, delivery_flag ) for element in xml_tree: # получаем теги из выгрузки price_tag=element.find('price') store_tag=element.find('store') pickup_tag=element.find('pickup') vendor_tag=element.find('vendor') description_tag=element.find('description') delivery_price_tag=element.find('local_delivery_cost') if element.find('local_delivery_cost')!=None else xml.find('shop').find('local_delivery_cost') delivery_tag=element.find('delivery') off_url = element.find('url').text DPD = '%3Fdcid%3D' in off_url if DPD: DPDcity = int(off_url[off_url.find('%3Fdcid%3D')+10:off_url.find('%26')])#поиск параметра id города и преобразование в integer cnt+=1 # получаем параметры товара из БД item=session.query( Goods, Goods_stat, Region, Goods_price, Goods_section, Goods_block.name, Goods_block.delivery_type, Goods_block.flag_self_delivery, Supplier_price).\ join(Goods_stat, Goods.id==Goods_stat.goods_id).\ join(Goods_price, (Goods.id==Goods_price.goods_id) ).\ join(Goods_section, (Goods_section.guid==Goods.section_guid) ).\ join(Goods_block, (Goods_block.id==Goods.block_id) ).\ filter(Goods.id==element.attrib['id']).\ filter(Region.domain==DOMAIN).\ filter( (Goods_stat.city_id== Region.id) & (Goods_price.price_type_guid==Region.price_type_guid) ).\ first() # в выгрузке есть а в БД нет ид товара if item==None: print 'Ошибка в теге <OFFER>:' print 'ID товара: ', element.attrib['id'] ,' значение в файле:',description_tag.text, ' значение в базе данных не найдено' print '-'*80 continue #тег цена <price> if int(float(price_tag.text)) == 0: stat+=1 print 'Ошибка в теге <PRICE>:' print 'ID товара: ', element.attrib['id'] ,' Цена у данного товара равна нулю. ' print '-'*80 elif item[1].status == 5 and DPD != True: #if sipplier status used - take supplier price from database item_price = session.query(Supplier_price.price_supplier).\ filter( (Supplier_price.goods_id == element.attrib['id']) & (Supplier_price.price_type_guid == item[3].price_type_guid) ).\ first()[0] if int(float(price_tag.text))!= int(item_price): stat+=1 print 'Ошибка в теге <PRICE>: Цена поставщика' print 'ID товара: ', element.attrib['id'] ,' значение в файле:',int(float(price_tag.text)), ' значение в базе данных:', int(item_price) print '-'*80 else: actions_goods = session.query(Action_goods).group_by(Action_goods.action_id).\ filter(Action_goods.goods_id == item[0].id).\ filter(Action_goods.action_id != 63 ).all() #63 - акция лояльности, не должно попадать в выгрузку. if actions_goods: if len(actions_goods)>1: stat+=1 print 'ID товара: ', element.attrib['id'] ,' Данный товар участвует одновременно в 2 активных акциях, необходима ручная проверка наименования' print '-'*80 action_price_guid = session.query(Actions_price.price_type_guid).filter(Actions_price.action_set_id == actions_goods[0].set_id).all() if action_price_guid: action_price_guid = (x[0] for x in set(action_price_guid))#guid акционной цены товара во всех регионах good_price = session.query(City_price.price_type_guid).filter(City_price.city_id == item[2].id).filter(City_price.price_type_guid.in_(action_price_guid)).all()[0][0] #guid акционной цены товара в нужном регионе action_price = session.query(Goods_price.price).filter(Goods_price.price_type_guid == good_price).filter(Goods_price.goods_id == item[0].id).all() if action_price: action_price = action_price[0][0] main_price = item[3].price if item[1].status != 5 else item[3].price_supplier #if int(action_price) > int(main_price) and actions_goods[0].action_id not in (13,): # item_price = main_price #elif int(action_price) < int(main_price) and actions_goods[0].action_id in (13,): # item_price = main_price #else: # item_price = action_price if action_price < main_price and actions_goods[0].action_id not in (13,) and int(action_price) != 0: if int(float(price_tag.text)) != int(action_price): stat+=1 print 'Ошибка в теге <PRICE>: ЦЕНА АКЦИОННАЯ' print 'ID товара: ', element.attrib['id'] ,' значение в файле:', int(float(price_tag.text)), ' значение в базе данных:', int(action_price) print '-'*80 else: item_price = item[3].price if int(float(price_tag.text))!= int(item_price): stat+=1 print 'Ошибка в теге <PRICE>:' print 'ID товара: ', element.attrib['id'] ,' значение в файле:',int(float(price_tag.text)), ' значение в базе данных:', int(item_price) print '-'*80 else: item_price = item[3].price if int(float(price_tag.text))!= int(item_price): stat+=1 print 'Ошибка в теге <PRICE>:' print 'ID товара: ', element.attrib['id'] ,' значение в файле:',int(float(price_tag.text)), ' значение в базе данных:', int(item_price) print '-'*80 else: item_price = item[3].price if int(float(price_tag.text))!= int(item_price): stat+=1 print 'Ошибка в теге <PRICE>:' print 'ID товара: ', element.attrib['id'] ,' значение в файле:',int(float(price_tag.text)), ' значение в базе данных:', int(item_price) print '-'*80 else: item_price = item[3].price if int(float(price_tag.text))!= int(item_price): stat+=1 print 'Ошибка в теге <PRICE>:' print 'ID товара: ', element.attrib['id'] ,' значение в файле:',int(float(price_tag.text)), ' значение в базе данных:', int(item_price) print '-'*80 #тег статуса <available> if DPD == True: item_available = False else: item_available = ( item[1].status==1 ) if (element.attrib['available'] in ('true', 'True') ) != item_available: stat+=1 print 'Ошибка в теге <AVAILABLE>:' print 'ID товара: ', element.attrib['id'] ,' значение в файле:',element.attrib['available'], ' значение в базе данных:',item[1].status==1, item[1].status print '-'*80 #тег производитель <vendor> if (vendor_tag.text )!=(item[0].brand): stat+=1 print 'Ошибка в теге <VENDOR>:' print 'ID товара: ', element.attrib['id'] ,' значение в файле:', vendor_tag.text, ' значение в базе данных:', item[0].brand print '-'*80 # конец теста assert stat==0, (u'Errors:%d\nDPD:%s')%(stat,DPD) def test_yml_3(self): """ проверка корректности ( доступности ) ссылки на товар (полный перебор тест длится около 4 часов)""" xml=etree.parse(self.YML_FILE_NAME, parser=None ) xml_tree=etree.iterwalk(xml, events=("start", "end"), tag="url" ) cnt=1 stat=0 for element in xml_tree: try: link=urllib2.urlopen(element[1].text, None, self.WAIT_TIME) except: print ('%d.Stat:%d Link:%s')%(cnt, link.code, element[1].text ) stat +=1 cnt+=1 assert stat==0, (u'Bad links find:%d')%(stat)
52cb3262e678e729d788ea29806040f421d44a89
[ "Python" ]
1
Python
TerminalTesting/yml_yandex_SB
8a985fbf69819d679a401b5c1d69141913474d73
a12fd48e04e34d14786583f1e0d57f3e82120153
refs/heads/master
<file_sep># Semester-Project-PED1<file_sep>/************************************************** * MPPT ALGORITHM - INTRO760 - Fall 2018 * This code implements a P&O algorithm to be used within a PLECS C-script. * The C script block has different execution codes (Code declaration, code execution * and update function code, among others) so the functions in this code are called * with the same names in order to know where to place every chunk. * * Things to do: * 1) Variables to tune: * -Decide C-script sample time. With different values the system has different behaviour * with the code from 3/11, 0.5 showed an acceptable tracking. * -delta duty cycle constant must be optimized * 2) in order to avoid noise, a threshold could be added to the power delta analysis * 3) The system startup logic must be optimized, to avoid big deltas * 4)... * */ #define V_OC_threshold 43 enum state { STARTUP, VOLTAGE_EVALUATION, VOLTAGE_INC, VOLTAGE_DEC, OPEN_LOOP, }; double V, I, P, Vprevious, Iprevious, Pprevious, delta_V; static double D_delta = 0.01; static double D = 0; static enum state SYSTEM_STATE = STARTUP; static int startup_counter = 0; #define V_in Input(0); #define I_in Input(1); #define D_out Output(0); void Open_loop_decrease_D(void){ D = D - D_delta; } void calculate_power(void){ P = V * I; } void evaluate_voltage(void){ delta_V = V - Vprevious; } void save_variables(void){ Vprevious = V; Iprevious = I; Pprevious = P; } int power_is_increased(void){ return P > Pprevious; } int power_is_decreased(void){ return P < Pprevious; } <file_sep> --- title: "Exam 1" output: html_document: default pdf_document: default word_document: default --- # Part I: Estimating probabilities Remember to load the `mosaic` package first: ```{r message=FALSE, echo=FALSE} library(mosaic) options(digits = 4) library(pander) ``` ## Chile referendum data In this part we will use the **dataset `Chile`**. Remember to read the [description](http://www.rdocumentation.org/packages/car/functions/Chile) of the dataset as well as the [Wikipedia](https://en.wikipedia.org/wiki/Chilean_national_plebiscite,_1988) entry about the background. ```{r } Chile <- read.table("http://asta.math.aau.dk/dan/static/datasets?file=Chile.dat", header=TRUE, quote="\"") ``` NB: **This dataset has several missing values (`NA`)**. To remove these when you use `tally` you can add the argument `useNA = "no"`. - Do a **cross tabulation of the variables `vote` and `sex`**. ```{r size="small"} tally( ~ vote + sex, data = Chile, useNA = "no") ``` - Estimate the **probability of `vote=N`**. ```{r size="small"} tally( ~ vote + sex, data = Chile, useNA = "no", format ="percent", margin = 1) ``` ```{r size="small"} P1 = 14.336+20.7747 P1 ``` - Make a **95% confidence interval** for the probability of **`vote=N`**. *estimated standard error* of $\hat{\pi}$: $$se=\sqrt{\frac{\hat{\pi}(1-\hat{\pi})}{n}}$$ ```{r, fig.height = 3, fig.width = 5} n = 2532 #removing the NA se1 = sqrt((P1/100*(1-P1/100))/n) se1 ``` *Then we calculate the z value for a 95% of confidence interval using the next command:* ```{r, fig.height = 3, fig.width = 5} z = qdist("norm", 1-0.05/2) z ``` *the 95% of confidence interval is given by:* $$conf.int = \hat{\pi} \pm z·(se)$$ ```{r, echo = FALSE,fig.height = 3, fig.width = 5} P1inter = P1+z*100*c(-se1, se1) P1inter ``` Thus, the confidence interval is [33.25% 36.97%] **Checking** the results with *prop.test* ```{r} prop.test(~ vote, data = Chile, correct = FALSE, success= "N") ``` *We can see that both of the results match.* - Estimate the **probability of `vote=N` given that `sex=F`**. *Conditional probability* of the event $A$ given the event $B$: $$P(A|B)=\frac{P(A \text{ and } B)}{P(B)}$$ *The probability of being a female and voting N divided by the probability of bring female.* ```{r size="small"} P_NF = 14.336 tally( ~ vote + sex, data = Chile, useNA = "no", format ="percent", margin = 1) P_F = (4.107+14.336+14.297+18.957) P2 = P_NF/P_F ``` By looking at the table, $$P(F)=4.107+14.336+14.297+18.957 = 51.697\text{ %} $$ $$P(N\text{ and }F)=14.336 \text{ %} $$ $$P(N|F)=\frac{14.336}{51.697} =27.73 \text{ %} $$ - What would these probabilities satisfy if `vote` and `sex` were statistically independent? If information about $B$ doesn't change the probability of $A$ we talk about independence, i.e. $A$ is **independent** of $B$ if $$P(A|B) = P(A) \Leftrightarrow P(A \text{ and } B) = P(A)P(B)$$ *In this case, can be easily checked that the combined probability assuming that both A and B are independent, is different that the probability calculated previously.* ```{r } P1 = 0.35111*0.5107 P1 ``` # Part II: Sampling distributions and the central limit theorem This is a purely theoretical exercise where we investigate the random distribution of samples from a known population. ## House prices in Denmark The Danish real estate agency HOME has a database containing approximately 80.000 house prices for one-family houses under DKK 10 million for the period 2004-2016. The house prices (without all the additional information such as house size, address etc.) are available as a R data file `Home.RData` on the course webpage. If you download it you can load it using `load("Home.RData")` assuming you have saved it in the same directory as this Rmarkdown document. This will add the vector `price` to your work space. Alternatively, you can add it directly from the course website (this will download it every time you run the Rmarkdown document, so make sure you have a decent internet connection): ```{r echo=FALSE} load(url("http://asta.math.aau.dk/dan/static/datasets?file=Home.RData")) #load("Home.RData") ``` **Make a histogram of all the house prices** using a command like `histogram(price, breaks = 30)` inserted in a new code chunk (try to do experiments with the number of breaks): ```{r} par(mfrow=c(2,2)) hist(price, breaks = 30) hist(price, breaks = 60) hist(price, breaks = 100) hist(price, breaks = 200) ``` - **Explain** how a histogram is constructed. *In an Histogram, the area of each box corresponds to the relative frequency of the variable in each interval.* *In theory we can imagine an infinite number of observations, which would produce a nice smooth curve, where the area below the curve is 1. A function derived this way is also what we call the probability density function.* - Does this **histogram look like a normal distribution**? *This Histogram is not a Normal distribution, but a Right skew density shape.For example we can clearly see that the mean is not 0 (nomral distribution), but 1.9.* ```{r} mean(price) sd(price) ``` ```{r} median(price) ``` *It can be seen that, in this case, the median is lower than de mean. What means is that there are more samples at the left to the mean than at the right.* In this database (our population) the mean price is `r mean(price)` and the standard deviation is `r sd(price)`. **In many cases access to such databases is restrictive** and in the following we imagine that we are only allowed access to **a random sample of 40 prices** and the mean of this sample will be denoted `y_bar`. Before obtaining this sample we will use the Central Limit Theorem (CLT) to predict the distribution of `y_bar`: - What is the expected value of **`y_bar`**? By the CLT, it is known that the value of `y_bar` is the mean of the values in the sample. ```{r} y_bar = mean(price) y_bar ``` - What is the **standard deviation** of `y_bar` (also called the standard error)? By the same way, the standard error follows the next formula: $standard\text{ } error = \frac{\sigma}{\sqrt{n}}$ ```{r} sigma = sd(price) sd_error = sigma/sqrt(40) sd_error ``` - What is the **approximate distribution of `y_bar`**? *The approximate distribution of* `y_bar` *is a Normal distribution with the mean of the sample and the standard deviation equal to the standar deviation of the samples over the square root of the number of samples* $\hat y = N(\mu, \text{ }\frac{\sigma}{\sqrt{n}})$ Now **make a random sample of 40 house prices** and **calculate** the sample **mean**: ```{r} y <- sample(price, 40) y_bar2 = mean(y) y_bar2 sigma2 = sd(y) sigma2 ``` Repeat this command a few times. Is each mean price close to what you expected? *The mean price is close to the real value, as the standard error is small compared with the mean value.However, the standar deviation of the sample is higher than real the standard deviation* Use `replicate` to repeat the sampling 200 times and save each mean value in the vector `y_bar2`: ```{r} y_bar2 <- replicate(200, mean(sample(price, 40))) ``` Calculate the mean and standard deviation of the values in `y_bar2`. ```{r} mean(y_bar2) sd(y_bar2) ``` - How do they match with what you expected? *The mean of the vector is practically the same as the real mean* *The standard deviation of the vector is close to the standard error of the previous sample (with 40 samples)* - **Make a histogram** of the values in `y_bar` and **add the density curve** for the approximate distribution you predicted previously using `plotDist` with the argument `add = TRUE`.For example for a normal distribution with mean 2 and standard deviation of 0.2: ```{r fig.keep='last'} histogram(y_bar2, breaks = 15, type = "density") plotDist("norm", mean = y_bar, sd = sd_error, add = TRUE, col = "red") ``` *We can see that the colums have more or less similar shape than a normal distribution with a mean being around 2 and a sd of 0.2* - **Make a boxplot** of `y_bar` and explain how a boxplot is constructed. ```{r} bwplot( y_bar2) minim<-min(y_bar2) minim maximum<-max(y_bar2) maximum ``` *interquartile range =IQR=Q3-Q1;* *outlier<Q1-1.5·IQR;* *outlier>Q3+1.5·IQR* # Part III: Theoretical boxplot for a normal distribution Finally, consider the theoretical boxplot of a general normal distribution with mean $\mu$ and standard deviation $\sigma$, and find the probability of being an outlier according to the 1.5$\cdot$IQR criterion: - First **find the $z$-score of the lower/upper quartile**. I.e. the value of $z$ such that $\mu \pm z\sigma$ is the lower/upper quartile. q1=$\mu + z·sigma$ q3=$\mu - z·sigma$ ```{r} q1 <- qdist("norm", 0.25, plot = FALSE) q3 <-qdist("norm", 0.75, plot = FALSE) q1 q3 ``` - Use this to **find the IQR** (expressed in terms of $\sigma$). The IQR then is $(\mu+0.6745\sigma)-(\mu-0.6745\sigma) = 2\cdot0.6745\sigma = 1.349\sigma$ - Now find the $z$-score of **the maximal extent of the whisker**. I.e. the value of $z$ such that $\mu \pm z\sigma$ is the endpoint of lower/upper whisker. ```{r} Ll = -0.6745-1.5*1.349 Ul = 0.6745+1.5*1.349 Ll Ul ``` - Find the probability of being an outlier. ```{r} PLl = pdist("norm", q = Ll, mean = 0, sd = 1, plot = FALSE) PUl = pdist("norm", q = Ul, mean = 0, sd = 1, plot = FALSE) PIN = PUl-PLl POUT = 1-PIN POUT ```<file_sep>--- title: "Exam - stochastic processes" output: pdf_document: default html_document: default word_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(eval = TRUE) ``` # CO2 concentration in atmosphere R's built-in dataset `co2` is a time series of atmospheric CO2 concentration at the Mauna Loa observatory. We will analyse this dataset below. ## Explorative data analysis - Start as always by plotting the data. ```{r, echo = FALSE} par(mfrow = c(2,1), mar = c(2,2,2,2)) plot(co2) CO2_month <- ts(co2, start = 1959, freq = 12) CO2year <- aggregate(CO2_month, FUN = mean) plot(CO2year) ``` *It seems that the CO2 concentration increases linearly with time.* *Afterwards a monthly boxplot is shown in the next figure:* ```{r} cyc <- cycle(CO2_month) cyc <- factor(cyc, labels = month.abb) boxplot(CO2_month ~ cyc) abline(h=mean(co2), col = "red", lwd = 2) ``` *This boxplot shows the stationality. The CO2 concentration increases a little bit on the first semester of the year, and decreases on the second semester. Although, the variation is very small.* - Is this a second order stationary time series (explain what it means)? *To be a second order stationary time series the mean should be 0 and the variance should be constant in time. In this case we can clearly see that we have a trend (not repetitive sequnece) which means that the mean is not 0 (it is not a time series).* *Looking to the different graphs the ramdomness or the error term could be the only parameter close to a second order satationary time series (mean~0).* - Use `decompose` to make a decomposition of the data to remove any trend and seasonal component and explain the method of how this is done. ```{r} CO2_decomp <- decompose(CO2_month) CO2_trend <- CO2_decomp$trend CO2_no_trend <- CO2_month - CO2_trend plot(CO2_decomp) ``` *This method is based in the next equations:* $$x_t = m_t+s_t+z_t \quad \text{where } m_t: \text{trend, }s_t: \text{sesasonality and }z_t: \text{randomness}$$ - Save the random component as `co2rand` (omit any `NA` values), plot the correlogram of `co2rand` and explain the correlogram: What is it used for and how is it interpreted? What is assumed about the underlying process? ```{r } par(mfrow = c(2,1), mar = c(3,3,3,3)) plot(CO2_decomp$random) co2rand <- na.omit(CO2_decomp$random) acf(co2rand) ``` *It is a periodic correlogram, there is a sinusoidal seasonality going above the blue lines. In the lower part of the the blue lines there is a strong negative correlation whereas in the upper part of the limits there is a strong positive correlation.* ## Auto-regressive model of order 1 - Manually **fit a AR(1) model** using `lm` without an intercept: ```{r} n <- length(co2rand) y <- co2rand[2:n] x <- co2rand[1:(n-1)] fitlm <- lm(y ~ x-1) summary(fitlm) ``` - Explain the output of the last command above. Is there significant autocorrelation? What is the estimated lag 1 autocorrelation coefficient? *The summary command shows that there is a strong correlation between the actual value (y) and the previous one(x), as it can be seen in the p-value. Also, the F-test value is very high, what means that the actual model, is good model.* - Write down **the equation expressing the fitted model**. $$x_t = \alpha_1x_{t-1}+\epsilon_t$$ $$\text{being: autocorrelation coefficient }=\alpha_1=0.408$$ - Based on the data $x_1,\dots,x_n$ **what is the predicted value** for $x_{n+1}$? *Based on the previous equation, and assuming that the error* $\epsilon_t = 0$ *for predictions, the next expression can be obtained:* $$x_{n+k} = \alpha^kx_n$$ - What is the predicted value for $x_{n+10}$? $$x_{n+10} = \alpha^{10}x_n$$ ```{r, echo= FALSE} alpha <- coef(fitlm) x_n = co2rand[n] x_n10 = alpha^10*x_n x_n10 ``` - Save the model residuals (use `residuals(fitlm)`) and **plot the correlogram**. What is the theoretical acf for this model? Is the AR(1) model a good fit? ```{r, echo= FALSE} par(mfrow = c(2,1), mar = c(3,3,3,3)) fit_residuals <- residuals(fitlm) plot(fit_residuals) acf(fit_residuals) ``` *The ACF we obtain is not white noise, asit is can be seen that there is some seasonality with the lags at 5,11,12,17. This shows us that the model is not fitting properly the randomness component.* ## Higher order autoregressive moving average (ARMA) models - How do we **define higher order AR(p) processes**? *An AR(p) process is the one that uses several lag terms for explaining the current value * $$x_t = \alpha_1x_{t-1}+\alpha_2x_{t-2}+...+\alpha_px_{t-p}+w_t$$ *To ensure the model is stationary, all the roots of the characteristic equation must be found, and check that the absolute value of all of them is greater than 1.* $$1-\alpha_1z-\alpha_2z^2-...-\alpha_pz^p=0$$ - Use `lm` as above to **estimate an AR(2) model** for `co2rand`. Is the lag 2 autocorrelation coefficient significant according to a `summary` of the fitted model? ```{r} n <- length(co2rand) x <- co2rand[3:n] x1 <- co2rand[2:(n-1)] x2 <- co2rand[1:(n-2)] fitlm2 <- lm(x ~ x1 + x2 - 1) # -1 is for removing the intercept. summary(fitlm2) ``` *the predictor, X2 is not significant in this model. So, X2 (first value) doesnt have a strong correlation with the X (third value) due to the fact that the p value exceeds the 5%.* - **What is the partial autocorrelation function (pacf)** and how is it useful in relation to AR(p) processes? *The partial autocorrelation is the function that shows if there is any correlation between values that are not consecutive. The function is :* $$x_t=\beta_0+\beta_1*x_{t-1}+\beta_2*x_{t-2}+\epsilon $$ *If a time series has a strong correlation with the values lagged by one time step it most likely also has a trong correlation with the values lagged by two time steps: When today's value is highly influenced by yesterdays, then yesterdays will be highly influenced by the day before, and thus the lag 2 value influences the current value through the lag 1 value.* *For a strong deterministic trend the pacf only shows strong correlation in the first lag and after controlling for this the following lags show no extra correlation* - How is a **MA(q) process** defined? *A moving average (MA) process is a finite sum of stationary white noise terms. It is itself stationary, what means that the mean and variance are time-invariant.* $$x_t = w_t+\beta_1w_{t-1}+\beta w_{t-2}+...+\beta_qw_{t-q}$$ *where* $w_t$ *is white noise process with mean zero and variance * $\sigma_w^2$ *, and * $\beta_1, \beta_2,...,\beta_q$ * are the parameters to be estimated.* - Try to fit a collection of **ARMA(p,q) models for $p$ and $q$ at most 2, and find the best fitting model** one based on AIC. (Hint: If you called the models `ar1`, `ar2`, `ma1`, `ma2`, `arma11`, `arma12`, `arma21`, and `arma22` you can compare them all in a single call to `AIC`; `AIC(ar1, ar2, ma1, ma2, arma11, arma12, arma21, arma22)`) ```{r} ar1 <- arima(co2rand, order = c(1,0,0)) ar2 <- arima(co2rand, order = c(2,0,0)) ma1 <- arima(co2rand, order = c(0,0,1)) ma2 <- arima(co2rand, order = c(0,0,2)) arma11 <- arima(co2rand, order = c(1,0,1)) arma12 <- arima(co2rand, order = c(1,0,2)) arma21 <- arima(co2rand, order = c(2,0,1)) arma22 <- arima(co2rand, order = c(2,0,2)) AIC(ar1,ar2,ma1,ma2,arma11,arma12,arma21,arma22) ``` *The best fitting one is the last arma22 which has an AIC of -102.569646. In arma22 you take in consideration the last 2 previous values and the last 2 white noise values* *AIC the lower the better. The next function shows how the equation would look like:* $$x_t =\alpha_1x_{t-1}+\alpha_2x_{x-2}+w_t+\beta_1w_{t-1}+\beta_2w_{t-2}$$ - Write down **the parameter estimates of the final model**, and check whether it is a good fit to the data. ```{r, echo= FALSE} arma22 ``` ```{r, echo= FALSE} par(mfrow = c(2,1), mar = c(3,3,3,3)) resid_arma22 <- na.omit(arma22$residuals) plot(resid_arma22) acf(resid_arma22) ``` *The ACF shows that there is no interaction or seasonality between the lags. the residuals from this model is white noise, what means that the model is a good fit to the data.* - Give **95% confidence intervals for the parameter estimates** of the final model selected by AIC. ```{r} confint(arma22) ``` ## Prediction - **Make a prediction with an approximate 95% prediction interval** for the next value of the random component $x_{n+1}$ based on this model. ```{r } pred1 <- predict(arma22, n.ahead = 24) lower1 <- pred1$pred-2*pred1$se upper1 <- pred1$pred+2*pred1$se ts.plot(co2rand, pred1$pred, lower1, upper1, lty = c(1,2,3,3), xlim=c(1996,1999)) ``` *As we can see, the predicted value goes to zero, when we increase the prediction time.* - **If there was no autocorrelation** in the random component the approximate 95% prediction interval is given by $\bar{x} \pm 2\sqrt{s^2(1+1/n)}$. Calculate this prediciton interval and compare it with the one obtained above. What is the difference? Try to explain this. ```{r, echo= FALSE} x_bar <- mean(co2rand) se <- var(co2rand) n <- length(co2rand) lim <- sqrt(se*(1+1/n)) x_bar + c(-lim, lim) ``` *This confidence interval doesn´t take into account the previous values of the time series, but only a summary of them (by the mean value and the standard error).* *This way of getting the confidence interval is easier than the one based in the ARMA model, but it is also less accurate. * <file_sep>--- output: pdf_document: default html_document: default word_document: default --- # Exam 1 # Part I: Estimating probabilities Remember to load the `mosaic` package first: ```{r message=FALSE } library(mosaic) options(digits = 4) library(pander) ``` ## chile referendum data In this part we will use the dataset `chile`. Remember to read the [description](http://www.rdocumentation.org/packages/car/functions/chile) of the dataset as well as the [Wikipedia](https://en.wikipedia.org/wiki/chilean_national_plebiscite,_1988) entry about the background. ```{r} Chile <- read.table("http://asta.math.aau.dk/dan/static/datasets?file=Chile.dat", header=TRUE, quote="\"") ``` NB: This dataset has several missing values (`NA`). To remove these when you use `tally` you can add the argument `useNA = "no"`. - Do a cross tabulation of the variables `vote` and `sex`. 1) Chile dataset has 2700 obs. After removing the missing values 2500 remain. 2) Cross tabulation in percentage ```{r} chile<-tally(~vote+sex,data=Chile, useNA="no") n<-sum(chile) n chile<-tally(~vote+sex,data=Chile, useNA="no", format="percent") chile ``` - Estimate the probability of `vote=N`. ```{r} sum(chile[2,1:2]) pi<-14.336+20.774 pi ``` - Make a 95% confidence interval for the probability of `vote=N`. ```{r} se=sqrt((pi/100*(1-pi/100))/n) z = qdist("norm", 1-0.05/2) #Since qdist calculates the probability not taking into account the absolute value of z, for the left probability we obtain: z piInt= pi+z*100*c(-se,se) #100 times z since we are giving the conf int in percentage. piInt prop.test(~ vote, data = Chile, correct = FALSE, success= "N") ``` - Estimate the probability of `vote=N` given that `sex=F`. ```{r} tally(~vote+sex,data=Chile, useNA="no",format="percent",margin=1) piCond<-14.336/(51.698) piCond ``` - What would these probabilities satisfy if `vote` and `sex` were statistically independent? This fact would mean that P(`vote`) does not depend on P(`sex`) applying this: P(`vote`|P`sex`)=P(`vote`)*P(`sex`). ```{r} #P(`vote=N`) pi #P(`sex=F`) pif<-51.698 #P(P`vote`)*P(`sex`) pi*0.01*pif*0.01 #Whereas P(P`vote`|P`sex`) piCond #So the vote is conditioned by the sex ``` # Part II: Sampling distributions and the central limit theorem This is a purely theoretical exercise where we investigate the random distribution of samples from a known population. ## House prices in Denmark The Danish real estate agency HOME has a database containing approximately 80.000 house prices for one-family houses under DKK 10 million for the period 2004-2016. The house prices (without all the additional information such as house size, address etc.) are available as a R data file `Home.RData` on the course webpage. If you download it you can load it using `load("Home.RData")` assuming you have saved it in the same directory as this Rmarkdown document. This will add the vector `price` to your work space. Alternatively, you can add it directly from the course website (this will download it every time you run the Rmarkdown document, so make sure you have a decent internet connection): ```{r} load(url("http://asta.math.aau.dk/dan/static/datasets?file=Home.RData")) ``` Make a histogram of all the house prices using a command like `histogram(price, breaks = 30)` inserted in a new code chunk (try to do experiments with the number of breaks): ```{r} #With my own deffinition for the breaks histogram(price, breaks = c(0,3.33,6.66,10)) #Using the R default algorithm for making breaks par(mfrow=c(2,2)) hist(price, breaks = 2) hist(price, breaks = 10) hist(price, breaks = 100) hist(price, breaks = 1000) #As we increase the number of breaks, the graph aproximates to a probability density function. Related with this, the smaller the break is, the smaller the frequencies become (so few observations can comply with that precise value). #The sum of the area of the bars is equal to 1 independently of the number of bars. ``` - Explain how a histogram is constructed. To construct a histogram from a continuous variable the first is to split the data into intervals, called bins or breaks. In the example above, each bin contains the number of occurrences of dataset scores within that break. The y axis represents the frequency for each break. The sum of the area of all the bars has to be equal to 1. - Does this histogram look like a normal distribution? No. Although it has kind of a bell shape as the normal distribution, there is a notizable right skew. The normal distibution is symetrical around 0. Since the median is lower than the mean, there are more samples to the left of the mean than to the right of the mean. ```{r} median(price) mean(price) ``` In this database (our population) the mean price is `r mean(price)` and the standard deviation is `r sd(price)`. In many cases access to such databases is restrictive and in the following we imagine that we are only allowed access to a random sample of 40 prices and the mean of this sample will be denoted `y_bar`. Before obtaining this sample we will use the Central Limit Theorem (CLT) to predict the distribution of `y_bar`: Central Limit Theorem: For random sampling with a large sample size n, the sampling distribution of the sample mean y is approximately a normal distribution. - What is the expected value of `y_bar`? ```{r} mean(price) ``` - What is the standard deviation of `y_bar` (also called the standard error)? ```{r} sd(price)/sqrt(40) ``` - What is the approximate distribution of `y_bar`? N(1.929,0.2015) Now make a random sample of 40 house prices and calculate the sample mean: ```{r} y <- sample(price, 40) #sample give us random values from a vector. With n we specify the number of values we want to take mean(y) #Repeat this command a few times. Is each mean price close to what you expected? y <- sample(price, 40) mean(y) y <- sample(price, 40) mean(y) #Yes they are close to the estimated mean. ``` Use `replicate` to repeat the sampling 200 times and save each mean value in the vector `y_bar`: ```{r} y_bar <- replicate(200, mean(sample(price, 40))) ``` Calculate the mean and standard deviation of the values in `y_bar`. ```{r} mean(y_bar) sd(y_bar) ``` - How do they match with what you expected? They match perfectly with the CLT prediction as the number of samples increases enough (200 times). - Make a histogram of the values in `y_bar` and add the density curve for the approximate distribution you predicted previously using `plotDist` with the argument `add = TRUE`. For example if you predicted a normal distribution with mean 2 and standard deviation 0.2: ```{r fig.keep='last'} histogram(y_bar, breaks = 15, type="density",ylim=c(0,3)) plotDist("norm", mean = 2, sd = 0.2, add = TRUE, col = "red", ylim=c(0,3)) ``` - Make a boxplot of `y_bar` and explain how a boxplot is constructed. ```{r} boxplot(y_bar) ``` 1) Calculate the median, lower and upper quartiles. 2) Draws a line at the median and a box between the upper and lower quartiles. 3) Calculate interquartile range (upper quartile - lower quartile). 4) Calculate the following values: - L1 = lower quartile - 1.5$\cdot$IQR - L2 = lower quartile - 3.0$\cdot$IQR - U1 = upper quartile + 1.5$\cdot$IQR - U2 = upper quartile + 3.0$\cdot$IQR 5. Draw a line for lower quartile limit (L1). Similarly, draw a line for upper quartile limit (U1). 6. Measurements between L2 and L1 / between U1 and U2 are drawn as circles. Measurements smaller than L2 / larger that U2 are marked by a x. # Part III: Theoretical boxplot for a normal distribution Finally, consider the theoretical boxplot of a general normal distribution with mean $\mu$ and standard deviation $\sigma$, and find the probability of being an outlier according to the 1.5$\cdot$IQR criterion: - First find the $z$-score of the lower/upper quartile. I.e. the value of $z$ such that $\mu \pm z\sigma$ is the lower/upper quartile. q1=$\mu + z*sigma$ q3=$\mu - z*sigma$ ```{r} q1 <- qdist("norm", 0.25, plot = FALSE) q3 <-qdist("norm", 0.75, plot = FALSE) q1 q3 ``` - Use this to find the IQR (expressed in terms of $\sigma$). The IQR then is $(\mu+0.6745\sigma)-(\mu-0.6745\sigma) = 2\cdot0.6745\sigma = 1.349\sigma$ - Now find the $z$-score of the maximal extent of the whisker. I.e. the value of $z$ such that $\mu \pm z\sigma$ is the endpoint of lower/upper whisker. ```{r} Ll = -0.6745-1.5*1.349 Ul = 0.6745+1.5*1.349 Ll Ul ``` - Find the probability of being an outlier. ```{r} PLl = pdist("norm", q = Ll, mean = 0, sd = 1, plot = FALSE) PUl = pdist("norm", q = Ul, mean = 0, sd = 1, plot = FALSE) PIN = PUl-PLl POUT = 1-PIN POUT ``` <file_sep>--- output: pdf_document: default html_document: default word_document: default --- # Exam 2 You can download the combined lecture notes for this module at: <http://asta.math.aau.dk/dan/2017f/asta/?file=handouts/module-B.pdf> It is highly recommended that you answer the exam using Rmarkdown (you can simply use the exam Rmarkdown file as a starting point). Remember to load the `mosaic` package first: ```{r message=FALSE} library(mosaic) ``` ## Part I: Directed reading activities An educator conducted an experiment to test whether new directed reading activities in the classroom will help elementary school pupils improve some aspects of their reading ability. She arranged for a third grade class of 21 students to follow these activities for an 8-week period. A control classroom of 23 third graders followed the same curriculum without the activities. At the end of the 8 weeks, all students took a Degree of Reading Power (DRP) test, which measures the aspects of reading ability that the treatment is designed to improve. Read in the data: ```{r} reading <- read.table("http://asta.math.aau.dk/dan/static/datasets?file=reading.dat", header=TRUE) head(reading) ``` Use a boxplot to compare the of measurements of `DRP` for `Treated`(direct reading activities) and `Control` visually. ```{r} 'we want to see the score of each group, DRP=the experiment they have done' bwplot(Response~Treatment,data=reading) 'WHAT CAN BE SEEN IN THIS BOXPLOT? 1-treated group all the quartos are higehr than in the control some childresn score higher because the y axes is higher, but the treated perform better, this is not statisticaly significant cause if you change the observation you will obtain different values...' ``` Use `favstats` to make a numerical summary of the measurements for `Treated` and `Control`. ```{r} a<-favstats(Response ~ Treatment, data = reading) a 'now we see the response in relation to treatmeant, so the mean is 10 points higher!, the min, q1 compare it with the previous quartil graph, interesting favstats(Respose~Treatment,)' ``` ```{r} Control <- subset(reading, Treatment == "Control") Treated <- subset(reading, Treatment == "Treated") y1 = mean(~ Response, data = Control) y2 = mean(~ Response, data = Treated) y1 y2 s1 = sd(~ Response, data = Control) s2 = sd(~ Response, data = Treated) s2 s1 'S es la variacion y s^2 es la S=Sd desviacion tipica' ``` - Write down a point estimate of the mean of DRP for students following the new *directed reading activities* and explain how this is calculated. $$\overline{y}_{Treated}=\frac{1}{n_2}\sum_{i=1}^{n_2}{y_i}; \mbox{with }{y_1}\mbox{in the treated group}$$ ```{r} 'we just need to multiply each observation and divide it by the size of our variable.' ``` $$se=\sqrt{\frac{\pi(1-\pi)}{n}}$$ the sum of all the obs, divided by the obs of the group, explain the formula 'how the mean is calc' - Write down a point estimate of the standard deviation of DRP for this group and explain how this is calculated. $$S_{treated}=\sqrt{\frac{\sum(yi-\overline{y})^2}{n-1}}$$ - Write down a 95% confidence interval for the mean of DRP for this group and explain how this is calculated. ```{r} 'we use t score because the number of samples is less than 30' yvar=51.447619 s=11.00736 n=21 t<-qdist("t", 1-0.025, df=n-1) t 'remember that s/sqrt(n) is equal to se' interval951<-yvar-t*s/sqrt(n) interval952<-yvar+t*s/sqrt(n) interval951 interval952 ' So you are 95% confident that the real mean will be between those interval=56.46 and 46.44' ``` *All those results can be obtained by the comand* `t.test` ```{r} 'So we use t.test to comare it with the actual results calculated previously and we can say that in interval confidence for a 95 % is more or less the same' t.test( ~Response, data = Treated, conf.level = 0.95) ``` Use the command `t.test` to compare the mean DRP of the two groups. ```{r} t.test(Response ~ Treatment , data = reading) 'If Pvalue is less than 0.05 we can say that we reject the zero hypothesis as it is unprobable to occur, as a consequence we can say that the mean will be more probable to happen in the alternative hypothesis. Dentro del resultado t test el intervalo de confianza del 95% es para la hypothesis, If 0 is inside the interval and the pvalue is more than 0.05 we can say that our zero hypothesis is probable to happen In the contrary if the 0 is not in the interval and p-value<0.05 we can reject the zero hyp because is unprobable to happen, as a conseqence we can tanke the alternative hypotehsis.' 'What does the -18 and -1 confidence interval mean?? that if you make another experiment with new samples, your difference (d=10) will be always between (18 and 1) with the 95% of probability sometimes d could be=9, 11, 15 being still inside the interval.' ``` Go through the details of the output from t.test. Your analysis must include an account of - What the relevant null hypothesis and the corresponding alternative hypothesis is. ```{r} ' dependent sample: if we take the wiegh of our class one day, then we ate some chocholoate and see the weghts tomorrow for the same sample=the same class. independent sample: if we take the weights of different classes. WE ASSUME THAT IT IS INDEPENDENT for the calculations.the first 3 questions are related making a hypothesis and the last question is related to' ``` *The null hypothesis is* $$H_0:\hat\mu_1=\hat\mu_2$$ *and the alternative hypothesis is * $$H_a:\hat\mu_1\neq\hat\mu_2$$ - Choice and calculation of test statistic. ```{r} 'For obtaining the test statistic, it is neccesary to calculate the standard error of the difference, as follows: we choose the t score as there are 22 observations for treatment and 22 observations for control the samples which is less than 30. it is true that in overall there are 44 samples, however you have to count each of the samples independently to choose the best suitble statistic calculation (t-score, z-score). ' ``` $$se_d=\sqrt{\frac{s_1^2}{n_1}+\frac{s_2^2}{n_2}}$$ ```{r, echo=FALSE} a<-favstats(Response ~ Treatment, data = reading) a Control <- subset(reading, Treatment == "Control") Treated <- subset(reading, Treatment == "Treated") s1 <- sd(~ Response, data = Control) s2 <- sd(~ Response, data = Treated) n1<-23 n2<-21 s2 s1 sed = sqrt((s1^2/n1)+(s2^2/n2)) sed 'es lo q se desvia de la diferencia por arriba y por abajo. en este caso la d= es 10 mas o menos (y1(media del sampel)-y2(media del sample2)) the Sed is 4.3 which means thatif we make another sample or a new experiment, we can say that if we make the difference between both means again the error will vary between 10+4.3 and 10-4.3 (divided by 2???? nose preguntar). ' ``` *The value of t for the t.test is calculated as follows:* $$t=\frac{\overline y_2-\overline y_1}{se_d}\mbox{ }{\mu_1} and {\mu_2}\mbox{the difference is equal to 0}$$ ```{r, echo = FALSE} tobs = (y1-y2)/sed tobs 'tenemos una z , teniendo la t=z (eje X) miramos la probabilidad de estar a la derecha de esa observacion' ``` - Calculation of p-value and its interpretation in connection to a conclusion of the analysis. ```{r} 'qdits("norm") we use it for the z score qdits("t") we use it for the z score degree od freedom because the t score varies with the degree of freedom. n=number of observations bigger than 30 you use a z score n=number of observations less than 30 you use a t score' ``` *Once obtained the t value, the probability of occurrence of this value is obtained by the t curve. The p-value is defined as the left probability of this value times two. When the p-value is small, we can consider rejecting the* $H_0$ *hypothesis.* ```{r, echo = FALSE} 'you obtain the degrees of freedom df from the t.test previous exercises, which is 38, t.test(Response ~ Treatment , data = reading)' t.test(Response ~ Treatment , data = reading) P <- 2*pdist("t", q = tobs, df = 37.855) P ``` and if we put t for the t score - Calculation and interpretation of a relevant confidence interval. ```{r} 'independent they are not all the same students' ``` ## Part II: Determining sample size _In this part there is no dataset to load into R and analyze. You should just use R as a calculator when you apply the relevant formulas (which are towards the end of the lecture notes for module 1)._ To estimate the proportion of danish companies with less than 10 employees determine the necessary sample size for the estimate to be accurate to within 0.06 with probability 0.90. Based on results from a previous study in 2013, we expect the proportion to be about 0.70. ```{r} #how many companies you have to take to be ass aquerrate as 0.7 with a prob of 0.9' #90% means you can be on the right 5% and to the left %5' ``` *The margin of error when estimating a proportion is* $$M = z \sqrt {\frac{\pi(1-\pi)}{n}}$$ *Solving the equation for obtaining n* prop.test(Chile$vote, 2532, success="N", correct=FALSE) $$n = \pi(1-\pi)(\frac{z}{M})^2$$ *With the given values, the sample size can be calculated* ```{r} M = 0.06 pi = 0.7 z<-qdist("norm", p= 0.05, mean = 0, sd = 1, plot = FALSE) 'with q dist you calculate the z value for a probability of 10 %. 5% to the right and 5% to the left' n = pi*(1-pi)*(z/M)^2 n ``` *If we want to be more conservative, we can use the value of* $\pi=0.5$ $$n = (\frac{z}{2M})^2$$ ```{r, echo=FALSE} 'now if we decrease the pi we have less information about the proportion, so if we want a 90 percent of te confidence interval we have to increase the samples.' M = 0.06 pi = 0.5 z<-qdist("norm", p= 0.05, mean = 0, sd = 1, plot = FALSE) n = pi*(1-pi)*(z/M)^2 n ```<file_sep>V=V_in; I=I_in; update_function(); update_function(void){ switch (SYSTEM_STATE){ case STARTUP: { if(V > V_OC_threshold) { SYSTEM_STATE = OPEN_LOOP; D = 0.8; } }break; case OPEN_LOOP: { Open_loop_decrease_D(); calculate_power(); save_variables(); startup_counter++; if (startup_counter >= 5) SYSTEM_STATE = VOLTAGE_EVALUATION; }break; case VOLTAGE_EVALUATION: { evaluate_voltage(); if (delta_V >= 0) SYSTEM_STATE = VOLTAGE_INC; if (delta_V < 0) SYSTEM_STATE = VOLTAGE_DEC; }break; case VOLTAGE_INC: { calculate_power(); if (power_is_increased()) D = D - D_delta; if (power_is_decreased()) D = D + D_delta; save_variables(); SYSTEM_STATE = VOLTAGE_EVALUATION; }break; case VOLTAGE_DEC: { calculate_power(); if (power_is_increased()) D = D + D_delta; if (power_is_decreased()) D = D - D_delta; save_variables(); SYSTEM_STATE = VOLTAGE_EVALUATION; }break; } printf("System state: %d \n", SYSTEM_STATE); } <file_sep> /***** * This code is NOT executed once per timestep. Check documentation for further info. */ void output_function(); output_function(){ Output(0) = D; } <file_sep>--- output: html_document: default pdf_document: default word_document: default --- # Exam 3 You can download the combined lecture notes for this module at: <http://asta.math.aau.dk/dan/2017f/asta/?file=handouts/module-C.pdf> Remember to load the `mosaic` package first: ```{r message=FALSE} library(mosaic) ``` ## House prices In this exercise you will study the data described in Agresti EXAMPLE 9.10. You are studying house sales in Gainesville, Florida, where among other things the data contain the selling price (`Price`), property taxes (`Taxes`) and house size (`Size`). Read in the data: ```{r} HousePrices <-read.table("http://asta.math.aau.dk/dan/static/datasets?file=HousePrice.dat", header=TRUE) head(HousePrices) ``` - **Make a relevant plot of the variables** and discuss how they are related. ```{r, fig.width = 6, fig.height = 6, echo=FALSE} splom(HousePrices, pch = 16, cex = 0.5) ``` *we can see that the 3 variables are highly related to each other in a sense that they make a more or less a linear correlation. AS one of the variables increase the other one also, so we expect to have high values of correlation between variables* - **Explain the concept of correlation** and determine whether there is significant positive **correlation between `Taxes` and `Size`**. *The Correlation measures the strength of dependence between the variable y and variable x. In other words refers to how close two variables are to having a linear relationship with each other.* *Lets take x and y as parameters that could be correlated. * *Thus, *$s_y$ *and* $s_x$ *denote the sample standard deviation of y and x.* *The corresponding prediction equation is then * $$\hat y_t = \frac{a}{s_y}+\frac{s_x}{s_y}bx_t$$ *Then, the standardized regression coefficient, also called the correlation is: * $$r = \frac{s_x}{s_y}b$$ *In this model we can calculate the correlation of Taxes and Size by means of the next command:* ```{r} cor(HousePrices) ``` *As could be deduced before plotting, there are a strong relation between Prices and Taxes, and also between Size and Prices. This graphic also shows that there is a correlation between Size and Taxes.* *Some values are extremes, and coud be removed to get a more accurate model* *using the next command a correlation test has been made:* ```{r} cor.test(~Taxes+Size, data=HousePrices) ``` *We can say watching the p-value that our zero hypothesis is rejected due to the value is bellow %5... which accomplishes the alternative hypothesis.It also can be stated that there is a significant (p=2.2e-16) correlation between taxes and size.* *On te other hand, we can say with a 95% of confidence level that the correlation will be around 0.7416 and 0.8745.* **Fit a multiple regression model** with **Price as the response** variable and **`Taxes` and `Size` as predictors**. ```{r} model <- lm( Price ~ Taxes+Size, data = HousePrices ) model ``` - What are the parameters of the model and what is the **interpretation of these parameters**? *The intercept point (-28608.74) means the price when both Taxes and Size are equal to zero. In other words it is the offset of the equation. We can also see the slope of each of the explanatory variables(x1 and x2) which are beta1=66.51 for Taxes and beta2=39.6 for Size* - What is the **prediction equation**? $$ \widehat y = -28608.74+39.60x_1+66.51x_2 \quad \text{,where x1 is Taxes and x2 is Size} $$ **Explain the output of the model** where `model` is the fitted multiple regression model. This explanation should as a minimum include: *Model without interactions:* $$y = \alpha+\beta_1x_{1}+\beta 2·{x_2}+e$$ ```{r} summary(model) ``` - **Calculation of `t value`** and determination and **interpretation of p-value**. *The t-value is calculated as shown:* $$ t = \frac{\text Estimate}{\text {Standard Error}} $$ *Once obtained the t value, the probability of occurrence of this value is obtained by the t curve. The p-value is defined as the left probability of this value times two.* ```{r } P = 2*pdist("t", q = 5.72, df = 97) P ``` *In this case, the t-value for Taxes and Size is high, so the P-value is small. In both cases the Pvalue is almost zero, what means that there is almost no probability that the variables Taxes ans Size are not related with the variable Price. * - **Degrees of freedom** *In this case, we have 100 observations and 3 variables. Thus, the model have 100-3=97 degrees of freedom.* - **Interpretation of `Multiple R-squared`.** *The Multiple R-Squared means the relative reduction in prediction error. For calculating the R-squared there is a need to calculate to variables the TSS and SSE. The Tss is the squarred error between the observation and the mean, and the SSE, which is the squarred error between the regression line and the observation.* $$R^2 = \frac{TSS-SSE}{TSS} \quad \text {}$$ - How the table of output can be used to construct **confidence intervals for parameters**. *We can construct a confidence interval for each parameter by following the next graph.* ```{r } t<-qdist("t", p = 0.025, df = 100-3) t ``` $$ \text {for a 95% confidence interval: }\quad t = 1.9847$$ $$\text {for the variable Taxes} \quad (min,max) = b_1 \pm tse_b = 39.601 \pm 1.9847\cdot 6.917 = (25.87, \quad 53.33)$$ $$\text {for the variable Size} \quad (min,max) = b_2 \pm tse_b = 66.512 \pm 1.9847\cdot 12.817 = (41.07, \quad 91.95)$$ *Checking the results with the confint function for a 95% of the confidence level:* ```{r} confint(model) ``` - **Interpretation of F-statistic** *It shows if the model can be reduced into a single value (the intercept point), because all the predictors are not significant (Null Hypothesis), depending on the p-value.* $$F = \frac{(n-k-1)R^2}{k(1-R^2)} = \frac{(100-2-1)\cdot0.7722}{2(1-0.7722)} = 164.4$$ ```{r} 1 - pdist("f", 164.4, df1=2, df2=97, plot = FALSE) ``` Finally, you have to investigate whether or not there is an **interaction between the effect of `Taxes` and the effect of `Size` as predictors of `Price`**. *interaction model equation:* $$y = \alpha+\beta_1x_{1}+\beta_2·{x_2}+\beta_3·{x_1}·{x_2}$$ ```{r} model2 <- lm( Price ~ Taxes*Size, data = HousePrices ) summary(model2) ``` *df=n-4=100-4=96, we have for parameters (x1,x1,x1x2,y)* *Looking at the predictors in this model, it seems that the single predictors are not needed for explaining the model, but only the multiple predictor. * *We can say that the first model has a lower p value is so its a better model comparing to the new one with interactions. According to the p value we can see that the two predictros(taxes and size) are dependent due to a very low p value.t value (the x axis) of the bell, it is positive (right side). the higher is the t value, you are more separeted from the mean and more to the edge, which is very unprobable to happen.* *You can also say that you can reject the null hypothesis as the pvalue is lower than %5* *Again we can see that the t value is calculated by the estimate divided the sandard error.* *As a conclusion we finally we choose the first model as the best model, as the significance (the estimates are more close to be next to the regression line than the new one.* *comparing both R squares we can see that the new model has a higher value of R^2=0.78 whereas the old ones was 0.77, getting as close to 1 is favorable or better as your SSE will get to 0 having a a line as fitted as possible.* *if you remove one you have to run the model again and see the results because the p values will change and maybe you can reject one variable or not. don know, run it !* *About the R-squared, it is slightly higher because we introduce one new predictor. Although, this second model is not as good as the previous one.* <file_sep>--- output: pdf_document: default html_document: default word_document: default --- # Exam 3 You can download the combined lecture notes for this module at: <http://asta.math.aau.dk/dan/2017f/asta/?file=handouts/module-C.pdf> Remember to load the `mosaic` package first: ```{r message=FALSE} library(mosaic) ``` ## House prices In this exercise you will study the data described in Agresti EXAMPLE 9.10. You are studying house sales in Gainesville, Florida, where among other things the data contain the selling price (`Price`), property taxes (`Taxes`) and house size (`Size`). Read in the data from the next link: ```{r} HousePrices <- read.table("http://asta.math.aau.dk/dan/static/datasets?file=HousePrice.dat", header=TRUE) head(HousePrices) 'we can see that we have a sample of 100 observations relating prices, taxes and size.' ``` - Make a relevant plot of the variables and discuss how they are related. ```{r } x11();splom(HousePrices,pch=16,cex=0.5) 'prof: so here you can see size y x taxes, very gh corrreltaion so , intrersting the covariant linearly independent' 'how to read the graph? each of the rows variable is in the y axes. so for example the first square 1left upper part, the size is Y and X is Taxes.' 'we can see that the 3 variables are highly related to each other in a sense that they make a more or less a linear correlation. AS one of the variables increase the other one also, so we expect to have high values of correlation between variables' ``` - Explain the concept of correlation and determine whether there is significant positive correlation between `Taxes` and `Size`. ```{r} 'Correlation measures the strength of dependence between y and x OR refers to how close two variables are to having a linear relationship with each other.WHEN=-1 NEGATIVE SLOPE' correlation<-cor(HousePrices) correlation 'A higher correlation value means that while one variable is increasing the other one is also increasing proportionally. However tha imporatnt thing is: the higher the value of the correlation(max=1) the the slope of the curvewill be more similar to a line. However the correlation can be also negative, which means that it is inversamente proportional(negative proportional) to the previous slope, which in that case will be the opposite thing making an X. So from the houseprices file we can say that the 3 varaibles (taxes, price and size) are highly correlated due to the fact that its values are close to 1 (higher than %80).Price and taxes are the one that are more correlated with a (84 %). which means that when prices increase the taxes will also increase more or less proportional to each other.' relation_between_variables<-cor.test(~Taxes+Size, data=HousePrices) relation_between_variables 'We can say watching the p-value that our zero hypothesis is not accomplished due to the value is bellow %5... it means that your value will be more probable to be close to one, which accomplishes the alternative hypothesis. So the 0 hypothesis is rejected because the p value is less than 5%. consequently the alternative hypothesis is the one that it is valid. On te other hand, you can say with the 95% of confidence interval that the correlation will be around 0.7416 and 0.8745. ``` Fit a multiple regression model with Price as the response variable and `Taxes` and `Size` as predictors. ```{r} linear_model<-lm(Price~Size+Taxes, data=HousePrices) model<-linear_model model 'prof:if the size is increase by one you have 66.1 multiplied' 'cut of the line, when x=0 y takes that value= -28608.74 value. when x1 and x2 are 0, in other words it is an offset. we can also see the slope of each of the explanatory variables which are 66.51=beta1 for Size and 39.6=beta2 forTaxes. it is a surface in 3-D. -the mean response is in other words a 2 dimensional plane in 3 dimensional space.we determine alfa beta1 and beta 2 via least squares deviation from the plane.' ``` - What are the parameters of the model and what is the interpretation of these parameters? - What is the prediction equation? $$ \widehat y = -28608.74+66.51*x1+39.6*x2 $$ Explain the output of ```{r } s<-summary(model) s 'We can see the most significant paameters of our model, firs of all the residuals, which are the gneral parameters of our model, where we can see which has been the maximum and minimum points of the plot,MIN=THe largest minimum deviation is-- and the largest deviation is---. as well as the median and the first Quartile and 3 quartil location?. Afterwards we can see the information of each of the variables, in this case the intercept (alfa) the size and the taxes an its corresponding values. The intercept is also described as an offset, the starting point is displaced in a higher or lower value than 0. It can be also seen the estimated slope of each of the variables, its standard error as well as the t value, which is the estimate ((alfa, beta )=slope) divided by the standard error. stand error=tita(y|x)=which is the standard deviation of the deviations from the line. The table also provides us with the most important parameter of our model, the p value,which tell us how sure we are that the estimates are 0. we can say that any of the values can be rejected as anyone exceeds %5 of p value, so every variable is needed for the prediction of the model.We can also obtain the estimated values and the standard erro, the dividin this two values you obtain the t-value. the command itself also reminds you the best probabilities for your model with stars; *** being the highest and the best result, and * the less best which is equal to the 5%. the other values bellow that one are rejected. p value=is a good predictor p value for 0 hyp: *** very unlikely to happen in the 0 hyp ** very sign * is significant but we are not imprressed no stars-we have to look for conclusions' y_hat<-predict(model) y_hat 'we have 3 variables,size, taxes and Price so we have a plane. if we had 2 varibales we would have a line instead of having a surface.in this VECTOR we have two rows one with the round numbers which is the x1 and x2 (predictors) and the other one for the y(predicted value). so when x1 and x2 are =1 y is 230527.67.' ``` where `model` is the fitted multiple regression model. This explanation should as a minimum include - Calculation of `t value` and determination and interpretation of p-value. ```{r} 'estimated which is the slope' estimated_INTERCEPT<--28608.744 standard_error_INTERCEPT<-13519.09 t_value=estima_INTERCEPT<-estimated_INTERCEPT/standard_error_INTERCEPT estimated_SIZE<-66.512 standard_error_SIZE<-12.817 t_value=estima_SIZE<-estimated_SIZE/standard_error_SIZE estimated_TAXES<-39.601 standard_error_TAXES<-6.917 t_value=estima_TAXES<-estimated_TAXES/standard_error_TAXES ``` - Interpretation of `Multiple R-squared`. ```{r} ' correletaion about th epredctive value and the real value, also r sqr is the relation between the values look the notebook grph tts= is the sum of squared errors from the mean SSE=Sum of squared errors from the prediction line.=it is the sum of errors agains the y hat line. Where y_hat is the predicted line ' ``` - How the table of output can be used to construct confidence intervals for parameters. This should be supplemented by actual calculation for the current data using `confint`. ```{r} confint(model) 'the confidence interval which is calculated : estimated +-z*se' ``` Finally, you have to investigate whether or not there is an interaction between the effect of `Taxes` and the effect of `Size` as predictors of `Price`. ```{r} new_model<-lm(Price~Size*Taxes, data=HousePrices) summary(model) summary(new_model) 'prof:you should make another interaction no only taxes and size, look at the output and see if there is interaction or not.' 'NOTES FROM PDFwe are making a prediction plane, y has to be normally distribuited in this plane depending on its variables.' 'we can say that the first model has a lower p value is so its a better model comparing to the new one. According to the p value we can see that the two predictros(taxes and size) are dependent due to a very low p value. t value the x axis of the bell, only one part, it is positive so in the right side. the higher you are you are more separeted from the mean and more to the edge' 'You can also say that you can reject' 'Conclusion we finally we choose the first model as the right or best model, as the significance (the estimates are more close to be next to the previous line than the new one)is better.' 'comparing both R squares we can see that the new model has a higher value of R^2=0.78 whereas the old ones was 0.77, getting as close to 1 is favorable or better as your SSE will get to 0 having a a line as fitted as possible.' 'noTE:it is better not to include education for the model because it is not agood predictable model with this vareable, so remove it. if you remove one you have to run the model again and see the results because the p values will change and maybe you can reject one variable or not. don know, run it !' 'f statisticsyou can simplify the model rjectring the variables, if p value of this model is close to 0 you cannot reject any of the variables. so the variables are strong to the model.' ```<file_sep>--- output: pdf_document: default html_document: default word_document: default --- # Exam It is highly recommended that you answer the exam using Rmarkdown (you can simply use the exam Rmarkdown file as a starting point). # Part I: Estimating probabilities Remember to load the `mosaic` package first: ```{r message=FALSE} library(mosaic) options(digits = 4) ``` ## Chile referendum data In this part we will use the dataset `Chile`. Remember to read the [description](http://www.rdocumentation.org/packages/car/functions/Chile) of the dataset as well as the [Wikipedia](https://en.wikipedia.org/wiki/Chilean_national_plebiscite,_1988) entry about the background. ```{r} Chile <- read.table("http://asta.math.aau.dk/dan/static/datasets?file=Chile.dat", header=TRUE, quote="\"") ``` NB: This dataset has several missing values (`NA`). To remove these when you use `tally` you can add the argument `useNA = "no"`. - Do a cross tabulation of the variables `vote` and `sex`. ```{r} TableChile<-tally(~vote+sex, data=Chile, useNA = "no") ``` - Estimate the probability of `vote=N`. ```{r} suma<-sum(TableChile[2,1:2])/(sum(TableChile[1:4,1:2])) suma a<-(sum(TableChile[1:4,1:2])) a VoteN<-(363+526)/2532 VoteN ``` - Make a 95% confidence interval for the probability of `vote=N`. ```{r} 'What is pi_hat? is a proportion. the ones voting N among the other ones. the probablity ' n<-2532 pi_hat<-((363+526)/2532) pi_hat 'p-value: which is 0.05, so you obtain the z value, why divided by 2?? because R only takes the whole area of the left side of the graph. So you know that for 95 percent there must be 2.5 to the right and 2.5 to the left. But R only calculates the whole area to the left... so you do the 97.5 probability and the multiplied by two to know the 95% of confidence interval.' z1<-qdist("norm", 1-0.05/2) z1 estimated_standard_error<-sqrt(pi_hat*(1-pi_hat)/(n)) estimated_standard_error confidence_interval991<-pi_hat+z1*estimated_standard_error confidence_interval991 confidence_interval992<-pi_hat-z1*estimated_standard_error confidence_interval992 prop.test(Chile$vote,p=pi_hat, 2532, success="N", correct=FALSE) 'we use prop test for a proportion. in this case it calculates all the parameters for N, saying that the other votes are bad. that is made by the command success. the answer of the prop test: 1-pvalue>0.05 so we can say that the zero hyp is true. 2-we calculate the interval confidence which is betwween 0.3328-0.3699, where our pi_hat value is in that interval=zero hyp TRUE. So you are sure, if you do another experiment with different samples that your proportion(pihat)will be between that interval (0.33-0.36) with a 95% of confidence level' ``` - Estimate the probability of `vote=N`, given that `sex=F`. ```{r} 'Conditional probability (probablity of vote N having a condiotion, in this case those which are N have to be female F.' ProbabilityNFemale<-363/(sum(TableChile[1:4,1:1])) ProbabilityNFemale #or you can do it this way: sumaF<-sum(TableChile[2,1:1])/(104+363+362+480) sumaF ``` - What would these probabilities satisfy if `vote` and `sex` were statistically independent? ```{r} 'Now both probabilities are independent, so the answer is the probability to be a woman and have voted for N?' P_independent<-((363+526)/2532)*(1309/2532) P_independent ``` # Part II: Sampling distributions and the central limit theorem This is a purely theoretical exercise where we investigate the random distribution of samples from a known population. ## House prices in Denmark The Danish real estate agency HOME has a database containing approximately 80.000 house prices for one-family houses under DKK 10 million for the period 2004-2016. The house prices (without all the additional information such as house size, address etc.) are available as a R data file `Home.RData` on the course webpage. If you download it you can load it using `load("Home.RData")` assuming you have saved it in the same directory as this Rmarkdown document. This will add the vector `price` to your work space. Alternatively, you can add it directly from the course website (this will download it every time you run the Rmarkdown document, so make sure you have a decent internet connection): ```{r} load(url("http://asta.math.aau.dk/dan/static/datasets?file=Home.RData")) ``` Make a histogram of all the house prices using a command like `histogram(price, breaks = 30)` inserted in a new code chunk (try to do experiments with the number of breaks): ```{r} 'this command makes an histogram with 30 columns, if you change the number30 to 100 it will make 100 columns' histogram(price, breaks =30) ``` ```{r} 'or you can use the next command to put the colummns, for example for 3 columns' histogram(price, breaks=c(0,3.333,6.666,10)) ``` - Explain how a histogram is constructed. ```{r} 'A histogram is an accurate graphical representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable (quantitative variable) and was first introduced by <NAME>.[1] It is a kind of bar graph. To construct a histogram, the first step is to "bin" the range of values-that is, divide the entire range of values into a series of intervals-and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins (intervals) must be adjacent, and are often (but are not required to be) of equal size.[2] If the bins are of equal size, a rectangle is erected over the bin with height proportional to the frequency - the number of cases in each bin. A histogram may also be normalized to display relative frequencies. It then shows the proportion of cases that fall into each of several categories, with the sum of the heights equaling ' ``` - Does this histogram look like a normal distribution? ```{r} 'no, because it does not have the characteristic bell shaped curve' ``` In this database (our population) the mean price is `r mean(price)` and the standard deviation is `r sd(price)`. ```{r} mean_value<-mean(price) mean_value standard_deviation<- sd(price) standard_deviation ``` In many cases access to such databases is restrictive and in the following we imagine that we are only allowed access to a random sample of 40 prices and the mean of this sample will be denoted `y_bar`. Before obtaining this sample we will use the Central Limit Theorem (CLT) to predict the distribution of `y_bar`: ```{r} '(page 97) For random sampling with a large sample size n, the sampling distribution of the sample mean y is approximately a normal distribution. http://onlinestatbook.com/stat_sim/sampling_dist/ The approximate normality of the sampling distribution applies no matter what the shape of the population distribution. This is quite remarkable. For large random samples, the sampling distribution of y is approximately normal even if the population distribution is highly skewed, U shaped.' ``` - What is the expected value of `y_bar`? ```{r} y_bar<-mean(price) y_bar ``` - What is the standard deviation of `y_bar` (also called the standard error)? ```{r} 'see example page 97' se<-sd(price)/sqrt(40) se ``` - What is the approximate distribution of `y_bar`? ```{r} 'it is a normal distribution with a mean of 1.929 and a standard deviation of 0.2015' ``` *the aproximate distribution of y_bar is a normal distribution with the mean od the sample and the standard deviation eual to the standard deviation of the samples over the square root of the number of sampas* Now make a random sample of 40 house prices and calculate the sample mean: ```{r} 'First of all we make a random sample (40 elements) of the price vector, with the next command:' y <- sample(price, 40) y 'and we calculate the mean for this new sample' mean_valuey<-mean(y) mean_valuey 'this is the actual mean of the other sample(80000 elements) calculated previously:' mean_value<-mean(price) mean_value ``` Repeat this command a few times. Is each mean price close to what you expected? Use `replicate` to repeat the sampling 200 times and save each mean value in the vector `y_bar`: ```{r} 'so now we take 200 means of a vector of different 40 samples.' y_bar2 <- replicate(200, mean(sample(price, 40))) y_bar2 ``` Calculate the mean and standard deviation of the values in `y_bar`. ```{r} Final_mean<-mean(y_bar2) Final_mean Final_standard_deviation<-sd(y_bar2) Final_standard_deviation 'Now we compare these values to the first 80000 elements mean and standard deviation and we expect that it will be more or less the same page100 example interestinf' y_bar se ``` - How do they match with what you expected? - Make a histogram of the values in `y_bar` and add the density curve for the approximate distribution you predicted previously using `plotDist` with the argument `add = TRUE`. For example if you predicted a normal distribution with mean 2 and standard deviation 0.2: ```{r fig.keep='last'} histogram(y_bar2, breaks = 15, type = "density") plotDist("norm", mean = 2, sd = 0.2, add = TRUE, col = "red") ``` - Make a boxplot of `y_bar` and explain how a boxplot is constructed. ```{r } boxplot(y_bar2) ``` # Part III: Theoretical boxplot for a normal distribution Finally, consider the theoretical boxplot of a general normal distribution with mean $\mu$ and standard deviation $\sigma$, and find the probability of being an outlier according to the 1.5$\cdot$IQR criterion: - First find the $z$-score of the lower/upper quartile. I.e. the value of $z$ such that $\mu \pm z\sigma$ is the lower/upper quartile. ```{r} 'lowe quartile is the first quartile Q1 (25%) and the upper quartile is the thir onde Q3(%75)' z1<-qdist("norm", 0.75) 'Z will be the same for a normal distribution (mu=0, se=1) for the upper Q3 and lower Q1 quartil' ``` - Use this to find the IQR (expressed in terms of $\sigma$). ```{r} 'inter quartil range=coeficiente de los quartiles: En estadística descriptiva, se le llama rango intercuartílico o rango intercuartil, a la diferencia entre el tercer y el primer cuartil de una distribución' mu=0 sigma=1 IQR=(mu+sigma*z1)-(mu-sigma*z1) IQR 'si estas 1.5 veces el IQR significa q estas fuera de tu rango ' ``` - Now find the $z$-score of the maximal extent of the whisker. I.e. the value of $z$ such that $\mu \pm z\sigma$ is the endpoint of lower/upper whisker. ```{r} mu=0 sigma=1 IQR=(mu+sigma*z1)-(mu-sigma*z1) ``` - Find the probability of being an outlier. ```{r} 'la poabilidad de estar en los limites. Asiq vas a tneer una probabilidad q es el area (%2.2 mas o menos) a la izquierda y otros 2.2 a la derecha.' z1<-qdist("norm", 0.25) z1 outlier<-2*pdist("norm", z1-1.5*IQR) outlier ```<file_sep>--- output: html_document: default pdf_document: default word_document: default --- # Exam 4 In this exercise you will study a dataset concerning vital capacity, which is the maximal amount of air, that can be exhaled after a maximal inhalation. Read in the data: ```{r} vitcap <- read.table("http://asta.math.aau.dk/dan/static/datasets?file=vitcap.dat", header=TRUE) head(vitcap) ``` In the dataset, the variable `vital.capacity` has been measured on 84 workers in the cadmium industry. The next variable is the factor `exposure` with 3 levels, indicating the level of cadmium exposure: - A: None - B: Less than 10 years - C: More than 10 years The data set also contains dummy variables for the factor `exposure`: - `z1=1` if `exposure=B` and 0 otherwise. - `z2=1` if `exposure=C` and 0 otherwise. You will use these two variables later on. ## First part. Only Exposure Make a model and carry out an analysis investigating the effect of the factor `exposure` on the response `vital.capacity`. In that connection **you should calculate/interpret the F-test for no effect of `exposure`**. ```{r message=FALSE} library(mosaic) ``` ```{r, echo = FALSE, fig.width=8, } boxplot(vital.capacity~exposure, data = vitcap) abline(h=mean(vitcap$vital.capacity), col = "red", lwd = 2) ``` *1-The workers of exposure type A and B in overall have more people with a better vital capacity than in type C. As 50% of the workers are above the value 4, whereas the Q1 of the type C starts at 3. You can also see that for exposure type A and B the box atleast the box is 50% higher than the mean (red line) whereas type C is bellow 50%.* *2-We can also see that there are people with higher vital capacity rate at the exposure type A and C (around 6) whereas type b record is around 5.2.* ```{r, echo = FALSE, fig.width=8, } xyplot(vital.capacity~exposure, data = vitcap) ``` ```{r, echo=FALSE, results='hide'} names(vitcap) ``` ```{r} model_exposure <- lm(vital.capacity~exposure, data = vitcap) model_exposure ``` ```{r} summary(model_exposure) ``` *It can be seen the slope of each of the parameters beta1, beta2, intercept. The degrees of freedom can be calculated by df=n-3=84-3=81* *tvalue=estimate/stand_error. We can also see that the tvalue and the pvalue have an inverse relation. When t-value increases, the p-value decreases.* *Looking to the p values of the table, we can see that there are some predictors that not good predictors for the model such as exposureB (p=95%). ExposureB in not influencing or may not affect the model,so it can be stated that exposure b is not a good predictor* *On the other hand We can reject the alternative hypothesis due to the F-statistics pvalue is higher than %5. * *R_Sqaured value as well as the F statitics value is very low which again states that we can reject the alternative hypothesis, in other words we can accept the null hypothesis.* *We cannot reject the zero hypothesis (in my words accept the 0 hyp) we can see in the boxplot that the means if we take more samples probably would be equal so that is why we can say the zero hyp is true.* ## Second part. Including Age **We expand the analysis to include the workers age** - the variable `age` - as a predictor. Make a model and carry out an analysis investigating the effect of the **predictors `exposure` and `age`** on the response `vital.capacity`. In that connection you should: ```{r } xyplot(vital.capacity~age, groups = exposure, data = vitcap, type = c("p","r"), auto.key = TRUE) ``` *This plot shows that the slopes of the different exposure groups are different, altough we cannot be sure whether this difference is relevant or not. For having a more powerfull evidence, we implement a model including the two variables 'age' and 'exposure'.* ```{r } model_main<-lm(vital.capacity~exposure+age,data = vitcap) ``` ```{r } summary(model_main) ``` *In this model without interaction, we can see that the efect of age has much more influence in the model than the difference exposures.* *We can argue that exposure b and c are not good predictors for this model as its p value is bigger than 5%* *this time the degrees of freedom are 80 instead of 81 as we have included one more variable to the model (age)* *Looking at the p value of the f statistic we can state that we can reject the null hypothesis as the p value doesnt exceed the 5%.Afterwards another model has been impleented in order to see the results applying an interaction.* ```{r, echo=FALSE, results='hide'} model_age<-lm(vital.capacity~age,data = vitcap) summary(model_age) ``` - investigate whether there is **interaction between the effects of `exposure` and `age`** ```{r} model_interaction<-lm(vital.capacity~age*exposure,data = vitcap) summary(model_interaction) ``` *The model with interaction shows that there is a relevant interaction between age and exposure C, that should be taken into account in the model.* *Interaction between age and exposureB is not relevan at all, it is not a good predictor for the model.* *Exposure C now is a good predictor, whereas in the model without interaction we can clearly see that it was not a relevant parameter.* *Looking at the F statistic pvalue, we still can reject he null hypothesis. The pvalue is lower in the model with interacion than the one without ineraction.* *So far we can expect that the model with interation is better than the one without.* *Then, we make an anova comparison between the three models considered above (model only with exposure, model with exposure and age without interaction and model with both variables and interaction). * ```{r } anova(model_exposure, model_main) ``` *The model wihtout interaction including the age is a better model, significant pvalue.* ```{r } anova(model_main,model_interaction) ``` *The anova test shows that both the models with two variables are better than the one with only one variable. Considering these last two models(without and with interacion), the model WITH INTERACTION is better than the one without interaction.* - give a graphical interpretation of such an interaction ```{r } xyplot(vital.capacity~age, groups = exposure, data = vitcap, type = c("p","r"), auto.key = TRUE) ``` *Looking at the xyplot, we can see that the slopes of the three exposures types(A,B,C) are different. If there is no interaction, all the slopes should be equal so that they would be in paralel. The only difference between the curves would be the offset. However, as the anova test shows, there are some interactions between the different exposures which looking at the plotthe different slopes are reasonable because there are some interactions.* ## Third part. Comparing Exposure B and C Consider the following two models, where we introduce the dummy variables. *In this part, we make two different models, one with both exposure A and B together (model1) and another with the three exposures separated (model2).* ```{r} model1 <- lm(vital.capacity ~ age*z2, data = vitcap) model2 <- lm(vital.capacity ~ age*z1 + age*z2, data = vitcap) ``` - Use an F-test to show that there is no significant difference between `model1` and `model2`. ```{r} anova(model1,model2) ``` *We can see from the ANOVA comparison that the complex model is not better than the simple model (p-value = 0.5064). The F test, has a F value of 0.68 and a Pvalue of 0.5 which is not significant.* - Give an interpretation of the difference between the two models. ```{r } summary(model1) summary(model2) ``` *From the first model We can actually see that the parameters used for model 1 are very significant, which are good predictors, whereas in the more complex model(second) we can see that there are some parameters such as z1, and interaction between age and z1 that are not relevant at all. So it could be interesting to analize how the model behaves without one of there predictors.* *As a conclusion we could say that the simplest model (model1) is a better model as the p value is lower than in the model 2.* <file_sep>--- title: "Exam 2" output: html_document: default pdf_document: default word_document: default --- Remember to load the `mosaic` package first: ```{r message=FALSE} library(mosaic) ``` ## Part I: Directed reading activities An educator conducted an experiment to test whether new directed reading activities in the classroom will help elementary school pupils improve some aspects of their reading ability. She arranged for a third grade class of 21 students to follow these activities for an 8-week period. A control classroom of 23 third graders followed the same curriculum without the activities. At the end of the 8 weeks, all students took a Degree of Reading Power (DRP) test, which measures the aspects of reading ability that the treatment is designed to improve. Read in the data: ```{r} reading <- read.table("http://asta.math.aau.dk/dan/static/datasets?file=reading.dat", header=TRUE) head(reading) ``` **Use a boxplot to compare the of measurements** of `DRP` for `Treated`(direct reading activities) and `Control` visually. *we want to see the score of each group, DRP=the experiment they have done* ```{r} bwplot(Response ~ Treatment , data = reading) ``` *As it can be seen in the boxplots, the response dispersion for the Treated students is more narrow than the one for Control students, which states that there are not very extreme values between the treated students. Also, we can state that the treated students in overall have a higher grade (the mean value and the median is slightly higher for the Treated students) = so in overall the treated ones are better trained for a reading exam than the non treated ones.Although there are some non treated students that have higher marks than the treated ones. There are not outliers in any sample* Use `favstats` to **make a numerical summary of the measurements** for `Treated` and `Control`. ```{r} favstats(Response ~ Treatment, data = reading) ``` *The summary results are in concordance with the boxplots. The mean for the Treated students is higher, whereas the standard deviation is lower.* ### Working with Treated students - **Write down a point estimate of the mean** of DRP for students following the new *directed reading activities* and explain how this is calculated. *The point estimate of the mean for Treated students is the mean of the partial sample of those students. The same approximation is done for the Control Students.* $$\overline y_{Treated} = \frac{1}{n_1} \sum\limits_{i=1}^{n_1}{y_i} \quad \text{, where } y_i \text { are the values for the Treated group} $$ ```{r, echo = FALSE} Control <- subset(reading, Treatment == "Control") Treated <- subset(reading, Treatment == "Treated") y1 = mean(~ Response, data = Control) y2 = mean(~ Response, data = Treated) y2 ``` - **Write down a point estimate of the standard deviation** of DRP for this group and explain how this is calculated. *The point estimate of the standard deviation for Treated students is the standard deviation of the partial sample of those students. The same approximation is done for the Control Students. * $$s = \sqrt{\frac{\sum\limits_{i=1}^{n_1}{(y_i-\overline y_T)^2}}{n_1-1}}$$ *The -1 in the denominator is due to the Bessel correction. * ```{r } n1 = 23 n2 = 21 s1 = sd(~ Response, data = Control) s2 = sd(~ Response, data = Treated) s1 s2 ``` *Also, the standard error is aproximated by the next formula* $$se = \frac{\sigma}{\sqrt n}$$ ```{r} se2 = s2/sqrt(n2) se2 ``` - Write down a **95% confidence interval for the mean** of DRP for this group and explain how this is calculated. *The 95% confidence interval for the Treated group is defined as follows: * $(a,b) = \overline y \pm t(se)$ *we use t score because the number of samples is less than 30* ```{r} t<-qdist("t", p = 0.025, df = 21-1) t y2+c(t*se2,-t*se2) ``` *All those results can be obtained by the comand* `t.test` ```{r} t.test( ~Response, data = Treated, conf.level = 0.95) ``` *We can say with a 95% of confidence level that if we take antoher sample the mean will be aroun that interval (46.46-56.48)* ### Comparing Treated and Control students Use the **command `t.test` to compare the mean DRP of the two groups**. ```{r} t.test(Response ~ Treatment , data = reading) ``` Go through the details of the output from t.test. - What the relevant **null hypothesis** and the corresponding **alternative hypothesis** is. *The null hypothesis is* $H_0:\hat\mu_1=\hat\mu_2$ *and the alternative hypothesis is * $H_a:\hat\mu_1\neq\hat\mu_2$ *We can reject the 0 Hypothesis as the pvalue is less than 5%. The means are not equal!* - Choice and **calculation of test statistic**. *First, is neccesary to calculate the standartd error of the sample difference, as follows:* $se_d=\sqrt{\frac{s_1^2}{n_1}+\frac{s_2^2}{n_2}}$ ```{r, echo=FALSE} sed = sqrt(s1^2/n1+s2^2/n2) sed ``` *The value of t for the t.test is calculated as follows:* $t=\frac{\overline y_2-\overline y_1}{se_d}$ ```{r } y1 y2 t = (y1-y2)/sed t ``` - **Calculation of p-value** and its interpretation in connection to a conclusion of the analysis. *Once obtained the t value, the probability of occurrence of this value is obtained by the t curve. The p-value is defined as the left probability of this value times two.* ```{r } P = 2*pdist("t", q = t, df = 37.855) P ``` When the p-value is small, we can consider that we can reject the* $H_0$ *hypothesis. - **Calculation** and interpretation of a relevant **confidence interval**. *The confidence interval represents the range in between the difference of means is, with some certainty. It is calculated by the t value, the difference of means and the standard error, as follows:* $$(a,b) = (\bar y_2-\bar y_1)\pm t(se_d)$$ $$(a,b) = (41.52-51.47)\pm 2(4.3)$$ *First, we have to calculate the t value, with a 95% confidence.* ```{r, echo = FALSE} t2 <- qdist("t", p = 0.025, df = 37.855) t2 ``` *Then, we calculate the confidence interval (95%).* ```{r, echo = FALSE} d = y1-y2 d+c(t2*sed,-t2*sed) ``` ## Part II: Determining sample size Estimate the proportion of danish companies with less than 10 employees determine the necessary sample size for the estimate to be accurate to within 0.06 with probability 0.90. Based on results from a previous study in 2013, we expect the proportion to be about 0.70. *The margin of error when estimating a proportion is* $M = z \sqrt {\frac{\pi(1-\pi)}{n}}$ *Solving the equation for obtaining n* $n = \pi(1-\pi)(\frac{z}{M})^2$ *With the given values, the sample size can be calculated* ```{r } M <- 0.06 pi <- 0.7 z<-qdist("norm", p= 0.05, mean = 0, sd = 1) z n <- pi*(1-pi)*(z/M)^2 n ``` ```{r, echo=FALSE} M = 0.06 pi = 0.5 z<-qdist("norm", p= 0.05, mean = 0, sd = 1, plot = FALSE) n = pi*(1-pi)*(z/M)^2 ``` <file_sep>--- title: "Exam - stochastic processes" output: html_document: default pdf_document: default word_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(eval = TRUE) ``` # CO2 concentration in atmosphere R's built-in dataset `co2` is a time series of atmospheric CO2 concentration at the Mauna Loa observatory. We will analyse this dataset below. ## Explorative data analysis - Start as always by plotting the data. ```{r} plot(co2) ``` ```{r} CO1 <-ts(co2, start=1959, frequency = 12) CO1 ``` ```{r} cyc1 <- cycle(CO1) cyc1 cyc <- factor(cyc1, labels = month.abb) boxplot(CO1 ~ cyc1) ``` - Is this a second order stationary time series (explain what it means)? This is not stationary, as there is clearly a trend and seasonality. The covariance in the 4th and 6th leg should be the same as in the 5th and 7th. There is a small seasonality with an increase in months 4,5,6 but nothing significant - Use `decompose` to make a decomposition of the data to remove any trend and seasonal component and explain the method of how this is done. ```{r} CO1_decomp <- decompose(CO1) CO1_trend <- CO1_decomp$trend CO1_no_trend <- co2 - CO1_trend ts.plot(CO1_trend, CO1_no_trend+CO1_trend,lty = c(1,2)) ``` $$x=m+s+z$$ in which m is the trend and we subtract the trend from x thus eliminating it. - Save the random component as `co2rand` (omit any `NA` values), plot the correlogram of `co2rand` and explain the correlogram: What is it used for and how is it interpreted? What is assumed about the underlying process? ```{r} co2rand <- na.omit(CO1_decomp$random) acf(co2rand) ``` *We decomposed the timeseries by taking the random component out and plotting in the correlogram above. The legs extend the H0 hypothesis band in a periodical fashion (at 0.5 is negative, at 1 is positive, at 1.5 is negative again and finaly at 2 it is positive)* ## Auto-regressive model of order 1 - Manually fit a AR(1) model using `lm` without an intercept: ```{r} n <- length(co2rand) y <- co2rand[2:n] x <- co2rand[1:(n-1)] fitlm <- lm(y ~ x - 1) summary(fitlm) ``` - Explain the output of the last command above. Is there significant autocorrelation? What is the estimated lag 1 autocorrelation coefficient? *The p-value is low so there is a strong correlation between the current value and the last value.* - Write down the equation expressing the fitted model. $$x_t=\alpha_1*x_{t-1}+w_t$$ *The estimate is random, if the co2rand is ran a couple of times* - Based on the data $x_1,\dots,x_n$ what is the predicted value for $x_{n+1}$? Based on the following equation the $x_{n+1}$ factor can be calculated as: $${x}_{n+1}=\alpha_1*x_n$$ ```{r} xn_1<- 0.40841* co2rand[n] xn_1 ``` where $\alpha_1=0.4084139$ which is coef(fitlm) in our case. - What is the predicted value for $x_{n+10}$? $$ x_{n+10} = \alpha^{10}*x_n$$ ```{r} xn_10<- 0.40841^10* co2rand[n] xn_10 ``` - Save the model residuals (use `residuals(fitlm)`) and plot the correlogram. What is the theoretical acf for this model? ```{r} residuals(fitlm) par(mfrow = c(2,1), mar = c(4,4,1,1)) plot(residuals(fitlm)) acf(residuals(fitlm)) ``` From the plot we obtained we could've said that it is white noise, but from the correlogram it is shown that there is some seasonality with the legs at 5, 11, 12, 17 . - Is the AR(1) model a good fit? ## Higher order autoregressive moving average (ARMA) models - How do we define higher order AR(p) processes? $$ x_t=\alpha*x_{t-1}+\alpha_2*x_{t-2}+\dots+\alpha_p*x_{t-p}$$ - Use `lm` as above to estimate an AR(2) model for `co2rand`. Is the lag 2 autocorrelation coefficient significant according to a `summary` of the fitted model? ```{r} n <- length(co2rand) x <- co2rand[3:n] x1 <- co2rand[2:(n-1)] x2 <- co2rand[1:(n-2)] fitlm1 <- lm(x ~ x1 +x2 - 1) summary(fitlm1) ``` -1 is from removing the intercept. The lag 2 autocorrelation coefficient is not significant because x2 is not significant on a 5% level (p-value) - What is the partial autocorrelation function and how is it useful in relation to AR(p) processes? The partial autocorrelation is the function that shows if there is any correlation between values that are not consecutive. The function is : $$x_t=\beta_0+\beta_1*x_{t-1}+\beta_2*x_{t-2}+\epsilon $$ - How is a MA(q) process defined? $$x_t=w_t+\beta_1*w_{t-1}+\beta_2*w{t-2}+\dots+\beta_q*w_{t-q} $$ where $w_t$ is the white noise and $ \beta_1,\beta_2, \beta_3 $ are the parameters to be estimated. - Try to fit a collection of ARMA(p,q) models for $p$ and $q$ at most 2, and find the best fitting one based on AIC. (Hint: If you called the models `ar1`, `ar2`, `ma1`, `ma2`, `arma11`, `arma12`, `arma21`, and `arma22` you can compare them all in a single call to `AIC`; `AIC(ar1, ar2, ma1, ma2, arma11, arma12, arma21, arma22)`) ```{r} ar1 <- arima(co2rand, order= c(1,0,0)) ar2 <- arima(co2rand, order= c(2,0,0)) ma1 <- arima(co2rand, order= c(0,0,1)) ma2 <- arima(co2rand, order= c(0,0,2)) arma11 <- arima(co2rand, order= c(1,0,1)) arma12 <- arima(co2rand, order= c(1,0,2)) arma21 <- arima(co2rand, order= c(2,0,1)) arma22 <- arima(co2rand, order= c(2,0,2)) AIC(ar1,ar2,ma1,ma2,arma11,arma12,arma21,arma22) ``` The btst fitting ones are the last arma21 arma22 which have an AIC of -89.839092 and -102.569646 . In arma22 you take in consideration the last 2 previous values and the last 2 white noise values - Write down the parameter estimates of the final model, and check whether it is a good fit to the data. ```{r} arma22 ``` - Give 95% confidence intervals for the parameter estimates of the final model selected by AIC. (Hint: Use `confint`.) ```{r} confint(arma22) ``` ## Prediction - Make a prediction with an approximate 95% prediction interval for the next value of the random component $x_{n+1}$ based on this model. ```{r} pred12 <- predict(arma22, n.ahead = 40) pred12 ``` ```{r} pred1 <- predict(arma22, n.ahead = 1) lower1 <- pred1$pred-2*pred1$se upper1 <- pred1$pred+2*pred1$se ts.plot(co2rand, pred1$pred, lower1, upper1, lty = c(1,2,3,3), xlim=c(1980,2000)) ``` *We can see from the prediction plot that the values predicte tend to stabilize around the mean (0, 0.5, -0.5) - If there was no autocorrelation in the random component the approximate 95% prediction interval is given by $$\bar{x} \pm 2\sqrt{s^2(1+1/n)}$$. Calculate this prediciton interval and compare it with the one obtained above. What is the difference? Try to explain this. ```{r} posint <- mean(co2rand)+2*sd(co2rand)*sqrt(1+1/n) posint negint <- mean(co2rand)-2*sd(co2rand)*sqrt(1+1/n) negint pred12 ``` This equation is just a correction to the previous one by taking the mean and adding a standard deviation to get a new prediction. We don't into account the last values in making this confidence interval(which sometimes it's a good ideea to do that) ```{r} ts.plot(window(co2rand,start=1996),pred12$pred-2*pred12$se,pred12$pred+2*pred12$se,col=c(1,2,2)) ```
8e0af65cc9a2360d3da1b43bcc9ad434a0dfd124
[ "Markdown", "C", "RMarkdown" ]
14
Markdown
NicolaiFransen/Semester-Project-PED1
1bdc7db807f1d49b18426b817350ad6811d8d928
feed5312f2ecae13171521137cddeaf1cee7503c
refs/heads/master
<file_sep># 마케팅 속 인공지능 이 코드는 Siraj Raval 의 유투브 비디오 "마케팅 속 인공지능" 에 설명 된 코드입니다. ## 간단한 설명 이 코드는 Siraj Raval 의 유투브 영상 [ "마케팅 속 인공지능" ](https://www.youtube.com/watch?v=FYMjXD3G__Y&lc=z23hgfkpdnfjyt0n1acdp431kuaxfkhbz5py54gjhedw03c010c) 에 설명된 코드입니다. ## 사용법 주피터 노트북은 깃헙에서 바로 읽기가 가능합니다. 이 코드를 실행하기 위해서는 keras 와 tensorrec 프레임워크의 설치가 필요합니다. 둘 다 [pip](https://pip.pypa.io/en/stable/installing/)을 통해 설치가 가능합니다. tensorrec 프레임워크 [저장소](https://github.com/jfkirk/tensorrec)입니다. ## IPython [ 코드 돌려보기 (Colab) ](https://colab.research.google.com/github/edwithschoolofai/AI_In_Marketing/blob/master/AI%20for%20Advertising.ipynb) ## 감사의 말 Francois Chollet과 Tensorrec에 감사의 말씀을 전합니다. 이 코드는 제가 조금만 변형한 것입니다. <file_sep>import numpy as np import tensorrec # Build the model with default parameters model = tensorrec.TensorRec() # Generate some dummy data interactions, user_features, item_features = tensorrec.util.generate_dummy_data( num_users=100, num_items=150, interaction_density=.05 ) # Fit the model for 5 epochs model.fit(interactions, user_features, item_features, epochs=5, verbose=True) # Predict scores for all users and all items predictions = model.predict(user_features=user_features, item_features=item_features) # Calculate and print the recall at 10 r_at_k = tensorrec.eval.recall_at_k(model, interactions, k=10, user_features=user_features, item_features=item_features) print(np.mean(r_at_k))
5806abdcb11c81b1f1146df3ac945838d234259b
[ "Markdown", "Python" ]
2
Markdown
edwithschoolofai/AI_In_Marketing
359f56522551e57c3267965168537f701452241e
8a7ac60eb981944256f6a5db178cbec445c1e870
refs/heads/master
<repo_name>Ara217/second-project<file_sep>/index.php <?php echo "hello world"; echo "hello world"; echo "hello Ara"; safds;flsdsadkljfa's' echo "hello branch master"; echo "string"; ?>
fee33cf38b099126801315694387b4128b522ef3
[ "PHP" ]
1
PHP
Ara217/second-project
c2cb39395c0ad45411cb3ec9712ac684192fe5be
7feeded6e21d8f1edd1add828c8da9d2e7e9e946
refs/heads/master
<file_sep>import React, { Component } from 'react' class SearchFood extends Component { constructor(props) { super(props) this.state = { name: '' } } handleFormSubmit = e => { e.preventDefault() console.log(this.props) this.props.searchFood(this.state.name) this.setState({ name: '', }) } handleInputChange = e => { let { name, value } = e.target this.setState({ [name]: value }) } render() { return ( <section> <form onSubmit={this.handleFormSubmit}> <label> Search: <input type="text" name="name" value={this.state.name} onChange={this.handleInputChange} /> </label> <br /> <input type="submit" value="Enviar" /> </form> </section> ) } } export default SearchFood;<file_sep>import React, { Component } from 'react' import foods from './foods.json' import { Link } from 'react-router-dom'; import AddFood from './form' import SearchFood from './search-food' class FoodBox extends Component { constructor() { super() this.state = {allFoods: foods} } addOneFood = food => { const foodCopy = [...this.state.allFoods] foodCopy.push(food) this.setState({ allFoods: foodCopy }) } searchOneFood = food => { this.setState({ allFoods: [this.state.allFoods.find(elm => elm.name === food)] }) } render() { return ( <div> <p>asdas</p> <AddFood addFood={this.addOneFood} /> <SearchFood searchFood = {this.searchOneFood}/> {this.state.allFoods.map((elm)=> <div className="box"> <article className="media"> <div className="media-left"> <figure className="image is-64x64"> <img src={elm.image} /> </figure> </div> <div className="media-content"> <div className="content"> <p> <strong>{elm.name}</strong> <br /> <small>{elm.calories}</small> </p> </div> </div> <div className="media-right"> <div className="field has-addons"> <div className="control"> <input className="input" type="number" value="1" /> </div> <div className="control"> <button className="button is-info"><Link to='/form'> +</Link> </button> </div> </div> </div> </article> </div> )} </div> ) } } export default FoodBox
46f20188813507b05a3a3608503b5e2f91ed7dfc
[ "JavaScript" ]
2
JavaScript
lusuelves/lab-react-ironnutrition
2bc77222d58fac41423e6cc769cd3ea195c4777b
169bb1a45a7b6eee9a628056951c1b34865053ab
refs/heads/master
<file_sep>import numpy as np import gym from RL_brain import DeepQNetwork #from cnn_brain import DeepQNetwork import argparse import matplotlib.pyplot as plt import pickle import gzip np.set_printoptions(threshold=np.inf) #print(env.observation_space.shape[0]) parser = argparse.ArgumentParser(description='Train or test neural net motor controller.') parser.add_argument('--train', dest='train', action='store_true', default=False) parser.add_argument('--test', dest='test', action='store_true', default=True) args = parser.parse_args() def env_init(): Q1=0 Q2=0 stat=0 return Q1,Q2,stat step_set=[] reward_set=[] if args.train: RL = DeepQNetwork(n_actions=2, #n_features=env.observation_space.shape[0], n_features=3, learning_rate=0.01, e_greedy=0.9, replace_target_iter=100, memory_size=2000, e_greedy_increment=0.001,) Q1,Q2,stat=env_init() for steps in range(20000): if Q1>10 or Q2>10: Q1,Q2,stat=env_init() if np.random.random()<0.25: Q1+=1 if np.random.random()<0.25: Q2+=1 obs=np.array([Q1,Q2,stat]) action=RL.choose_action(obs) if action ==0: #change if stat==0: stat=2 elif stat==1: stat=3 elif stat==2: stat=1 if Q2>0: Q2-=1 elif stat==3: stat=0 if Q1>0: Q1-=1 elif action == 1: #keep on if stat==0: if Q1>0: Q1-=1 elif stat==1: if Q2>0: Q2-=1 else: print("Action error!") reward = -(Q1**2+Q2**2) obs_=np.array([Q1,Q2,stat]) RL.store_transition(obs,action,reward,obs_) if steps>200: RL.learn() if steps%50==0: print(reward) reward_set.append(reward) step_set.append(steps) #plt.scatter(steps, reward) obs=obs_ plt.plot(step_set,reward_set) plt.savefig('train.png') RL.store() plt.show() #RL.plot_cost() if args.test: RL = DeepQNetwork(n_actions=2, #n_features=env.observation_space.shape[0], n_features=3, learning_rate=0.01, e_greedy=1., replace_target_iter=100, memory_size=2000, e_greedy_increment=None,) step_set=[] reward_set=[] Q1,Q2,stat=env_init() RL.restore() for steps in range(1000): if Q1>10 or Q2>10: Q1,Q2,stat=env_init() if np.random.random()<0.25: Q1+=1 if np.random.random()<0.25: Q2+=1 obs=np.array([Q1,Q2,stat]) action=RL.choose_action(obs) print(obs, action) if action ==0: #change if stat==0: stat=2 elif stat==1: stat=3 elif stat==2: stat=1 if Q2>0: Q2-=1 elif stat==3: stat=0 if Q1>0: Q1-=1 elif action == 1: #keep on if stat==0: if Q1>0: Q1-=1 elif stat==1: if Q2>0: Q2-=1 else: print("Action error!") reward = -(Q1**2+Q2**2) obs_=[Q1,Q2,stat] if steps%50==0: print(reward) obs=obs_ steps+=1 reward_set.append(reward) step_set.append(steps) plt.plot(step_set,reward_set) plt.savefig('test.png') plt.show() <file_sep>import numpy as np from RL_brain2 import DeepQNetwork #from cnn_brain import DeepQNetwork import argparse import matplotlib.pyplot as plt import pickle import gzip import time import tkinter as tk from env import crossing from visual import Visual np.set_printoptions(threshold=np.inf) #print(env.observation_space.shape[0]) parser = argparse.ArgumentParser(description='Train or test neural net motor controller.') parser.add_argument('--train', dest='train', action='store_true', default=False) parser.add_argument('--test', dest='test', action='store_true', default=False) args = parser.parse_args() def road_map(): cross1=crossing(light_state=0,q_states=[0,0,0,1]) cross2=crossing(light_state=0,q_states=[0,0,1,0]) step_set=[] reward_set=[] if args.train: RL = DeepQNetwork(n_actions=4, #2*2 #n_features=env.observation_space.shape[0], n_features=10, #2*5 learning_rate=0.01, e_greedy=0.9, replace_target_iter=100, memory_size=2000, e_greedy_increment=0.001,) # hit control: # on_hit = False # next_step=0 # def hit_me(): # global on_hit # global next_step # if on_hit == False: # on_hit = True # next_step=0 # else: # on_hit = False # next_step=1 # b = tk.Button(window, text='Next Step', width=15, # height=2, command=hit_me) # b.pack() visual=Visual() cross1=crossing(light_state=0,q_states=[0,0,0,1]) cross2=crossing(light_state=0,q_states=[0,0,1,0]) obs=np.concatenate((cross1.car_nums, cross1.light_state, cross2.car_nums, cross2.light_state),axis=None) for steps in range(20000): visual.visual_before(cross1, cross2) action=RL.choose_action(obs) if action == 0: action1 =0 action2 =0 elif action ==1: action1 =1 action2 =0 elif action ==2: action1 =0 action2 =1 elif action ==3: action1 =1 action2 =1 #interaction between crossroads and interaction between crossroad and peripheral peri_cars1, in_cars1 = cross1.state_change(action1) peri_cars2, in_cars2 = cross2.state_change(action2) # print(peri_cars1, in_cars1, peri_cars2, in_cars2) visual.visual_peri(peri_cars1,peri_cars2) reward=0 for i in range (4): if cross2.q_states[i]==1: cross2.car_nums[i]+=in_cars1 if cross1.q_states[i]==1: cross1.car_nums[i]+=in_cars2 reward = reward - cross1.car_nums[i]**2 - cross2.car_nums[i]**2 visual.visual_after(cross1, cross2) obs_=np.concatenate((cross1.car_nums, cross1.light_state, cross2.car_nums, cross2.light_state),axis=None) RL.store_transition(obs,action,reward,obs_) if steps>200: RL.learn() if steps%50==0: print(steps,reward) reward_set.append(reward) step_set.append(steps) #plt.scatter(steps, reward) obs=obs_ # window.mainloop() plt.plot(step_set,reward_set) plt.savefig('train2.png') RL.store() plt.show() #RL.plot_cost() if args.test: RL = DeepQNetwork(n_actions=4, #2*2 #n_features=env.observation_space.shape[0], n_features=10, #2*5 learning_rate=0.01, e_greedy=1., replace_target_iter=100, memory_size=2000, e_greedy_increment=None,) cross1=crossing(light_state=0,q_states=[0,0,0,1]) cross2=crossing(light_state=0,q_states=[0,0,1,0]) RL.restore() for steps in range(1000): obs=np.concatenate((cross1.car_nums, cross1.light_state, cross2.car_nums, cross2.light_state),axis=None) # print(obs) action=RL.choose_action(obs) if action == 0: action1 =0 action2 =0 elif action ==1: action1 =1 action2 =0 elif action ==2: action1 =0 action2 =1 elif action ==3: action1 =1 action2 =1 peri_cars1, in_cars1 = cross1.state_change(action1) peri_cars2, in_cars2 = cross2.state_change(action2) reward=0 for i in range (4): if cross2.q_states[i]==1: cross2.car_nums[i]+=in_cars1 if cross1.q_states[i]==1: cross1.car_nums[i]+=in_cars2 reward = reward - cross1.car_nums[i]**2 - cross2.car_nums[i]**2 obs_=np.concatenate((cross1.car_nums, cross1.light_state, cross2.car_nums, cross2.light_state),axis=None) if steps%50==0: print(reward) obs=obs_ steps+=1 reward_set.append(reward) step_set.append(steps) plt.plot(step_set,reward_set) plt.savefig('test2.png') plt.show() <file_sep>import numpy as np from RL_brain2 import DeepQNetwork import argparse import matplotlib.pyplot as plt import pickle import gzip import time import tkinter as tk from env import crossing from visual import Visual np.set_printoptions(threshold=np.inf) #print(env.observation_space.shape[0]) parser = argparse.ArgumentParser(description='Train or test neural net motor controller.') parser.add_argument('--train', dest='train', action='store_true', default=True) # parser.add_argument('--test', dest='test', action='store_true', default=True) args = parser.parse_args() # size of crossroads grid grid_x=4 grid_y=4 RL = DeepQNetwork(n_actions=2**(grid_x*grid_y), #0,1 for each crossroad n_features=5*(grid_x*grid_y), #2*5 (5 = 4 numbers of cars + 1 light state) learning_rate=0.01, e_greedy=0.9, replace_target_iter=100, memory_size=2000, e_greedy_increment=0.001,) x=[] y=[] for i in range(grid_x): x.append(i+1) for i in range(grid_y): y.append(i+1) #property of visualization times=100 #interval: crossroad & crossroad bias=6 #distance: light & center of crossroad bias_t=20 #distance: text(car_number) & center of crossroad bias_=40 #distance: coming car & center of crossroad b=2 #size of oval & rectangle #q_states is the inner/peripheral property of crossroads q_states=[[([1] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] for xx in x: for yy in y: if xx==1: q_states[xx][yy][2]=0 #0 for peripherial road, 1 for inner road if xx==grid_x: q_states[xx][yy][3]=0 if yy==1: q_states[xx][yy][0]=0 if yy==grid_y: q_states[xx][yy][1]=0 #initial light_states of crossroads light_states=[[0 for i in range(grid_y+1)]for j in range(grid_x+1)] def int2bin(n, count=24): #10 -> binary """returns the binary of integer n, using count number of digits""" return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) def crossroads_map(x,y): cross={} #dictionary of crossroads for xx in x: for yy in y: lab=str(xx)+str(yy) #string lab for addressing each crossroad, xx ~ [1,grid_x] #Initialization cross_=crossing(car_nums=np.array([0,0,0,0]),light_state=0,q_states=q_states[xx][yy]) cross[lab]=cross_ return cross step_set=[] reward_set=[] if args.train: #Initializing cross=crossroads_map(x,y) visual=Visual() obs=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs=np.concatenate((obs, cross[lab].car_nums, cross[lab].light_state), axis=None) #Training steps for steps in range(200000): visual.visual_before(cross,x,y,times,b,bias,bias_t) action=RL.choose_action(obs) action_set=[[0 for i in range(grid_y+1)]for j in range(grid_x+1)] peri_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] in_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] #light state changes, cars numbers change, interactions between crossroads and peripherals for xx in x: for yy in y: lab=str(xx)+str(yy) #10->binary coding for action(1 value), like if action=128, 9 bits binary coding #of it is 010000000, indicating a 3*3 grid with each crossroad having action of #'0''1''0''0''0''0''0''0''0'(storing in action set), each action is either '0' or '1', #for 'change state' or 'keep on'. The binary number is set to be (grid_x*grid_y) bits, # correspongding to the number of crossroads in grid. action_set[xx][yy]=int(int2bin(action,grid_x*grid_y)[(xx-1)*grid_y+yy-1]) peri_cars[xx][yy], in_cars[xx][yy]=cross[lab].state_change(action_set[xx][yy]) #interactions among crossroads for xx in x: for yy in y: lab=str(xx)+str(yy) if cross[lab].q_states[0]==1: if yy-1>0 and in_cars[xx][yy-1][0]>0: #having incoming cars from neighbors cross_=cross[lab] cross_.car_nums[0]+=in_cars[xx][yy-1][0] cross[lab]=cross_ if cross[lab].q_states[1]==1: if yy+1<=grid_y and in_cars[xx][yy+1][1]>0: cross_=cross[lab] cross_.car_nums[1]+=in_cars[xx][yy+1][1] cross[lab]=cross_ if cross[lab].q_states[2]==1: if xx-1>0 and in_cars[xx-1][yy][2]>0: cross_=cross[lab] cross_.car_nums[2]+=in_cars[xx-1][yy][2] cross[lab]=cross_ if cross[lab].q_states[3]==1: if xx+1<=grid_x and in_cars[xx+1][yy][3]>0: cross_=cross[lab] cross_.car_nums[3]+=in_cars[xx+1][yy][3] cross[lab]=cross_ #in the same diagram as the above 'visual_before', showing the incoming cars visual.visual_peri(peri_cars,x,y,times,b,bias,bias_,bias_t,grid_x,grid_y) reward=0 for xx in x: for yy in y: lab=str(xx)+str(yy) for i in range (4): reward = reward - cross[lab].car_nums[i]**2 #show the result of state tranformation in another diagram 'visual_after', i.e. the result of 'visual_before' visual.visual_after(cross,x,y,times,b,bias,bias_t) time.sleep(10) obs_=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs_=np.concatenate((obs_, cross[lab].car_nums, cross[lab].light_state), axis=None) RL.store_transition(obs,action,reward,obs_) if steps>200: RL.learn() if steps%50==0: print(steps,reward) reward_set.append(reward) step_set.append(steps) #plt.scatter(steps, reward) obs=obs_ plt.plot(step_set,reward_set) plt.savefig('train2.png') RL.store() plt.show() #RL.plot_cost() <file_sep>import numpy as np import argparse import matplotlib.pyplot as plt import pickle import gzip import time import tkinter as tk class Visual: def __init__( self, ): window = tk.Tk() window.title('my window') window.geometry('500x500') self.canvas = tk.Canvas(window, bg='white', height=200, width=300) self.canvas_ = tk.Canvas(window, bg='white', height=200, width=300) def visual_before(self, cross1, cross2): # visualize if cross1.light_state==0: cross1_lr='red' cross1_ud='green' elif cross1.light_state==1: cross1_lr='green' cross1_ud='red' elif cross1.light_state==2: cross1_lr='red' cross1_ud='yellow' elif cross1.light_state==3: cross1_lr='yellow' cross1_ud='red' if cross2.light_state==0: cross2_lr='red' cross2_ud='green' elif cross2.light_state==1: cross2_lr='green' cross2_ud='red' elif cross2.light_state==2: cross2_lr='red' cross2_ud='yellow' elif cross2.light_state==3: cross2_lr='yellow' cross2_ud='red' self.canvas.delete('all') self.canvas.create_oval(75, 100, 80, 105, fill=cross1_lr) #left self.canvas.create_oval(125, 100, 130, 105, fill=cross1_lr) #right self.canvas.create_oval(100, 75, 105, 80, fill=cross1_ud) #up self.canvas.create_oval(100, 125, 105, 130, fill=cross1_ud) #down self.canvas.create_text(50, 100, text = cross1.car_nums[2],font=("bold", 22),fill = 'black') #left self.canvas.create_text(100, 50, text = cross1.car_nums[0],font=("bold", 22),fill = 'black') #up self.canvas.create_text(100, 150, text = cross1.car_nums[1],font=("bold", 22),fill = 'black') #down # self.canvas.create_text(150, 100, text = '1',fill = 'black') self.canvas.create_oval(175, 100, 180, 105, fill=cross2_lr) #left self.canvas.create_oval(225, 100, 230, 105, fill=cross2_lr) #right self.canvas.create_oval(200, 75, 205, 80, fill=cross2_ud) #up self.canvas.create_oval(200, 125, 205, 130, fill=cross2_ud) #down self.canvas.create_text(250, 100, text = cross2.car_nums[3],font=("bold", 22),fill = 'black') #right self.canvas.create_text(200, 50, text = cross2.car_nums[0],font=("bold", 22),fill = 'black') #up self.canvas.create_text(200, 150, text = cross2.car_nums[1],font=("bold", 22),fill = 'black') #down self.canvas.create_text(150, 75, text = cross2.car_nums[2],font=("bold", 22),fill = 'black') #left(up) self.canvas.create_text(150, 125, text = cross1.car_nums[3],font=("bold", 22),fill = 'black') #left(down) def visual_peri(self, peri_cars1, peri_cars2): if peri_cars1[0]==1: self.canvas.create_rectangle(100, 30, 105,35, fill = 'black' ) if peri_cars1[1]==1: self.canvas.create_rectangle(100, 165, 105,170, fill = 'black' ) if peri_cars1[2]==1: self.canvas.create_rectangle(30, 100, 35,105, fill = 'black' ) # if peri_cars1[3]==1: # self.canvas_create_rectangle(155, 100, 160,105, fill = 'black' ) if peri_cars2[0]==1: self.canvas.create_rectangle(200, 30, 205,35, fill = 'black' ) if peri_cars2[1]==1: self.canvas.create_rectangle(200, 165, 205,170, fill = 'black' ) # if peri_cars2[2]==1: # self.canvas_create_rectangle(40, 100, 45,105, fill = 'black' ) if peri_cars2[3]==1: self.canvas.create_rectangle(265, 100, 270,105, fill = 'black' ) self.canvas.pack() self.canvas.update() def visual_after(self, cross1, cross2): if cross1.light_state==0: cross1_lr='red' cross1_ud='green' elif cross1.light_state==1: cross1_lr='green' cross1_ud='red' elif cross1.light_state==2: cross1_lr='red' cross1_ud='yellow' elif cross1.light_state==3: cross1_lr='yellow' cross1_ud='red' if cross2.light_state==0: cross2_lr='red' cross2_ud='green' elif cross2.light_state==1: cross2_lr='green' cross2_ud='red' elif cross2.light_state==2: cross2_lr='red' cross2_ud='yellow' elif cross2.light_state==3: cross2_lr='yellow' cross2_ud='red' self.canvas_.delete('all') self.canvas_.create_oval(75, 100, 80, 105, fill=cross1_lr) #left self.canvas_.create_oval(125, 100, 130, 105, fill=cross1_lr) #right self.canvas_.create_oval(100, 75, 105, 80, fill=cross1_ud) #up self.canvas_.create_oval(100, 125, 105, 130, fill=cross1_ud) #down self.canvas_.create_text(50, 100, text = cross1.car_nums[2],font=("bold", 22),fill = 'black') #left self.canvas_.create_text(100, 50, text = cross1.car_nums[0],font=("bold", 22),fill = 'black') #up self.canvas_.create_text(100, 150, text = cross1.car_nums[1],font=("bold", 22),fill = 'black') #down # self.canvas.create_text(150, 100, text = '1',fill = 'black') self.canvas_.create_oval(175, 100, 180, 105, fill=cross2_lr) #left self.canvas_.create_oval(225, 100, 230, 105, fill=cross2_lr) #right self.canvas_.create_oval(200, 75, 205, 80, fill=cross2_ud) #up self.canvas_.create_oval(200, 125, 205, 130, fill=cross2_ud) #down self.canvas_.create_text(250, 100, text = cross2.car_nums[3],font=("bold", 22),fill = 'black') #right self.canvas_.create_text(200, 50, text = cross2.car_nums[0],font=("bold", 22),fill = 'black') #up self.canvas_.create_text(200, 150, text = cross2.car_nums[1],font=("bold", 22),fill = 'black') #down self.canvas_.create_text(150, 75, text = cross2.car_nums[2],font=("bold", 22),fill = 'black') #left(up) self.canvas_.create_text(150, 125, text = cross1.car_nums[3],font=("bold", 22),fill = 'black') #left(down) self.canvas_.pack() self.canvas_.update() <file_sep> # Deep Reinforcement Learning for Traffic Lights Control ## Background (More about model description, see in _Intelligent Transportation System.md_) [_Deep Reinforcement Learning for Intelligent Transportation Systems_ NIPS 2018 Workshop MLITS](https://openreview.net/forum?id=BJl846ey97) The states transformation principle is shown in the graph: <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/states.png" width="30%"> </p> __States__ representation: ''0'': green light for direction 1 and hence red light for direction 2;\ ''1'': green light for direction 2 and hence red light for direction 1;\ ''2'': yellow light for direction 1 and hence red light for direction 2;\ ''3'': yellow light for direction 2 and hence red light for direction 1. __Actions__ representation: (contrary to in paper) ⓪: change state\ ①: keep on ## Getting Started To run this repo, you need to use **Pyhton 3.5**. Generally, use `python xxx.py --train` for training and `python xxx.py --test` for testing. Running the code in different categories: ### Deep Q-Networks (DQN): **./1.one_way_two_queue**: `python light_constr.py --train/test` **./2.two_intersections(linear)**: `python lights.py --train/test` **./3.grid_square_network**: `python lights.py --train` **./4.multithread_for_grid**: `python lights.py --train/test` **./5.one_agent_for_each_intersection**: ```python lights_re.py --train/test``` ### Deep Deterministic Policy Gradients (DDPG): Generally, use `python -m run.py --alg=ddpg --num_timesteps=xxx --train` for training, `python -m run.py --alg=ddpg --num_timesteps=xxx --test` for testing and `python -m run.py --alg=ddpg --num_timesteps=xxx --retrain` for retraining from last saved checkpoint. **./6.ddpg_for_single**, **./7.ddpg_for_linear** and **./8.ddpg_for_grid**: `python -m run.py --alg=ddpg --num_timesteps=1e4 --train/test/retrain` # Deep Q-Networks ## Single Unidirectional Intersection (two roads) ### Model Description: It is one intersection with only two unidirectional roads, no left or right turning. The number of cars on each road is denoted as ![equ.1](https://latex.codecogs.com/gif.latex?Q_1,&space;Q_2\in&space;I) respectively. The state of the traffic light is denoted by state S, which can be in one of the following four states * "0": green light for road Q_1, and hence red light for road Q_2; * "1": red light for road Q_1, and hence green light for road Q_1; * "2": yellow light for Q_1, and red light for road Q_2; * "3": red light for road Q_1, and yellow light for road Q_2; And the transition of states, which is called the action in RL algorithm, can be: * "0": change; * "1": keep on; According to general transportation principles, the state transition of traffic lights could only be unidirectional, which is ![equ.1](https://latex.codecogs.com/gif.latex?"0"\rightarrow{"2"}\rightarrow{"1"}\rightarrow{"3"}\rightarrow{"0"}) under our definition of light states above. The trained RL agent takes the tuple [Q_1, Q_2, S] as input and generates action choice for traffic light. <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/1inter.png" width="25%"> </p> ### Training: <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/train.png" width="40%"> </p> Code in **./1.one_way_two_queue**. ## Linear-Network Intersections ### Model Description: Linear network model is combined with multiple single intersections on a line, as shown in the following graph. Noticing that we don't care much about the outcoming roads, which is denoted by dashed lines. <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/linear_network5.png" width="70%"> </p> ### Visualized Simulation in Experiments: the color of lights is 'green' or 'red' or 'yellow'. The black rectangular represents incoming car for periphery of road networks. The numbers indicates number of cars on each road. If the light is 'green', the number of cars in that road will reduce the number of passing cars after transition. If there is 'black rectangular', the number of cars in the corresponding road will increase one after transition. The upper image is the state before transition, while the lower image is the state after transition. <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/Screenshot.png" width="60%"> </p> ### Training: <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/train1.png" width="40%"> </p> Code in **./2.two_intersections(linear)**. ## Grid-Square-Network Intersections ### Model Description: <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/grid_square_network.png" width="40%"> </p> ### Visualized Simulation in Experiments: <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/4*4.png" width="35%"> </p> ### Training: <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/2*2_100m.png" width="40%"> </p> Code in **./3.grid_square_network**. ## Multi-thread version code for grid network Apply multi-thread for accelerating training process. Code in **./4.multithread_for_grid**. ## Agent for single intersection Single agent for every intersection (instead of single agent for whole road network), input of agent is from each one intersection. All intersections share the same agent, every time agent stores [obs,a,r,obs_] for each intersection, share the same overall reward (`lights.py`) or restore each reward for each intersection (`lights_re.py`). Code in **./5.one_agent_for_each_intersection**. # Deep Deterministic Policy Gradients ## Background Basic environments are similar with for DQN, only with main/branch road difference. For all 3 circumstances, main road is direction 2, and branch road is direction 1, larger coming and passing rates on main roads than branch roads. Another difference of DDPG version environment with DQN version is the number of cars on roads (coming, queueing, passing) are more realistic values like 16, 8, etc instead of 0, 1. ## Single Bidirectional Intersection (four roads) <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/ddpg4single.png" width="80%"> </p> Code in **./6.ddpg_for_single**. ## Linear-Network Intersections Testing of 10*1 linear network. <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/ddpg4linear.png" width="100%"> </p> Code in **./7.ddpg_for_linear**. ## Grid-Square-Network Intersections Testing of 10*5 grid network. <p align="center"> <img src="https://github.com/quantumiracle/DQN_traffic_light_control/blob/master/images/ddpg4grid1.png" width="100%"> </p> Code in **./8.ddpg_for_grid**. # Citation: If you use this repository for any projects, please cite this paper: ``` @article{liu2018deep, title={Deep Reinforcement Learning for Intelligent Transportation Systems}, author={<NAME> <NAME> <NAME> <NAME>}, journal={arXiv preprint arXiv:1812.00979}, year={2018} } ``` <file_sep>import numpy as np from RL_brain import DeepQNetwork import argparse import matplotlib.pyplot as plt import matplotlib matplotlib.use('Agg') import pickle import os import gzip import time import tkinter as tk from env import crossing from visual import Visual import threading as th from threading import Thread import urllib import tensorflow as tf from multiprocessing.dummy import Pool as ThreadPool from multiprocessing import Process np.set_printoptions(threshold=np.inf) parser = argparse.ArgumentParser(description='Train or test neural net motor controller.') parser.add_argument('--train', dest='train', action='store_true', default=False) parser.add_argument('--test', dest='test', action='store_true', default=True) args = parser.parse_args() # os.environ["CUDA_VISIBLE_DEVICES"] = "1" grid_x=4 grid_y=1 RL = DeepQNetwork(n_actions=2**(grid_x*grid_y), n_features=5*(grid_x*grid_y), # learning_rate=0.01, e_greedy=0.9, replace_target_iter=100, memory_size=10000, e_greedy_increment=0.001,) window = tk.Tk() window.title('my window') window.geometry('1000x1000') canvas = tk.Canvas(window, bg='white', height=1000, width=1000) x=[] y=[] for i in range(grid_x): x.append(i+1) for i in range(grid_y): y.append(i+1) #parameters for visualizing times=100 bias=6 bias_t=20 bias_=40 b=2 q_states=[[([1] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] for xx in x: for yy in y: #q_states is the inner/peripheral property of crossroads if xx==1: q_states[xx][yy][2]=0 #0 for peripherial road, 1 for inner road if xx==grid_x: q_states[xx][yy][3]=0 if yy==1: q_states[xx][yy][0]=0 if yy==grid_y: q_states[xx][yy][1]=0 light_states=[[0 for i in range(grid_y+1)]for j in range(grid_x+1)] def int2bin(n, count=24): #10 -> binary """returns the binary of integer n, using count number of digits""" return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) def crossroads_map(): cross={} #dictionary of crossroads for xx in x: for yy in y: lab=str(xx)+str(yy) cross_=crossing(car_nums=np.array([0,0,0,0]),light_state=0,q_states=q_states[xx][yy]) cross[lab]=cross_ return cross # cross[]={''} def worker(train_steps): cross=crossroads_map() # visual=Visual() reward_set=[] obs=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs=np.concatenate((obs, cross[lab].car_nums, cross[lab].light_state), axis=None) for steps in range(train_steps): action=RL.choose_action(obs) action_set=[[0 for i in range(grid_y+1)]for j in range(grid_x+1)] peri_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] in_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] #light state changes, cars numbers change, interactions between crossroads and peripherals for xx in x: for yy in y: lab=str(xx)+str(yy) action_set[xx][yy]=int(int2bin(action,grid_x*grid_y)[(xx-1)*grid_y+yy-1]) peri_cars[xx][yy], in_cars[xx][yy]=cross[lab].state_change(action_set[xx][yy]) #interactions among crossroads for xx in x: for yy in y: lab=str(xx)+str(yy) if cross[lab].q_states[0]==1: if yy-1>0 and in_cars[xx][yy-1][0]>0: cross_=cross[lab] cross_.car_nums[0]+=in_cars[xx][yy-1][0] cross[lab]=cross_ if cross[lab].q_states[1]==1: if yy+1<=grid_y and in_cars[xx][yy+1][1]>0: cross_=cross[lab] cross_.car_nums[1]+=in_cars[xx][yy+1][1] cross[lab]=cross_ if cross[lab].q_states[2]==1: if xx-1>0 and in_cars[xx-1][yy][2]>0: cross_=cross[lab] cross_.car_nums[2]+=in_cars[xx-1][yy][2] cross[lab]=cross_ if cross[lab].q_states[3]==1: if xx+1<=grid_x and in_cars[xx+1][yy][3]>0: cross_=cross[lab] cross_.car_nums[3]+=in_cars[xx+1][yy][3] cross[lab]=cross_ # visual.visual_peri(peri_cars,x,y,times,b,bias,bias_,bias_t,grid_x,grid_y) reward=0 for xx in x: for yy in y: lab=str(xx)+str(yy) for i in range (4): reward = reward - cross[lab].car_nums[i]**2 # visual.visual_after(cross,x,y,times,b,bias,bias_t) obs_=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs_=np.concatenate((obs_, cross[lab].car_nums, cross[lab].light_state), axis=None) RL.store_transition(obs,action,reward,obs_) obs=obs_ def learn(lr_steps,learning_rate): for steps in range(lr_steps): RL.learn(learning_rate) step_set=[] reward_set=[] class ThreadWithReturnValue(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): Thread.__init__(self, group, target, name, args, kwargs) self._return = None def run(self): print(type(self._target)) if self._target is not None: self._return = self._target(*self._args, **self._kwargs) def join(self, *args): Thread.join(self, *args) return self._return if args.train: ''' ###test### part of code is used to create a specific thread for showing reward curve during training process ''' train_steps=1000000 lr_steps=1 learning_rate=0.01 workers = 3 processes = [] step_set=[] # multithreading--call #of workers for sampling (CPU) coord = tf.train.Coordinator() for p_number in range(workers): #using multi-thread instead of multi-process p=th.Thread(target=worker, args=(train_steps,)) # p = Process(target=worker, args=(train_steps,)) # p=ThreadWithReturnValue(target=worker, args=(train_steps,)) p.daemon = True p.start() processes.append(p) ########## ###test### cross=crossroads_map() # visual=Visual() reward_set=[] obs=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs=np.concatenate((obs, cross[lab].car_nums, cross[lab].light_state), axis=None) ###test### ########## for step in range (train_steps): step_set.append(step) ########## ###test### action=RL.choose_action(obs) action_set=[[0 for i in range(grid_y+1)]for j in range(grid_x+1)] peri_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] in_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] #light state changes, cars numbers change, interactions between crossroads and peripherals for xx in x: for yy in y: lab=str(xx)+str(yy) action_set[xx][yy]=int(int2bin(action,grid_x*grid_y)[(xx-1)*grid_y+yy-1]) peri_cars[xx][yy], in_cars[xx][yy]=cross[lab].state_change(action_set[xx][yy]) #interactions among crossroads for xx in x: for yy in y: lab=str(xx)+str(yy) if cross[lab].q_states[0]==1: if yy-1>0 and in_cars[xx][yy-1][0]>0: cross_=cross[lab] cross_.car_nums[0]+=in_cars[xx][yy-1][0] cross[lab]=cross_ if cross[lab].q_states[1]==1: if yy+1<=grid_y and in_cars[xx][yy+1][1]>0: cross_=cross[lab] cross_.car_nums[1]+=in_cars[xx][yy+1][1] cross[lab]=cross_ if cross[lab].q_states[2]==1: if xx-1>0 and in_cars[xx-1][yy][2]>0: cross_=cross[lab] cross_.car_nums[2]+=in_cars[xx-1][yy][2] cross[lab]=cross_ if cross[lab].q_states[3]==1: if xx+1<=grid_x and in_cars[xx+1][yy][3]>0: cross_=cross[lab] cross_.car_nums[3]+=in_cars[xx+1][yy][3] cross[lab]=cross_ # visual.visual_peri(peri_cars,x,y,times,b,bias,bias_,bias_t,grid_x,grid_y) reward=0 for xx in x: for yy in y: lab=str(xx)+str(yy) for i in range (4): reward = reward - cross[lab].car_nums[i]**2 obs_=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs_=np.concatenate((obs_, cross[lab].car_nums, cross[lab].light_state), axis=None) obs=obs_ reward_set.append(reward) if step%20 ==0: print(step,', ',reward) plt.plot(step_set,reward_set) plt.savefig('reward1.png') ###test### ########## #decay learning rate if step%40000==0: learning_rate=learning_rate*0.2 if step%1000==0: RL.store() #call learning(GPU backpropagation) every 0.001 second during each step, #therefore the training frequency is about 1000Hz time.sleep(0.001) q=th.Thread(target=learn, args=(lr_steps,learning_rate)) # q=Process(target=learn, args=(lr_steps,learning_rate)) # q=ThreadWithReturnValue(target=learn, args=(lr_steps,learning_rate)) q.daemon = True q.start() processes.append(q) coord.join(processes) RL.store() if args.test: RL.test_set() # no exploration noise cross=crossroads_map() visual=Visual() obs=[] Q1_set=[] Q2_set=[] Q3_set=[] Q4_set=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs=np.concatenate((obs, cross[lab].car_nums, cross[lab].light_state), axis=None) RL.restore() for steps in range(1000): for xx in x: for yy in y: lab=str(xx)+str(yy) visual.visual_before(cross,x,y,times,b,bias,bias_t) action=RL.choose_action(obs) action_set=[[0 for i in range(grid_y+1)]for j in range(grid_x+1)] peri_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] in_cars=[[([0] * 4) for i in range(grid_y+1)]for j in range(grid_x+1)] #light state changes, cars numbers change, interactions between crossroads and peripherals for xx in x: for yy in y: lab=str(xx)+str(yy) action_set[xx][yy]=int(int2bin(action,grid_x*grid_y)[(xx-1)*grid_y+yy-1]) peri_cars[xx][yy], in_cars[xx][yy]=cross[lab].state_change(action_set[xx][yy]) #interactions among crossroads for xx in x: for yy in y: lab=str(xx)+str(yy) if cross[lab].q_states[0]==1: if yy-1>0 and in_cars[xx][yy-1][0]>0: cross_=cross[lab] cross_.car_nums[0]+=in_cars[xx][yy-1][0] cross[lab]=cross_ if cross[lab].q_states[1]==1: if yy+1<=grid_y and in_cars[xx][yy+1][1]>0: cross_=cross[lab] cross_.car_nums[1]+=in_cars[xx][yy+1][1] cross[lab]=cross_ if cross[lab].q_states[2]==1: if xx-1>0 and in_cars[xx-1][yy][2]>0: cross_=cross[lab] cross_.car_nums[2]+=in_cars[xx-1][yy][2] cross[lab]=cross_ if cross[lab].q_states[3]==1: if xx+1<=grid_x and in_cars[xx+1][yy][3]>0: cross_=cross[lab] cross_.car_nums[3]+=in_cars[xx+1][yy][3] cross[lab]=cross_ if xx==1: Q1_set.append(cross[lab].car_nums[2]) elif xx==2: Q2_set.append(cross[lab].car_nums[2]) elif xx==3: Q3_set.append(cross[lab].car_nums[2]) elif xx==4: Q4_set.append(cross[lab].car_nums[2]) visual.visual_peri(peri_cars,x,y,times,b,bias,bias_,bias_t,grid_x,grid_y) reward=0 for xx in x: for yy in y: lab=str(xx)+str(yy) for i in range (4): reward = reward - cross[lab].car_nums[i]**2 visual.visual_after(cross,x,y,times,b,bias,bias_t) time.sleep(10) obs_=[] for xx in x: for yy in y: lab=str(xx)+str(yy) obs_=np.concatenate((obs_, cross[lab].car_nums, cross[lab].light_state), axis=None) if steps%50==0: print(steps,reward) if steps%100==0: plt.plot(step_set,reward_set) plt.savefig('test2.png') reward_set.append(reward) step_set.append(steps) obs=obs_ window.mainloop() #plot for linear road network plot_len=100 ax1=plt.subplot(2,1,1) plt.sca(ax1) plt.plot(step_set[:plot_len],reward_set[:plot_len]) plt.ylabel('-Loss',fontsize=15) ax2=plt.subplot(2,1,2) plt.sca(ax2) plt.plot(step_set[:plot_len], Q1_set[:plot_len],'--',label='X1') plt.plot(step_set[:plot_len], Q2_set[:plot_len],label='X2') plt.plot(step_set[:plot_len], Q3_set[:plot_len],label='X3') plt.plot(step_set[:plot_len], Q4_set[:plot_len],label='X4') plt.xlabel('Steps',fontsize=15) plt.ylabel('Cars Numbers',fontsize=15) # set legend leg = plt.legend(loc=4,prop={'size': 15}) legfm = leg.get_frame() legfm.set_edgecolor('black') # set legend fame color legfm.set_linewidth(0.5) # set legend fame linewidth plt.savefig('test.png') plt.show()
72427434275ad468ddd9a079da1f8d3339757f62
[ "Markdown", "Python" ]
6
Python
sagar23sj/Reinforcement_Learning_for_Traffic_Light_Control
464c17ba25ebcb49f78d6cdcc96d7fe3764d7508
efa191a643290b35bc926942de357b4a929aadd9
refs/heads/master
<file_sep>#!/bin/sh #### Creates ifcfg-tap$1 file and stores in /etc/sysconfig/network directory ####### if [ -z "$1" ] ; then echo "USAGE : $0 <path_to_networking> <number of the tap interface>" exit 1; fi if [ $2 = "0" ]; then echo " (Note: tap0 cannot be configured)"; exit 1; fi if [ ! -d $1 ]; then echo "Error: $1 does not exist, exiting"; exit 2; fi iface="$1/ifcfg-tap$2"; if [ -f $iface ]; then echo "$iface exists." else echo "create $iface"; echo -e "DEVICE=tap$2\nTUNNEL=Tap\nONBOOT=yes\nSTARTMODE=auto\nBRIDGE=br$2\nINTERFACETYPE=tap\nTUNNEL_LOCAL_IPADDR=0.0.0.0\nTUNNEL_SET_PERSISTENT=yes" \ > $iface fi <file_sep>#!/bin/sh if [ $# -ne "2" ]; then echo "Usage: $0 Input_Port_number Output_Port_number" echo "Usage example for Flow13 $0 1 3" exit 1; fi IN_PORT=$1 OUT_PORT=$2 FLOW_NAME=Flow$IN_PORT$OUT_PORT ##################################################################### ##### No need to change anything from here on ##### ##################################################################### echo "rr(of_protocol)." echo "InPortField1 = #ofp_field{field = in_port, value = <<$IN_PORT:32>>}." echo "Match1 = #ofp_match{oxm_fields = [InPortField1]}." echo "ActionOutput1 = #ofp_instruction_write_actions{" echo "actions = [#ofp_action_set_queue{port =" echo "$OUT_PORT," echo "" echo "queue_id = 1}," echo "" echo "#ofp_action_output{port = $OUT_PORT}]}." echo "$FLOW_NAME = #ofp_flow_mod{table_id = 0," echo "" echo "priority = 1," echo "" echo "command = add," echo "" echo "match = Match1," echo "" echo "instructions = [ActionOutput1]" echo "" echo "}." echo "ofs_userspace:ofp_flow_mod(state, $FLOW_NAME)." <file_sep>#!/bin/sh LINC_SCRIPT_DIR=/usr/local/src/linc/misc_tools ### Change the value of num_interfaces to correspond to the number required if [ -z "$1" ] ; then echo "USAGE : $0 <num_interfaces>" exit fi num_interfaces=$1 ### Interface numbering starts at 1, by default, and are sequential start_if_num=01 ##################################################################### ##### No need to change anything from here on ##### ##################################################################### # find the version of OS we care about echo "Looking for config directory" netdir="" ; for trydir in /etc/sysconfig/network \ /etc/sysconfig/network-scripts ; do if [ -d $trydir ] ; then netdir=$trydir; fi ; done ; if [ -z "$netdir" ] ; then echo "No config directory found"; exit else echo "using directory $netdir"; fi; echo "Creating Bridges, Taps and add the same to physical interfaces ..." echo "=================================" for ((i=start_if_num; i <= num_interfaces; i++)) do $LINC_SCRIPT_DIR/create_ifcfg_eth $netdir $i $LINC_SCRIPT_DIR/create_ifcfg_br $netdir $i $LINC_SCRIPT_DIR/create_ifcfg_tap $netdir $i done <file_sep>OFBuild ======= Openflow and LINC setup utilities<file_sep>#!/bin/sh #### Creates ifcfg-eth$1 file and stores in /etc/sysconfig/network directory ####### if [ -z "$1" ] ; then echo "USAGE : $0 <path_to_networking> <number of the eth interface>" exit 1; fi if [ $2 = "0" ]; then echo " (Note: eth0 cannot be configured)"; exit 1; fi if [ ! -d $1 ]; then echo "Error: $1 does not exist, exiting"; exit 2; fi iface="$1/ifcfg-eth$2"; if [ -f $iface ]; then echo "$iface exists." else echo "create $iface"; echo -e "DEVICE=eth$2\nTYPE=Ethernet\nNM_CONTROLLED=no\nONBOOT=no\nNETMASK=255.255.255.0\nSTARTMODE=auto\nBridge=br$2" > $iface fi <file_sep>#!/bin/sh ### Change the value of num_interfaces to correspond to the number required if [ -z "$1" ] ; then echo "USAGE : $0 <num_interfaces>" exit fi ### Change the value of num_interfaces to correspond to the number required num_interfaces=$1 ### Interface numbering starts at 1, by default, and are sequential start_if_num=1 ### OF-Controller Host Name ##### OF_CONTROLLER_HOST_NM='"localhost"' ### OF-Controller Host Port # ##### OF_CONTROLLER_HOST_PORT=6633 ### Network Speed ### NW_SPEED_VAL=1 NW_SPEED_VAL_TYPE=gibps ##################################################################### ##### No need to change anything from here on ##### ##################################################################### echo "[" echo " {of_switch," echo " [" echo " {controllers," echo " [" echo " {"$OF_CONTROLLER_HOST_NM", $OF_CONTROLLER_HOST_PORT}" echo " ]}," echo " {ports," echo " [" for ((i=start_if_num; i <= num_interfaces; i++)) do echo " {$i, [" echo " {rate, {$NW_SPEED_VAL, $NW_SPEED_VAL_TYPE}}," echo " {queues, [{1, [{min_rate, 0}," echo " {max_rate, 1000}]}]}" if [ $i -eq $num_interfaces ]; then echo " ]}" else echo " ]}," fi done echo " ]}," echo " {backends," echo " [" echo " {userspace, [" echo " {ports," echo " [" for ((i=start_if_num; i <= num_interfaces; i++)) do if [ $i -eq $num_interfaces ]; then echo " {$i, [{interface, \"tap$i\"}]}" else echo " {$i, [{interface, \"tap$i\"}]}," fi done echo " ]}" echo " ]}" echo " ]}" echo " ]}," echo " {lager," echo " [" echo " {handlers," echo " [" echo " {lager_console_backend, info}," echo " {lager_file_backend," echo " [" echo " {\"log/error.log\", error, 10485760, \"\$D0\", 5}," echo " {\"log/console.log\", info, 10485760, \"\$D0\", 5}" echo " ]}" echo " ]}" echo " ]}," echo " {sasl," echo " [" echo " {sasl_error_logger, {file, \"log/sasl-error.log\"}}," echo " {errlog_type, error}," echo " {error_logger_mf_dir, \"log/sasl\"}, % Log directory" echo " {error_logger_mf_maxbytes, 10485760}, % 10 MB max file size" echo " {error_logger_mf_maxfiles, 5} % 5 files max" echo " ]}" echo "]." <file_sep>#!/bin/sh #### Creates ifcfg-br$1 file and stores in /etc/sysconfig/network directory ####### if [ -z "$1" ] ; then echo "USAGE : $0 <path_to_networking> <number of the bridge interface>" exit 1; fi if [ $2 = "0" ]; then echo " (Note: br0 cannot be configured)"; exit 1; fi if [ ! -d $1 ]; then echo "Error: $1 does not exist, exiting"; exit 2; fi iface="$1/ifcfg-br$2"; if [ -f $iface ]; then echo "$iface exists." else echo "create $iface"; echo -e "DEVICE=br$2\nTYPE=Bridge\nNM_CONTROLLED=no\nONBOOT=no\nSTARTMODE=auto\nDELAY=0\nBRIDGE=yes\nBRIDGE_PORTS='eth$2 tap$2'\nBRIDGE_FORWARDDELAY=0" \ > $iface fi
6f1e765289d63cb484c3ef0d756b3070c3424726
[ "Markdown", "Shell" ]
7
Shell
slchorne/OFBuild
b02223ef8cb23fb5152a93b35fe7ebb80b469b4d
d9df4dfbdd24bfec5a21ba0d0ee2bbdafd0cad78
refs/heads/master
<repo_name>perillamint/better_picard_usb_twister<file_sep>/stepper.hpp class Stepper { public: Stepper(PinName en, PinName dir, PinName step); ~Stepper(); void init(); void enable(); void disable(); void reset(); void step(uint8_t dir, uint8_t speed); void stepNoCount(uint8_t dir, uint8_t speed); void stepToward(int16_t offset, uint8_t speed); void doStepTick(); void stop(); void setDestOffset(int16_t offset); void setSpeed(uint8_t speed); void setContMode(uint8_t dir); int16_t getOffset(); uint8_t getSpeed(); bool isMoving(); bool isContMode(); protected: DigitalOut en; DigitalOut dir; DigitalOut pulse; uint8_t contdir; uint8_t speed; int16_t offset; int16_t destOffset; };<file_sep>/stepper.cpp #include "mbed.h" #include "stepper.hpp" Stepper::Stepper(PinName en, PinName dir, PinName step): en{en}, dir{dir}, pulse{step} { this -> offset = 0; this -> destOffset = 0; this -> speed = 1; this -> contdir = 0; } Stepper::~Stepper() { // } void Stepper::init() { this -> dir = 0; this -> en = 0; this -> pulse = 0; } void Stepper::enable() { this -> en = 0; } void Stepper::disable() { this -> en = 1; } void Stepper::reset() { this -> offset = 0; this -> destOffset = 0; } void Stepper::step(uint8_t dir, uint8_t speed) { if (dir > 1) return; if (dir == 1) { this -> offset += 1; } else { this -> offset -= 1; } this -> stepNoCount(dir, speed); } void Stepper::stepNoCount(uint8_t dir, uint8_t speed) { if (dir > 1) return; this -> dir = dir; this -> pulse = 1; ThisThread::sleep_for(1ms); // TODO: Make it adjustable this -> pulse = 0; ThisThread::sleep_for(1ms); // TODO: Make it adjustable } void Stepper::stepToward(int16_t offset, uint8_t speed) { if (this -> offset > offset) { this -> step(0, speed); } else if (this -> offset < offset) { this -> step(1, speed); } } void Stepper::doStepTick() { if (this -> contdir == 0) { this -> stepToward(this -> destOffset, this -> speed); } else { this -> stepNoCount(this -> contdir - 1, this -> speed); } } void Stepper::stop() { this -> contdir = 0; this -> destOffset = this -> offset; } void Stepper::setDestOffset(int16_t offset) { this -> destOffset = offset; } void Stepper::setSpeed(uint8_t speed) { this -> contdir = 0; this -> speed = speed; } void Stepper::setContMode(uint8_t dir) { if (dir > 1) { this -> contdir = 0; } else { this -> contdir = dir + 1; } } int16_t Stepper::getOffset() { return this -> offset; } uint8_t Stepper::getSpeed() { return this -> speed; } bool Stepper::isMoving() { return this -> offset != this -> destOffset; } bool Stepper::isContMode() { return this -> contdir != 0; }<file_sep>/main.cpp /* mbed Microcontroller Library * Copyright (c) 2019 ARM Limited * SPDX-License-Identifier: Apache-2.0 */ #include "mbed.h" //#include "USBSerial.h" #include "usb/USBHID.h" #include "stepper.hpp" #define PICARD_USB_TWISTER_SERIAL 1 USBHID hid(false, 8, 8, 0x0461, 0x0021, PICARD_USB_TWISTER_SERIAL); DigitalOut led(PC_12); // CMD // 0x08 - moveTo // 0x0a, magic -32768 - Cont + // 0x08, magic -32768 - Cont - // 0x00 - Halt // 0x01, magic -32768 - Set zero Stepper stepper0(D8, D7, D6); //Stepper stepper1(D12, D5, D4); Thread reportThread; Thread commandThread; Thread motorThread; void reportThreadMain() { HID_REPORT output_report = { .length = 8, .data = {0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} }; for(;;) { led = !led; output_report.data[0] = ((0x10 - stepper0.getSpeed()) << 4); if (stepper0.isContMode()) { output_report.data[0] += 0x0a; } else if (stepper0.isMoving()) { output_report.data[0] += 0x09; } else { output_report.data[0] += 0x00; } int16_t curpos = stepper0.getOffset(); memcpy(&(output_report.data[1]), &curpos, 2); hid.send(&output_report); ThisThread::sleep_for(10ms); } } void commandThreadMain() { HID_REPORT command = { .length = 8, .data = {0x00} }; for(;;) { bool isSuccess = hid.read(&command); if (!isSuccess) { ThisThread::sleep_for(1ms); continue; } uint8_t spd = 0x10 - (command.data[0] >> 4); uint8_t cmd = command.data[0] & 0x0f; int16_t pos = (int16_t)((uint16_t)(command.data[2] << 8) + command.data[1]); stepper0.setSpeed(spd); printf("spd: %u", spd); switch (cmd) { case 0x08: if (pos == -32768) { // Cont + stepper0.setContMode(1); } else { stepper0.setDestOffset(pos); } break; case 0x0a: if (pos == -32768) { // Cont - stepper0.setContMode(0); } else { //WTF? printf("Uh-oh\r\n"); } break; case 0x00: stepper0.stop(); break; case 0x01: stepper0.reset(); break; } } } void stepMotor(int16_t destpos) { stepper0.stepToward(destpos, 1); } void motorThreadMain() { for(;;) { stepper0.doStepTick(); ThisThread::yield(); } } int main() { DigitalOut disc(PC_11); disc = 0; // Enable USB Pull UP printf("USB PullUP activated.\r\n"); printf("USB activated.\r\n"); hid.connect(); printf("HID OK!\r\n"); reportThread.start(reportThreadMain); commandThread.start(commandThreadMain); motorThread.start(motorThreadMain); for(;;) { ThisThread::sleep_for(1s); } }
bac0d7efa4750635c6cf6e5378aa86619e12c225
[ "C++" ]
3
C++
perillamint/better_picard_usb_twister
9a251da66c0dd1fc45a2a7e583c8e483b8c64b8d
6dc800a322f91cf97c49cac7536df5f4a87ba2b8
refs/heads/master
<repo_name>rahulgawale/gunguna-dev<file_sep>/src/main/java/com/gunguna/dev/repository/package-info.java /** * Spring Data JPA repositories. */ package com.gunguna.dev.repository; <file_sep>/src/main/java/com/gunguna/dev/domain/package-info.java /** * JPA domain objects. */ package com.gunguna.dev.domain; <file_sep>/src/main/java/com/gunguna/dev/config/package-info.java /** * Spring Framework configuration files. */ package com.gunguna.dev.config;
bfa38559ca99d63e5d44ee562e0c2f34d486702c
[ "Java" ]
3
Java
rahulgawale/gunguna-dev
b817e2c96c10aadfc9fce82b609df68e377a4ead
2ce09c9a8797b0b125c9f6efff05455ed4e5f883
refs/heads/master
<file_sep># Personal Profile [doudoudzj.github.io](doudoudzj.github.io) <NAME>'s Profile Page(豆振江的个人简介页面) <file_sep><?php if (pathinfo($_SERVER['HTTP_HOST'], PATHINFO_EXTENSION) == 'com') { include 'index.html'; } else { include 'index_zh_CN.html'; }
4240040aac38e376c2cc2091c5f6c1e87dd9934a
[ "Markdown", "PHP" ]
2
Markdown
doudoudzj/mypage
6fc3a6935477d009c6805ed2628b4e8e301d36b6
bad033d53645e241aea080b87e35ba89f9cf1f27
refs/heads/master
<file_sep>from appJar import gui app=gui() axes=app.addPlot("Results",[0,1,2,3,4,5],[0,1,2,3,4,5]) axes.set_xlabel("Actual Distance") axes.set_ylabel("Reported Distance") # this demonstrates that the update plot function isn't used to append # updatePlot leads to wiping of old data # simple update def update(): app.updatePlot("Results",[10,9,8,7,6],[10,9,8,7,6]) app.refreshPlot("Results") app.addButton("Update",lambda:update()) app.go() <file_sep># Module to run testing of the LDS on the linear stage import lds from lds import serial_port import stage import time import csv from openpyxl import Workbook import threading lds_reads=[] stage_reads=[] e=threading.Event() class trial_counter(): def __init__(self,num): self.num=num global z_run # used to create a pointer which can be shared/updated between two different modules z_run=trial_counter(0) global offset class test_result: def __init__(self,deg,dist,inten,error,act_dist): self.deg=deg self.dist=dist self.inten=inten self.error=error self.act_dist=act_dist class test: def __init__(self,conversion:int,offset:int): self.conversion=conversion self.offset=offset self.stage=stage.stage(self.conversion,self.offset) time.sleep(1) # initialize connection to motor (TCP) self.motor=self.stage.connect() time.sleep(1) self.serial=lds.create_session(serial_port) time.sleep(1) self.laser=lds.lds() time.sleep(1) # start the laser spinning self.laser.start(self.serial) time.sleep(1) # do a full scan self.serial.write(b'GetLDSScan\r\n') time.sleep(1) def start_laser(self): self.laser.start(self.serial) def stop_laser(self): self.laser.stop(self.serial) # used to obtain all of the version information from the bot (serial command) def get_bot_info(self): r=self.laser.bot_info(self.serial) return r # used to close connections and stop laser def quit(self): # move to home self.home() # stop the laser self.stop_laser() # close serial connection try: self.serial.close() # close TCP connection except: pass try: self.stage.disconnect(self.motor) except: pass return True def home(self): self.stage.move_ab(self.motor,self.offset) time.sleep(1) mflag=self.stage.get_moving(self.motor) # pause the program while the motor is still moving while mflag != 0: time.sleep(1) mflag=self.stage.get_moving(self.motor) def convert_to_excel(self,results,file_name): wb=Workbook() j=1 # append the degree offset global offset wb.active.append(["Calculated Degree Offset"]) wb.active.append([offset]) wb.active.append([]) wb.active.append([]) bot_ver=self.get_bot_info() p='' for i in bot_ver: if i.isprintable(): p=p+i p=p.split(",") for x in p: wb.active.append([x]) for i in results: ws=wb.create_sheet("Trial "+str(j)) for x in i: ws.append(x) ws.append([]) ws.append([]) j=j+1 if file_name==None: file_name='test_results' name=file_name+'.xlsx' wb.save(filename=name) # this has been deprecated, now using excel to output the data def convert_to_csv(self,results,file_name): if file_name==None: file_name='test_results.csv' else: file_name=file_name+'.csv' with open(file_name,mode='w',newline='') as test_results: results_writer=csv.writer(test_results,delimiter=',',quotechar='"') for i in results: results_writer.writerow(i) test_results.close() # calculate the offset at the closest possible distance def offset_test(self): self.stage.move_ab(self.motor,self.offset) mflag=self.stage.get_moving(self.motor) while mflag!=0: time.sleep(1) mflag=self.stage.get_moving(self.motor) global offset offset=self.laser.calculate_offset(self.serial) return offset # automated test def auto_test(self,deg,A,B,step,readings,runs,file_name): global latest_lds_read global latest_stage_read global lds_reads global stage_reads global z_run #lds_reads=[] #stage_reads=[] # error checking if deg>359 or deg<0: print("Error:invalid degree parameter") return None if A < self.offset: print ("Error: A value is too small") return None if B > 6000: print("Error: B value is too large") if step<=0 or step>6000: print("Error: invalid step value") return None if B < A: print("Error: B is smaller than A") return None if readings<1: print("Invalid number of readings at each interval") return None if runs<1: print("Invalid number of runs") return None num_of_ints=(B-A)/step # check this one if num_of_ints.is_integer() is not True: print("Error: interval doesn't give an equal spacing") return None # calculate the degree ofset before anything else: # the function definition prints it to the command line as well self.offset_test() # counter for number of runs full_results=[] z_run.num=1 while z_run.num<=runs: # initialize list of results # used for a list of test_result class # results=[] # used for a string of results lds_reads.clear() stage_reads.clear() results_list=[['Degree','Actual Distance','Laser Distance','Intensity','Error',]] count=0 # starts at distance A if e.isSet() == False: self.stage.move_ab(self.motor,A) time.sleep(1) mflag=self.stage.get_moving(self.motor) # pause the program while the motor is still moving while mflag != 0: time.sleep(1) mflag=self.stage.get_moving(self.motor) p=self.stage.stage_pos(self.motor) else: return # get a reading from the lds a specified number of times if e.isSet()==False: for i in range(0,readings): scan=self.laser.deg_scan(self.serial,deg) if scan==None: print("Error in LDS scan") return None else: #data=test_result(scan.deg,scan.dist,scan.inten,scan.error,p) data_list=[scan.deg,p,scan.dist,scan.inten,scan.error] latest_lds_read=str(scan.dist) latest_stage_read=str(p) lds_reads.append(float(scan.dist)) stage_reads.append(float(p)) #print(vars(data)) #results.append(data) results_list.append(data_list) count = count+1 else: return # move to new distance while count<=num_of_ints and e.isSet()==False: if e.isSet()==True: return self.stage.move_rel(self.motor,step) time.sleep(1) mflag=self.stage.get_moving(self.motor) # pause the program while the motor is still moving while mflag != 0: time.sleep(1) mflag=self.stage.get_moving(self.motor) p=self.stage.stage_pos(self.motor) # get a reading from the lds a specified number of times if e.isSet()==False: for i in range(0,readings): if e.isSet()==False: scan=self.laser.deg_scan(self.serial,deg) if scan==None: print("Error in LDS scan") return None else: #data=test_result(scan.deg,scan.dist,scan.inten,scan.error,p) data_list=[scan.deg,p,scan.dist,scan.inten,scan.error] latest_lds_read=str(scan.dist) latest_stage_read=str(p) #print(latest_lds_read) #print(latest_stage_read) lds_reads.append(float(scan.dist)) stage_reads.append(float(p)) #results.append(data) results_list.append(data_list) else: return count=count+1 else: return # return the results #name=file_name+'_trial'+str(z_run.num) #self.convert_to_csv(results_list,name) #return results z_run.num=z_run.num+1 full_results.append(results_list) # reset the counter at the end of the trials z_run.num=0 self.convert_to_excel(full_results,file_name) <file_sep># Code to create GUI for the LDS testing interface for the linear stage # <NAME>, July 2019 from appJar import gui import test # module with functions controlling testing from test import e, lds_reads, stage_reads, z_run import stage import lds import socket import time import threading from multiprocessing import Process, Pipe from multiprocessing.managers import BaseManager import os import ttkthemes global e global lds_reads global stage_reads global in_auto in_auto=False conv=2556.7 off=493 test_object=test.test(conv,off) global most_recent_test global total_runs total_runs=0 # set up of the gui # if not using ttk themes, just use app=gui() app=gui(useTtk=True) app.setLocation("CENTER") app.setStretch("both") app.setSticky("nesw") app.setTitle("LDS Testing on 6 Meter Linear Stage") # this theme can be configured using any of the options found on the site, entirely optional, comment out if desired app.setTtkTheme("arc") app.ttkStyle.configure("TLabel",font=20) app.ttkStyle.configure("TButton",font=20) app.addLabel("params","Input Parameters for the System") app.addLabelNumericEntry("Conversion (default is 2556.7): ") app.addLabelNumericEntry("Offset (default is 493): ") app.addLabelEntry("COM Port: ") def sys_params(): global test_object global conv conv=app.getEntry("Conversion (default is 2556.7): ") # None is used here because this is numeric entry if conv!=None: test_object.conversion=conv test_object.stage.conversion=conv #print(test_object.conversion) global off off=app.getEntry("Offset (default is 493): ") # None is used here because this is numeric entry if off!=None: print("Offset changed") test_object.offset=off test_object.stage.offset=off #print(test_object.offset) global com com=app.getEntry("COM Port: ") # "" is used here because this is a general entry if com!="": print("COM port changed") test_object.stop_laser() test_object.serial.close() test_object.serial=lds.create_session(com) test_object.laser.start(test_object.serial) app.addButton("Update Parameters",lambda:sys_params()) # manual side of the interface app.startFrame("LEFT",row=0,column=0) app.setPadding(15,15) # start the laser app.addButton("Start LDS Laser",lambda:test_object.start_laser()) # stop the laser app.addButton("Stop LDS Laser",lambda:test_object.stop_laser()) # manual movement of the linear stage - absolute position app.addLabelEntry("Move to absolute position (mm):") app.setEntryDefault("Move to absolute position (mm):",0) def manual_abs(): abs_pos=app.getEntry("Move to absolute position (mm):") abs_pos=int(abs_pos) test_object.stage.move_ab(test_object.motor,abs_pos) app.addNamedButton("Go","absolute",lambda:manual_abs()) # manual movement of the linear stage - relative position app.addLabelEntry("Move to relative position (mm):") app.setEntryDefault("Move to relative position (mm):",0) def manual_rel(): abs_pos=app.getEntry("Move to relative position (mm):") abs_pos=int(abs_pos) test_object.stage.move_rel(test_object.motor,abs_pos) app.addNamedButton("Go","relative",lambda:manual_rel()) app.addLabel("Single Test Scan Results:") app.addTable("Scan Results",[["Degree","Distance","Intensity","Error"]]) def test_scan(): # clear out the last trial app.deleteAllTableRows("Scan Results") # perform the scan and parsing results=test_object.laser.full_scan(test_object.serial) if results==None: results=test_object.laser.full_scan(test_object.serial) # add the results to the table if results != None: app.addTableRows("Scan Results",results) else: print("Error in scanning, please re-run the scan.") app.addButton("Test Laser Scan",lambda:test_scan()) app.startSubWindow("Robot Version Info") app.setStretch("both") app.setSticky("nesw") app.addScrolledTextArea("Version",colspan=10,rowspan=10) app.stopSubWindow() global bot bot=test_object.get_bot_info() app.setTextArea("Version",bot) app.hideSubWindow("Robot Version Info") # a button used to get a pop-up with all of the version information for the robot def print_bot_info(): app.showSubWindow("Robot Version Info") app.addButton("Get Robot Version Info",lambda:print_bot_info()) app.stopFrame() # automated side of the interface app.startFrame("CENTER",row=0,column=1) app.setPadding(15,15) # auto test functionality app.addLabelEntry("Desired Degree: ",row=1) app.addLabelEntry("Starting Distance A: ",row=2,rowspan=1) app.addLabelEntry("Ending Distance B: ",row=3) app.addLabelEntry("Step Interval: ",row=4) app.addLabelEntry("Readings per Interval: ",row=5) app.addLabelEntry("Custom File Name: ",row=6) app.addLabelEntry("Number of Runs: ",row=7) def gui_auto_test(): global test_object global most_recent_test global in_auto in_auto=True d=int(app.getEntry("Desired Degree: ")) a=int(app.getEntry("Starting Distance A: ")) b=int(app.getEntry("Ending Distance B: ")) s=int(app.getEntry("Step Interval: ")) r=int(app.getEntry("Readings per Interval: ")) rs=int(app.getEntry("Number of Runs: ")) global total_runs total_runs=rs f=app.getEntry("Custom File Name: ") most_recent_test=f if f=="": f=None most_recent_test='test_results' t=threading.Thread(target=test_object.auto_test,args=(d,a,b,s,r,rs,f,),daemon=True) t.start() t.join() app.destroySubWindow("Auto Test Running") e.clear() in_auto=False return # this e is initialized in the test module def set_flag(): global e e.set() return def auto_test_wrapper(): app.startSubWindow("Auto Test Running",modal=True) app.addLabel("The auto test is currently running. Do not close this window while test is running. To stop the test please hit the quit button below. Note that any collected data may be lost.") app.addButton("Quit Auto Test",lambda:set_flag()) app.stopSubWindow() app.showSubWindow("Auto Test Running") time.sleep(1) try: app.thread(gui_auto_test) except: app.destroySubWindow("Auto Test Running") time.sleep(1) app.addButton("Auto Test",lambda:auto_test_wrapper(),row=8) def set_white_values(): app.setEntry("Desired Degree: ","0") app.setEntry("Starting Distance A: ","500") app.setEntry("Ending Distance B: ","6000") app.setEntry("Step Interval: ","25") app.setEntry("Readings per Interval: ","1") app.setEntry("Custom File Name: ","whitecard") app.setEntry("Number of Runs: ","1") def set_grey_values(): app.setEntry("Desired Degree: ","0") app.setEntry("Starting Distance A: ","500") app.setEntry("Ending Distance B: ","3500") app.setEntry("Step Interval: ","25") app.setEntry("Readings per Interval: ","1") app.setEntry("Custom File Name: ","greycard") app.setEntry("Number of Runs: ","1") app.addButton("White Card Test",lambda:set_white_values(),row=9) app.addButton("Grey Card Test",lambda:set_grey_values(),row=10) # this could theoretically be altered to open any file in the folder using an entry field, probably not necessary for the time being? def open_csv(): global most_recent_test os.startfile(most_recent_test) app.addButton("Open Most Recent Test Results",lambda:open_csv(),row=11) app.addLabelEntry("Calculated Degree Offset: ",row=12) # this is for calculating the degree offset outside of the auto test def get_offset(): global in_auto in_auto=True global test_object r=test_object.offset_test() app.setEntry("Calculated Degree Offset: ",str(r)) in_auto=False app.addButton("Calculate Offset",lambda:get_offset(),row=13) app.stopFrame() app.startFrame("RIGHT",row=0,column=2) # widget to show the current position of the linear stage app.addLabel("Current Stage Position","Current Stage Position",row=0,column=0) def update_pos(): if in_auto==False: try: pos= test_object.stage.stage_pos(test_object.motor) app.setLabel("Current Stage Position","Current Stage Position : "+str(pos)+" (mm)") except: pass else: app.setLabel("Current Stage Position","Current Stage Position : IN AUTO TEST") app.addLabel("Latest Stage Reading : ","Latest Stage Reading : ",row=1,column=0) def latest_stage(): try: latest_stage_read=stage_reads[-1] #print(latest_stage_read) app.setLabel("Latest Stage Reading : ", "Latest Stage Reading : "+str(latest_stage_read)+" (mm)") except: pass app.addLabel("Latest LDS Reading : ","Latest LDS Reading : ",row=2,column=0) def latest_lds(): try: latest_lds_read=lds_reads[-1] #print(latest_lds_read) app.setLabel("Latest LDS Reading : ","Latest LDS Reading : "+str(latest_lds_read)+" (mm)") except: pass app.addLabel("Current Run Number : ",row=3,column=0) def latest_run(): global z_run global total_runs app.setLabel("Current Run Number : ","Current Run Number : "+str(z_run.num)+" out of "+str(total_runs)) axes=app.addPlot("Results",stage_reads,lds_reads,row=4,column=0) axes.set_xlabel("Actual Distance (mm)") axes.set_ylabel("Reported Distance (mm)") def update_plot(): app.updatePlot("Results",stage_reads,lds_reads,keepLabels=True) app.refreshPlot("Results") # functions which the GUI runs all the time (to update values and plot) app.registerEvent(update_pos) app.registerEvent(latest_lds) app.registerEvent(latest_stage) app.registerEvent(update_plot) app.registerEvent(latest_run) app.stopFrame() # sequence to quit the app app.setStopFunction(lambda:test_object.quit()) # start the app app.go()<file_sep># Script/module to get LDS Data from Robot through serial port # <NAME> import serial import time import subprocess import numpy class reading: def __init__(self,deg,dist,inten,error): self.deg=deg self.dist=dist self.inten=inten self.error=error # parameter for serial port so it can be edited from the GUI # it's set automatically to what it was when the code was written global serial_port serial_port='COM5' def create_session(s_port): # need to call this command otherwise not permitted to make serial connection - only on Linux #subprocess.call(['sudo chmod 666 /dev/ttyACM0'],shell=True) #initialize the session # timeout of 3 seconds s=serial.Serial(s_port,timeout=10) return s def close_session(s): s.close() return None class lds(): # this class relies on an already created session object (see above) def start(self,s): # starts the LDS s.write(b'TestMode On\r\n') time.sleep(1) s.write(b'SetLDSRotation On\r\n') # how long does the LDS need to warm up? Does this matter? time.sleep(3) def full_scan(self,s): # returns a list of readings response=s.reset_input_buffer() s.write(b'GetLDSScan\r\n') time.sleep(1) response=s.read(10000) response=response.decode("utf-8",errors="ignore") #print(response) results=[] all_degs=response.splitlines() # print(all_degs) # all_degs=all_degs[2:363] for i in all_degs: line=i.split(",") if line[0] != '' and line[0].isnumeric()==True and int(line[0])>=0 and int(line[0])<=359: #print(line[0]) if len(line) == 4: distance=int(line[1]) if line[2] != None and line[2].isnumeric()==True: l2=int(line[2]) else: l2=None if line[3] != None and line[3].isnumeric()==True: l3 = int(line[3]) else: l3=None new_read=[int(line[0]),distance,l2,l3] results.append(new_read) # sometimes the strings get messed up and index errors get thrown, need to restart the scan else: return None return results def deg_scan(self,s,deg:int): # this call gets all degrees response=s.reset_input_buffer() s.write(b'GetLDSScan\r\n') time.sleep(1) response=s.read(10000) response=response.decode("utf-8",errors="ignore") all_degs=response.splitlines() for i in all_degs: line=i.split(",") if line[0] != '' and line[0].isnumeric() ==True and line[0]==str(deg): if len(line) > 1: distance=int(line[1]) if line[2] != None and line[2].isnumeric()==True: l2=int(line[2]) else: l2=None if line[3] != None and line[3].isnumeric()==True: l3 = int(line[3]) else: l3=None new_read=reading(int(line[0]), distance, l2, l3) return new_read return None def stop(self,s): s.write(b'SetLDSRotation Off\r\n') time.sleep(1) # Returns def bot_info(self,s): s.reset_input_buffer() s.write(b'GetVersion\r\n') time.sleep(1) response=s.read(10000) response=response.decode("utf-8") # need to parse for important information here as requested by Pawel # irrelevant data is removed a=response.split("LCD Panel,0,0,0,",1) b=a[1].split("Locale",1) chunk1=b[0] c=b[1].split("MAG_SENSOR_ORIG",1) d=c[1].split("NTP URL",1) chunk2=d[0] e=d[1].split("Software Git") e[1]="Software Git"+e[1] f=e[1].split("UI Name") chunk3=f[0] parsed_data=chunk1+chunk2+chunk3 parsed_data=parsed_data.splitlines() return parsed_data def calculate_offset(self,s): # get a full scan packet scan=self.full_scan(s) # check the scan for success counter=0 # try to scan ten times, should work the first time but this is a failsafe while scan==None and counter<10: scan=self.full_scan(s) counter=counter+1 if scan==None and counter>=10: return None # initialize lists x=[] y=[] # pull data from the first ten degrees of the list for i in range(0,11): entry=scan[i] #print(entry) # check error code and distance if entry[3] == 0 and 450 <= entry[1] <= 525: # append degree x.append(i) # append distance y.append(entry[1]) #print(entry[1]) else: print("Degree %d lost because of error or distance not between 450 and 525"%i) # pull data from the last ten degrees of list deg=-10 for i in range(350,360): entry=scan[i] #print(entry) # check error code and distance if entry[3] == 0 and 450 <= entry[1] <= 525: # append degree x.append(deg) # append distance y.append(entry[1]) #print(entry[1]) else: print("Degree %d lost because of error or distance not between 450 and 525"%deg) # always increase the degree number deg=deg+1 # calculate the quadratic fit using the x and y arrays r=numpy.polynomial.polynomial.Polynomial.fit(x,y,2) # extract coefficients coeff=r.convert().coef m=(-1*coeff[1])/(2*coeff[2]) #print(coeff) print("This is the calculated true zero degree using a quadratic fit:") print(m) return m if __name__=="__main__": s=serial.Serial(serial_port,timeout=3) s.write(b'TestMode On\r\n') time.sleep(1) #s.write(b'GetWifiStatus\r\n') #time.sleep(1) #response=s.read(100) #print(response.decode("utf-8")) s.write(b'SetLDSRotation On\r\n') time.sleep(5) s.write(b'GetLDSScan\r\n') time.sleep(1) response=s.read(10000) response=response.decode("utf-8") print(response) s.write(b'SetLDSRotation Off\r\n') time.sleep(1) s.reset_output_buffer() s.close() # isolate 0th degree data scan=response.split("GetLDSScan") scan=scan[-1] scan=scan.split("\n") for i in scan: # print(i) if i[0]=="0": # isolate values line=i.split(",") # store results in an object new_read=reading(line[0],line[1],line[2],line[3]) # print(vars(new_read)) <file_sep># small script to get a csv output of lds single scan import lds import csv l=lds.lds() s=lds.create_session('COM5') l.start(s) r=l.full_scan(s) def convert(results,file_name): if file_name==None: file_name='test_results.csv' else: file_name=file_name+'.csv' with open(file_name,mode='w',newline='') as test_results: results_writer=csv.writer(test_results,delimiter=',',quotechar='"') for i in results: results_writer.writerow(i) test_results.close() convert(r,"test_lds_scan") l.stop(s) <file_sep># Module to interact with the linear stage # <NAME> import socket import time class stage: def __init__(self,conversion:int,offset:int): # this is the number of motor steps that is equal to 1 mm self.conversion=conversion # position value for the far end of the stage # this is for the 6m linear stage, change for another stage self.end_of_stage=conversion*(-5975-offset) # close end of the stage position = 0 self.offset=offset # initializes the TCP connection def connect(self): m=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # these values won't change for the 6m linear stage but will be different for other instruments m.connect(("192.168.33.1",503)) time.sleep(.1) #m.settimeout(15) return m def get_pos(self,m): # request and recieve position in motor steps, not millimeters m.send(b'PR P\r\n') try: r=m.recv(128) time.sleep(.1) except: print("pos exception") time.sleep(5) r=m.recv(128) time.sleep(.1) # r=r.encode("utf-8") l=r.splitlines() # return the last line of the response (in case there's other things in buffer) # convert string to a decimal number # remove this print statement once you know it's isolating the right value pos=int(l[-1],10) return pos def stage_pos(self,m): # returns the stage position in millimeters # offset calculated using laser tool is added to this position steps=self.get_pos(m) if steps==0: return self.offset else: real=steps/(self.conversion*-1) real=real+self.offset return round(real) # move the stage to an absolute position from home def move_ab(self,m,dist:int): # calculate the position: p=self.conversion*(dist-self.offset)*-1 # need to check to make sure position isn't off the stage if p<=0 and p>=((self.end_of_stage-self.offset)*self.conversion): m.send(b'MA %d\r\n'%p) #pos=None #while pos!=p: #pos=self.get_pos(m) #time.sleep(1) return True else: print("Invalid position for absolute move") return False def move_rel(self,m,dist:int): # get the original position start=self.get_pos(m) # calculate the position to move p=self.conversion*(dist)*-1 end=start+p # need to check to make sure final position isn't off the stage if end<=0 and end>=(-5975*self.conversion): m.send(b'MR %d\r\n'%p) #pos=None #while pos!=end: #pos=self.get_pos(m) #time.sleep(1) return True else: print("Invalid position for relative move") return False def get_echo(self,m): m.send(b'PR EM\r\n') #time.sleep(1) r=m.recv(1024) l=r.splitlines() echo=int(l[-1],10) return echo def get_maxvel(self,m): m.send(b'PR VM\r\n') #time.sleep(1) r=m.recv(1024) l=r.splitlines() vel=int(l[-1],10) return vel def get_moving(self,m): # gets the moving flag to see if stage is still moving m.send(b'PR MV\r\n') try: r=m.recv(128) time.sleep(.1) except: print("moving exception") time.sleep(5) r=m.recv(128) time.sleep(.1) l=r.splitlines() moving=int(l[-1],10) return moving # this function doesn't work def set_echo(self,m,mode): m.send(b'EM=%d\r\n'%mode) check=self.get_echo(m) if check==mode: return True else: return None # doesn't work even when sending the commands through the shell, not a function issue, permissions?? def set_maxvel(self,m,maxv): m.send(b'VM=%d\r\n'%maxv) check=self.get_maxvel(m) if check==maxv: return True else: return None # also doesn't work def set_pos(self,m,pos): m.send(b'P=%d\r\n'%pos) check=self.get_pos(m) if check==pos: return True else: return None # important to call every time to end the TCP connection def disconnect(self,m): m.shutdown('SHUT_RDWR') m.close() <file_sep>import test import time t=test.test(2556.7,493) time.sleep(1) while True: localtime = time.asctime(time.localtime(time.time())) print("Local current time : " + str(localtime)) position=t.stage.stage_pos(t.motor) print("Position : " + str(position))
1de0b06d9c6123003ab30716225692b2988cbb71
[ "Python" ]
7
Python
mzvyagin/linear_stage
c830f263c1d72d9b408147bed3c53458d649eff4
1800d3e54e84ea7c92fe9022aca6d21fabf114d7
refs/heads/master
<repo_name>Beletskyy/Git<file_sep>/src/Student.java /** * Created by bvm on 24.09.2015. */ public class Student { } <file_sep>/README.md # Git Git My sdxz czxczx <file_sep>/src/TestBoolean.java /** * Created by bvm on 02.10.2015. */ public class TestBoolean { public static void main(String[] args) { boolean a = false; boolean b = true; boolean c = false; boolean r1 = a||b&&c;//false boolean r2 = b||c&&a||c;//true System.out.println(r1); System.out.println(r2); boolean a1 = true; boolean b1 = false; boolean c1 = false; boolean r3 = a||b&&c;//false boolean r4 = b||c&&a||c;//true System.out.println(r3); System.out.println(r4); } }
703db955891df601690dfd8a39ec7f0597792e45
[ "Markdown", "Java" ]
3
Java
Beletskyy/Git
bb5139d025dbb17e8db5ea7076ad2e863a788672
087167636d5605d631800f9f0ff8b270820262ca
refs/heads/master
<repo_name>subc/lng_novel<file_sep>/narou_downloader.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import requests import yaml import codecs from bs4 import BeautifulSoup from subprocess import PIPE, Popen import re import sys import time def main(start, finish): print 'start' # read yaml _base_yml = './narou_data/{}.yml' counter = 0 for x in range(0, 4): yml_path = _base_yml.format(x) with open(yml_path) as f: data = yaml.load(f) for record in data: counter += 1 if start <= counter <= finish: if 'ncode' in record: novel = Novel(record) novel.download('./narou_data') print '[+]downloaded: {} : {}'.format(counter, novel.title) # _url = 'http://ncode.syosetu.com/{}/{}/' class Novel(object): _data = None base_path = None def __init__(self, data): assert(type(data) == dict) self._data = data @property def title(self): return self._data['title'].replace('\r\n', '').replace('\n', '') @property def ncode(self): return self._data['ncode'] @property def general_all_no(self): return int(self._data['general_all_no']) @property def global_point(self): return int(self._data['global_point']) @property def filepath(self): return "./narou_data/novel/{}.txt".format(self.ncode) def get_url(self, num): return 'http://ncode.syosetu.com/{}/{}/'.format(self.ncode.lower(), num) def download(self, base_path): self.base_path = base_path c = [self.title] # download 30話くらい for x in range(2, min(self.general_all_no, 20)): url = self.get_url(x) body = download(url) soup = BeautifulSoup(body, 'lxml') contents = soup.find_all("div", attrs={"id": "novel_honbun"}) if contents: contents = contents[0] else: print "[-]Error No Contents {}:{}".format(str(x), self.title) continue c.append(contents.get_text()) time.sleep(0.3) writer(self.filepath, b''.join(c)) def download(url): _base_cmd = "curl '{url}' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: ja,en-US;q=0.8,en;q=0.6' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Referer: http://ncode.syosetu.com/n6450bt/7/' -H 'Cookie: bs.test.cen; OX_plg=swf|shk|pm; ses=zGDy5JNfPzq8DnAAzWbP90; lineheight=0; fontsize=0; novellayout=0; fix_menu_bar=1; _gat=1; _td=5294520f-2d0c-44de-ae14-325b427cfb63; nlist1=9s5x.8-hwgx.3-karn.5-k9dh.5-kb0s.5-k1bv.5-kd19.0-8hrp.b; ks2=e42qgwt7n3sw; sasieno=0; smplineheight=0; smpfontsize=0; smpnovellayout=0; _ga=GA1.2.678180494.1480608954' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' --compressed" c = _base_cmd.format(url=url) output = cmdline(c).stdout.readlines() output_str = b''.join(output) return output_str def cmdline(command): """ コマンドを実行する。shell=Trueの場合シェル経由で実行する。 :param command: str :return: Popen """ return Popen( args=command, stdout=PIPE, stderr=PIPE, shell=True ) def writer(filepath, body): with codecs.open(filepath, mode='w', encoding='utf8') as fw: fw.write(body) if __name__ == '__main__': argvs = sys.argv # コマンドライン引数を格納したリストの取得 assert len(argvs) == 3, argvs start_index = int(argvs[1]) limit = int(argvs[2]) main(start_index + 1, start_index + limit) <file_sep>/tfidf.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from collections import defaultdict from math import sqrt import re from janome.tokenizer import Tokenizer import nltk import codecs from subprocess import PIPE, Popen import yaml class TFIDF(object): _t = None @classmethod def gen(cls, text, enable_one_char=False): """ Get TF-IDF :param text: str :rtype :list[list[str, float]] """ _text = cls.filter(text) return cls.analysis(_text, enable_one_char=enable_one_char) @classmethod def similarity(cls, tfidf1, tfidf2): """ Get TF-IDF and Cosine Similarity cosθ = A・B/|A||B| :param tfidf1: list[list[str, float]] :param tfidf2: list[list[str, float]] :rtype : float """ tfidf2_dict = {key: value for key, value in tfidf2} ab = 0 # A・B for key, value in tfidf1: value2 = tfidf2_dict.get(key) if value2: ab += float(value * value2) # |A| and |B| a = sqrt(sum([v ** 2 for k, v in tfidf1])) b = sqrt(sum([v ** 2 for k, v in tfidf2])) return float(ab / (a * b)) @classmethod def some_similarity(cls, base_url, data): """ :param base_url: str :param data: list[lost[str, str]] :rtype : list[lost[str, str, float]] """ base_tfidf = cls.gen_web(base_url) return [[title, url, cls.similarity(base_tfidf, cls.gen_web(url))] for title, url in data] @classmethod def analysis(cls, text, enable_one_char): """ Calc TF-IDF textを形態素解析して名詞の数を返却(Morphological Analysis) :param text: str :rtype : dict{str: int} """ result = defaultdict(int) result2 = {} count = 0 t = cls._get_tokenizer() # 形態素解析 for token in t.tokenize(text): if '名詞' not in token.part_of_speech: continue count += 1 if '非自立' in token.part_of_speech: continue if '代名詞' in token.part_of_speech: continue if '接尾' in token.part_of_speech: continue if '数' in token.part_of_speech: continue if not enable_one_char: if len(token.surface) == 1: continue result[token.surface] += 1 result2[token.surface] = token # TF-IDF計算 result3 = [] for key in result: result3.append([key, result[key]]) result3.sort(key=lambda x: x[1], reverse=True) result4 = [] for r in result3[:100]: result4.append([r[0], float(float(r[1])/float(count))]) return result4 @classmethod def filter(cls, text): """ textをフィルターしてノイズを排除する :param text: str :rtype : str """ # アルファベットと半角英数と改行とタブを排除 text = re.sub(r'[a-zA-Z0-9¥"¥.¥,¥@]+', b'', text) text = re.sub(r'[!"“#$%&()\*\+\-\.,\/:;<=>?@\[\\\]^_`{|}~]', b'', text) text = re.sub(r'[\n|\r|\t|年|月|日]', b'', text) return text @classmethod def _get_tokenizer(cls): if TFIDF._t is not None: return TFIDF._t TFIDF._t = Tokenizer() return TFIDF._t def cmdline(command): """ コマンドを実行する。shell=Trueの場合シェル経由で実行する。 :param command: str :return: Popen """ return Popen( args=command, stdout=PIPE, stderr=PIPE, shell=True ) def file_read(filepath): with codecs.open(filepath, mode='r', encoding='utf8') as f: body = b'' for x in f.readlines(): body += x return body def file_writer(filepath, body): with codecs.open(filepath, mode='a', encoding='utf8') as fw: fw.write(body) def main(): path_output = './tfidf.txt' _next = 'N2335DE.txt' # 銀河鉄道の夜 if not _next: path_night_of_milky_way_train = './data/ao2/3.txt' body_night_of_milky_way_train = file_read(path_night_of_milky_way_train) tfidf_night_of_milky_way_train = TFIDF.gen(body_night_of_milky_way_train) file_writer(path_output, yaml.dump({str('ginga'): tfidf_night_of_milky_way_train})) # novels read novels = cmdline('ls -1 ./narou_data/novel/').stdout.readlines() _exec = False for i, novel_filename in enumerate(novels): novel_filename = novel_filename.replace('\r\n', '').replace('\n', '') if _exec is False: print novel_filename, _next, novel_filename == _next if novel_filename == _next: _exec = True continue novel_path = './narou_data/novel/' + novel_filename novel_body = file_read(novel_path) novel_tfidf = TFIDF.gen(novel_body) file_writer(path_output, yaml.dump({str(novel_filename): novel_tfidf})) print "[+]success {}: {}".format(str(i), novel_filename) if __name__ == '__main__': main() <file_sep>/convert_sjis_to_utf8.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import re def main(): p = ["./data/ao/{}.txt".format(x) for x in range(1, 11)] p2 = ["./data/ao2/{}.txt".format(x) for x in range(1, 11)] for i in range(0, 10): with codecs.open(p2[i], mode='w', encoding='utf8') as fw: with codecs.open(p[i], mode='r', encoding='shift_jis') as f: for x in f.readlines(): x = filter_j(x) fw.write(x) def filter_j(x): print x, type(x) x = re.sub(r'[.*]', "", x) x = re.sub(r'[#.*]', "", x) x = re.sub(r'《.*》', "", x) return x if __name__ == '__main__': main() <file_sep>/anal.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from collections import defaultdict from math import sqrt import re from janome.tokenizer import Tokenizer import nltk import codecs class TFIDF(object): _t = None @classmethod def gen(cls, text, enable_one_char=False): """ Get TF-IDF :param text: str :rtype :list[list[str, float]] """ _text = cls.filter(text) return cls.analysis(_text, enable_one_char=enable_one_char) @classmethod def similarity(cls, tfidf1, tfidf2): """ Get TF-IDF and Cosine Similarity cosθ = A・B/|A||B| :param tfidf1: list[list[str, float]] :param tfidf2: list[list[str, float]] :rtype : float """ tfidf2_dict = {key: value for key, value in tfidf2} ab = 0 # A・B for key, value in tfidf1: value2 = tfidf2_dict.get(key) if value2: ab += float(value * value2) # |A| and |B| a = sqrt(sum([v ** 2 for k, v in tfidf1])) b = sqrt(sum([v ** 2 for k, v in tfidf2])) return float(ab / (a * b)) @classmethod def some_similarity(cls, base_url, data): """ :param base_url: str :param data: list[lost[str, str]] :rtype : list[lost[str, str, float]] """ base_tfidf = cls.gen_web(base_url) return [[title, url, cls.similarity(base_tfidf, cls.gen_web(url))] for title, url in data] @classmethod def analysis(cls, text, enable_one_char): """ Calc TF-IDF textを形態素解析して名詞の数を返却(Morphological Analysis) :param text: str :rtype : dict{str: int} """ result = defaultdict(int) result2 = {} count = 0 t = cls._get_tokenizer() # 形態素解析 goi_counter = 0 goi_dict = defaultdict(int) for token in t.tokenize(text): if cls.goi_filter(token): goi_counter += 1 goi_dict[token.surface] += 1 if '名詞' not in token.part_of_speech: continue count += 1 goi_counter += 1 if '非自立' in token.part_of_speech: continue if '接尾' in token.part_of_speech: continue if '数' in token.part_of_speech: continue if not enable_one_char: if len(token.surface) == 1: continue result[token.surface] += 1 result2[token.surface] = token print "語彙力:{} / {}".format(float(len(goi_dict.keys())) / float(goi_counter), goi_counter) # TF-IDF計算 result3 = [] for key in result: result3.append([key, result[key]]) result3.sort(key=lambda x: x[1], reverse=True) result4 = [] for r in result3[:100]: # print r[0], float(float(r[1])/float(count)), result2[r[0]] result4.append([r[0], float(float(r[1])/float(count))]) return result4 @classmethod def goi_filter(cls, token): """ 形容詞 副詞 :param token: :return: """ for ng in ['名詞', '非自立', '助詞類接続', '助詞']: if ng in token.part_of_speech: return False if '形容詞' in token.part_of_speech: return True if '副詞' in token.part_of_speech: return True return False @classmethod def filter(cls, text): """ textをフィルターしてノイズを排除する :param text: str :rtype : str """ # アルファベットと半角英数と改行とタブを排除 text = re.sub(r'[a-zA-Z0-9¥"¥.¥,¥@]+', b'', text) text = re.sub(r'[!"“#$%&()\*\+\-\.,\/:;<=>?@\[\\\]^_`{|}~]', b'', text) text = re.sub(r'[\n|\r|\t|年|月|日]', b'', text) # 日本語以外の文字を排除(韓国語とか中国語とかヘブライ語とか) jp_chartype_tokenizer = nltk.RegexpTokenizer(r'([ぁ-んー]+|[ァ-ンー]+|[\u4e00-\u9FFF]+|[ぁ-んァ-ンー\u4e00-\u9FFF]+)') text = ''.join(jp_chartype_tokenizer.tokenize(text)) return text @classmethod def _get_tokenizer(cls): if TFIDF._t is not None: return TFIDF._t TFIDF._t = Tokenizer() return TFIDF._t def main(): novel_keys = [ '<KEY>', '<KEY>', '<KEY>', '<KEY>', 'N6768BF.txt', 'N7031BS.txt', 'N3726BT.txt', ] novels_path = ["./narou_data/novel/{}".format(x) for x in novel_keys] for i in range(0, len(novel_keys)): with codecs.open(novels_path[i], mode='r', encoding='utf8') as f: print "-----------------" body = b'' for x in f.readlines(): body += x print len(body), novels_path[i] tfidf = TFIDF.gen(body) if __name__ == '__main__': main() <file_sep>/narou_dev.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import requests import yaml import codecs def main(): print 'start' _base_url = 'http://api.syosetu.com/novelapi/api/?length=1000-&allcount=10000&title=1&lim=500&out=yaml&of=t-n-gp-ga&order=hyoka&st={}' _base_filepath = './narou_data/{}.yml' for x in range(0, 100): filepath = _base_filepath.format(x) url = _base_url.format(1 + 500 * x) r = download(url) if r: body = r.text writer(filepath, body) print '[+]download success :{}'.format(x) else: print '[-]download fail :{}'.format(x) def download(url): count = 0 while True: count += 1 r = requests.get(url) if r.status_code == 200: return r if count > 5: return None def writer(filepath, body): with codecs.open(filepath, mode='w', encoding='utf8') as fw: fw.write(body) if __name__ == '__main__': main()
ef0a9d2139ba8a0b0a850a98881d844c76a2655e
[ "Python" ]
5
Python
subc/lng_novel
64124daee09687624479e802310a008a3e7ec5cf
425ee8879d8568496813ec366c79aa2434e3a69a
refs/heads/master
<file_sep># LeeCode-Practice Record the questions I practiced on LeeCode <file_sep> public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> result = new ArrayList<Integer>(); for(int i = 0; i < nums.length; i++) { int temp = nums[i] % nums.length; if(temp == 0){ temp = nums.length; } nums[temp-1] += nums.length; } for(int i = 0; i < nums.length; i++) { if(nums[i] <= nums.length){ result.add(i+1); } } return result; } <file_sep>public class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> q = new PriorityQueue<>(new Comparator<Integer>(){ @Override public int compare(Integer a, Integer b){ if(a < b){ return 1; } return -1; } }); for(int i = 0; i < nums.length; i++ ){ q.add(nums[i]); } int i = 1; while(!q.isEmpty() && i < k){ q.poll(); i++; } return q.peek(); } } <file_sep>/** * public class TreeNode { * public int key; * public TreeNode left; * public TreeNode right; * public TreeNode(int key) { * this.key = key; * } * } */ public class Solution { public TreeNode reconstruct(int[] pre) { // Write your solution here if (pre == null || pre.length < 1) { return null; } return reconstruct(pre, 0, pre.length - 1); } public TreeNode reconstruct(int[] pre, int start, int end) { if (start > end) { //here is the leaf node return null; } //new a root node TreeNode newRoot = new TreeNode(pre[start]); //find x int x = start + 1; while (x <= end && pre[x] < pre[start]){ x++; } //recursion newRoot.left = reconstruct(pre, start + 1, x - 1); newRoot.right = reconstruct(pre, x, end); return newRoot; } public ArrayList<ArrayList<Integer>> combine(int n, int k) { if (n == 0 || k == 0) { return new ArrayList<ArrayList<Integer>>(); } int[] nums = new int[n]; for (int i = 1; i <= n; i++) { nums[i - 1] = i; } List<List<Integer>> result = new ArrayList<ArrayList<Integer>>(); List<Integer> cur = new ArrayList<>(); addCombine(result, cur, 0, nums, k); return result; } public void addCombine(List<List<Integer>> result, List<Integer> cur, int index, int[] nums, int k) { if (cur.size() == k) { result.add(new ArrayList<>(cur)); return; } for (int i = index; i < nums.length; i++) { cur.add(nums[i]); addCombine(result, cur, i + 1, nums, k); cur.remove(cur.size() - 1); } } } <file_sep> public List<Integer> getRow(int rowIndex) { /*use recursive way to solve the problem*/ List<Integer> result = new ArrayList<Integer>(); return helper(rowIndex, result); } private List<Integer> helper(int row, List<Integer> result){ if(row == 0){ result.add(1); return result; } result = helper(row - 1, result); List<Integer> temp = new ArrayList<Integer>(); temp.add(1); for(int i = 0; i < result.size() - 1; i++){ temp.add(result.get(i) + result.get(i+1)); } temp.add(1); return temp; } <file_sep>package sophiecui; import java.util.*; public class Solution { public int max = 1440; public String nextClosestTime(String time) { Set<Character> items = new HashSet<>(); char[] array = time.toCharArray(); for (char c : array) { if (c != ':' && !items.contains(c)) { items.add(c); } } List<Character> result = new ArrayList<>(); for (Character c : array) { result.add(c); } List<Character> cur = new ArrayList<>(); int target = changeTimeToInt(time); dfs(items, cur, target, result); String str = ""; for (Character c : result) { str += c; } return str; } private int changeTimeToInt(String time) { char[] array = time.toCharArray(); int hours = (array[0] - '0') * 10 + array[1] - '0'; int min = (array[3] - '0') * 10 + array[4] - '0'; return hours * 60 + min; } private void dfs(Set<Character> items, List<Character> cur, int target, List<Character> result) { if (cur.size() == 4) { int temp = changeStringToInt(cur); if (temp < 1) return; int diff = 0; if (temp <= target) { diff = 1440 - (target - temp); } else { diff = temp - target; } if (diff < max) { //update result updateResult(cur, result); max = diff; } return; } for (Character c : items) { cur.add(c); dfs(items, cur, target, result); cur.remove(cur.size() - 1); } } private void updateResult(List<Character> cur, List<Character> result) { result.set(0, cur.get(0)); result.set(1, cur.get(1)); result.set(2, ':'); result.set(3, cur.get(2)); result.set(4, cur.get(3)); } private int changeStringToInt(List<Character> cur) { int hour = (cur.get(0) - '0') * 10 + cur.get(1) - '0'; int min = (cur.get(2) - '0') * 10 + cur.get(3) - '0'; if (hour < 0 || hour > 24 || min < 0 || min > 59) { return -1; } return hour * 60 + min; } public int[] mergeSort(int[] array) { if (array == null || array.length <= 1) { return array; } split(array, 0, array.length - 1); return array; } private void split(int[] array, int left, int right) { if (left >= right) { return; } int mid = left + (right - left) / 2; split(array, left, mid); split(array, mid + 1, right); merge(array, left, mid, mid + 1, right); } private void merge(int[] array, int start1, int end1, int start2, int end2) { int[] help = new int[array.length]; for (int i = 0; i < array.length; i++) { help[i] = array[i]; } int i = start1; int j = start2; int k = start1; while (i <= end1 && j <= end2) { array[k++] = help[i] < help[j] ? help[i++] : help[j++]; } while (i <= end1) { array[k++] = help[i++]; } while (j <= end2) { array[k++] = help[j++]; } return; } public int[] quickSort(int[] array) { if (array == null || array.length <= 1) { return array; } quickSort(array, 0, array.length - 1); return array; } private void quickSort(int[] array, int start, int end){ if (start >= end){ return; } Random seed = new Random(); int pivot = start + seed.nextInt (end - start); int index = partition(array, start, end, pivot); quickSort(array, start, index - 1); quickSort(array, index + 1, end); } public int partition(int[] array, int start, int end, int pivot){ int i = start; int j = end - 1; swap(array, end, pivot); while (i <= j) { if (array[i] >= array[end]){ swap(array, i, j--); continue; } else if (array[j] < array[end]){ swap(array, i++, j); continue; } else { i++; } } swap(array, i, end); return i; } private void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } <file_sep>/* use the for method*/ public class Solution { public void rotate(int[] nums, int k) { if(nums.length == 0 || nums.length == 1){ return; } k = k % nums.length; if(k == 0){ return; } int mid = nums.length - k - 1; int[] array1 = new int[nums.length - k]; for (int i = 0; i < nums.length - k; i++){ array1[i] = nums[i]; } int j = 0; for(int i = mid + 1; i< nums.length; i++){ nums[j] = nums[i]; j++; } for(int i = 0;j< nums.length;j++){ nums[j] = array1[i]; i++; } return; } }
9de0e8c9c7774a6c8cc762be5d0c581fcd9b7f5a
[ "Markdown", "Java" ]
7
Markdown
sophiecui/LeeCode-Practice
4570cba1d0ca61da70415c9788ed873a3659572f
1d4a6f08eb7bce6f798f79d50c5488a8f1a63997
refs/heads/master
<file_sep>/* NOTES To Do: 1. More coloring prototyping Bugs: 1. Right-click event doesn't work until 2nd or 3rd try. After it does work, the pop-up is also associated with normal clicks. No idea why. 2. Double-check flag highlighting (rogue flag highlighting) Other Ideas (not immediately necessary): 1. Wikipedia mock page with draggable/segmented DIV's */ /*** Loop through all cell elements in the table and add event listeners ***/ /*** This code deals with elements that will be added dynamically to the page ***/ document.addEventListener('DOMContentLoaded', function() { var div1 = document.getElementById("popout-div1"); var bgp = chrome.extension.getBackgroundPage(); var currentUrl = bgp.currentTabUrl; var urlBase = currentUrl.split("/")[2]; div1.innerHTML = "current URL = " + bgp.currentTabUrl; // Variables for event PHP url and flag save PHP url var eventPHPUrl = "https://idl.ils.unc.edu/rsearch2/v21_matrix1/log_event.php"; var bookmarkPHPUrl = "https://idl.ils.unc.edu/rsearch2/v21_matrix1/save_bookmark.php"; // Grab all individual table cells var tbl_cells = document.getElementsByClassName("tbldrop"); // Add event listeners to DOM, focusing on table elements for (var i=0; i < tbl_cells.length; i++) { // Setting data tooltip attribute in loop // tbl_cells[i].setAttribute("title", "Drag text here"); /*** EVENT LISTENERS FOR MATRIX CELLS ***/ // Add mouseover listener for each matrix cell tbl_cells[i].addEventListener("mouseover", function(e) { var eventData = logEvent("mouseover", this.id); console.log(eventData); // Post to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log("post executed..."); }); // Add mouseout listener for each matrix cell tbl_cells[i].addEventListener("mouseout", function(e) { var eventData = logEvent("mouseout", this.id); console.log(eventData); // Post data to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("got back " + data); }); console.log("executed post..."); }); // Add click listener for each matrix cell tbl_cells[i].addEventListener("click", function(e) { var eventData = logEvent("click", this.id); // Post code to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log("post executed..."); }) // Add drag over event listener to each table cell tbl_cells[i].addEventListener("dragover", function(e) { e.preventDefault(); this.parentElement.className += " dragpulse"; e.dataTransfer.dropEffect = "copy"; // may be required to drop on DIV console.log("drag over"); // Add event logger var eventData = logEvent("dragover", this.id); // Post code to PHP $.post(bookmarkPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log("post executed..."); return false; }); // Add drag leave event listener to each table cell tbl_cells[i].addEventListener("dragleave", function(e) { e.preventDefault(); this.parentElement.className = ""; console.log("drag leave"); // Add event logger var eventData = logEvent("dragleave", this.id); // Post code to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log("post executed..."); return false; }); // Add drop event listener to each table cell tbl_cells[i].addEventListener("drop", function(e) { e.preventDefault(); this.parentElement.className = ""; //e.stopPropogation(); var src = e.dataTransfer.getData("Text"); console.log("drop..."); console.log(src); this.notes += "\n" + src; // Initialize an array and push flag ID ints to this var flagIds = []; // Grab all flag elements and push to `flagIds` array above var flags = document.getElementsByClassName("textflag"); console.log("Flag elements:"); console.log(flags); for (var i=0; i < flags.length; i++) { // Push just the int of the ID to the array flagIds.push(parseInt(flags[i].id.split("-")[1])); } // Dynamically assign ID's to flag icons if (flagIds.length > 0) { // Sort flag ID's to look up max var sortedFlagIds = flagIds.sort() var maxId = sortedFlagIds.pop() // Set new ID when flag is added to DOM // Need to figure out CSS for flag spacing.... this.innerHTML += "&nbsp;<a href='#' id='flaglink-" + String(maxId + 1) + "'" + "data-toggle='popover' class='flag-link'><img class='textflag' id='flag-" + String(maxId + 1) + "'" + "src='icons/flag25.png' /></a>"; } else { var maxId = -1; // Initialize ID's at 0 if there are no flags present on page this.innerHTML += "&nbsp;<a href='#' id='flaglink-0' data-toggle='popover' class='flag-link'><img class='textflag' id='flag-0' src='icons/flag25.png' /></a>"; } var currentFlagId = 'flag-' + String(maxId + 1); var currentLinkId = 'flaglink-' + String(maxId + 1); console.log(currentFlagId); console.log(currentLinkId); // Call attribute assignment function below on flags assignNewAttribute("noteText", src.trim(), currentFlagId); assignNewAttribute("column", this.id.split("c")[1], currentFlagId); assignNewAttribute("source_url", bgp.currentTabUrl, currentFlagId); // Calling function to tab number of elements in cell console.log(this.id); var cellChildren = tabulateCellChildren(this.id); console.log("number of cell children:"); console.log(cellChildren); // Add event logger var eventData = logEvent("flag_drop", this.id); eventData["source_url"] = bgp.currentTabUrl; // Post code to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log(eventData); // document.querySelector("#notesdiv").value = this.notes; return false; }); // Add click event listener to each table cell - displays cell text in notes area // tbl_cells[i].addEventListener("click", function(e) { // console.log("tbl cell clicked"); // document.querySelector("#notesdiv").value=""; // }); } // Keyboard delete function $(document).keyup(".circle-div", function(e) { // Count number of highlighted flags var highlightFlags = document.getElementsByClassName("circle-div"); if (highlightFlags.length > 0) { // Empty block to allow code below to execute if number of highlightFlags is > 0 // This looks a little weird, but prevents lots of nested if-statements } else { // There are no highlighted flags - break out of function return; }; // Check that delete key has been pressed if (e.keyCode == 8) { // Check that user has confirmed deletion, then delete var confirmation = confirm("Are you sure you want to remove this note?"); // User has confirmed deletion - delete flag if (confirmation == true) { var element = document.getElementsByClassName("circle-div")[0]; var parentElement = element.parentNode; console.log(parentElement); // Grab flag element to be removed var flagElement = parentElement.getElementsByClassName("textflag")[0]; console.log(flagElement); // Remove flag element $("#" + flagElement.id).remove(); // Remove link element $("#" + parentElement.id).remove(); // Remove displayed notes area text document.querySelector("#notesdiv").innerHTML = "Selected text will appear here"; }; }; var eventData = logEvent("flag_delete", this.id); // Post code to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); }); // JQuery function to get nice hover tooltips $("body").ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); /*** Flag functions ***/ // Add click-delete functionality to link of flag pop-up $("body").on("click", "#deleteLink", function() { console.log("clicked delete link..."); var element = document.getElementById(this.id); var parentElement = element.parentNode.parentNode.parentNode; // Grab flag element to be removed var flagElement = parentElement.getElementsByClassName("textflag")[0]; console.log(flagElement); // Grab link element to be removed var linkElement = parentElement.getElementsByClassName("flag-link")[0]; // Remove flag element $("#" + flagElement.id).remove(); // Remove link element $("#" + linkElement.id).remove(); // Remove displayed notes area text document.querySelector("#notesdiv").innerHTML = "Selected text will appear here"; }); // Test link wrapping for flag elements $(document).on("contextmenu", ".textflag", function(e) { e.preventDefault(); $('[data-toggle="popover"]').popover({html: true, title: "", content: "<a href='#' id='deleteLink'>Delete Flag</a>", trigger: "focus", placement: "top"}); console.log("Popover function clicked..."); return true; }); // Flag click function - highlights selected flags $(document).on("click", ".textflag", function() { // Log data from click var eventData = logEvent("flag_click", this.id); // Post code to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); var parentElement = this.parentNode; eventData["note_text"] = this.getAttribute("noteText"); eventData["source_url"] = this.getAttribute("source_url"); console.log(eventData); // Display notes in appropriate area document.querySelector("#notesdiv").innerHTML = this.getAttribute("noteText"); // Indicate selected flag on click var flags = document.getElementsByClassName("textflag"); $("#" + this.id).toggleClass("circle-div"); // Loop through and remove other background highlight for (var i=0; i < flags.length; i++) { if (flags[i].id !== this.id) { flags[i].className = "textflag"; }; }; return true; }); // Flag "click-off" function // This function fires when a user initially selects a flag(s) and later // clicks anywhere else on the DOM $(document).on("click", function(e) { // Select and store highlighted flag as variable var container = document.getElementsByClassName("circle-div")[0]; // Check whether a flag has been clicked // If not, remove selected flag class if (container !== e.target) { document.getElementById("notesdiv").innerHTML = "Selected text will appear here"; container.className = "textflag"; } }); // Flag double-click function $(document).on("dblclick", ".textflag", function() { var url = this.getAttribute("source_url"); var win = window.open(url, "_blank"); // Grab event data var eventData = logEvent("double_click", this.id); // Post code to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); }); // Column click function $(document).on("click", ".col-link", function() { // Log column click event var eventData = logEvent("column_click", this.id); console.log("COLUMN FUNCTION CLICKED..."); var colColor = this.getAttribute("color"); // Remove individual flag outline $(".textflag").removeClass("circle-div"); // Set text for notes summary area document.querySelector("#notesdiv").innerHTML = ""; var tbl = document.getElementById("texttable"); var numRows = tbl.rows.length - 1; var columnId = this.id.substr(this.id.length - 1); // Loop through number of rows in the table for (var i=0; i < numRows; i++) { // Loop through and display stuff in text area console.log("column function clicked..."); var itemName = tbl.rows[i + 1].getElementsByClassName("row-link")[0].innerText; // Figuring out how to get item names var columnElements = tbl.rows[i + 1].getElementsByTagName("td")[columnId].getElementsByClassName("textflag"); //var colColor = tbl.rows[i + 1].getElementsByClassName("col-link").getAttribute("color"); //console.log(colColor); // Check the number of flags if (columnElements.length > 0) { // Loop through the column elements and display items in text area for (var j=0; j < columnElements.length; j++) { console.log(columnElements[j]); var elementText = columnElements[j].getAttribute("noteText"); var notesArea = document.querySelector("#notesdiv"); notesArea.innerHTML += "<div>"; //notesArea.style.opacity = 0; notesArea.innerHTML += "<b>Item: " + itemName + "</b>"; notesArea.innerHTML += "<div id='textholder' style='background-color:" + colColor + "'>" + elementText + "</div>"; //notesArea.style.opacity = 1; notesArea.innerHTML += "</div>" }; }; // columnText.push(columnElements); }; }); // Row click function // Not sure if we're actually going to use this - may need to be removed $(document).on("click", ".row-link", function() { // Log column click event var eventData = logEvent("row_click", this.id); console.log("ROW FUNCTION CLICKED..."); // Remove individual flag outline $(".textflag").removeClass("circle-div"); // Set text for notes summary area document.querySelector("#notesdiv").innerHTML = ""; var tbl = document.getElementById("texttable"); var numCols = tbl.rows[0].getElementsByTagName("th").length - 1; var rowId = this.id.substr(this.id.length - 1); var colHeaders = document.getElementsByClassName("col-link"); console.log(colHeaders.length); // Associate columns with column colors var colMap = {}; for (i=0; i < colHeaders.length; i++) { colMap[i+1] = [colHeaders[i].innerText, colHeaders[i].getAttribute("color")]; }; console.log(colMap); console.log(this); var rowId = this.id.substr(this.id.length - 1); console.log(tbl.rows[parseInt(rowId)]); var rowFlags = tbl.rows[parseInt(rowId)].getElementsByClassName("textflag"); console.log(rowFlags); var colName = this.innerText; for (var i=0; i < rowFlags.length; i++) { var elementText = rowFlags[i].getAttribute("noteText"); var notesArea = document.querySelector("#notesdiv"); var colId = parseInt(rowFlags[i].getAttribute("column")); console.log(colId); notesArea.innerHTML += "<div>"; //notesArea.style.opacity = 0; notesArea.innerHTML += "<b>Dimension: " + colMap[colId][0] + "</b>"; notesArea.innerHTML += "<div id='textholder' style='background-color:" + colMap[colId][1] + "'>" + elementText + "</div>"; //notesArea.style.opacity = 1; notesArea.innerHTML += "</div>" }; }); /*** Notes area functions ***/ // Notes area mouseover/mouseout/click/scroll functions $(document).on("mouseover", "#notesdiv", function(e) { // Log data var eventData = logEvent("mouseover", this.id); // Post data to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log("post executed..."); }); $(document).on("mouseout", "#notesdiv", function(e) { // Log data var eventData = logEvent("mouseout", this.id); // Post data to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log("post executed..."); }); $(document).on("click", "#notesdiv", function(e) { // Log data var eventData = logEvent("click", this.id); // Post data to PHP $.post(eventPHPUrl, eventData, function(data) { console.log("data posted: " + data); }); console.log("post executed..."); }); }); // Update popout depending on current tab address function updatePopout() { chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) { var div1 = document.getElementById("popout-div1"); var bgp = chrome.extension.getBackgroundPage(); if (tabs[0].url.indexOf("popout.html") < 0) { var currentTabUrl = tabs[0].url; bgp.currentTabUrl = tabs[0].url; console.log("0 id = " + tabs[0].id); console.log("0 url = " + tabs[0].url); console.log("popout cur url = " + currentTabUrl); div1.innerHTML = "current URL = " + currentTabUrl; } return currentTabUrl; }); }; // Helper function for adding simple eventListeners function logEvent(eventType, elementId) { var data = {"event_type": eventType, //"element_id": elementId, "event_target": elementId, "timestamp": Date.now()}; console.log(data); return data; }; // Helper function for quickly tabbing up element children function tabulateCellChildren(elementId) { var el = document.getElementById(elementId); var numChildren = el.childNodes.length; return numChildren; }; // Helper function for creating new flag attributes and assigning them function assignNewAttribute(attributeName, attributeValue, currentFlagId) { console.log("Executing new attribute function..."); // Simple type-check for attributeName if (typeof attributeName === "string") { } else { console.log("You must pass a string for attributeName"); } var newAttribute = document.createAttribute(attributeName); newAttribute.value = attributeValue; document.getElementById(currentFlagId).setAttributeNode(newAttribute); }; chrome.tabs.onActivated.addListener(updatePopout); chrome.tabs.onUpdated.addListener(updatePopout); chrome.windows.onFocusChanged.addListener(updatePopout); <file_sep> document.addEventListener('DOMContentLoaded', function() { var div1 = document.getElementById("popup-div1"); var bgp = chrome.extension.getBackgroundPage(); div1.innerHTML = "current URL = " + bgp.currentTabUrl; //div1.innerHTML = "<b>ZZZ</b>"; });<file_sep>// document.body.style.border = "5px solid red"; // console.log("border added"); // console.log("yyy"); // Adding page load listener document.addEventListener("DOMContentLoaded", function() { console.log("Entering page load listener..."); // Call log function var pageLoadData = logEvent("page_load", window.location.href); console.log(pageLoadData); // Insert post here }); // Adding link event click listeners var linkArray = document.getElementsByTagName("a"); for (i=0; i < linkArray.length; i++) { linkArray[i].addEventListener("click", function(e) { console.log("link clicked..."); console.log(this.href); var linkData = logEvent("link_click", this.href); console.log(linkData); // Insert post here }); }; console.log(linkArray); // Adding scroll listener document.addEventListener("scroll", function() { var h = document.documentElement, b = document.body, st = "scrollTop", sh = "scrollHeight"; var scrollPct = h[st] || b[st] / ((h[sh] || b[sh]) - h.clientHeight) * 100; // Need to figure out how to get this to the DB // Look into additional fields var scrollData = {"action_type": "scroll", "scroll_pct": scrollPct, "url": window.location.href, "timestamp": Date.now()}; console.log(scrollData); // Insert post here }, false); // Function for updating popout function updatePopout() { chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) { var div1 = document.getElementById("popout-div1"); var bgp = chrome.extension.getBackgroundPage(); if (tabs[0].url.indexOf("popout.html") < 0) { var currentTabUrl = tabs[0].url; bgp.currentTabUrl = tabs[0].url; console.log("0 id = " + tabs[0].id); console.log("0 url = " + tabs[0].url); console.log("popout cur url = " + currentTabUrl); div1.innerHTML = "current URL = " + currentTabUrl; } }); }; // Function for recording event data - same as in popout code function logEvent(eventType, elementId) { var data = {"event_type": eventType, //"element_id": elementId, "event_target": elementId, "timestamp": Date.now()}; console.log(data); return data; }; <file_sep># Structured Search App This repository contains code and documentation for an interface facilitating a structured information retrieval study conducted through the School of Information and Library Science at the University of North Carolina at Chapel Hill. ## Repository Structure ### Subdirectories * **css**: subdirectory containing any CSS styling, including bootstrap and custom written CSS for the interface * **icons**: static images used for the interface * **js**: subdirectory containing any JavaScript libraries necessary for interface (e.g. jQuery, bootstrap.js, etc.) ### Main Directory Files * **background.js**: background JavaScript file used for tracking current content page that user is on * **manifest.json**: JSON file containing configuration options for running Google Chrome extension * **popout.html**: base HTML file outlining elements in interface webpage * **popout.js**: JavaScript file containing jQuery and JavaScript functions for tracking and facilitating user interaction with interface * **rtest.js**: JavaScript file containing JavaScript functions for tracking user interactions on the content page during search task * **wiki_mock.html**: HTML prototype for draggable DIV's necessary for Wikipedia search task
2dd850c9fdd9c374b29ab8d637e44eb46d52eea0
[ "JavaScript", "Markdown" ]
4
JavaScript
kylejshaffer/structured_search_app
92bcee27fe37e4a875c41e6fd5926f31f55cf197
fd4885cee73a25c066d9b8e19966245e9c3d1d89
refs/heads/master
<repo_name>anupgupta-arg/Swift_DS_Algo<file_sep>/Queue.swift //: [Previous](@previous) import Foundation var str = "Hello, Queues in Swift" //: [Next](@next) //Let's look at implementing queues in Swift. While Swift does not come with a default implementation of a queue, it’s easy to write one that uses an array! You could also implement a queue using a linked list, like we did for stacks, but we’ll leave that as a challenge for you to figure out on your own. // //Queues Practice //Make a Queue class using an array! Hint: You can use any Swift array method you'd like. Try to implement each method in as few lines as possible and use the test cases as a guide. import Foundation class Queue { var storage: [Int] init(head: Int) { storage = [head] } // add the element to the queue func enqueue(_ element: Int) { storage.append(element); } // return the next element to be dequeued from the queue // if the queue is empty, return nil func peek() -> Int? { return storage[0]; } // remove and return the next element to be dequeued func dequeue() -> Int? { return storage.remove(at: 0); } } // Test cases // Setup let q = Queue(head: 1) q.enqueue(2) q.enqueue(3) // Test peek print(q.peek()!) // Should be 1 // Test dequeue print(q.dequeue()!) // Should be 1 // Test enqueue q.enqueue(4) print(q.dequeue()!) // Should be 2 print(q.dequeue()!) // Should be 3 print(q.dequeue()!) // Should be 4 q.enqueue(5) print(q.peek()!) // Should be 5 <file_sep>/Stack.swift //: [Previous](@previous) import Foundation var str = "Hello, Stack" //: [Next](@next) //Stacks Practice //We’ve added the completed linked list code below. If you scroll down to the bottom of the code, you’ll see we’ve also defined a Stack class with two methods, push() and pop(). Your task is to implement these methods to get the stack working. // //push(): Adds a node to the beginning of the linked list (ll) //pop(): deletes the node at the beginning of the linked list (ll), and returns the deleted node //Use the test cases to guide you when implementing these methods. Hint: When implementing push() and pop(), you can use the methods we previously defined for the LinkedList. class Stack { var ll: LinkedList init(top: Node?) { self.ll = LinkedList(head: top) } // add a node to the top of the stack func push(_ node: Node) { ll.insertNode(node, at: 1); } // remove and return the topmost node from the stack func pop() -> Node? { guard ll.head != nil else { return nil } let deletedNode = ll.getNode(atPosition: 1) if let value = deletedNode?.value { ll.deleteNode(withValue: value) } return deletedNode } } class Node { var value: Int var next: Node? init(value: Int) { self.value = value } } class LinkedList { var head: Node? init(head: Node?) { self.head = head } func append(_ node: Node) { guard head != nil else { head = node return } var current = head while let _ = current?.next { current = current?.next } current?.next = node } func getNode(atPosition position: Int) -> Node? { guard position > 0 else { return nil } var counter = 1 var current = head while current != nil && counter <= position { if counter == position { return current } current = current?.next counter += 1 } return nil } func insertNode(_ node: Node, at position: Int) { guard position > 0 else { return } var counter = 1 var current = head if position > 1 { while current != nil && counter < position { if counter == position - 1 { node.next = current?.next current?.next = node } current = current?.next counter += 1 } } else if position == 1 { node.next = head head = node } } func deleteNode(withValue value: Int) { var current = head var previous: Node? while current?.value != value && current?.next != nil { previous = current current = current?.next } if current?.value == value { if previous != nil { previous?.next = current?.next } else { head = current?.next } } } } // Test cases // Set up some nodes let n1 = Node(value: 1) let n2 = Node(value: 2) let n3 = Node(value: 3) let n4 = Node(value: 4) // Start setting up a Stack let stack = Stack(top: n1) // Test stack functionality stack.push(n2) stack.push(n3) print(stack.pop()!.value) // Should be 3 print(stack.pop()!.value) // Should be 2 print(stack.pop()!.value) // Should be 1 print(stack.pop()?.value) // Should be nil stack.push(n4) print(stack.pop()!.value) // Should be 4 <file_sep>/README.md # Swift Data Structure & Algorithum ### Binary Search & Linear Search Searches and sorts can be tricky to visualize and understand. If you need to, go through the video a few more times until it really sinks in. Here is a supplementary visualization that might help as well! http://www.cs.armstrong.edu/liang/animation/web/BinarySearch.html If you feel like you struggled with this material, check out this visualization. There's a coded solution there too, but it's in Python, so let's walk through a Swift implementation. https://www.cs.usfca.edu/~galles/visualization/Search.html
2da8aaf47fba447a4bdc95c33957b442bd549455
[ "Swift", "Markdown" ]
3
Swift
anupgupta-arg/Swift_DS_Algo
7fdc58a7e72227d56f9409000acda6d5e2c3aac1
73d91106d6cb7c0b787ba47c4641f9ee9376001f
refs/heads/master
<repo_name>FP-2019-G/examen-02-ciclos-alandin1<file_sep>/examen.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Examen 2</title> </head> <body> <h1>Examen parcial 2</h1> <h3>Problema 1 "Ciclo simple"</h3> <form> Ingrese dos numeros: <br> <input type="number" id="num1E1"> <input type="number" id="num2E1"> <input type="button" value="Calcular" id="btnE1"> <ul id="listaE1"></ul> </form> <h3>Problema 2 "Tabla de multiplicar"</h3> <form> Ingrese un numero: <br> <input type="number" id="num1E2"> <input type="button" value="Calcular" id="btnEj2"> <table id="tablaE2" border="3px"></table> </form> <h3>Problema 3 "Pares e impares"</h3> <form> </form> </body> <script src="index.js"></script> </html><file_sep>/index.js var btnEj1 = document.querySelector('#btnEj1') var btnEj2 = document.querySelector('#btnEj2') // ejercicio 1 btnE1.addEventListener('click', () => { let num1 = document.querySelector('#num1E1').value let num2 = document.querySelector('#num2E1').value let lista1 = document.querySelector('#listaE1') let i = 1 while (i <= num1){ let agregar = document.createElement('li') agregar.value = i agregar.textContent = i lista1.appendChild(agregar) i = i + num2 } }) //Ejercicio 2 btnEj2.addEventListener('click', () => { let numE2 = document.querySelector('#num1E2') let tablaE2 = document.getElementById('tablaE2') let i = 12 let num = Number(numE2.value) while (i >= 1){ let multi = num * i let fila = tablaE2.insertRow(-1) let celda = fila.insertCell(0) celda.textContent = num + ' X ' + i + ' = ' + multi i-- } })
34184d70404ca1e90305e63553226375ac3bfd85
[ "JavaScript", "HTML" ]
2
HTML
FP-2019-G/examen-02-ciclos-alandin1
56f177c54c26837ce6f7cb7159b87c404b867562
2e3be029bdc7ac51c539b58e6684c27ef7d805b8
refs/heads/master
<file_sep>import 'babel-register'; import getConfig from 'hjs-webpack'; import toHtml from 'vdom-to-html'; import app from './src/views/app'; export default getConfig({ in: 'src/main.js', out: 'public', clearBeforeBuild: true, html (context) { function render (state) { return context.defaultTemplate({ html: toHtml(app(state)) }); } return { 'about.html': render({url: '/about', count: 0}), 'index.html': render({url: '/', count: 0}) }; } });
8a8191edecd8fe5a868cb57407c907f8680662a3
[ "JavaScript" ]
1
JavaScript
bbatliner/feather-app
1123bfd24b85ea06fc42efb8450c470abedcc9c8
ced5a4a30dc289493c4611c3a16f60cfeb7d8c92
refs/heads/main
<file_sep>var form = document.getElementById("my-form"); form.addEventListener('submit', function(e) { e.preventDefault(); let email = document.getElementById('email').value; let number = document.getElementById('number').value; let quant = document.getElementById('quantity').value; let addr = document.getElementById('address').value; let size = document.getElementById('size').value; let clr = document.getElementById('colour').value; let tagl = document.getElementById('tag').value; if (email === "") { alert("Enter email"); return; } if (number === "") { alert("Enter number"); return; } var phoneno = /^\d{10}$/; if (!number.match(phoneno)) { alert('Phone number must have 10 digits only'); return; } let today = new Date(); let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); recipt = `Thankyou!.. \n Order placed Successfully Here is Your RECEIPT : \nTagline: ${tagl} \nPhoneNumber: ${number} \nEmail: ${email} \nAddress: ${addr} \nSize: ${size} \nColor: ${clr} \nQuantity: ${quant}\n Receipt issued on Date ${date}`; alert(recipt); });
2f9ad0ed25b6689b16ebcce5e831805980ce526b
[ "JavaScript" ]
1
JavaScript
SonyHotchandani/Tshirts
f7e89aeec54af3d61a9783825769789c04427f5d
0784a51d66e9fe402be6c36b8472b686af1ff671
refs/heads/master
<repo_name>Jumponit/EmbeddedSystems<file_sep>/System/System/Queues.h /* * Queues.h * Defines constants, types and function prototypes for general purpose * FIFO (byte-oriented) queue functions. * * Created: 3/2/2015 3:32:56 PM * Author: barryef */ #ifndef QUEUES_H_ #define QUEUES_H_ #include "System.h" // // Queue Control Block // #define QCB_MAX_COUNT 8 // defines maximum number of system queues. #define Q_FULL 0 // bit position of FULL status bit in QCB flags byte #define Q_EMPTY 1 // bit position of EMPTY status bit in QCB flags byte // // Defined System Queues // #define SERIAL0_IN_Q 0 // ID of USART0 serial inbound queue #define SERIAL0_OUT_Q 1 // ID of USART0 serial outbound queue // // Queue Control Block Type // typedef struct { byte in; // index of next char to be placed in queue (if not full) byte out; // index of next char to be removed from queue (if not empty) byte smask; // mask used to maintain circular queue access (mod size) byte flags; // stores full and empty flags int available; // number of bytes available to be read from queue char *pQ; // pointer to queue data buffer } QCB; // // Function Prototypes // byte Q_putc(byte , char); byte Q_getc(byte , char * ); uint8_t Q_create(int , char * ); void Q_delete(byte); int Q_used(byte); int Q_unused(byte); #endif /* QUEUES_H_ */<file_sep>/System/System/Serial.h /* * Serial.h * * Created: 3/3/2016 2:25:08 PM * Author: joycemj */ #ifndef SERIAL_H_ #define SERIAL_H_ #define SERIAL_5N1 0x00 #define SERIAL_6N1 0x02 #define SERIAL_7N1 0x04 #define SERIAL_8N1 0x06 #define SERIAL_5N2 0x08 #define SERIAL_6N2 0x0A #define SERIAL_7N2 0x0C #define SERIAL_8N2 0x0E #define SERIAL_5E1 0x20 #define SERIAL_6E1 0x22 #define SERIAL_7E1 0x24 #define SERIAL_8E1 0x26 #define SERIAL_5E2 0x28 #define SERIAL_6E2 0x2A #define SERIAL_7E2 0x2C #define SERIAL_8E2 0x2E #define SERIAL_5O1 0x30 #define SERIAL_6O1 0x32 #define SERIAL_7O1 0x34 #define SERIAL_8O1 0x36 #define SERIAL_5O2 0x38 #define SERIAL_6O2 0x3A #define SERIAL_7O2 0x3C #define SERIAL_8O2 0x3E typedef struct { volatile uint8_t ucsra; volatile uint8_t ucsrb; volatile uint8_t ucsrc; volatile uint8_t reserved; volatile uint16_t ubrr; volatile uint8_t udr; }SERIAL_PORT_REGS; typedef struct { uint8_t rx_qid; uint8_t tx_qid; char *rx_buffer; int rx_bufsize; char *tx_buffer; int tx_bufsize; }SERIAL_PORT; #define P0_RX_BUFFER_SIZE 64 #define P0_TX_BUFFER_SIZE 64 #define P1_RX_BUFFER_SIZE 32 #define P1_TX_BUFFER_SIZE 32 #define P2_RX_BUFFER_SIZE 32 #define P2_TX_BUFFER_SIZE 32 #define P3_RX_BUFFER_SIZE 32 #define P3_TX_BUFFER_SIZE 32 void serial_open(long speed, int config); char serial_read(); void serial_write(char data); int Serial_open(int port, long speed, int config); void Serial_close(int); void Serial_config(int, long, int); int Serial_available(int); int Serial_read(int); int Serial_write(int, char); void Serial0_config(long,int); char Serial0_poll_read(); void Serial0_poll_write(char); void Serial0_poll_print(char *); int Serial_write_string(int port, char * data, int data_length); int Serial_read_string(int port, char * data, int data_length); #endif /* SERIAL_H_ */<file_sep>/System/System/acx.c /* * acx.c * * Created: 3/20/2014 11:34:55 AM * Author: <NAME> * * */ #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include "System.h" #include "acx.h" //--------------------------------------------------- // Stack Control //--------------------------------------------------- STACK_CONTROL stack[MAX_THREADS]; //--------------------------------------------------- // Stack Memory //--------------------------------------------------- byte x_thread_stacks[STACK_MEM_SIZE]; //--------------------------------------------------- // Thread Delay Counters //--------------------------------------------------- unsigned int x_thread_delay[MAX_THREADS]; unsigned long x_system_counter = 0; //--------------------------------------------------- // Exec State Variables //--------------------------------------------------- byte x_thread_id; byte x_thread_mask; byte x_disable_status; byte x_suspend_status; byte x_delay_status; //--------------------------------------------------- // Local Functions //--------------------------------------------------- void init_System_Timer(void); //--------------------------------------------------- // ACX Functions //--------------------------------------------------- void x_init(void) { cli(); //Disable interrupts // Initialize thread status variables x_disable_status = 0xfe; // disable all threads except thread 0 x_suspend_status = 0x00; // not suspended... x_delay_status = 0x00; // and not delayed x_thread_id = 0; // start as thread 0 x_thread_mask = 0x01; // Initialize Stacks stack[T0_ID].sp = x_thread_stacks + T0_STACK_BASE_OFFS; stack[T0_ID].spBase = x_thread_stacks + T0_STACK_BASE_OFFS; stack[T1_ID].sp = x_thread_stacks + T1_STACK_BASE_OFFS; stack[T1_ID].spBase = x_thread_stacks + T1_STACK_BASE_OFFS; stack[T2_ID].sp = x_thread_stacks + T2_STACK_BASE_OFFS; stack[T2_ID].spBase = x_thread_stacks + T2_STACK_BASE_OFFS; stack[T3_ID].sp = x_thread_stacks + T3_STACK_BASE_OFFS; stack[T3_ID].spBase = x_thread_stacks + T3_STACK_BASE_OFFS; stack[T4_ID].sp = x_thread_stacks + T4_STACK_BASE_OFFS; stack[T4_ID].spBase = x_thread_stacks + T4_STACK_BASE_OFFS; stack[T5_ID].sp = x_thread_stacks + T5_STACK_BASE_OFFS; stack[T5_ID].spBase = x_thread_stacks + T5_STACK_BASE_OFFS; stack[T6_ID].sp = x_thread_stacks + T6_STACK_BASE_OFFS; stack[T6_ID].spBase = x_thread_stacks + T6_STACK_BASE_OFFS; stack[T7_ID].sp = x_thread_stacks + T7_STACK_BASE_OFFS; stack[T7_ID].spBase = x_thread_stacks + T7_STACK_BASE_OFFS; // Put "canary" values at each stack boundary (low end) // to allow debug detection of stack overflow x_thread_stacks[0] = STACK_CANARY; x_thread_stacks[T0_STACK_BASE_OFFS+1] = STACK_CANARY; x_thread_stacks[T1_STACK_BASE_OFFS+1] = STACK_CANARY; x_thread_stacks[T2_STACK_BASE_OFFS+1] = STACK_CANARY; x_thread_stacks[T3_STACK_BASE_OFFS+1] = STACK_CANARY; x_thread_stacks[T4_STACK_BASE_OFFS+1] = STACK_CANARY; x_thread_stacks[T5_STACK_BASE_OFFS+1] = STACK_CANARY; x_thread_stacks[T6_STACK_BASE_OFFS+1] = STACK_CANARY; // Initialize System Timer init_System_Timer(); // Copy return address to Thread 0 stack area // // NOTE: This works for Atmega2560 having 3-byte return addresses // Does not work for parts having two byte return addresses byte *ps = (byte *)SP; stack[T0_ID].sp[0] = ps[5]; // copy low byte of ret address to T0 stack stack[T0_ID].sp[-1] = ps[4]; // copy mid byte of ret address to T0 stack stack[T0_ID].sp[-2] = ps[3]; // copy high byte of ret address to T0 stack stack[T0_ID].sp[-3] = ps[2]; // pushed reg stack[T0_ID].sp[-4] = ps[1]; // pushed reg // Update hardware SP SP = (int)(stack[T0_ID].sp-5); sei(); // Enable interrupts // return to caller. } /*-------------------------------------------------------------------------------------- Function: x_new Description: Creates a new thread by associating a function pointer with a specified thread ID and stack. The thread may be created in either an enabled or disabled state as specified by the isEnabled parameter. A thread may replace itself by another thread (or restart itself) by specifying its own ID for this function. If ID ofthe calling thread is specified then this function does not return to the caller but jumps to the kernel scheduler. In this case the new (replacement) thread will be scheduled according to its status. Input: int tid - the ID of the thread to be created/replaced (a number between 0 and 7) PTHREAD pthread - a pointer to a function (PTHREAD type - see kernel.h) byte isEnabled - 1=thread initially enabled, 0=thread initially disabled. Returns: none ---------------------------------------------------------------------------------------*/ void x_new(byte tid, PTHREAD pthread, byte isEnabled) { PTU u; //a union that gives access to a thread pointer a byte at a time // Get stack base pointer for this thread ID byte *psb = stack[tid].spBase; // Copy return address of thread onto its stack u.pthread = pthread; *psb-- = u.addr[0]; *psb-- = u.addr[1]; *psb-- = u.addr[2]; // Used for 2560 -- 3-byte return address psb -= THREAD_CONTEXT_SIZE; // Save new stack pointer in this thread's stack pointer save area. // If the current thread is being replaced, this new stack pointer // will take effect after rescheduling (below) stack[tid].sp = psb; byte tmask = bit2mask8(tid); if(isEnabled){ x_disable_status &= ~tmask; } else { x_disable_status |= tmask; } //------------------------------------------------------------------- // If this is not the current thread just return to calling thread //------------------------------------------------------------------- if(tid != x_getTID()){ return; } //------------------------------------------------------------------- // If the calling thread is being replaced/reinitialized // then go to rescheduling loop. // NOTE: A call is OK here--modifying the stack below where // it has just been initialized //------------------------------------------------------------------- x_schedule(); } //------------------------------------------------------------- // init_System_Timer // // Sets system timer (Timer 0) for system tick interval // Start with 2 msec tick //------------------------------------------------------------- void init_System_Timer(void) { // DDRB |= 0x20; // temporary for testing--PB.5 is output TCCR0A = 0x02; // Mode 2 - CTC OCR0A = 250; // match count to give 1 msec TIMSK0 = 2; // enable OCR0A compare match interrupt TCCR0B = 0x03; // Start timer (clkIO/64 prescaler) return; } /*-------------------------------------------------------------------------------------- Function: x_delay Description: Delays the calling thread by the specified number of system "ticks" by loading the thread's delay value and setting its delay status bit to '1'. The kernel timer decrements the delay values each system tick tick and clears the delay status bits of any that reach zero. Input: none Returns: Does not return, but enters scheduling loop. ---------------------------------------------------------------------------------------*/ void x_delay(int ticks) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { x_thread_delay[x_getTID()] = ticks; x_delay_status |= x_thread_mask; } x_yield(); } /*-------------------------------------------------------------------------------------- Function: x_gtime Description: Returns current value of the 'k_longtime' system tick counter. Access to the system tick counter must be atomic since it involves reading a multi-byte value that is written by an interrupt handler. The k_longtime counter is incremented each system tick. The 32-bit counter will overflow after (2**32) * (tick_period) seconds. For example, if the tick interval is 1msec, then it will overflow in about 49 days. Ifthis kind of overflow will affect thread timing, it is the responsibility of each thread to check the value returned to make sure that if overflow occurs, the timing of the thread does not cause a failure. Input: none Returns: long time - a copy of the system tick counter (32 bits) ---------------------------------------------------------------------------------------*/ unsigned long x_gtime(){ long val; ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ val = x_system_counter; } return val; } /*-------------------------------------------------------------------------------------- Interrupt Service Routine: TIMER0_COMPA_vect Description: This interrupt is triggered every N msec based on TIMER0 COMPARE MATCH. The ISR decrements the first NUM_THREADS delay values and resets (to zero) the k_delay_status bits if each thread whose counter reaches zero. If a thread is delayed and its counter reaches zero, then it is made READY and may be scheduled to run. ----------------------------------------------------------------------------------------*/ ISR(TIMER0_COMPA_vect) { // Increment system counter x_system_counter++; char msk = 0x01; // start with thread 0 unsigned int *pdelay = x_thread_delay; //decrement delays for(char i = 0; i < NUM_THREADS; i++){ (*pdelay)--; if(*pdelay == 0){ x_delay_status &= ~msk; } msk <<= 1; pdelay++; } } /*-------------------------------------------------------------------------------------- Function: x_suspend Description: Set specified thread's suspend status bit Input: tid - thread ID Returns: none ---------------------------------------------------------------------------------------*/ void x_suspend(byte tid) { x_suspend_status |= (1 << tid); } /*-------------------------------------------------------------------------------------- Function: x_resume Description: Clears specified thread's suspend status bit Input: tid - thread ID Returns: none ---------------------------------------------------------------------------------------*/ void x_resume(byte tid) { x_suspend_status &= ~(1 << tid); } /*-------------------------------------------------------------------------------------- Function: x_disable Description: Set specified thread's DISABLE status bit Input: tid - thread ID Returns: none ---------------------------------------------------------------------------------------*/ void x_disable(byte tid) { x_disable_status |= (1 << tid); } /*-------------------------------------------------------------------------------------- Function: x_enable Description: Clears specified thread's DISABLE status bit Input: tid - thread ID Returns: none ---------------------------------------------------------------------------------------*/ void x_enable(byte tid) { x_disable_status &= ~(1 << tid); } <file_sep>/System/System/Serial.c /* * Serial.c * * Created: 3/3/2016 2:24:42 PM * Author: joycemj, <NAME> */ #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include <stdlib.h> #include "Queues.h" #include "acx.h" #include "Serial.h" char buffer[QCB_MAX_COUNT][64]; //Initialize serial ports. SERIAL_PORT ports[4] = { {0, 0, buffer[0], P0_RX_BUFFER_SIZE, buffer[1], P0_TX_BUFFER_SIZE}, {0, 0, buffer[2], P1_RX_BUFFER_SIZE, buffer[3], P1_TX_BUFFER_SIZE}, {0, 0, buffer[4], P2_RX_BUFFER_SIZE, buffer[5], P2_TX_BUFFER_SIZE}, {0, 0, buffer[6], P3_RX_BUFFER_SIZE, buffer[7], P3_TX_BUFFER_SIZE} }; //Initialize serial regs SERIAL_PORT_REGS *regs[4] = { (SERIAL_PORT_REGS *) 0xC0, (SERIAL_PORT_REGS *) 0xC8, (SERIAL_PORT_REGS *) 0xD0, (SERIAL_PORT_REGS *) 0x130 }; /* * Serial_open * * Serial_open configures the specified serial port (USART) for operation according the specified baud rate and configuration. * It uses Queue functions to allocate a QCB to manage transmit and receive buffers. It initializes the interface between the * ISRs (RXC and UDRE) and the queues for the port by initializing the QCB "handles" to be used by the ISRs. The RXCx interrupt is enabled. * Serial_open returns 0 for success and -1 if an error occurs (e.g., bad port ID, baud rate, frame parameters or invalid buffer sizes). * * @param int port - specifies USART 0, 1, 2 or 3. For right now, 0 is the only one active. * @param long speed - baud rate * @param constant that specifies framing parameters (data bits, parity, stop bits) * @return returns 0 for success and -1 if an error occurs */ int Serial_open(int port, long speed, int config) { if (port < 0 || port > 3) { return -1; } //Creates a Rqueue forRX and TX ports[port].rx_qid = Q_create(ports[port].rx_bufsize, ports[port].rx_buffer); ports[port].tx_qid = Q_create(ports[port].tx_bufsize, ports[port].tx_buffer); //Sets U2X0 to 1 for lowest error rate regs[port]->ucsra |= (1<<U2X0); //Changed made here long reg_set = -1; switch(speed) { case 2400: reg_set = 832; break; case 4800: reg_set = 416; break; case 9600: reg_set = 207; break; case 14400: reg_set = 138; break; case 19200: reg_set = 103; break; case 28800: reg_set = 68; break; case 38400L: reg_set = 51; break; case 57600L: reg_set = 34; break; case 76800L: reg_set = 25; break; case 115200L: reg_set = 16; break; case 230400L: reg_set = 8; break; case 250000L: reg_set = 7; break; } //Protects from interrupts ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { regs[port]->ubrr = reg_set; //Sets the baud rate regs[port]->ucsrc = config; //Sets the data frame structure regs[port]->ucsrb = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0); //Enables RX, TX, and RX interrupt } sei(); //Enables global interrupts return 0; } /* * Serial_close * * Turns off the specified serial port (USART) function by * disabling transmitter and receiver, deleting the queues, disabling interrupts, etc. * * @param int port - the port ID of the serial port to close. */ void Serial_close(int port) { regs[port]->ucsrb = 0; Q_delete(ports[port].rx_qid); Q_delete(ports[port].tx_qid); } /* * Serial_available * * Returns number of bytes available for reading from the specified serial port. * * @param int port - the serial port ID. * @return int - Number of byte avaible for reading. */ int Serial_available(int port) { return Q_used(ports[port].rx_qid); } /* * Serial_read * * Read next available character from the specified port. If no character is available a value of -1 is returned. * Note that the return type is int rather then char or an 8-bit type. This allows for the test for -1 to work. * Any 8-bit character (including 0xFF) returned as an int (e.g. 0x00FF) will be positive. * You should test for -1 before using the return value as a character. * * @param int port - the serial port ID * @return data or -1 if queue is empty */ int Serial_read(int port) { char qdata = 0; int data; if (Q_getc(ports[port].rx_qid, &qdata)) { data = qdata; return data; } else { return -1; } } /* * Serial_write_string * * Writes a string to the serial port one byte at a time. * * @param int port - the port ID * @param char * data - the character array to be written * @param int data_length - the length of the char array * @return int - always returns 1. */ int Serial_write_string(int port, char * data, int data_length) { int i = 0; while( data[i] != 0x00) { Serial_write(port, data[i]); i++; } return 1; } /* * Serial_read_string * * Reads a string form a specified serial port. * * @param int port - the port ID * @param char * data - the array to be read into * @param int data_length - the length of the char array * @return int - 1 if sucessful, 0 if not */ int Serial_read_string(int port, char * data, int data_length) { char latest; int i = 0; //loop until end of data while (i < data_length) { //get latest character latest = Serial_read(port); if (latest != 0xFF) { if (latest == 0x0D) { //the input has terminated data[i] = 0x00;//null terminate string return 1; } //write the next character into the buffer data[i++]=latest; } //if we got back a -1 from Serial_read, just loop again x_yield(); } //we've used more than the whole array, error return 0; } /* * Serial_write * * Writes one data byte to the serial port. This function enables the transmit ISR (UDRIEx = 1) and blocks until the * write to the corresponding queue is successful. The return value is always 1. * * @param int port - the port ID * @param char data - the char to be written to the serial port. * @return 1 if successful, -1 if not */ int Serial_write(int port, char data) { if (Q_putc(ports[port].tx_qid, data)) { //regs[port].ucsrb |= (0x1 << 5); //Commented out line regs[port]->ucsrb |= (1<<UDRIE0); //regs[port].ucsra |= (0x1 << 5); //This might be wrong. return 1; } return -1; } /* * ISR(USART0_UDRE_vect) * * Called when UDRIE0 is flagged. */ ISR(USART0_UDRE_vect) { char data; if (Q_getc(ports[0].tx_qid, &data)) { UDR0 = data; } else { regs[0]->ucsrb &= ~(0x1<<UDRIE0); } } /* * ISR(USART1_UDRE_vect) * * Called when UDRIE1 is flagged. */ ISR(USART1_UDRE_vect) { char data; if (Q_getc(ports[1].tx_qid, &data)) { UDR1 = data; } else { regs[1]->ucsrb &= ~(0x1 << 5); } } /* * ISR(USART2_UDRE_vect) * * Called when UDRIE2 is flagged. */ ISR(USART2_UDRE_vect) { char data; if (Q_getc(ports[2].tx_qid, &data)) { UDR2 = data; } else { regs[2]->ucsrb &= ~(0x1 << 5); } } /* * ISR(USART3_UDRE_vect) * * Called when UDRIE3 is flagged. */ ISR(USART3_UDRE_vect) { char data; if (Q_getc(ports[3].tx_qid, &data)) { UDR3 = data; } else { regs[3]->ucsrb &= ~(0x1 << 5); } } /* * ISR(USART0_RX_vect) * * Called when there is a value in UDR0 */ ISR(USART0_RX_vect) { Q_putc(ports[0].rx_qid, UDR0); } /* * ISR(USART1_RX_vect) * * Called when there is a value in UDR1 */ ISR(USART1_RX_vect) { Q_putc(ports[1].rx_qid, UDR1); } /* * ISR(USART2_RX_vect) * * Called when there is a value in UDR2 */ ISR(USART2_RX_vect) { Q_putc(ports[2].rx_qid, UDR2); } /* * ISR(USART3_RX_vect) * * Called when there is a value in UDR3 */ ISR(USART3_RX_vect) { Q_putc(ports[3].rx_qid, UDR3); } <file_sep>/System/System/Debug/makedep.mk ################################################################################ # Automatically-generated file. Do not edit or delete the file ################################################################################ acx.c acx_asm.S delay_usec.s DS18B20.c main.c Queues.c Serial.c <file_sep>/System/System/Queues.c /* * Queues.c * * Author : <NAME> */ #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include <stdbool.h> #include "System.h" #include "Queues.h" byte Q_putc(byte qid, char data); byte Q_getc(byte qid, char *pdata ); uint8_t Q_create(int qsize, char * pbuffer); void Q_delete(byte qid); int Q_used(byte qid); int Q_unused(byte qid); QCB queues[QCB_MAX_COUNT]; bool occupied[8] = {false, false, false, false, false, false, false, false}; /* * Puts one byte of data into the specified queue. */ byte Q_putc(byte qid, char data) { QCB *qcb = &queues[qid]; if (qcb->flags != 1) //Checks if queue is full { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *(qcb->pQ + qcb->in) = data; //Grabs byte qcb->available += 1; if (qcb->flags == 2) //Checks if queue was empty, and if so, turns off flag { qcb->flags = 0; } if (((qcb->in + 1) & qcb->smask) != qcb->out) //Checks if queue has wrapped around { qcb->in = (qcb->in + 1) & qcb->smask //If not, increments the value for next slot } else { qcb->in = (qcb->in + 1) & qcb->smask; //If so, increment but set full flag qcb->flags = 1; } } return 1; } else { return 0; } } /* * Returns the next (FIFO) byte from the specified queue. */ byte Q_getc(byte qid, char *pdata) { QCB *qcb = &queues[qid]; if (qcb->flags != 2) //Checks if queue is empty { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *pdata = *(qcb->pQ + qcb->out); //Sets next byte to the given value qcb->available -= 1; if (qcb->flags == 1) //Checks if queue was full, and if so, clears full flag { qcb->flags = 0; } if (((qcb->out + 1) & qcb->smask) != qcb->in) //Checks if queue is empty { qcb->out = (qcb->out + 1) & qcb->smask; //If not, increments pointer for next byte } else { qcb->out = (qcb->out + 1) & qcb->smask; //If so, increment, but set empty flag qcb->flags = 2; } } return 1; } return 0; } /* * Creates a queue of the specified size. */ uint8_t Q_create(int qsize, char * pbuffer) { if ((qsize <= 0) || (qsize > 256) || (qsize & (qsize - 1)) != 0) //Checks for valid size { return -1; } for (int i = 0; i < QCB_MAX_COUNT; i++) //Checks all queues { if (occupied[i] == false) //If it finds a queue unoccupied, set all parameters to defaults { queues[i].in = 0; queues[i].out = 0; queues[i].smask = qsize - 1; queues[i].flags = 2; queues[i].available = 0; queues[i].pQ = pbuffer; occupied[i] = true; return i; } } return -1; } /* * Deletes the specified queue. */ void Q_delete(byte qid) { queues[qid].in = 0; queues[qid].out = 0; queues[qid].smask = 0; queues[qid].flags = 0; queues[qid].available = 0; queues[qid].pQ = NULL; occupied[qid] = false; } /* * Returns the number of bytes currently being stored in the specified queue. */ int Q_used(byte qid) { if (qid >= QCB_MAX_COUNT) { return -1; } return queues[qid].available; } /* * Returns the number of empty bytes in the specified queue. */ int Q_unused(byte qid) { if (qid >= QCB_MAX_COUNT) { return -1; } if (queues[qid].out > queues[qid].in) { return (queues[qid].out - queues[qid].in); } else if (queues[qid].in > queues[qid].out) { return ((queues[qid].smask + 1) - (queues[qid].in - queues[qid].out)); } else { return 0; } } <file_sep>/System/System/main.c /* * main.c * * Authors: <NAME>, <NAME>, and <NAME> */ #include <avr/io.h> #include <util/delay.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "System.h" #include "Serial.h" #include "Queues.h" #include "acx.h" #include "DS18B20.h" #define light_bulbs PB5 //Digital pin 11 #define fans PB4 //Digital pin 11 /* * The most-recently measured temperature in degrees Celsius */ volatile int last_temp = 0; /* * The most-recently requested temperature for the controlled box, * in degrees Celsius */ volatile int target_temp = 0; /* * If true, box is in service mode */ volatile char service_mode = 0; /* * Number of milliseconds to wait between temperature sampling. */ volatile unsigned int sample_rate = 1000; /* * If true, current reporting mode is celsius, otherwise Fahrenheit. */ volatile char celsius = 1; /* * The over-temperature set point in celsius */ volatile int over_temp = 80; /* * Number of seconds allowed to reach target temperature. */ volatile int timeout = 300; /* * The format used for all temperature reading output. */ char * format = "Last temp: %d degrees Celsius\n\r"; /* * Permanently shut down the system. */ void shut_down(void) { PORTB |= (0x1 << light_bulbs) | (0x1 << fans); x_disable(1); x_disable(0); } /* * Reverse the effects of shut down. */ void start_up(void) { PORTB |= ~(0x1 << fans); x_enable(0); x_enable(1); } /* * Periodically check for abort condition */ void timeout_controller(void) { while(1) { /* * As a workaround for the maxiumum number of milliseconds, * we x_delay for every second in the global timeout variable. */ for (int i = 0; i < timeout; i++) { x_delay(1000); } if (last_temp < target_temp-1) { char * message = "Timeout occurred; Shutting down.\n\r"; Serial_write_string(0, message, strlen(message)); shut_down(); x_disable(3); } } } /* * Handles serial I/O */ void io_controller(void) { Serial_open(0,19200,SERIAL_8N1); //prepare serial communications /* * These variables are used for processing input instructions */ int command_len = 8; int opcode_len = 2; int operand_len = 6; char command[command_len]; char opcode[opcode_len]; char operand[operand_len]; /* * These variables are used for output */ char message[64]; char * str; char * formatStr; while(1) { //if we are able to read a command if(Serial_read_string(0,command,command_len)) { //extract the two-character opcode opcode[0] = command[0]; opcode[1] = command[1]; //extract a numeric operand, if there is one for (int i = 0; i < operand_len; i++) { if (command[i+2] != 0x00) { operand[i] = command[i+2]; } else { operand[i] = 0x00; } } /************************************************************************/ /* Mode-selection commands */ /************************************************************************/ if(!strcmp(opcode,"SM")) {//set service mode to true; /* * SM - Enter Service Mode */ str = "Entering Service Mode\n\r"; Serial_write_string(0,str,strlen(str)); service_mode = 1; } else if (!strcmp(opcode,"TM")) {//toggle service mode /* * TM - Toggle Modes */ service_mode = !service_mode; if (service_mode) { str = "Entering Service Mode\n\r"; Serial_write_string(0,str,strlen(str)); } else { str = "Entering Operating Mode\n\r"; Serial_write_string(0,str,strlen(str)); } } else if (!strcmp(opcode, "OM")) {//set service mode to false /* * OM - Enter Operating Mode */ str = "Entering Operating Mode\n\r"; Serial_write_string(0,str,strlen(str)); service_mode = 0; } else { /************************************************************************/ /* Mode-specific commands */ /************************************************************************/ if(service_mode) { //do service mode things if (!strcmp(opcode, "GT")) { /* * GT - Get current Temperature */ char fmt_temp = last_temp; if (!celsius) { //this is equivalent to (9/5)*C + 32 fmt_temp = ((fmt_temp + (fmt_temp << 3))+160)/5; } sprintf((char *) message, format, fmt_temp); Serial_write_string(0, (char *) message, strlen((char *) message)); } else if (!strcmp(opcode, "OV")) { /* * OV#+ - set maximum allowed temperature before shutdown * Expects a 1-3 digit temperature in Celsius */ over_temp = atoi(operand); formatStr = "Over-temperature set to %d degrees Celsius\n\r"; sprintf((char *) message,formatStr,over_temp); Serial_write_string(0, (char *) message, strlen((char *) message)); } else if (!strcmp(opcode, "SO")) { /* * SO#+ - set the timeOut * Expects a 1-3 digit number of minutes to attempt to reach * target temperature before shutting down. */ timeout = atoi(operand) * 60; formatStr = "Timeout set to %d seconds\n\r"; sprintf((char *) message,formatStr,timeout); Serial_write_string(0, (char *) message, strlen((char *) message)); x_new(3, timeout_controller, 1);//kick off the timeout } else if (!strcmp(opcode, "TL")) { /* * TL - Toogle Lights */ PORTB ^= (0x1 << light_bulbs); str = "Toggling Lights\n\r"; Serial_write_string(0,str,strlen(str)); } else if (!strcmp(opcode, "TF")) { /* * TF - Toggle fans */ PORTB ^= (0x1 << fans); str = "Toggling Fans\n\r"; Serial_write_string(0,str,strlen(str)); } else { /* * Catch-all: If execution reaches here, the user has entered an * opcode that is not valid in Service Mode. */ str = "Unrecognized command\n\r"; Serial_write_string(0,str,strlen(str)); } } else { //do operating mode things if (!strcmp(opcode, "ST")) { /* * ST#+ - Set Target temperature * Expects a 1-3 digit Celsius temperature as the target. */ target_temp = atoi(operand); if (target_temp < 0 || target_temp > 125) { str = "Invalid temperature selection.\n\r"; Serial_write_string(0,str,strlen(str)); } else { formatStr = "Set target temperature to %d degrees Celsius\n\r"; sprintf((char *) message,formatStr,target_temp); Serial_write_string(0, (char *) message, strlen((char *) message)); } } else if (!strcmp(opcode, "SR")) { /* * SR#+ - Set sample rate * Expects a 1-5 digit sample rate in milliseconds. */ sample_rate = atoi(operand); formatStr = "Set sample rate to %u\n\r"; sprintf((char *) message,formatStr,sample_rate); Serial_write_string(0, (char *) message, strlen((char *) message)); } else if (!strcmp(opcode, "SD")) { /* * SD_ - Set Display format * Expects a character indicating the desired display format. * C - Degrees Celsius * F - Degrees Fahrenheit * X - Hexadecimal number, still Degrees Celsius */ switch (operand[0]) { case 'F': format = "Last temp: %d degrees Fahrenheit\n\r"; celsius = 0; str = "Set format to Fahrenheit\n\r"; Serial_write_string(0,str,strlen(str)); break; case 'C': format = "Last temp: %d degrees Celsius\n\r"; celsius = 1; str = "Set format to Celsius\n\r"; Serial_write_string(0,str,strlen(str)); break; case 'X': celsius = 1; format="Last temp: %x raw hex"; str = "Set format to Celsius Hexadecimal\n\r"; Serial_write_string(0,str,strlen(str)); break; default: str = "Unrecognized format\n\r"; Serial_write_string(0,str,strlen(str)); break; } } else { /* * Catch-all: If execution reaches here, the user has entered an * opcode that is not valid in Operating Mode. */ str = "Unrecognized command\n\r"; Serial_write_string(0,str,strlen(str)); } } } } else { str = "Error reading command\n\r"; Serial_write_string(0,str,strlen(str)); } x_yield(); } } /* * Controller for the box * * Fans on by default */ void box_controller(void) { //Configure pins and enable fans DDRB |= (0x1 << light_bulbs) | (0x1 << fans); PORTB &= ~(0x1 << fans); while(1) { if (last_temp >= over_temp) { //abort if temperature too high char * message = "Maximum Temperature exceeded; Shutting down.\n\r"; Serial_write_string(0, message, strlen(message)); shut_down(); } if (!service_mode) { //only perform logic here in operating mode if (last_temp < target_temp) { //enable lights PORTB &= ~(0x1 << light_bulbs); } else { //disable lights PORTB |= (0x1 << light_bulbs); } } x_delay(sample_rate); //wait for next temperature reading to act again } } /* * Polls sensor for temperature every second */ void sensor_controller(void) { //Check for sensor presence char presence = ow_reset(); //keep checking until we detect a sensor while (! presence) { presence = ow_reset(); //give other threads a chance to act during this process x_yield(); } //prep I/O char message[64]; char fmt_temp; //monitor temperature while(1) { last_temp = ow_read_temperature(); if (!service_mode) { fmt_temp = last_temp; if (!celsius) { //this is equivalent to (9/5)*C + 32 fmt_temp = ((fmt_temp + (fmt_temp << 3))+160)/5; } sprintf((char *) message, format, fmt_temp); Serial_write_string(0, (char *) message, strlen((char *) message)); } x_delay(sample_rate); } } /* * Initialize the operating threads of the system. */ int main(void) { x_init(); //Launch main threads x_new(2, io_controller, 1); x_new(1, sensor_controller, 1); x_new(3, timeout_controller, 1); x_new(0, box_controller, 1); //replaces main with box control logic) } <file_sep>/System/System/acx.h /* * acx.h * * Created: 3/20/2014 11:08:37 AM * Author: <NAME> */ #ifndef ACX_H_ #define ACX_H_ #include "System.h" #define MAX_THREADS 8 #define NUM_THREADS 8 #define STACK_CANARY 0xAA #define T0_STACK_SIZE 256 #define T1_STACK_SIZE 256 #define T2_STACK_SIZE 256 #define T3_STACK_SIZE 256 #define T4_STACK_SIZE 256 #define T5_STACK_SIZE 256 #define T6_STACK_SIZE 256 #define T7_STACK_SIZE 256 #define STACK_MEM_SIZE (T0_STACK_SIZE + T1_STACK_SIZE + \ T2_STACK_SIZE + T3_STACK_SIZE + T4_STACK_SIZE +\ T5_STACK_SIZE + T6_STACK_SIZE + T7_STACK_SIZE) #define T0_STACK_BASE_OFFS (T0_STACK_SIZE-1) #define T1_STACK_BASE_OFFS (T0_STACK_BASE_OFFS+T1_STACK_SIZE) #define T2_STACK_BASE_OFFS (T1_STACK_BASE_OFFS+T2_STACK_SIZE) #define T3_STACK_BASE_OFFS (T2_STACK_BASE_OFFS+T3_STACK_SIZE) #define T4_STACK_BASE_OFFS (T3_STACK_BASE_OFFS+T4_STACK_SIZE) #define T5_STACK_BASE_OFFS (T4_STACK_BASE_OFFS+T5_STACK_SIZE) #define T6_STACK_BASE_OFFS (T5_STACK_BASE_OFFS+T6_STACK_SIZE) #define T7_STACK_BASE_OFFS (T6_STACK_BASE_OFFS+T7_STACK_SIZE) #define T0_ID 0 #define T1_ID 1 #define T2_ID 2 #define T3_ID 3 #define T4_ID 4 #define T5_ID 5 #define T6_ID 6 #define T7_ID 7 #define THREAD_CONTEXT_SIZE 18 // Number of bytes (registers) saved during context switch #ifndef __ASSEMBLER__ #define x_getTID() x_thread_id //typedef void(* PTHREAD)(int, char * ); //--------------------------------------------------------------------------- // PTHREAD is a type that represents how threads are called-- // It is just a pointer to a function returning void // that is a passed an int and a char * as parameters. //--------------------------------------------------------------------------- typedef void (*PTHREAD)(void); //--------------------------------------------------------------------------- // This union is used to provide access to both bytes of a thread address //--------------------------------------------------------------------------- typedef union { PTHREAD pthread; byte addr[3]; // This works for 2560 not UNO -- assumes 3-byte return address } PTU; //--------------------------------------------------------------------------- // This type is used for entries in the stack control table //--------------------------------------------------------------------------- typedef struct { byte *sp; byte *spBase; }STACK_CONTROL; // ACX Function prototypes void x_init(void); void x_delay(int); void x_schedule(void); void x_new(byte, PTHREAD , byte); void x_yield(void); byte bit2mask8(int); void x_suspend(byte); void x_resume(byte); void x_disable(byte); void x_enable(byte); #endif #endif /* ACX_H_ */
bfaf57307c68141117fc0275a6a69230bee52cf3
[ "C", "Makefile" ]
8
C
Jumponit/EmbeddedSystems
8d68f3949c6826012bc7d50cfaeacce9c30b8d80
ddde94ca59c5b98d825380fd08007dfc4d2c2356
refs/heads/master
<repo_name>YevgeniySob/backend-project<file_sep>/app/controllers/reports_controller.rb class ReportsController < ApplicationController before_action :find_report, only: %i[show update delete] def show render json: @report end def index @reports = Report.all render json: @reports end def new_comment report = Report.find_by(id: params[:reportId]) report.comments.create(content: params[:content], report_id: params[:reportId], user_id: params[:userId], points: 0) render json: report end def create # Cloudinary::Uploader.upload("image file", :public_id => 'uniq_id') # /w_130,h_100,c_fill/ state_id = State.find_by(abbreviation: params[:state]).id report = Report.new(description: params[:description], title: params[:title], date: params[:date], state_id: state_id, votes: 0, user_id: params[:id]) if report.save id = report.id Cloudinary::Uploader.upload(params[:image].tempfile, public_id: report.id) report.update(image: "https://res.cloudinary.com/dont-mess/image/upload/w_500/#{id}.jpg") Address.create(city: params[:city], street: params[:street], zipcode: params[:zipcode], report_id: id) ReportGeolocation.create(latitude: params[:latitude], longitude: params[:longitude], report_id: id) render json: ReportSerializer.new(report) else render json: {error: 'get outahere'} end end def points comment = Comment.find_by id: params[:commentId] direction = params[:where] if direction == 'up' comment.update(points: comment.points + 1) render json: comment elsif direction == 'down' comment.update(points: comment.points - 1) render json: comment else render json: { error: 'cant upvote or downvote comment' } end end def report_by_state @reports = State.find_by(abbreviation: params[:state]).reports render json: @reports end def vote vote = params[:vote] report = Report.find_by(id: params[:reportId]) if vote == 'up' report.update(votes: report.votes += 1) elsif vote == 'down' report.update(votes: report.votes -= 1) end end private def find_report @report = Report.find_by(id: params[:id]) end end <file_sep>/app/models/user.rb class User < ApplicationRecord has_one :user_geolocation has_many :reports has_many :comments has_secure_password validates :username, presence: true, uniqueness: true, case_sensitive: false # validates :email, presence: true, uniqueness: true, case_sensitive: false def reports_num self.reports.length end end <file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController before_action :find_user, only: %i[show update delete] def show render json: @user end def index @reports = User.find_by(id: params[:id]).reports render json: @reports end def create user = User.new(user_params) if user.save user_id = user.id token = encode_token(user_id) render json: { user: UserSerializer.new(user), token: token }, status: 201 else render json: { errors: 'beep boop beep bop' } end end # def update # # end # # def delete # # end private def user_params params.require(:user).permit(:first_name, :last_name, :username, :password, :email) end def find_user @user = User.find_by(id: params[:id]) end end <file_sep>/testing.rb vegetables = ['Asparagus, Broccoli, Carrots, Cauliflower, Celery, Corn, Cucumbers, Lettuce, Mushrooms, Onions, Peppers, Potatoes Spinach, Squash, Zucchini, Tomatoes'] condiments_sauces = ['BBQ sauce', 'Gravy', 'Honey', 'Ketchup', 'Mustard', 'Mayonnaise', 'Pasta sauce', 'Relish', 'Salad dressing', 'Salsa', 'Soy sauce', 'Steak sauce', 'Syrup', 'Worcestershire sauce'] dairy = ['Butter', 'Margarine', 'Cottage cheese', 'Half & half', 'Milk', 'Sour cream', 'Whipped cream', 'Yogurt'] baked_goods = ['Bagels', 'Croissants', 'Buns', 'Cake', 'Cookies', 'Donuts', 'Pastries', 'bread', 'Pie', 'Pita bread', 'Sliced bread'] fruits = ['Apples', 'Avocados', 'Bananas', 'Berries', 'Cherries', 'Grapefruit', 'Grapes', 'Kiwis', 'Lemons', 'Limes', 'Melon', 'Nectarines', 'Oranges', 'Peaches', 'Pears', 'Plums'] various_groceries = ['Bouillon cubes', 'Cereal', 'Coffee Filters', 'Instant potatoes', 'Lemon juice', 'Lime juice', 'Mac & cheese', 'Olive oil', 'Packaged meals', 'Pancake Waffle mix', 'Pasta', 'Peanut butter', 'Pickles', 'Rice', 'Tea', 'Vegetable oil', 'Vinegar'] meat = ['Bacon', 'Sausage', 'Beef', 'Chicken', 'Ground beef', 'Turkey', 'Ham', 'Pork', 'Lunchmeat', 'Turkey'] baking = ['Baking powder', 'Baking Soda', 'Bread crumbs', 'Cake', 'Brownie mix', 'Cake icing', 'Decorations', 'Chocolate chips', 'Cocoa', 'Flour', 'Shortening' , 'Sugar' , 'Sugar substitute', 'Yeast'] cheese = ['Blue cheese', 'Cheddar', 'Cottage cheese', 'Cream cheese', 'Feta', 'Goat cheese', 'Mozzarella' , 'Parmesan' , 'Provolone' , 'Ricotta', 'Swiss'] # refrigerated = ['Eggs', English muffins, Fruit juice, Hummus , Ready-bake breads, Tofu, Tortillas] # Canned foods, Applesauce, Baked beans, Broth, Fruit, Olives, Tinned meats, Tuna / Chicken, Soup / Chili, Tomatoes, Veggies # Seafood, Catfish , Crab , Lobster , Mussels , Oysters , Salmon , Shrimp , Tilapia , Tuna <file_sep>/app/models/report.rb class Report < ApplicationRecord belongs_to :user belongs_to :state has_many :comments has_one :report_geolocation has_one :address end <file_sep>/app/serializers/user_serializer.rb class UserSerializer < ActiveModel::Serializer attributes :id, :username, :reports_num, :first_name, :last_name, :email, :image, :created_at has_one :user_geolocation # has_many :reports end <file_sep>/app/serializers/user_geolocation_serializer.rb class UserGeolocationSerializer < ActiveModel::Serializer attributes :longitude, :latitude end <file_sep>/app/serializers/comment_serializer.rb class CommentSerializer < ActiveModel::Serializer attributes :content, :points, :username, :created_at, :id belongs_to :user end <file_sep>/config/routes.rb Rails.application.routes.draw do # User routes get '/user', to: 'users#show' post '/signup', to: 'users#create' # Auth routes get '/auto_login', to: 'auth#auto_login' post '/login', to: 'auth#login' # Report routes get '/report', to: 'reports#show' post '/new_report', to: 'reports#create' get '/reports', to: 'reports#index' post '/report_vote', to: 'reports#vote' get '/report_by_state', to: 'reports#report_by_state' post '/add_comment', to: 'reports#new_comment' post '/points', to: 'reports#points' end <file_sep>/app/serializers/report_serializer.rb class ReportSerializer < ActiveModel::Serializer attributes :id, :title, :description, :votes, :image, :date, :time belongs_to :user belongs_to :state has_many :comments has_one :report_geolocation has_one :address end <file_sep>/db/seeds.rb User.create(username: 'test', password: '123', first_name: 'Yevgeniy', last_name: 'Sobolev') count = 1 5.times do count += 10 User.create(username: Faker::Internet.username, first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, password: '123', email: Faker::Internet.email, image: "https://picsum.photos/id/#{count}/50/50") end count = 1 User.all.length.times do UserGeolocation.create(latitude: Faker::Address.latitude, longitude: Faker::Address.longitude, user_id: count) count += 1 end abbr = ['AK', 'AL', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY'] states = ['Alaska', 'Alabama', 'Arkansas', 'American Samoa', 'Arizona', 'California', 'Colorado', 'Connecticut', 'District of Columbia', 'Delaware', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Iowa', 'Idaho', 'Illinois', 'Indiana', 'Kansas', 'Kentucky', 'Louisiana', 'Massachusetts', 'Maryland', 'Maine', 'Michigan', 'Minnesota', 'Missouri', 'Mississippi', 'Montana', 'North Carolina', 'North Dakota', 'Nebraska', 'New Hampshire', 'New Jersey', 'New Mexico', 'Nevada', 'New York', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Virginia', 'Virgin Islands', 'Vermont', 'Washington', 'Wisconsin', 'West Virginia', 'Wyoming'] abbr.each_with_index do |abr, idx| State.create(name: states[idx], abbreviation: abr) end count = 1 State.all.length.times do picnum = 13 7.times do Report.create(title: Faker::Lorem.sentence(2), description: Faker::Lorem.paragraph, votes: 0, image: "https://picsum.photos/id/#{picnum}/500/300", date: Faker::Date.between(2.days.ago, Date.today), state_id: count, user_id: User.all.sample.id) picnum += rand(1...5) end count += 1 end count = 1 Report.all.length.times do Address.create(city: Faker::Address.city, street: Faker::Address.street_address, zipcode: Faker::Address.zip_code, report_id: count) ReportGeolocation.create(latitude: Faker::Address.latitude, longitude: Faker::Address.longitude, report_id: count) rand(5...20).times do Comment.create(content: Faker::Lorem.sentence(10), points: 0, user_id: User.all.sample.id, report_id: count) end count += 1 end <file_sep>/app/serializers/state_serializer.rb class StateSerializer < ActiveModel::Serializer attributes :abbreviation, :name end
ad1c762016b90f149597d31f18fe9322284e90e3
[ "Ruby" ]
12
Ruby
YevgeniySob/backend-project
377394396eec28f80b2954216e3f0405a475c3c1
c3b6b53fad06ff50682cdd6da9ba96255695a4c1
refs/heads/master
<file_sep>package roleManagement; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; @WebServlet("/addRole") public class addRole extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = null; String systemRoleNew = null; String adminManagedNew = null; BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String json = ""; if (br != null) { json = br.readLine(); System.out.println(json); } try { JSONObject data = new JSONObject(json); name = (String) data.get("name"); systemRoleNew = (String) data.get("systemRoleNew"); adminManagedNew = (String) data.get("adminManagedNew"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/role_management", "root", "stevecookhere"); stmt = con.createStatement(); int count = stmt.executeUpdate("insert into roles(name, systemrole , adminrole) values('" + name + "','" + systemRoleNew + "','" + adminManagedNew + "')"); System.out.println(count); JSONObject jo = new JSONObject(); if (count >= 1) { jo.put("status", 1); } else { jo.put("status", 0); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jo.toString()); jo = null; stmt.close(); con.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } } <file_sep>package roleManagement; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; @WebServlet("/deleteRole") public class deleteRole extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("id"); Connection con = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/role_management", "root", "stevecookhere"); stmt = con.createStatement(); int count = stmt.executeUpdate("DELETE FROM roles WHERE ID =" + name); JSONObject jo = new JSONObject(); if (count >= 1) { jo.put("status", 1); } else { jo.put("status", 0); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(jo.toString()); jo = null; stmt.close(); con.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } }
1a9830188316534c8b873bc19b6b70e362f3344c
[ "Java" ]
2
Java
deepukr007/roleManagement
142573bd309bd4379f2ad32869cb56e6522121a0
d8e5d9a8ca4a3c2aae7bfaaa9272c68b5808b6eb
refs/heads/main
<repo_name>VardanMelik/React-Dapp<file_sep>/README.md # React-Dapp React Dapp <file_sep>/timer.js /* 4:01 2/5 https://www.youtube.com/watch?v=nU0uqk0jLdw&list=PLbbtODcOYIoHJQ9sTs0e8kn7YV39W9Vcp&index=2 */
e971bb18c35cbb3898c3d82f13660504bf906571
[ "Markdown", "JavaScript" ]
2
Markdown
VardanMelik/React-Dapp
8b02c21433dd5bc396e320eeed5f3a0d40c7c732
29116ebef54bd2f8fcb8ecb870b2cf7739ee5789
refs/heads/master
<file_sep>import { combineReducers } from 'redux'; // 'as' redeclares the 'reducer' variable as 'form' import { reducer as form } from 'redux-form'; import authReducer from './auth_reducer'; const rootReducer = combineReducers({ // ES6 automatically expands to form: form since key and value are the same form, auth: authReducer }); export default rootReducer; <file_sep>import axios from 'axios'; import { browserHistory } from 'react-router'; import { AUTH_USER, UNAUTH_USER, AUTH_ERROR, FETCH_MESSAGE } from './types'; const ROOT_URL = 'http://localhost:3090'; export function signinUser ({ email, password }) { // redux thunk allows action creator to return a function return function(dispatch) { // submit em/pw to server axios.post(`${ROOT_URL}/signin`, { email, password }) // javascript promises .then(response => { // if req good: // - update state to show user is authenticated dispatch({ type: AUTH_USER }); // - save JWT token localStorage.setItem('token', response.data.token); // - redirect user to the route '/feature' // programmatic navigation, swap views browserHistory.push('/feature'); }) // fail case .catch(() => { // if req bad: // - show error to user now dispatch(authError('Incorrect Login')); }); } } // action creator for new user signup export function signupUser({ email, password }) { return function(dispatch) { axios.post(`${ROOT_URL}/signup`, { email, password }) .then(response => { dispatch({ type: AUTH_USER }); localStorage.setItem('token', response.data.token); browserHistory.push('/feature'); }) // fail case - fix error dispatch .catch(({response}) => dispatch(authError(response.data.error))); } } // add separate action creator for errors export function authError(error) { return { type: AUTH_ERROR, payload: error }; } // get rid of saved token and set user to unauth export function signoutUser() { localStorage.removeItem('token'); return { type: UNAUTH_USER }; } // new action creator export function fetchMessage() { // redux redux return function(dispatch) { axios.get(ROOT_URL, { headers: { authorization: localStorage.getItem('token') } }) .then(response => { dispatch({ type: FETCH_MESSAGE, payload: response.data.message }); }); } } <file_sep>import React from 'react'; export default() => <div>Hello and welcome to my authentication project</div>; <file_sep># Authentication project- Client Side Using react, redux, redux-form, redux-thunk Backend for authentication project is in this repo: https://github.com/kcmartin/server-arr
4269351f1ab2dcb89d1b943bebb0410e143dbf08
[ "JavaScript", "Markdown" ]
4
JavaScript
kcmartin/client-arr
4c2a592dcaf3cda7829f673103009dba60c5d737
3e707c0076ded56fd9e3cd1338834d1a7347c397
refs/heads/master
<file_sep>#!/bin/bash apt-get update apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev -y git clone git://github.com/sstephenson/rbenv.git .rbenv echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc echo 'eval "$(rbenv init -)"' >> ~/.bashrc source ~/.profile mkdir -p ~/.rbenv/plugins git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc source ~/.profile curl -fsSL https://gist.github.com/mislav/a18b9d7f0dc5b9efc162.txt | rbenv install --patch 2.1.1 rbenv global 2.1.1 echo "gem: --no-ri --no-rdoc" > ~/.gemrc <file_sep>chef-solo ========= To prepare, run in the target server: `bash <(curl -s https://raw.githubusercontent.com/niksan/chef-solo/master/prepare_server.bash)`
fd53a88726f5e42a488cb87d66c10ce2f063ab84
[ "Markdown", "Shell" ]
2
Shell
niksan/chef-solo
f0cf30fc982e9d451bd1b126ceecef3dfe2b8a23
c20255d5d46add9a605a471db4b839cb75f09465
refs/heads/main
<repo_name>Cryptographerdll/Theorie-Ofppt-2011-En-Csharp<file_sep>/README.md # Theorie-Ofppt-2011-En-Csharp /* on souhaite créer une application C# qui gére le système d'information d'une société de création de logiciels * Les Développeurs sont caractérisés en général par un matricule , un nom , un email * Par défaut la majorité des développeurs qui travaillent à la société sont des développeurs externes qui sont payés a l'heure travaillée . * Le taux horaire appliqué est négocié avec le développeur externe au moment de son engagement . * certains de ces développeurs sont recrutés en permanence par la société , Ils sont dis des développeurs internes ou permanentes . * Les développeurs internes percoivent un salaire mensuel dépendant de leur catégorie (S : Senior , J: Junior), Les juniors touchent un salaire de 5000 Dh/Mois * et les Seniors touchent un salaire de 8000 Dh/Mois , Dans les deux cas ce salaire représente le salaire fixe d'un développeur interne . Ils bénéficient également des heures * supplémentaires payés , à la fin de chaque Mois , un taux de 150Dh/Heure pour les juniors et 200Dh/Heure pour les seniors , En résume le salaire mensuel d'un développeur est * calculé selon la régle suivante : * * Interne : * Salaire = salaire fixe (5000 ou 8000) + Nombre heures travaillés * taux horaire; * Externe : * Salaire = Nombre heures travaillés * taux horaire; * * Questions : * 1- Créer les Classes développeur intern et extern avec un constructeur d'initialisation est les methodes d'accées aux proprietés . Les deux classes sont en relation d'héritage . (2Pts) * * 2-Ajouter aux classes créées en 1 , la Méthode de Calcul_Salaire (); Qui recoit comme paramétre le nombre d'heures à payer ( dans le cas de developpeur interne ce nombre représente * les heures supplémentaires travaillée qui doivent être payées en plus de salaire fixe) et qui calcule le salaire d'un développeur selon les régles de calcule mentionnées ci-dessus . on demande * que cette methode soit polymorphique . (2Pts) */ <file_sep>/DéveloppeurExterne.cs using System; using System.Collections.Generic; using System.Text; namespace Theorie_2011_Focus { class DéveloppeurExterne { #region "Exercice Text et Questions" /* on souhaite créer une application C# qui gére le système d'information d'une société de création de logiciels * Les Développeurs sont caractérisés en général par un matricule , un nom , un email * Par défaut la majorité des développeurs qui travaillent à la société sont des développeurs externes qui sont payés a l'heure travaillée . * Le taux horaire appliqué est négocié avec le développeur externe au moment de son engagement . * certains de ces développeurs sont recrutés en permanence par la société , Ils sont dis des développeurs internes ou permanentes . * Les développeurs internes percoivent un salaire mensuel dépendant de leur catégorie (S : Senior , J: Junior), Les juniors touchent un salaire de 5000 Dh/Mois * et les Seniors touchent un salaire de 8000 Dh/Mois , Dans les deux cas ce salaire représente le salaire fixe d'un développeur interne . Ils bénéficient également des heures * supplémentaires payés , à la fin de chaque Mois , un taux de 150Dh/Heure pour les juniors et 200Dh/Heure pour les seniors , En résume le salaire mensuel d'un développeur est * calculé selon la régle suivante : * * Interne : * Salaire = salaire fixe (5000 ou 8000) + Nombre heures travaillés * taux horaire; * Externe : * Salaire = Nombre heures travaillés * taux horaire; * * Questions : * 1- Créer les Classes développeur intern et extern avec un constructeur d'initialisation est les methodes d'accées aux proprietés . Les deux classes sont en relation d'héritage . (2Pts) * * 2-Ajouter aux classes créées en 1 , la Méthode de Calcul_Salaire (); Qui recoit comme paramétre le nombre d'heures à payer ( dans le cas de developpeur interne ce nombre représente * les heures supplémentaires travaillée qui doivent être payées en plus de salaire fixe) et qui calcule le salaire d'un développeur selon les régles de calcule mentionnées ci-dessus . on demande * que cette methode soit polymorphique . (2Pts) */ #endregion private string _matricule; private string _nom; private string _email; private double _taux; private double _salaire; #region "Setters" public void setMatricule(string matricule) { this._matricule = matricule; } public void setNom(string nom) { this._nom = nom; } public void setEmail(string email) { this._email = email; } public void setTaux(double taux) { this._taux = taux; } public void _setSalaire(double salaire) { this._salaire = salaire; } #endregion #region "Getters" public string _getMatricule () { return this._matricule; } public string _getNom() { return this._nom; } public string _getEmail() { return this._email; } public double _gettaux() { return this._taux; } public double _getSalaire() { return this._salaire; } #endregion #region "Constructor Par Defaut" public DéveloppeurExterne() { } #endregion #region "Constructor d'Initialisation" public DéveloppeurExterne(string matricule, string nom, string email, double taux) { _matricule = matricule; _nom = nom; _email = email; _taux = taux; } #endregion #region "Method Calcul_salaire" public virtual double Calcul_salaire(int nbr_heures) // Développeur externe salaire Mensuel . { _setSalaire(nbr_heures * _taux); return nbr_heures * _taux; } #endregion } } <file_sep>/DéveloppeurInterne.cs using System; using System.Collections.Generic; using System.Text; namespace Theorie_2011_Focus { class DéveloppeurInterne : DéveloppeurExterne { /* * Interne : * Salaire = salaire fixe (5000 ou 8000) + Nombre heures travaillés * taux horaire; * Externe : * Salaire = Nombre heures travaillés * taux horaire; * * Questions : * 1- Créer les Classes développeur intern et extern avec un constructeur d'initialisation est les methodes d'accées aux proprietés . Les deux classes sont en relation d'héritage . (2Pts) * * 2-Ajouter aux classes créées en 1 , la Méthode de Calcul_Salaire (); Qui recoit comme paramétre le nombre d'heures à payer ( dans le cas de developpeur interne ce nombre représente * les heures supplémentaires travaillée qui doivent être payées en plus de salaire fixe) et qui calcule le salaire d'un développeur selon les régles de calcule mentionnées ci-dessus . on demande * que cette methode soit polymorphique . (2Pts) */ private string _categorie; private double _salaire; #region "Setters" public void _setCategorie(string Categorie) { this._categorie = Categorie; } #endregion #region "Getters" public string _getCategorie() { return this._categorie; } #endregion #region "Constructor Par Défaut" public DéveloppeurInterne() { } #endregion #region "Constructor 'Initialisation" public DéveloppeurInterne(string matricule, string nom, string email, double taux, string Categorie, double Salaire) : base(matricule, nom, email, taux) { this._categorie = Categorie; _setSalaire(Salaire); } #endregion #region "Methode Calcule_Salaire" public override double Calcul_salaire(int nbr_heures) { if (_categorie.Equals("J")) { setTaux(200); _setSalaire(_getSalaire() + base.Calcul_salaire(nbr_heures)); } else { setTaux(150); _setSalaire(_getSalaire() + base.Calcul_salaire(nbr_heures)); } return _getSalaire(); } #endregion } } <file_sep>/Projet.cs using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Collections; using System.Linq; using System.Threading.Tasks; namespace Theorie_2011_Focus { class Projet { public ArrayList participants = new ArrayList(); public void AjouterParticipant(object o) { participants.Add(o); } public Double CalculSalaireParticipant() { Double salaire = 0; foreach(Object o in participants) { if(o is DéveloppeurExterne) { var t = (DéveloppeurExterne)o; salaire += t._getSalaire(); } else { var t = (DéveloppeurInterne)o; salaire += t._getSalaire(); } } return salaire; } } }
11e4f5180803da92e9d92990e56ed4246a176051
[ "Markdown", "C#" ]
4
Markdown
Cryptographerdll/Theorie-Ofppt-2011-En-Csharp
3963d7e2487f24ece2aff1c9105e5272ff8e3695
cdafc1ce37a4ea7fcb071eca9c10a9e0f0993d0c
refs/heads/master
<repo_name>UnknownAD/hijack_xss<file_sep>/sessid_store.php <?php session_start(); $database=new PDO("pgsql:host=localhost;dbname=postgres","postgres","<password>") or die('unable to reach the database'); if(isset($_GET['user'])){ $name=$_GET['user']; $sessid=$_COOKIE['PHPSESSID']; $cmd="INSERT INTO SESSIONS (name,sessid) values('$name','$sessid')"; echo $cmd; $execution=$database->prepare($cmd); $resut=$execution->execute(); }else{ try{ $sessid=$_COOKIE['PHPSESSID']; $execution=$database->prepare("SELECT NAME FROM SESSIONS WHERE SESSID='$sessid'"); $execution->execute(); print_r($execution->fetchAll()); }catch(exception $error){echo $error;} } ?> <file_sep>/README.md # hijack_xss supportez nous -_- pas forcement avec une valeur superieure... address bitcoin; bc1qgur7sklu6ql4spl5tt2pyyysfv74axpxu0d4yk <file_sep>/hijacking.py import socket import sys sessid=sys.argv[1] attack=socket.socket(socket.AF_INET,socket.SOCK_STREAM); attack.connect(('localhost',80)) http_headers=f"POST /env.php HTTP/1.1\r\nHost: 127.0.0.1\r\nCookie:PHPSESSID={sessid}\r\nConnection: Close\r\n\r\n" #http_headers="GET /env.php HTTP/1.1\r\nHost: localhost\r\nConnection: Close\r\n\r\n" attack.send(bytes(http_headers,'us-ascii')) print(attack.recv(1024).decode('us-ascii')) attack.close()
5e1df5fef37b43423e402ed4e147f186d4806ae4
[ "Markdown", "Python", "PHP" ]
3
PHP
UnknownAD/hijack_xss
361d46d32d3bf4fcfdc017355732d2e55892f828
27a65f82035e62b485ec22e1c8bcdf5992bb4787
refs/heads/master
<repo_name>zijieliu123/Adventure_goofball_Jimmy-<file_sep>/_pasted_code_7/src/Adventure.java // <NAME>'s adventure project // I got help from StackOverflow :) // Importing scanner import java.util.Scanner; public class Adventure { // Using scanner as an instance variable, it is needed in everything. private Scanner input = new Scanner(System.in); // and introduction and to get the user's name. public void intro() { System.out.println("Welcome to Goofball, I am Ben. What's your name?"); String answer = input.next(); System.out.println("\nhi " + answer + " Not that your name matters but it's company policy. \n"); first_choice(); } // First choice that the player makes, ask an question and get and answer. public void first_choice() { System.out.println("Now we proceed to the goofball challenge, which one would you attempt first?"); System.out.println("\na.weird pranks, \nb.get out of this weird place. "); String answer = input.next(); // if input is "a" move to goof decision step. if (answer.equals("a")) goof_decision(); // if answer is "b" move to getout step. else if (answer.equals("b")) getout_decision(); // if they are dumb, give an error. else input_error(); } // goof decision step, public void goof_decision() { System.out.println("\nNow you have to prank the CEO. Dont question why it is COMPANY POLICY."); System.out.println("\na. slap him \nb. hide his lunch and dinner(both are sandwiches)"); String answer = input.next(); // if answer is 'a' move on to fired step. if (answer.equals("a")) youare_fired(); // if answer is 'b' move on to navigate maze step. else if (answer.equals("b")) navigate_maze(); // if they are dumb, give an error. else input_error(); } // navigate maze step public void navigate_maze() { System.out.println("\nCongradulations, you passed the first test! Now you will have to naviagte a maze that is designed to test your limits."); System.out.println("The maze is dark, make your choice wisely."); System.out.println("\na. go in without carrying anyhting \nb. search your surroundings before you go in(you see a torch and a knife)"); String answer = input.next(); // if input 'a' move on to slipped death step. if (answer.equals("a")) oops_slipped(); // if input 'b' move on to boss step. else if (answer.equals("b")) meet_boss(); // if they are dumb, give an error. else input_error(); } // meet boss step public void meet_boss() { System.out.println("\nYou hear footsteps in front of you, you pointed your torch forward and you see a dragon!"); System.out.println("The dragon(water breathing), comes closer to you every second, what do you do? "); System.out.println("\na. kill the dragon with your knife!!! \nb. run away \nc. cut a rope that you see leads up to a huge weight"); String answer = input.next(); // if input 'a' move on to swallowed step. if (answer.equals("a")) swallowed_alive(); // if input 'b' move on to coward step. else if (answer.equals("b")) coward_exe(); // if input 'c' move on to third challenge step else if (answer.equals("c")) third_challenge(); // if they are dumb, give an error. else input_error(); } // Third challenge step public void third_challenge() { System.out.println("\nAs you can see, the challenges are becoming harder and harder."); System.out.println("Congradulations on the last challenge, however the thrid challenge is, to send yourself into space wearing pajamas and land on moon"); System.out.println("As to the rest don't ask me it is company policy :), have fun figuring out how to come back!"); System.out.println("\nTimer is ticking, a cage appeared and trapped you. What do you do?"); System.out.println("\na. punch cage and yell \nb. do nothing \nc. change into pajamas "); String answer = input.next(); // if input 'a' move on to plasma death step. if (answer.equals("a")) plasma_death(); // if input 'b' move on to thrown out step. else if (answer.equals("b")) thrownoutof_rocket(); // if input 'c' move on to launch step. else if (answer.equals("c")) launch_phase(); // if they are dumb, give an error. else input_error(); } // launch step public void launch_phase() { System.out.println("\nYou are being launched into space as you put on your pajamas"); System.out.println("You see out of the window that you finally was able to leave the GOOFball factory"); System.out.println("You are relieved, but also afraid of what is to come"); System.out.println("Bang, an astroid clashed with your spacecraft, you panicked as the radio plays: astroid zone, watch out!"); System.out.println("What do you do? \na. manually maneuver spacecraft \nb. continue to sit on automated driving \nc. click BaCkToEaRtH.EXE because you can't take it anymore"); String answer = input.next(); // if input 'a' move on to arrive on moon step. if (answer.equals("a")) arriveon_moon(); // if input 'b' move on to crash landing step. else if (answer.equals("b")) crash_landing(); // if input 'c' move on to explode step. else if (answer.equals("c")) spaceship_explode(); // if they are dumb, give an error. else input_error(); } // arrive on moon step public void arriveon_moon() { System.out.println("\nYou passed the astroid field! You can see the moon just infront of you as your spaceship goes closer"); System.out.println("Now you have two choices: \na. pilot back to Earth without landing on the moon \nb. land on the moon \n what do you do?"); String answer = input.next(); // if input 'a' move on to goofball death step. if (answer.equals("a")) Goofball_death(); // if input 'b' move on too moon boss step. else if (answer.equals("b")) moon_boss(); // if they are dumb, give an error. else input_error(); } // moon boss step public void moon_boss() { System.out.println("\nWow, you finally landed on moon!"); System.out.println("Strangely, your pajamas protected you from the hotile environment"); System.out.println("You landed near some sort of ancient burial mound, suddenly the ground cracked and a lunar serpent appeared. What do you do?"); System.out.println("\na. knife it, \nb. run"); String answer = input.next(); // if input 'a' move on to swallowed death step. if (answer.equals("a")) swallowed_death(); // if input 'b' move on to back to earth step. else if (answer.equals("b")) backto_earth(); // if they are dumb, give an error. else input_error(); } // back to earth step public void backto_earth() { System.out.println("\nthe serpent chased you until you saw some sort of portal on the ground, you picked up a strange weapon on the way to deal with the serpent, you blew its head off."); System.out.println("you stepped into the portal and was teleported back to Earth"); System.out.println("However, the goofball has taken over everything, you must stop him!!!"); System.out.println("\na.do nothing \nb.go back to the goofball factory"); String answer = input.next(); // if input 'a' move on to clown death step if (answer.equals("a")) clown_death(); // if input 'b' move on to grand finale step. else if (answer.equals("b")) grand_finale(); // if they are dumb, give an error. else input_error(); } // grand finale step public void grand_finale() { System.out.println("\nYou arrived at the factory, now it is ruled by the goofball tyrant."); System.out.println("You wentinside and demolished the goofball tyrant and freed everyone from slavery"); System.out.println("You realized that the weapon you picked up is insanely powerful, what do you do now?"); System.out.println("\na. sell the weapon \nb. rule the world \nc. go back to your life "); String answer = input.next(); // if input 'a' move on to FBI arrest step. if (answer.equals("a")) FBI_arrest(); // if input 'b' move on to overthrown death step. else if (answer.equals("b")) overthrown_death(); // if input 'c' move on to happy ending step. else if (answer.equals("c")) happy_ending(); // if they are dumb, give an error. else input_error(); } // a possible end of game step public void getout_decision() { System.out.println("The goofball burned you to ashes when you tried to run out."); } // a possible end of game step public void youare_fired() { System.out.println("YOU ARE FIRED, literally, the goofball tyrant burned you to ashes"); } // a possible end of game step public void oops_slipped() { System.out.println("Because you did not bring a flashlight, you fell down a crack in the floor and got impaled by spikes. RIP"); } // a possible end of game step public void swallowed_alive() { System.out.println("yuk, skull, stomach acid, darkness, now you are part of the collection inside the dragon's belly."); } // a possible end of game step public void coward_exe() { System.out.println("goofball installed virus on you, when you run away you were killed by coward.exe, lol"); } // a possible end of game step public void plasma_death() { System.out.println("The cage burned you to ashes, not a great idea."); } // a possible end of game step public void thrownoutof_rocket() { System.out.println("in the middle of the ascent you were thrown out of rocket, should have wore that pajamas :)"); } // a possible end of game step public void crash_landing() { System.out.println("OOOOOOF your spacehsip landed, but not on the moon, now you are trapped for life on a small metoeor."); } // a possible end of game step public void spaceship_explode() { System.out.println("Sit and do nothing? BOOOOM!"); } // a possible end of game step public void Goofball_death() { System.out.println("You piloted manually back home, you left your rocket in the backyard and went back to your life, until you heard knocks on your door."); System.out.println("\nYou opened the door... GOOFBALL. You were never seen again. "); } // a possible end of game step public void swallowed_death() { System.out.println("you were melted in the serpent's stomach acid. RIP"); } // a possible end of game step public void clown_death() { System.out.println("You were turned into a clown by goofball, you worked to your death"); } // a possible end of game step public void FBI_arrest() { System.out.println("Your weapon was solf for 10 trillion, you are rich for life!"); System.out.println("\nThat is unti.... FBI OPEN UP!"); } // a possible end of game step public void overthrown_death() { System.out.println("You became a tyrant after you killed goofball, but were overthrown. LOL "); } // a possible end of game step public void happy_ending() { System.out.println("NEVER BE GREEDY! You went back to your old life, became a trillionaire and lived happily ever after"); System.out.println("THE END"); } // dumb people control public void input_error() { System.out.println("not a valid input"); } // main method to get the game started public static void main(String[] args) { Adventure tester = new Adventure(); // only need intro running, rest is linked. tester.intro(); } }
ef25479aaf3c68810d2acea3a25cbebb022a0f88
[ "Java" ]
1
Java
zijieliu123/Adventure_goofball_Jimmy-
5473e314fc89f76fc973f5abafb67b6175b23de1
7696451d29618bcd7f3e332081c691836e72d49a
refs/heads/master
<file_sep>$(document).ready(function() { var nextItemNumber = 1 ; $('.add-btn').click(function() { if ($('#add-input').val()=='') { alert('Please Input An Item For Your List'); return; } //console.log($('#add-input').val()); $('.list').append ('<li class="item" item-number="' + nextItemNumber + '">\ <h3 class="item-title" item-number="' + nextItemNumber + '">'+$('#add-input').val()+'</h3>\ <div class="yesno">\ <a href="#" class="yeslike" item-number="' + nextItemNumber + '"></a>\ <a href="#" class="nolike" item-number="' + nextItemNumber + '"></a>\ </div>\ </li>'); $("input[type=text]").val(""); $('.yeslike[item-number="' + nextItemNumber + '"]') .click(function(){ //alert('clicked yes' + $(this).attr('item-number')); if ($('.item[item-number="' + $(this).attr('item-number') + '"]').hasClass('green-bg')){ $('.item[item-number="' + $(this).attr('item-number') + '"]').removeClass('green-bg'); $('.item-title[item-number="' + $(this).attr('item-number') + '"]').removeClass('white'); } else { $('.item[item-number="' + $(this).attr('item-number') + '"]').addClass('green-bg'); $('.item-title[item-number="' + $(this).attr('item-number') + '"]').addClass('white'); } }); $('.nolike[item-number="' + nextItemNumber + '"]') .click(function(){ $('.item[item-number="' + $(this).attr('item-number') + '"]').animate({opacity: 0},500, function(){ $('.item[item-number="' + $(this).attr('item-number') + '"]').remove() }); }); nextItemNumber++; }); $('.clear-btn').click(function(){ /* $('.item').animate({opacity: 0},500, function(){ $('.item').remove() }); */ $('.item').fadeOut(500,function(){ $('.item').remove() }); }); });
7c38ef90ce020fff52eb48a12aa46b1baf0204f3
[ "JavaScript" ]
1
JavaScript
samkrauser/shopping-list-sizing
c29053ea4f32b47bda1e5526eb815e1c6d7587cc
8f659ee5c98e35b66c276e4aabfd1d2d3c15bf06
refs/heads/master
<repo_name>philberryman/haplo-test<file_sep>/README.md ## A Multi Path Story Editor # The brief Please write a web application which enables the user to write "multi-path stories." A multi-path story is composed of sentences. After each sentence, there are up to four possible next sentences, and after each of those, another four possible next sentences, and so on. Here's a short screencast which illustrates the application: [link](http://oneis-recruitment.s3.amazonaws.com/2014/stories-web-app.mp4) ## Approach # Data The first thing I thought about when planning the project was the data structure. What we are building is a set of pages where each page has 4 paths leading off it. Essentially each page is a parent with 4 children. I decided to store the pages as objects in an array. The objects needed the following properties: * id * parentId * story • position As we were only ever adding to the array the 'id' always equaled the same as the index position of the page. This made it easy to locate pages using bracket notation. Position is where this child displays when being viewed on parent page. Clockwise from top. 0 = top, 1 = right, 2 = bottom, 3 = left. # Routes **Get /** The home page route first checks if the session has any pages in memory already. If not the start of the story is created and it's children are then created using withChildren() function. We then retrieve the children for this page using getChildren() **Get :pageId** When a page is navigated to we first check if children nodes have been created in memory for this page using hasChildren(). If no children exist for the page we create them using withChildren(). We then retrieve the children for this page using getChildren() **Post /** This route updates the story property of the page. The post request is made by the client with the following properties: * pageId * story * parentId * position The pages array is updated using bracket notation to locate the correct element ``` pages[pageId] = { id: pageId, story: story, parentId: parentId, position: position, }; ``` ## Technology This application was built to run on Node using the Express.js framework and Handlebars.js for the HTML templating. Session management was done using the express-session library. An end to end test was created using Cypress. ## How to run On a machine with an up to date version of Node.js ... 1. Clone / Copy project to local machine 2. Navigate to folder 3. npm i 4. npm start To run tests (using Cypress) 5. npm test ## Thoughts on the project ... I hope that this project demonstrates an understanding of: * Application structure and flow * JS data structures (using arrays and objects) * Setting up a node application * Proving an application works using a testing framework ## Improvements The way pages are referenced by their position in the array may not be resilient if this application became more complex. This could be updated to use object methods to find the object with the matching 'id' property instead. For this project the method worked fine though. The tests show that the flow from the video example can be followed. They could be much more focused unit tests showing how each part of the functionality works though. Cypress was used for ease as the testing I have most recently done has been on React apps using Jest and Testing Library which I couldn't see easily how to use for this type of App. Jest unit tests may have been a better solution if possible. To make life easier for myself I used data-test-ids in the html to locate elements. Using Testing-Library with Cypress would have made navigating around the DOM more like a real user. ## Conclusion This was an enjoyable little project. Total time was about a day. A bit of time was needed to refresh myself with Node and Express which I havn't used for a while and Handlebars that I had never used. A couple of annoying bugs took far longer to find than I would have liked (one in particular with Handlebars variables). <file_sep>/index.js const express = require("express"); const app = express(); const engines = require("consolidate"); const bodyParser = require("body-parser"); const session = require("express-session"); app.engine("hbs", engines.handlebars); app.set("views", "./views"); app.set("view engine", "hbs"); app.use(bodyParser.urlencoded({ extended: true })); app.use( session({ name: "haplo-test", secret: "wheresthesummergone", resave: false, saveUninitialized: false, }) ); // checks if a page already has children const hasChildren = (pages, parentId) => { const children = pages.filter(page => page.parentId == parentId); return children.length === 0 ? false : true; }; // takes pages and parentId and returns pages with blank children added const withChildren = (pages, parentId) => { const pagesCopy = [...pages]; for (i = 0; i < 4; i++) { const nextId = pagesCopy.length; pagesCopy.push({ id: nextId, story: null, position: i, parentId: Number(parentId), }); } return pagesCopy; }; // filters pages array for chlidren of specified page (parent) const getChildren = (pages, parentId) => { const pagesCopy = [...pages]; const children = pagesCopy.filter(page => { return page.parentId === parentId; }); return children; }; app.get("/", (req, res) => { let pages = []; // check if pages object exists and if not create it with first part of story if (!req.session.pages) { pages = [ { id: 0, story: "Once upon a time there was a big bad wolf.", parentId: null, }, ]; } else { pages = [...req.session.pages]; } // check if child pages have been created for this page. If not we create them. if (!hasChildren(pages, 0)) { pages = withChildren(pages, 0); } // on the root, route we will always look at index [0] of the pages array const thisPage = pages[0]; // let's find the children of the current page const children = getChildren(pages, 0); const nextPages = pages.filter(page => { return page.parentId == 0; }); req.session.pages = pages; res.render("index", { thisPage, children }); }); app.post("/", (req, res) => { const pages = [...req.session.pages]; const pageId = Number(req.body.pageId); const story = req.body.story; const parentId = Number(req.body.parentId); const position = Number(req.body.position); // update pages array with story pages[pageId] = { id: pageId, story: story, parentId: parentId, position: position, }; // thisPage uses [parentId] as we're not changing page const thisPage = pages[parentId]; const children = getChildren(pages, parentId); req.session.pages = pages; res.render("index", { thisPage, children }); }); app.get("/:pageId", (req, res) => { let pages = [...req.session.pages]; const pageId = Number(req.params.pageId); if (!hasChildren(pages, pageId)) { pages = withChildren(pages, pageId); } const thisPage = pages[pageId]; const children = getChildren(pages, pageId); req.session.pages = pages; res.render("index", { thisPage, children }); }); const server = app.listen(3000, () => console.log("Server running at Port 3000") ); <file_sep>/cypress/integration/examples/video-example.js /// <reference types="Cypress" /> context("Connectors", () => { beforeEach(() => { cy.visit("localhost:3000"); }); it("does what is shown in the example video for the tech test", () => { cy.get('[data-test-id="textarea-0"]').type("He liked to chase rabits."); cy.get('[data-test-id="submit-0"]').click(); cy.get('[data-test-id="link-0"]').should( "contain", "He liked to chase rabits." ); cy.get('[data-test-id="textarea-1"]').type("He lived in the woods."); cy.get('[data-test-id="submit-1"]').click(); cy.get('[data-test-id="link-1"]').should( "contain", "He lived in the woods." ); cy.get('[data-test-id="textarea-2"]').type( "He was best friends with a tiger" ); cy.get('[data-test-id="submit-2"]').click(); cy.get('[data-test-id="link-2"]').should( "contain", "He was best friends with a tiger" ); cy.get('[data-test-id="textarea-3"]').type("He liked cooking pancakes."); cy.get('[data-test-id="submit-3"]').click(); cy.get('[data-test-id="link-3"]').should( "contain", "He liked cooking pancakes." ); cy.get('[data-test-id="link-2"]').click(); cy.get('[data-test-id="textarea-1"]').type( "Sometimes they went out to parties together." ); cy.get('[data-test-id="submit-1"]').click(); cy.get('[data-test-id="link-1"]').should( "contain", "Sometimes they went out to parties together." ); cy.get('[data-test-id="textarea-2"]').type( "The tiger lived in a cave and ate bunnies for dinner." ); cy.get('[data-test-id="submit-2"]').click(); cy.get('[data-test-id="link-2"]').should( "contain", "The tiger lived in a cave and ate bunnies for dinner." ); cy.get('[data-test-id="link-1"]').click(); cy.get('[data-test-id="textarea-1"]').type( "The tiger was very antisocial though so they didn't make many friends." ); cy.get('[data-test-id="submit-1"]').click(); cy.get('[data-test-id="link-1"]').should( "contain", "The tiger was very antisocial though so they didn't make many friends." ); cy.get('[data-test-id="textarea-2"]').type( "Once the wolf drank too much and was sick in the taxi home" ); cy.get('[data-test-id="submit-2"]').click(); cy.get('[data-test-id="link-2"]').should( "contain", "Once the wolf drank too much and was sick in the taxi home" ); cy.get('[data-test-id="textarea-0"]').type( "They liked to go to Michellin starred restaurants too" ); cy.get('[data-test-id="submit-0"]').click(); cy.get('[data-test-id="link-0"]').should( "contain", "They liked to go to Michellin starred restaurants too" ); cy.get('[data-test-id="link-0"]').click(); cy.get('[data-test-id="textarea-1"]').type( "But really they most loved pizza most." ); cy.get('[data-test-id="submit-1"]').click(); cy.get('[data-test-id="link-1"]').should( "contain", "But really they most loved pizza most." ); cy.get('[data-test-id="back"]').click(); cy.get('[data-test-id="link-0"]').click(); cy.get('[data-test-id="back"]').click(); cy.get('[data-test-id="link-2"]').click(); cy.get('[data-test-id="link-2"]').click(); cy.get('[data-test-id="back"]').click(); cy.get('[data-test-id="link-2"]').click(); cy.get('[data-test-id="textarea-0"]').type( "The tiger was also friends with a deer." ); cy.get('[data-test-id="submit-0"]').click(); cy.get('[data-test-id="link-0"]').should( "contain", "The tiger was also friends with a deer." ); cy.get('[data-test-id="textarea-3"]').type("The tiger was really mean."); cy.get('[data-test-id="submit-3"]').click(); cy.get('[data-test-id="link-3"]').should( "contain", "The tiger was really mean." ); cy.get('[data-test-id="link-3"]').click(); cy.get('[data-test-id="textarea-0"]').type( "He kept eating the wolfs dinner." ); cy.get('[data-test-id="submit-0"]').click(); cy.get('[data-test-id="link-0"]').should( "contain", "He kept eating the wolfs dinner." ); cy.get('[data-test-id="textarea-1"]').type( "Once he played a trick on the wolf" ); cy.get('[data-test-id="submit-1"]').click(); cy.get('[data-test-id="link-1"]').should( "contain", "Once he played a trick on the wolf" ); cy.get('[data-test-id="back"]').click(); }); });
fe97c3dfe412167722f0b99290358a5e2086f691
[ "Markdown", "JavaScript" ]
3
Markdown
philberryman/haplo-test
68038f6e79ac141dc528120c7e0be4ab7ccf3c4b
90307f5cdbc693609919bb5bf9b4e0f0163c9a65
refs/heads/master
<file_sep>//var selected_name; $(document).ready(function(){ console.log("document ready"); /*$("button").click(function(){ $.get("demo_test.asp", function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); });*/ /*$.get("/baselist", function(data, status){ debugger; var length = data.length; alert("get data"); });*/ $.ajax({ type: "GET", contentType: 'application/x-www-form-urlencoded; charset=utf-8;', url: "/baselist", dataType:"json", data: null,//{"startNum":startNum, "endNum":endNum}, async: true, cache: false, success: function(data){ for(var i = 0; i < data.length;i++){ var html = ""; // data-rel="popup" class="ui-btn" data-transition="slide" /*html += "<tr>"; html += "<td>"; html += i + 1; html += "</td>"; html += "<td href='#myPopup' data-rel='popup' class='ui-btn' data-transition='slide' >"; html += data[i].name; html += "</td>"; html += "</tr>"; $("#tbodyList").append(html);*/ html += "<a href='#pagetwo' class='ui-btn' onclick='myClick(this)' >" + data[i].name + "</a>"; $("#myContent").append(html); } /*$(".ui-btn").unbind('click').bind('click',function(a,b,c,d){ debugger; console.log("asd"); });*/ }, error:function (){ alert("서버와 통신중 에러가 발생하였습니다."); } }); $(document).on('pagebeforeshow', '#pagetwo', function(a,b,c){ console.log("page before show"); //$("#name").html(""); }); }); function myClick(objButton){ //alert(objButton.innerText);asd var selected_name = objButton.innerText; $("#selected_name")[0].innerText = "( " + objButton.innerText + " ) 의 생일을 입력하세요"; console.log("selected_name : " + selected_name); //$("#name").html('<option value="' + selected_name + '" >' + selected_name + '</option>'); $("#name")[0].value=selected_name; $("#name").hide(); } <file_sep>package com.sorang.controller; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.postgresql.util.PSQLException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.sorang.domain.Student; import com.sorang.mapper.StudentMapper; //@RestController @Controller public class HelloController { /*@RequestMapping("/") public String index() { return "index"; }*/ @Resource private StudentMapper studentMapper; @RequestMapping("/") public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="") String name) { /*//model.addAttribute("name", name); City find = cityMapper.findByState("seoul"); if (find != null) { System.out.println("find name : " + find.getName()); } //insert City city = new City(); city.setId(1); city.setName("mini"); city.setState("home"); city.setCountry("rangrang"); try { boolean res = cityMapper.insertCity(city); System.out.println("insert res : " + res); } catch(Exception e) { System.out.println("sorang exception : " + e.getMessage()); }*/ return "intro"; } @RequestMapping("/baselist") public @ResponseBody List<Student> getBaseStudentList(HttpServletRequest request) throws Exception{ List<Student> students = studentMapper.getAllStudents(); return students; } //@RequestMapping(value="/selectstudent", method=RequestMethod.POST) @RequestMapping("/selectstudent") public String selectStudent(Model model, HttpServletRequest request) { String month = request.getParameter("month"); String day = request.getParameter("day"); if (day.length() == 1) { day = "0".concat(day); }; String name = request.getParameter("name"); System.out.println(" selectStudent : " + name + " , " + month + " , " + day); Student req = new Student(); req.setName(name); req.setBirthday(Integer.parseInt(month + day)); Student ret = studentMapper.getStudent(req); if (ret == null) { // 생일을 잘못 입력한 케이스... return null; } else { model.addAttribute("name", ret.getName().trim()); model.addAttribute("mobile_number_student", ret.getMobile_number_student().trim()); model.addAttribute("mobile_number_mother", ret.getMobile_number_mother().trim()); model.addAttribute("mobile_number_father", ret.getMobile_number_father().trim()); model.addAttribute("phone_number_home", ret.getPhone_number_home().trim()); model.addAttribute("home_address", ret.getAddress().trim()); return "form"; } } @RequestMapping("/enterform") public String enterFormData(Model model, HttpServletRequest request) { Student st = new Student(); st.setName(request.getParameter("contact_name").trim()); st.setMobile_number_student(request.getParameter("mobile_student").trim()); st.setMobile_number_mother(request.getParameter("mobile_mother").trim()); st.setMobile_number_father(request.getParameter("mobile_father").trim()); st.setPhone_number_home(request.getParameter("phone").trim()); st.setAddress(request.getParameter("address").trim()); boolean ret = studentMapper.updateStudent(st); return "end"; } /** 관리자 페이지 **/ @RequestMapping("/rang") public String printAllData(Model model, HttpServletRequest request) { return "rangrang"; } @RequestMapping("/all") public @ResponseBody void printAllStudent(Model model) { List<Student> students = studentMapper.getAllStudents(); for(int i = 0; i < students.size(); i++) { Student student = students.get(i); System.out.println("print : " + student.toString()); } } @RequestMapping("/insert") public @ResponseBody void addStudent(Model model) { System.out.println("addStudent"); Student student = new Student(); student.setBirthday(123); student.setName("김민석"); //student.setMobile_number_student("01055554444"); //student.setMobile_number_father("01056784938"); //student.setMobile_number_mother("75347538475345"); //student.setAddress("서울 1235345345주공아파트"); studentMapper.insertStudent(student); } } <file_sep>package com.sorang.domain; import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = 1L; private int birthday; private String name; private String mobile_number_student; private String mobile_number_mother; private String mobile_number_father; private String phone_number_home; private String address; public Student() { this.birthday = 0; this.name = ""; this.mobile_number_student = ""; this.mobile_number_mother = ""; this.mobile_number_father = ""; this.phone_number_home = ""; this.address = ""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getBirthday() { return birthday; } public void setBirthday(int birthday) { this.birthday = birthday; } public String getMobile_number_student() { return mobile_number_student; } public void setMobile_number_student(String mobile_number_student) { this.mobile_number_student = mobile_number_student; } public String getMobile_number_mother() { return mobile_number_mother; } public void setMobile_number_mother(String mobile_number_mother) { this.mobile_number_mother = mobile_number_mother; } public String getMobile_number_father() { return mobile_number_father; } public void setMobile_number_father(String mobile_number_father) { this.mobile_number_father = mobile_number_father; } public String getPhone_number_home() { return phone_number_home; } public void setPhone_number_home(String phone_number_home) { this.phone_number_home = phone_number_home; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Student " + getName().trim() + " , " + getBirthday() + " , " + getMobile_number_student().trim() + " , " + getMobile_number_mother().trim() + " , " + getMobile_number_father().trim() + " , " + getAddress().trim(); } } <file_sep>$(document).ready(function(){ /*$("button").click(function(){ $.get("demo_test.asp", function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); });*/ /*$.get("/baselist", function(data, status){ debugger; var length = data.length; alert("get data"); });*/ $.ajax({ type: "GET", contentType: 'application/x-www-form-urlencoded; charset=utf-8;', url: "/baselist", dataType:"json", data: null,//{"startNum":startNum, "endNum":endNum}, async: true, cache: false, success: function(data){ for(var i = 0; i < data.length;i++){ var html = ""; html += "<tr style='border:1px solid black'>"; //html += "<td style='cursor:pointer;' onclick='fn_commissionDetail(" + '"' + commissionList[i].LOAN_COMMISSION_CD + '","' +commissionList[i].DEALING_COMP_CD + '","' + commissionList[i].FINANCIAL_INSTITUTION_CD + '"' + ")'>"; html += "<td>"; html += data[i].name; //html += data[i].FINANCIAL_INSTITUTION_NM + "은행<br/>"; html += "</td>"; html += "<td>"; html += data[i].name; html += "</td>"; html += "</tr>"; $("#tbodyList").append(html); } }, error:function (){ alert("서버와 통신중 에러가 발생하였습니다."); } }); });
bf7eecfe1924a949924e1f9a45a1fb17ce1b4fe9
[ "JavaScript", "Java" ]
4
JavaScript
kangsorang/emergency
17439bfcf859713b3d5d72e8a62afeb3ddd8c42f
6b2cf888c3ff93881a77856a1b800dc29888decf
refs/heads/main
<repo_name>emmYgd/user_interfaces<file_sep>/README.md # user_interfaces A set of user interfaces and amazing experiences More of frontend with bootstrap and W3-CSS, few backend with OOP PHP <file_sep>/Royal Diamond/option1/Backend/SendMail.php <?php require("Utilities.php") class SendMail { /*{contactName : contactName}, {orgName :orgName}, {contactPosition : contactPosition}, {orgWebsite : orgWebsite}, {orgEmail : orgEmail}, {subject : subject}, {message : message},*/ public function sendMail($contactName, $orgName, $contactPosition, $orgWebsite, $orgEmail, $subject, $message){ } } ?> <file_sep>/Royal Diamond/option1/Backend/Utilities.php <?php class Utilities{ public function SanitizeString($submitted_element){ //Escapes the user input for security $uname = htmlentities($submitted_element, ENT_QUOTES); return $uname; } ?> <file_sep>/EgotronWebsite/option1/js/contact_submit.js $( //Now call the object literal method when button is clicked: $("#submit").click(function(event){ //event.preventDefault(); //console.log("Hello World"); ClientServerComm(); //alert("Hello World") }), ) var getUserInfo = async function(){ //get the values of the user details: var contactName = $("#contact_name").val(); var orgName = $("#org_name").val(); var contactPosition = $("#contact_pos").val(); var orgWebsite = $("#org_web").val(); var orgEmail = $("#email").val(); var subject = $("#subject").val(); var message = $("#message").val(); //return all in JSON list format: return [ {contactName : contactName}, {orgName :orgName}, {contactPosition : contactPosition}, {orgWebsite : orgWebsite}, {orgEmail : orgEmail}, {subject : subject}, {message : message}, ]; } var ClientServerComm = async function(){ var contactInfo = await getUserInfo(); console.log(contactInfo); //send over to the server: $.ajax({ url:"../option1/Backend/ImplementContact.php", type:"POST", //mimeType: "application/json" //contentType: "application/json" data:{userInfo : JSON.stringify(contactInfo)}, dataType : "json", processData : false, beforeSend : function(x){ if(x && x.overrideMimeType){ x.overrideMimeType("application/json; charset=UTF-8"); } }, success : function(result){ if(result == "SUCCESS!"){ //Tell the User that they are successfully registered here... //Hide all elements, //Display Success alert("Mail sent successfully!"); } }, error : function(err){ //Indicate the error message... //if(err == "FAILURE!"){ alert("Error in server Comms!"); //} } }); } <file_sep>/EgotronWebsite/option1/Backend/ImplementContact.php <?php //require("SendMail.php"); //get the ajax data from client: $userInfo = $_POST["userInfo"]; //then start processing the Received List: $userInfoArrayList = $userInfo //json_decode($userInfo); echo $userInfoArrayList; foreach($userInfoArrayList as $arrayValue){ $contactName = $arrayValue.contactName; $orgName = $arrayValue.orgName; $contactPosition = $arrayValue.contactPosition; $orgWebsite = $arrayValue.orgWebsite; $orgEmail = $arrayValue.orgEmail; $subject = $arrayValue.subject; $message = $arrayValue.message; //try{ //$SendMailObj = new SendMail //$SendMailObj->sendMail($contactName, $orgName, $contactPosition, $orgWebsite, $orgEmail, $subject, $message); $contactNameWithPosition = $contactName . "\n" . $contactPosition; $messageWithOtherEssentials = $contactNameWithPosition .".\n" $message . ".\n" . $orgWebsite; //Add header contents: $headers = "From:"."<".$orgEmail."".$orgName">" . "\r\n"; $headers .= "Cc: <EMAIL>"."\r\n"; $egotronmail = "<EMAIL>"; //call the email function: mail($egotronmail, $subject, $messageWithOtherEssentials, $headers); //send success code back to the client if(true){ echo "SUCCESS!"; } /*catch(err){ //send error code back to the client.. echo "FAILURE!"; }*/ ?> <file_sep>/EgotronWebsite/option1/js/enroll_submit.js $( //Now call the object literal method when button is clicked: $("#submit").click(function(event){ //event.preventDefault(); //console.log("Hello World"); ClientServerComm(); //alert("Hello World") }), ) var getTruePass = async function(pass1, pass2){ if(pass1 == pass2){ //password great! return pass1 }else{ alert("Error! Password does not Match!") } } var getUserInfo = async function(){ //get the values of the user details: var UserFirstName = $("#first_name").val(); var UserLastName = $("#last_name").val(); var UserEmail = $("#email").val(); var AppUserName = $("#username").val(); //get the two passwords and compare if they match: var pass1 = $("#password").val(); var pass2 = $("#conf_pass").val(); var AppPassword = getTruePass(pass1, pass2); var training_choice = $("#training_choice").val(); //return all in JSON list format: return [ {firstName : UserFirstName}, {lastName : UserLastName}, {email : UserEmail}, {username : AppUserName}, {password : <PASSWORD>}, {choice : training_choice} ]; } var ClientServerComm = async function(){ var userInfo = getUserInfo(); //send over to the server: $.ajax({ url:"../Backend/Implement.php", type:"POST", //mimeType: "application/json" //contentType: "application/json" data:{userInfo : JSON.stringify(userInfo)}, dataType : "json", processData : false, beforeSend : function(x){ if(x && x.overrideMimeType){ x.overrideMimeType("application/json; charset=UTF-8"); } }, success : function(result){ //Tell the User that they are successfully registered here... //Hide all elements, //Display Success }, error : function(){ //Indicate the error message... alert("Error in server Comms"); } }); }
40bc889c2d49342aa739f7041e3758ca0d98650a
[ "Markdown", "JavaScript", "PHP" ]
6
Markdown
emmYgd/user_interfaces
e337b6302b610c07979f28154f8f6a6887661e82
563fd7a7172f92b5935a1f95ad323782a905539a
refs/heads/master
<repo_name>Savanand/ScrapeWeb<file_sep>/scrap_with_bs4.py import requests from bs4 import BeautifulSoup def fetch_data(url): r = requests.get(url) soup = BeautifulSoup(r.content) links = soup.find_all("a") for link in links: # if "http" in link.get("href"): print "<a href='%s'>%s</a>" %(link.get("href"), link.text) g_data = soup.find_all("div", {"class" : "info"}) # print item.contents[1].find_all("div",{"class": "phones phone primary"})[0].text for item in g_data: print item.contents[0].find_all("a", {"class": "business-name"})[0].text try: print item.contents[1].find_all("span", {"itemprop": "streetAddress"})[0].text print item.contents[1].find_all("span", {"itemprop": "addressLocality"})[0].text.replace(',', '') print item.contents[1].find_all("span", {"itemprop": "addressRegion"})[0].text print item.contents[1].find_all("span", {"itemprop": "postalCode"})[0].text except: pass try: print item.contents[1].find_all(["li","div"], {"class": "primary"})[0].text except: pass base_url = "http://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=San+Jose%2C+CA" urlpage2 = "http://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=San+Jose%2C+CA&page=2" urlp = "http://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=San+Jose%2C+CA"+ "&page=2" pages = 5 fetch_data(base_url) for page in range(2, pages): temp_url= base_url + "&page=" + str(page) fetch_data(temp_url) <file_sep>/README.md #Scraping Web ######Scraping web yellowpages.com ######Used Python Requests library ######Used Beautiful Soap 4
97d3adcac849bf090e7fd7270fd9572986556fdd
[ "Markdown", "Python" ]
2
Python
Savanand/ScrapeWeb
7ee6915dd97188d09b90f82ea52a96303b3adfc5
f36d931a2e73808eea1652df223314aa3f8baadd
refs/heads/main
<repo_name>Hannaanaya/Mi-p-gina-web<file_sep>/src/pages/Principal.js import React from 'react'; import Carrusel from '../componentes/Carrusel'; import Galery from '../componentes/Galery'; import Footer from '../componentes/Footer'; import Loading from '../componentes/Loading'; import api from '../api'; import './style/Principal.css'; class Principal extends React.Component { state = { loading: true, error: null, data: undefined } componentDidMount() { this.fetchData() } fetchData = async () => { this.setState({ loading: true, error: null }); try { const data = await api.badges.list(); this.setState({ loading: false, data: data }); } catch (error) { this.setState({ loading: false, error: error }); } }; render() { if(this.state.loading === true) { return <Loading />; } return( <div className="contenido"> <h2 className="col-sm-4 text-center">Mis historias</h2> <Carrusel title = "Condena Sangrienta" danger = "de abuso sexual, violencia gráfica y lenguaje inapropiado" categ = "+16" genero = "Fantasía" sinopsis = "Trae maldiciones a donde sus pies tocan la tierra. La carga que se le ha otorgado no podrá dejarla incluso con su muerte, tiene una misión que deberá cumplir. En ese mundo de misterio, magia perdida en el tiempo y fantásticos individuos, solo unos excepcionales humanos podrán salvarlo, claro que, con el riesgo de perder la vida en el camino. ¿Qué tan lejos estarán dispuestos a llegar por él?" title1 = "Corazón esclavisado" danger1 = "abuso sexual" categ1 = "+16" genero1 = "BL" sinopsis1 = "Una comandante de grandes ideales dirige el ejército del reino Mery. Cuando se enamora de la esclava favorita del clan Shion, una de las familias más poderosas que predomina el estado, Amaya está dispuesta a luchar por liberarla, aunque eso signifique traicionar a su país." title2 = "Mis poemas" categ2 = "Todo público" genero2 = "Poesía" sinopsis2 = "La definición de las emociones es diferente para todos." title3 = "Mi demonio Nicolás" danger3 = "de abuso sexual, violencia gráfica y lenguaje inapropiado" categ3 = "+18" genero3 = "BL/Suspenso-Terror" sinopsis3 = "Los hermanos Beryclooth. Su historia comenzó el día que fueron separados. A Arthur, su propia sangre le cortó sus alas; Nicolás conoció la verdadera oscuridad habitable en su alma, olvidándose del cielo para adentrarse en el infierno, renaciendo como un hombre malvado y sin miedo a nada. En el bajo mundo, él es conocido como 'El demonio'." /> <h2>Galería</h2> <Galery /> <br/> <div> <Footer /> </div> </div> ); } } export default Principal;<file_sep>/src/componentes/Loading.js import React, { Component } from 'react'; import loa from '../images/loading.gif' import './style/Loading.css'; class Loading extends Component { render() { return( <div className="Loading"> <img src={loa} width="150px" height="150px"/> </div> ); } } export default Loading;<file_sep>/src/componentes/Footer.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import './style/Footer.css'; class Footer extends Component { render() { return ( <div className="Footer"> <div className="container"> <div className="row text-center"> <div className="col-12 col-lg"> <Link to="/personajes"><p>Personajes</p></Link> </div> <div className="col-12 col-lg"> <Link to="/media"><p>Ilustración de personajes</p></Link> </div> <div className="col-12 col-lg"> <Link to=""><p>Más</p></Link> </div> </div> </div> </div> ); } } export default Footer;<file_sep>/src/componentes/Header.js import React, { Component } from 'react'; import logo from '../images/logo.jpg'; import './style/Header.css'; class Header extends Component { render() { return ( <div className="Header navbar navbar-expand-lg navbar-light"> <img src={logo} alt=""/> <h1 className="md" >Conoce a BlondMasked... </h1> <div className="Header_buscar"> <input type="text" placeholder="Busca una historia..." /> <button className="btn btn-primary text-center" >Buscar</button> </div> </div> ) } }; export default Header;<file_sep>/src/componentes/App.js import React from 'react'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import Layout from './Layout'; import Principal from '../pages/Principal'; import Personajes from '../pages/Personajes'; import Media from '../pages/components/Media'; function App() { return ( <BrowserRouter> <Layout> <Switch> <Route exact path="/" component={Principal} /> <Route exact path="/personajes" component={ Personajes } /> <Route exact path="/media" component={ Media } /> </Switch> </Layout> </BrowserRouter> ); } export default App;<file_sep>/src/pages/components/Box.jsx import React from 'react'; import '../style/Box.css'; const Box = ({ title, children }) => ( <div className="Box"> <h2 className="Box__title">{title}</h2> {children} </div> ); export default Box;<file_sep>/src/pages/components/Media.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import Loading from '../../componentes/Loading'; import Image from '../../componentes/Images'; import img1 from '../../images/media/pers/man/A (1).png'; import img2 from '../../images/media/pers/man/A (3).jpg'; import img3 from '../../images/media/pers/man/A (4).jpg'; import img4 from '../../images/media/pers/man/A (9).jpg'; import img5 from '../../images/media/pers/man/A (1).jpg'; import img6 from '../../images/media/pers/man/A (5).jpg'; import img7 from '../../images/media/pers/man/A (6).jpg'; import img8 from '../../images/media/pers/man/A (7).jpg'; import img9 from '../../images/media/pers/man/A (10).jpg'; import img10 from '../../images/media/pers/man/A (11).jpg'; import img11 from '../../images/media/pers/woman/F (1).jpeg'; import img12 from '../../images/media/pers/woman/F (2).jpg'; import img13 from '../../images/media/pers/woman/F (3).jpeg'; import img14 from '../../images/media/pers/woman/F (3).jpg'; import img15 from '../../images/media/pers/woman/F (4).jpeg'; import img16 from '../../images/media/pers/woman/F (4).jpg'; import img17 from '../../images/media/pers/woman/y (1).jpeg'; import img18 from '../../images/media/pers/woman/y (1).jpg'; import img19 from '../../images/media/pers/woman/y (2).jpeg'; import img20 from '../../images/media/pers/woman/y (3).jpeg'; import img21 from '../../images/media/pers/woman/y (4).jpeg'; import api from '../../api'; import '../style/Media.css'; class Media extends Component { state = { loading: true, error: null, data: undefined } componentDidMount() { this.fetchData() } fetchData = async () => { this.setState({ loading: true, error: null }); try { const data = await api.badges.list(); this.setState({ loading: false, data: data }) } catch (error) { this.setState({loading: false, data: error }) } }; render() { if (this.state.loading === true) { return <Loading /> } if (this.state.error) { return `Error` } return ( <div className="Media"> <Link to="/"> <button className="btn btn-primary" > Regresar a inicio </button> </Link> <div className="Media_container mt-5"> <h2><NAME></h2> <Image className="mt-2 mb-2" src={img1} /> <Image className="mt-2 mb-2 " src={img2} /> <Image className="mt-2 mb-2" src={img3} /> <Image className="mt-2 mb-2" src={img4} /> </div> <div className="Media_container mt-5"> <h2><NAME></h2> <Image className="mt-2 mb-2" src={img5} /> <Image className="mt-2 mb-2" src={img6} /> <Image className="mt-2 mb-2" src={img7} /> <Image className="mt-2 mb-2" src={img8} /> <Image className="mt-2 mb-2" src={img9} /> <Image className="mt-2 mb-2" src={img10} /> </div> <div className="Media_container mt-5"> <h2>Fiona Amaris</h2> <Image className="mt-2 mb-2" src={img11} /> <Image className="mt-2 mb-2" src={img12} /> <Image className="mt-2 mb-2" src={img13} /> <Image className="mt-2 mb-2" src={img14} /> <Image className="mt-2 mb-2" src={img15} /> <Image className="mt-2 mb-2" src={img16} /> </div> <div className="Media_container mt-5"> <h2><NAME></h2> <Image className="mt-2 mb-2" src={img17} /> <Image className="mt-2 mb-2" src={img18} /> <Image className="mt-2 mb-2" src={img19} /> <Image className="mt-2 mb-2" src={img20} /> <Image className="mt-2 mb-2" src={img21} /> </div> </div> ); } } export default Media;
b7d3e05e585377ba3941458cfa5a32cd61fe3914
[ "JavaScript" ]
7
JavaScript
Hannaanaya/Mi-p-gina-web
b729a268ad159f2fc7122646e46abadcfe8f6748
2b2b9349598256479b9760f746cdcbce5899cf6d
refs/heads/master
<repo_name>LeoJiaXin/uestc_lang_backend<file_sep>/ajax/course/get-some-students.php <?php /* it's a json array format [ { id : 1, name : 'myname', degree : 100, class : 'class A' },... ] */ require(dirname(__FILE__).'/../../../../../wp-load.php'); define(MAX_NUMBER_OF_STUDENTS_IN_A_PAGE,25); $list = array(); //set default velue if they have no value in _GET $page_index = $_GET['page_pos']?$_GET['page_pos']:0; $sec_type = $_GET['sec_type']; /*========== you code below ==========*/ // for example : //if $page_index is 4 and MAX_NUMBER_OF_STUDENTS_IN_A_PAGE is 25 // so return classes whose id is from 4*25 to (4+1)*25 /*========== you code above ==========*/ class obj{} $students = array(); for ($i=MAX_NUMBER_OF_STUDENTS_IN_A_PAGE*$page_index;$i<MAX_NUMBER_OF_STUDENTS_IN_A_PAGE*($page_index+1);$i++) { $element = new obj; $element->id = $i; $element->name='myname'; $element->degree = 100; $element->class = 'class A'; array_push($students,$element); } echo json_encode($students); ?><file_sep>/ajax/source/test.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php require(dirname(__FILE__).'/../../../../../wp-load.php'); echo do_shortcode('<div>123</div>sadasdasd[audio mp3="http://localhost:8080/wpweb/uestc_lang/wp-content/uploads/2015/01/高飞.mp3"][/audio]');?> </body> </html> <file_sep>/ajax/source/get-some-sources.php <?php /* [ { id : 1, name : 'source-name', size : '100MB', hot : 20, upload : '2014.12.20' },... ] */ require(dirname(__FILE__).'/../../../../../wp-load.php'); define(MAX_NUMBER_OF_SOURCES_IN_A_PAGE,25); $list = array(); $page_index = $_GET['page_pos']?$_GET['page_pos']:0; $sec_type = $_GET['sec_type']; /*========== you code below ==========*/ if ($sec_type) { $args = array( 'numberposts' => MAX_NUMBER_OF_SOURCES_IN_A_PAGE, 'offset' => $page_index*MAX_NUMBER_OF_SOURCES_IN_A_PAGE, 'category' => $sec_type, 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true ); $source_list = get_posts($args); if ($source_list) { for ($i=0;$i<count($source_list);$i++) { $element = json_decode($source_list[$i]->post_content); $element->id = $source_list[$i]->ID; $element->name = $source_list[$i]->post_title; array_push($list,$element); } } if ($page_index == 0) { $tmp = get_category($sec_type); if ($tmp && $tmp->count>0) { $list[0]->sum = ceil($tmp->count/MAX_NUMBER_OF_SOURCES_IN_A_PAGE); } } } /*========== you code above ==========*/ echo json_encode($list); ?><file_sep>/js/module/activity/main.js (function() { define(function(require, exports, module) { var $; $ = jQuery; $(function() { var Backbone, Content, List, Router, Utils; Backbone = require('backbone'); require('base/template/activity'); Utils = require('base/module/common/utils'); List = {}; Content = {}; List.Model = Backbone.Model.extend({ defaults: { name: '', hot: '', update: '', description: '' } }); List.Collection = Backbone.Collection.extend({ model: List.Model, pageIndex: 0, pageSum: 0, url: function() { return path + '/ajax/activity/get-some-activities.php?page_pos=' + this.pageIndex; } }); List.View = Backbone.View.extend({ template: JST['source/template/activity/list.hbs'], el: $('#dashboard-widgets-wrap'), pageindex: 1, pagesum: 1, initialize: function() {}, render: function() { var num, tmp, _i, _ref; $('#content-editor-preload').hide(); tmp = { row: this.model.length, pageIndex: this.model.pageIndex + 1, pageSum: this.model.pageSum }; tmp.list = []; for (num = _i = 0, _ref = this.model.length; 0 <= _ref ? _i < _ref : _i > _ref; num = 0 <= _ref ? ++_i : --_i) { tmp.list.push(this.model.models[num].attributes); } this.$el.html(''); this.$el.append(this.template(tmp)); this.afterRender(); }, afterRender: function() { $('.first-page').attr('href', '#list/0'); $('.pre-page').attr('href', '#list/' + (this.model.pageIndex < 1 ? 0 : this.model.pageIndex - 1)); if (this.model.pageSum === 0) { $('.next-page').attr('href', '#list/0'); } else { $('.next-page').attr('href', '#list/' + (this.model.pageIndex >= this.model.pageSum - 1 ? this.model.pageSum - 1 : this.model.pageIndex + 1)); } return $('.last-page').attr('href', '#list/' + (this.model.length > 0 ? this.model.pageSum - 1 : 0)); } }); Content.View = Backbone.View.extend({ template: JST['source/template/activity/content.hbs'], el: $('#content-enter'), initialize: function() {}, render: function() { $('#dashboard-widgets-wrap').html(''); this.$el.html(this.template(this.model.attributes)); $('#content-editor-preload iframe').css('height', '500px'); $('#content-editor-preload').show(); Utils.initSelectImage($('#post_header_upload'), $('#post_header_target')); if (this.model.get('description') != null) { tinymce.activeEditor.setContent(this.model.get('description')); } $('#content-form').ajaxForm({ url: path + '/ajax/activity/activity.php', dataType: 'json', type: 'get', beforeSubmit: function() { $('body').showLoading(); }, success: function(result) { if ((result != null) && result.state === 'success') { Root.Router.navigate('list/' + Root.List.Model.pageIndex, { replace: true, trigger: true }); } $('body').hideLoading(); }, error: function() { $('body').hideLoading(); } }); } }); Root.List = {}; Root.Content = {}; Root.List.Model = new List.Collection(); Root.Content.Model = new List.Model(); Root.List.View = new List.View({ model: Root.List.Model }); Root.Content.View = new Content.View({ model: Root.Content.Model }); Router = Backbone.Router.extend({ routes: { '': 'default', 'list/:pageindex': 'tolist', 'content(/:id)': 'tocontent', 'delete/:id': 'delete' } }); Root.Router = new Router(); Root.Router.on('route:default', function() { return Root.Router.navigate('list/0', { replace: true, trigger: true }); }); Root.Router.on('route:tolist', function(pageIndex) { var links; links = $('.wrap>h2>a').hide().attr('href', '#list/' + pageIndex); Root.List.Model.pageIndex = parseInt(pageIndex); return Root.List.Model.fetch({ reset: true, success: function() { if ((Root.List.Model.models[0] != null) && (Root.List.Model.models[0].attributes.sum != null)) { Root.List.Model.pageSum = Root.List.Model.models[0].attributes.sum; } return Root.List.View.render(); } }); }); Root.Router.on('route:tocontent', function(id) { $('.wrap>h2>a').show(); if (id != null) { return $.ajax({ url: path + '/ajax/employ/employ.php', data: { type: 'fetch', id: id }, dataType: 'json', type: 'get', success: function(result) { if (result.id != null) { result.type = 'edit'; Root.Content.Model.set(result); return Root.Content.View.render(); } } }); } else { Root.Content.Model.clear(); Root.Content.Model.set({ type: 'add', description: '' }); return Root.Content.View.render(); } }); Root.Router.on('route:delete', function(id) { var data; data = { type: 'delete', id: id }; return $.ajax({ url: path + '/ajax/employ/employ.php', data: data, dataType: 'json', type: 'get', success: function(result) { if (result.state === 'success') { return Root.Router.navigate('list/' + Root.List.Model.pageIndex, { replace: true, trigger: true }); } } }); }); Backbone.history.start(); }); }); }).call(this); <file_sep>/ajax/employ/employ.php <?php /* { id : 1, name : '<NAME>', description : 'sssssssssssss' } */ require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} switch ($_GET['type']) { case 'fetch' : $id = $_GET['id']; /*========== you code below ==========*/ if ($id) { $data = get_post($id); if ($data) { $employ = json_decode($data->post_content); if ($employ) { $employ->id = $data->ID; $employ->name = $data->post_title; echo json_encode($employ); exit; } } } $employ = new obj; $employ->state = "failed"; /*========== you code above ==========*/ echo json_encode($employ); break; case 'add' : $sec_type = $_GET['sec_type']; $result = new obj; if ($sec_type) { $employ = new obj; $title = $_GET['name']; $employ->img = $_GET['img']; $employ->desc = $_GET['desc']; $employ->description = str_replace("\n",'<br>',$_GET['description']); $aemploy = array( 'post_title' => $title, 'post_content' => json_encode($employ,JSON_UNESCAPED_UNICODE), 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array($sec_type) ); $result->id = wp_insert_post( $aemploy ); $result->state = 'success'; echo json_encode($result); exit; } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'edit' : $sec_type = $_GET['sec_type']; $id = $_GET['id']; $result = new obj; if ( $sec_type && $id) { $employ = new obj; $title = $_GET['name']; $employ->img = $_GET['img']; $employ->desc = $_GET['desc']; $employ->description = str_replace("\n",'<br>',$_GET['description']); $aemploy = array( 'ID' => $id, 'post_title' => $title, 'post_content' => json_encode($employ,JSON_UNESCAPED_UNICODE), ); $result->id = wp_update_post( $aemploy ); $result->state = 'success'; echo json_encode($result); exit; } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'delete' : $id = $_GET['id']; /*========== you code below ==========*/ $result = new obj; if (/* delete exam whose id is */$id/* in database successfully */) { if(wp_delete_post($id,true)) { $result->state = 'success'; echo json_encode($result); exit; } } $result->state = /*point out what is */'failed'; /*========== you code above ==========*/ echo json_encode($result); break; default : echo '{"state":"where is type"}'; } ?><file_sep>/ajax/employ/get-some-employ.php <?php /* it's a json array format [ { id : 1, title : 'this is a title', hot : 1000, update : '2014.12.20' },... ] */ require(dirname(__FILE__).'/../../../../../wp-load.php'); define(MAX_NUMBER_OF_EMPLOY_IN_A_PAGE,25); //set default velue if they have no value in _GET $page_index = $_GET['page_pos']?$_GET['page_pos']:0; $sec_type = $_GET['sec_type']; $employs = array(); if ($sec_type) { $args = array( 'numberposts' => MAX_NUMBER_OF_EMPLOY_IN_A_PAGE, 'offset' => $page_index*MAX_NUMBER_OF_EMPLOY_IN_A_PAGE, 'category' => $sec_type, 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true ); $employ_list = get_posts($args); if ($employ_list) { for ($i=0;$i<count($employ_list);$i++) { $employ = json_decode($employ_list[$i]->post_content); $employ->id = $employ_list[$i]->ID; $employ->name = $employ_list[$i]->post_title; array_push($employs,$employ); } } if ($page_index == 0) { $tmp = get_category($sec_type); if ($tmp && $tmp->count>0) { $employs[0]->sum = ceil($tmp->count/MAX_NUMBER_OF_EMPLOY_IN_A_PAGE); } } } echo json_encode($employs); ?><file_sep>/activity.php <div class="wrap"> <h2>最新活动<a href="#" class="add-new-h2">列表</a></h2> <div id="dashboard-widgets-wrap"></div> <?php include 'content-editor-preloader.php' ?> </div> <div class="clear"></div> <script type="text/javascript"> var moduleName = 'activity'; var extraCss =['showLoading/showLoading.css']; </script> <?php include 'js-config.php' ?> <?php <file_sep>/ajax/course/class.php <?php /* { id : 1, name : 'class-name', time : '100 hour', num : 20, max : 50, fea : '100$' detail : 'this is a class ......................................' } */ require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} switch ($_GET['type']) { case 'fetch' : $id = $_GET['id']; /*========== you code below ==========*/ if ($id) { $data = get_post($id); if ($data) { $class = json_decode($data->post_content); if ($class) { $class->id = $data->ID; $class->name = $data->post_title; echo json_encode($class); exit; } } } $class = new obj; $class->state = "failed"; /*========== you code above ==========*/ echo json_encode($class); break; case 'add' : $sec_type = $_GET['sec_type']; $result = new obj; if ($sec_type) { $class = new obj; $title = $_GET['name']; $class->time = $_GET['time']; $class->max = $_GET['max']; $class->fea = $_GET['fea']; $class->description = str_replace("\n",'<br>',$_GET['description']); $aclass = array( 'post_title' => $title, 'post_content' => json_encode($class,JSON_UNESCAPED_UNICODE), 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array($sec_type) ); $result->id = wp_insert_post( $aclass ); $result->state = 'success'; echo json_encode($result); exit; } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'edit' : $sec_type = $_GET['sec_type']; $id = $_GET['id']; $result = new obj; if ( $sec_type && $id) { $class = new obj; $class->name = $_GET['name']; $title = $_GET['name']; $class->time = $_GET['time']; $class->max = $_GET['max']; $class->fea = $_GET['fea']; $class->description = str_replace("\n",'<br>',$_GET['description']); $aclass = array( 'ID' => $id, 'post_title' => $title, 'post_content' => json_encode($class,JSON_UNESCAPED_UNICODE), ); $result->id = wp_update_post( $aclass ); $result->state = 'success'; echo json_encode($result); exit; } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'delete' : $id = $_GET['id']; /*========== you code below ==========*/ $result = new obj; if (/* delete exam whose id is */$id/* in database successfully */) { if(wp_delete_post($id,true)) { $result->state = 'success'; echo json_encode($result); exit; } } $result->state = /*point out what is */'failed'; /*========== you code above ==========*/ echo json_encode($result); break; default : echo '{"state":"where is type"}'; } ?><file_sep>/exam.php <?php include 'loader.php' ?> <div class="wrap"> <h2>模拟考试<a href="" class="add-new-h2">设置</a><a href="#list/0" class="add-new-h2">列表</a></h2> <div id="exam-main"> <a href="#list/0">考试时间编辑>></a> <div class="setting-wrapper"> <h4>插图(建议大小:690×350)<input type="button" id="banner_add" class="button" value="添加"></h4> <div id="setting-banner"></div> </div> <div class="setting-wrapper"> <h4>最佳学员设置(学员头像建议大小:80×80)<input type="button" id="best_add" class="button" value="添加"></h4> <div id="setting-best"></div> </div> <div class="setting-wrapper"> <h4>模拟考试介绍</h4> <div id="setting-description"></div> </div> <input type="button" id="exam-setting-submit" class="button" value="保存设置"> </div> <div id="dashboard-widgets-wrap"></div> <div id="content-enter"></div> </div> <div class="clear"></div> <?php wp_enqueue_media(); ?> <script src="<?php echo plugins_url('',__FILE__); ?>/js/jquery.form.js"></script> <script src="<?php echo plugins_url('',__FILE__); ?>/js/pickdate/picker.js"></script> <script src="<?php echo plugins_url('',__FILE__); ?>/js/pickdate/legacy.js"></script> <script src="<?php echo plugins_url('',__FILE__); ?>/js/pickdate/picker.date.js"></script> <script type="text/javascript"> var moduleName = 'exam'; var extraCss = ['showLoading/showLoading.css','pickdate/themes/default.css','pickdate/themes/default.date.css']; </script> <?php include 'js-config.php' ?> <?php <file_sep>/ajax/activity/get-some-activities.php <?php /* it's a json array format [ { id : 1, title : 'this is a title', hot : 1000, update : '2014.12.20' },... ] */ require(dirname(__FILE__).'/../../../../../wp-load.php'); define(MAX_NUMBER_OF_ACTIVITIES_IN_A_PAGE,25); //set default velue if they have no value in _GET $page_index = $_GET['page_pos']?$_GET['page_pos']:0; $args = array( 'numberposts' => MAX_NUMBER_OF_ACTIVITIES_IN_A_PAGE, 'offset' => $page_index*MAX_NUMBER_OF_ACTIVITIES_IN_A_PAGE, 'category_name' => 'activity', 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true ); $activity_list = get_posts($args); $activities = array(); if ($activity_list) { for ($i=0;$i<count($activity_list);$i++) { $activity = json_decode($activity_list[$i]->post_content); $activity->id = $activity_list[$i]->ID; $activity->name = $activity_list[$i]->post_title; array_push($activities,$activity); } } if ($page_index == 0) { $tmp = get_category(get_cat_ID('activity')); if ($tmp && $tmp->count>0) { $activities[0]->sum = ceil($tmp->count/MAX_NUMBER_OF_ACTIVITIES_IN_A_PAGE); } } echo json_encode($activities); ?><file_sep>/ajax/source/sources-issue.php <?php /* { type : [ { id : 1 title : 'listening', desc : 'this is for listening' },... ] } */ require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} $data = new obj; $args = array( 'parent' => get_cat_ID('source'), 'orderby' => 'name', 'hide_empty' => false ); $rec = get_categories($args); $data->type = array(); for ($i=0;$i<count($rec);$i++) { $element = new obj; $element->id = $rec[$i]->term_id; $element->title = urldecode($rec[$i]->slug); $element->desc = 'this is for listening'; array_push($data->type, $element); } echo json_encode($data); ?><file_sep>/content-editor-preloader.php <script src="<?php echo plugins_url('',__FILE__); ?>/js/jquery.form.js"></script> <div id="content-editor-preload" style="display:none;"> <form action="#" method="get" class="validate" id="content-form"> <div id="poststuff"> <div id="post-body" class="metabox-holder columns-2"> <div id="post-body-content"> <div id="content-enter"></div> <div class="postarea wp-editor-expand"> <?php $editor_id = 'detail'; $content = ''; $settings = array('wpautop' => true, 'media_buttons' => true, 'quicktags' => true, 'textarea_rows' => 100, 'textarea_name' => 'description' ); wp_editor( $content, $editor_id, $settings); ?> </div> </div> <div id="postbox-container-1" class="postbox-container"> <div id="side-sortables" class="meta-box-sortables ui-sortable"> <div id="submitdiv" class="postbox"> <div class="handlediv"><br></div> <h3 class="hndle"><span>deliver</span></h3> <div class="inside"> <div class="submitbox" id="submitpost"> <div id="minor-publishing"> <div id="minor-publishing-actions"> <div id="save-action"> <input type="submit" name="save" id="save-post" value="save as script" class="button"> <div class="spinner"></div> </div> <div id="preview-action"> <a href="#" class="preview button" target="wp-preview-129" id="post-preview">preview</a> </div> <div class="clear"></div> </div> <div id="misc-publishing-actions"> <div class="misc-pub-section misc-pub-post-status"> <label for="post_status">state:</label> <span class="post-status-display">script</span> <p>2 people has signed</p> <p>last edit time is ...</p> </div> </div> <div class="clear"></div> </div> <div id="major-publishing-actions"> <div id="delete-action"><a href="#" class="submitdelete deletion">move to dustbin</a></div> <div id="publishing-action"> <input type="submit" class="button button-primary button-large" value="publish"> </div> <div class="clear"></div> </div> </div> </div> </div> </div> </div> </div> </div> </form> </div><file_sep>/ajax/home/set_setting.php <?php require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} $id = $_GET['id']; if ($id) { $data = new obj; $data->id = $id; $data->banners = $_GET['banners']? $_GET['banners']:array(); $data->recent = $_GET['recent']; $args = array( 'ID' => $id, 'post_content' => json_encode($data,JSON_UNESCAPED_UNICODE), ); $id = wp_update_post( $args ); if ($id) { echo '{"result":"success"}'; exit; } } echo '{"result":"failed"}'; ?><file_sep>/uestc_lang_backend.php <?php /* Plugin Name: backend for uestc language center websites Plugin URI: http://no..... Description: this plugin can easily update or upload message for uestc language center's website Version: ver 0.0.1 Author: uestc language center Author URI: http://stillno.... License: A "Slug" license name e.g. GPL2 Copyright 2014 uestc language center (email : <EMAIL>) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ ?> <?php /*init menu*/ //remove admin bar function remove_admin_bar_links() { global $wp_admin_bar; $wp_admin_bar->remove_menu('updates'); $wp_admin_bar->remove_menu('comments'); $wp_admin_bar->remove_menu('new-content'); } //remove menus function remove_menus() { global $menu; $restricted = array( //__('Posts'), __('Pages'), __('Links'), //__('Medias'), __('Comments'), //__('Appearance'), //__('Plugins'), //__('Users'), __('Tools'), __('Settings')); $temp = json_encode($menu); end ($menu); while (prev($menu)){ $value = explode(' ', $menu[key($menu)][0]); for ($i=0;$i<count($restricted);$i++) { if(ereg('^'.$restricted[$i],$value[0])) { unset($menu[key($menu)]); } } } } //remove sub menu function remove_submenus() { global $submenu; // unset($submenu['themes.php']); //unset($submenu['plugins.php']); unset($submenu['index.php'][10]); unset($submenu['edit.php?post_type=page']); unset($submenu['index.php'][10]); // Removes 'Updates'. } //remove help and show item function hide_help() { echo'<style type="text/css">#contextual-help-link-wrap { display: none !important; } .update-nag{ display: none !important; } #footer-left, #footer-upgrade{ display: none !important; }#wp-admin-bar-wp-logo{display: none !important;}.default-header img{width:400px;}</style>'; } // function example_dashboard_widget_function() { // echo 'nothing'; // } // /*init menu*/ // // Create the function use in the action hook // function example_add_dashboard_widgets() { // wp_add_dashboard_widget('example_dashboard_widget', 'Example Dashboard Widget', 'example_dashboard_widget_function'); // } function u_add_pages() { add_menu_page('backend', '后台中心', 'manage_options', __FILE__, 'view_home'); } function view_home() { include 'main.php'; } function u_add_submenu() { add_submenu_page( 'uestc_lang_backend/uestc_lang_backend.php', 'exam', '模拟考试', 'manage_options', 'exam', 'edit_exam'); add_submenu_page( 'uestc_lang_backend/uestc_lang_backend.php', 'course', '语言课程', 'manage_options', 'course', 'edit_course'); add_submenu_page( 'uestc_lang_backend/uestc_lang_backend.php', 'source', '学习资源', 'manage_options', 'source', 'edit_source'); add_submenu_page( 'uestc_lang_backend/uestc_lang_backend.php', 'employ', '游学就业', 'manage_options', 'employ', 'edit_employ'); add_submenu_page( 'uestc_lang_backend/uestc_lang_backend.php', 'activity', '最新动态', 'manage_options', 'activity', 'edit_activity'); } // 用于显示菜单的内容,填写菜单页面的HTML代码即可 function edit_exam() { include 'exam.php'; } function edit_course() { include 'course.php'; } function edit_source() { include 'source.php'; } function edit_employ() { include 'employ.php'; } function edit_activity() { include 'activity.php'; } function init_backend() { if(!get_cat_ID('backend')) { $cat_id = wp_create_category( 'backend' ); wp_create_category('home',$cat_id); wp_create_category('exam',$cat_id); wp_create_category('exam-setting',$cat_id); $course_id = wp_create_category('course',$cat_id); $a_id = wp_create_category('a',$course_id); $b_id = wp_create_category('b',$course_id); $c_id = wp_create_category('c',$course_id); $d_id = wp_create_category('d',$course_id); $e_id = wp_create_category('e',$course_id); wp_create_category('a1',$a_id); wp_create_category('a2',$a_id); wp_create_category('a3',$a_id); wp_create_category('a4',$a_id); wp_create_category('a5',$a_id); wp_create_category('b1',$b_id); wp_create_category('b2',$b_id); wp_create_category('b3',$b_id); wp_create_category('b4',$b_id); wp_create_category('c1',$c_id); wp_create_category('c2',$c_id); wp_create_category('d1',$d_id); wp_create_category('d2',$d_id); wp_create_category('d3',$d_id); wp_create_category('d4',$d_id); wp_create_category('e1',$e_id); wp_create_category('e2',$e_id); wp_create_category('e3',$e_id); $source_id = wp_create_category('source',$cat_id); wp_create_category('f',$source_id); wp_create_category('g',$source_id); wp_create_category('h',$source_id); wp_create_category('i',$source_id); $employ_id = wp_create_category('employ',$cat_id); wp_create_category('j',$employ_id); wp_create_category('k',$employ_id); wp_create_category('l',$employ_id); wp_create_category('activity',$cat_id); } } if ( is_admin() ) { add_action('admin_menu','init_backend'); add_action('admin_menu', 'remove_menus'); add_action('admin_menu', 'remove_submenus'); add_action('admin_menu', 'u_add_pages'); add_action('admin_menu', 'u_add_submenu'); add_action('admin_head', 'hide_help'); add_action('wp_before_admin_bar_render', 'remove_admin_bar_links'); add_action('wp_dashboard_setup', 'example_add_dashboard_widgets' ); } ?> <file_sep>/ajax/source/source.php <?php /* { id : 1, name : 'what', size : '100MB', desc : 'this listening is mainly .........' } */ require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} switch ($_GET['type']) { case 'fetch' : $id = $_GET['id']; /*========== you code below ==========*/ if ($id) { $data = get_post($id); if ($data) { $source = json_decode($data->post_content); if ($source) { $source->id = $data->ID; $source->name = $data->post_title; echo json_encode($source); exit; } } } $source = new obj; $source->state = "failed"; /*========== you code above ==========*/ echo json_encode($source); break; case 'add' : $sec_type = $_GET['sec_type']; $result = new obj; if ($sec_type) { $source = new obj; $title = $_GET['name']; $source->size = $_GET['size']; $source->description = str_replace("\n",'<br>',$_GET['description']); $asource = array( 'post_title' => $title, 'post_content' => json_encode($source,JSON_UNESCAPED_UNICODE), 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array($sec_type) ); $result->id = wp_insert_post( $asource ); $result->state = 'success'; echo json_encode($result); exit; } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'edit' : $sec_type = $_GET['sec_type']; $id = $_GET['id']; $result = new obj; if ( $sec_type && $id) { $source = new obj; $title = $_GET['name']; $source->size = $_GET['size']; $source->description = str_replace("\n",'<br>',$_GET['description']); $asource = array( 'ID' => $id, 'post_title' => $title, 'post_content' => json_encode($source,JSON_UNESCAPED_UNICODE), ); $result->id = wp_update_post( $asource ); $result->state = 'success'; echo json_encode($result); exit; } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'delete' : $id = $_GET['id']; /*========== you code below ==========*/ $result = new obj; if (/* delete exam whose id is */$id/* in database successfully */) { if(wp_delete_post($id,true)) { $result->state = 'success'; echo json_encode($result); exit; } } $result->state = /*point out what is */'failed'; /*========== you code above ==========*/ echo json_encode($result); break; default : echo '{"state":"where is type"}'; } ?><file_sep>/ajax/course/get-some-classes.php <?php /* [ { id : 1, name : 'course-name', time : '100 hour', num : 20, max : 50 },... ] */ require(dirname(__FILE__).'/../../../../../wp-load.php'); define(MAX_NUMBER_OF_CLASSES_IN_A_PAGE,25); $list = array(); //set default velue if they have no value in _GET $page_index = $_GET['page_pos']?$_GET['page_pos']:0; $sec_type = $_GET['sec_type']; /*========== you code below ==========*/ if ($sec_type) { $args = array( 'numberposts' => MAX_NUMBER_OF_CLASSES_IN_A_PAGE, 'offset' => $page_index*MAX_NUMBER_OF_CLASSES_IN_A_PAGE, 'category' => $sec_type, 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true ); $class_list = get_posts($args); if ($class_list) { for ($i=0;$i<count($class_list);$i++) { $element = json_decode($class_list[$i]->post_content); $element->id = $class_list[$i]->ID; $element->name = $class_list[$i]->post_title; array_push($list,$element); } } if ($page_index == 0) { $tmp = get_category($sec_type); if ($tmp && $tmp->count>0) { $list[0]->sum = ceil($tmp->count/MAX_NUMBER_OF_CLASSES_IN_A_PAGE); } } } /*========== you code above ==========*/ echo json_encode($list); ?> <file_sep>/ajax/exam/get-exam-intro.php <?php require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} $args = array( 'numberposts' => 1, 'offset' => 0, 'category' => get_cat_ID('exam-setting'), 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true ); $setting_file = get_posts($args); $setting = null; if (!$setting_file) { $setting = new obj; $setting->banners = array(); $setting->best = array(); $setting->description = new obj; $setting->description->title = ''; $setting->description->content = ''; $new_setting = array( 'post_title' => 'setting', 'post_content' => json_encode($setting), 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(get_cat_ID('exam-setting')) ); $result = wp_insert_post( $new_setting ); if ($result) { $setting->id = $result; $uargs = array( 'ID' => $result, 'post_content' => json_encode($setting) ); $result = wp_update_post( $uargs ); echo json_encode($setting); } else { echo '{"result":"failed"}'; } } else { echo $setting_file[0]->post_content; } ?><file_sep>/ajax/course/student.php <?php /* { id : 1, name : 'myname', degree : 100, class : 'class A', img : '/img/avator.jpg', desc : 'thank you for ...' } */ require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} switch ($_GET['type']) { case 'fetch' : $id = $_GET['id']; /*========== you code below ==========*/ if ($id) { $data = get_post($id); if ($data) { $student = json_decode($data->post_content); if ($student) { $student->id = $data->ID; $student->name = $data->post_title; echo json_encode($student); exit; } } } $student = new obj; $student->state = "failed"; /*========== you code above ==========*/ echo json_encode($student); break; case 'add' : $sec_type = $_GET['sec_type']; $result = new obj; if ($sec_type) { $student = new obj; $student->img = $_GET['img']; $title = $_GET['name']; $student->degree = $_GET['degree']; $student->class = $_GET['class']; $student->feeling = $_GET['feeling']; $aclass = array( 'post_title' => $title, 'post_content' => json_encode($student,JSON_UNESCAPED_UNICODE), 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array($sec_type) ); $result->id = wp_insert_post( $aclass ); $result->state = 'success'; echo json_encode($result); exit; } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'edit' : $sec_type = $_GET['sec_type']; $id = $_GET['id']; $result = new obj; if ( $sec_type && $id) { $student = new obj; $student->img = $_GET['img']; $title = $_GET['name']; $student->degree = $_GET['degree']; $student->class = $_GET['class']; $student->feeling = $_GET['feeling']; $aclass = array( 'ID' => $id, 'post_title' => $title, 'post_content' => json_encode($student,JSON_UNESCAPED_UNICODE), ); $result->id = wp_update_post( $aclass ); if ($result->id) { $result->state = 'success'; echo json_encode($result); exit; } } $result->state = /*point out what is */'failed'; echo json_encode($result); break; case 'delete' : $id = $_GET['id']; /*========== you code below ==========*/ $result = new obj; if (/* delete exam whose id is */$id/* in database successfully */) { if(wp_delete_post($id,true)) { $result->state = 'success'; echo json_encode($result); exit; } } $result->state = /*point out what is */'failed'; /*========== you code above ==========*/ echo json_encode($result); break; default : echo '{"state":"where is type"}'; } ?><file_sep>/ajax/exam/exam.php <?php /* { id : 1, time : '2014.12.20' } */ require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} switch ($_GET['type']) { case 'fetch' : $id = $_GET['id']; /*========== you code below ==========*/ if ($id) { $data = get_post($id); if ($data) { $exam = json_decode($data->post_content); if ($exam) { $exam->id = $data->ID; echo json_encode($exam); exit; } } } $exam = new obj; $exam->state = "failed"; /*========== you code above ==========*/ echo json_encode($exam); break; case 'add' : $exam = new obj; $exam->time = $_GET['time']; /*========== you code below ==========*/ $result = new obj; $time = array( 'post_content' => json_encode($exam,JSON_UNESCAPED_UNICODE), 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(get_cat_ID('exam')) ); $result->id = wp_insert_post( $time ); if ($result->id) { $result->state = 'success'; }else{ $result->state = /*point out what is */'failed'; } /*========== you code above ==========*/ echo json_encode($result); break; case 'edit' : $id = $_GET['id']; $exam = new obj; $exam->time = $_GET['time']; /*========== you code below ==========*/ $result = new obj; $time = array( 'ID' => $id, 'post_content' => json_encode($exam,JSON_UNESCAPED_UNICODE), ); $result->id = wp_update_post( $time ); if ($result->id) { $result->state = 'success'; } else { $result->state = /*point out what is */'failed'; } /*========== you code above ==========*/ echo json_encode($result); break; case 'delete' : $id = $_GET['id']; /*========== you code below ==========*/ $result = new obj; if (/* delete exam whose id is */$id/* in database successfully */) { if(wp_delete_post($id,true)) { $result->state = 'success'; echo json_encode($result); exit; } } $result->state = /*point out what is */'failed'; /*========== you code above ==========*/ echo json_encode($result); break; default : echo '{"state":"where is type"}'; } ?><file_sep>/README.md uestc_lang_backend_plugin 电子科技大学语言中心后台网站的wordpress插件,需要配合相应的主题 <file_sep>/js/module/exam/main.js (function() { define(function(require, exports, module) { var $; $ = jQuery; $(function() { var Backbone, Content, List, Main, Router, Utils; Backbone = require('backbone'); require('base/template/exam'); Utils = require('base/module/common/utils'); List = {}; Content = {}; Main = { Models: {}, Collections: {}, Views: {} }; Main.Model = Backbone.Model.extend({ defaults: { banners: [], best: [], description: void 0 }, url: path + '/ajax/exam/get-exam-intro.php', initialize: function(m1, m2, m3) { this.mbanners = m1; this.mbest = m2; this.mdesc = m3; return this.on('change', this.pushdata); }, pushdata: function(model) { this.mbanners.reset(); this.mbest.reset(); this.mbanners.set(model.get('banners')); this.mbest.set(model.get('best')); return this.mdesc.set(model.get('description')); } }); Main.Models.Banner = Backbone.Model.extend({ defaults: { id: '', img: '', link: '' } }); Main.Models.Best = Backbone.Model.extend({ defaults: { id: '', img: '', name: '', "class": '', score: '' } }); Main.Models.Description = Backbone.Model.extend(); Main.Collections.Banner = Backbone.Collection.extend({ model: Main.Models.Banner, size: '1000*500' }); Main.Collections.Best = Backbone.Collection.extend({ model: Main.Models.Best, size: '64*64' }); List.Model = Backbone.Model.extend({ defaults: { time: '' } }); List.Collection = Backbone.Collection.extend({ model: List.Model, pageIndex: 0, pageSum: 0, url: function() { return path + '/ajax/exam/get-some-exam-messages.php?page_pos=' + this.pageIndex; } }); Main.Views.Banner = Backbone.View.extend({ template: JST['source/template/exam/banner-row.hbs'], el: $('#setting-banner'), events: { 'click .del_img': 'remove', 'change input': 'setValue' }, initialize: function() { $('#banner_add').bind('click', { model: this.model }, function(e) { return e.data.model.add(new Main.Models.Banner()); }); this.listenTo(this.model, 'add', this.addView); this.listenTo(this.model, 'remove', this.removeView); this.listenTo(this.model, 'reset', this.clearView); }, setValue: function(ele) { var cid, data, property; data = ele.currentTarget.name.split('-'); if (data.length >= 2) { property = data[0]; cid = data[1]; return this.model.get(cid).set(property, ele.currentTarget.value); } }, remove: function(ele) { var cid; cid = ele.currentTarget.id.replace('del', ''); this.model.remove(cid); }, addView: function(model, collection) { model.set({ id: model.cid }); this.$el.append(this.template(model.attributes)); Utils.initSelectImage($('#' + model.attributes.id + 'btn'), $('#' + model.attributes.id + 'url'), function(text) { return model.set({ img: text }); }); }, removeView: function(model) { $('#img-row' + model.cid).remove(); }, clearView: function() { this.$el.html(''); } }); Main.Views.Best = Backbone.View.extend({ template: JST['source/template/exam/best-row.hbs'], el: $('#setting-best'), events: { 'click .del_img': 'remove', 'change input': 'setValue' }, initialize: function() { $('#best_add').bind('click', { model: this.model }, function(e) { return e.data.model.add(new Main.Models.Best()); }); this.listenTo(this.model, 'add', this.addView); this.listenTo(this.model, 'remove', this.removeView); this.listenTo(this.model, 'reset', this.clearView); }, setValue: function(ele) { var cid, data, property; data = ele.currentTarget.name.split('-'); if (data.length >= 2) { property = data[0]; cid = data[1]; return this.model.get(cid).set(property, ele.currentTarget.value); } }, remove: function(ele) { var cid; cid = ele.currentTarget.id.replace('del', ''); this.model.remove(cid); }, addView: function(model, collection) { model.set({ id: model.cid }); this.$el.append(this.template(model.attributes)); Utils.initSelectImage($('#' + model.attributes.id + 'btn'), $('#' + model.attributes.id + 'url'), function(text) { return model.set({ img: text }); }); }, removeView: function(model) { $('#img-row' + model.cid).remove(); }, clearView: function() { this.$el.html(''); } }); Main.Views.Description = Backbone.View.extend({ template: JST['source/template/exam/description.hbs'], el: $('#setting-description'), events: { 'change input': 'setValue', 'blur textarea': 'setValue' }, initialize: function() { this.listenTo(this.model, 'change', this.render); }, setValue: function(ele) { this.model.set(ele.currentTarget.name, ele.currentTarget.value); }, render: function() { this.$el.html(''); this.$el.html(this.template(this.model.attributes)); } }); List.View = Backbone.View.extend({ template: JST['source/template/exam/list.hbs'], el: $('#dashboard-widgets-wrap'), initialize: function() {}, render: function() { var num, tmp, _i, _ref; $('#content-enter').html(''); tmp = { row: this.model.length, pageIndex: this.model.pageIndex + 1, pageSum: this.model.pageSum }; tmp.list = []; for (num = _i = 0, _ref = this.model.length; 0 <= _ref ? _i < _ref : _i > _ref; num = 0 <= _ref ? ++_i : --_i) { tmp.list.push(this.model.models[num].attributes); } this.$el.html(''); this.$el.append(this.template(tmp)); this.afterRender(); }, afterRender: function() { $('.first-page').attr('href', '#list/0'); $('.pre-page').attr('href', '#list/' + (this.model.pageIndex < 1 ? 0 : this.model.pageIndex - 1)); if (this.model.pageSum === 0) { $('.next-page').attr('href', '#list/0'); } else { $('.next-page').attr('href', '#list/' + (this.model.pageIndex >= this.model.pageSum - 1 ? this.model.pageSum - 1 : this.model.pageIndex + 1)); } return $('.last-page').attr('href', '#list/' + (this.model.length > 0 ? this.model.pageSum - 1 : 0)); } }); Content.View = Backbone.View.extend({ template: JST['source/template/exam/content.hbs'], el: $('#content-enter'), initialize: function() { this.listenTo(this.model, 'change', this.render); }, render: function() { $('#dashboard-widgets-wrap').html(''); this.$el.html(this.template(this.model.attributes)); $('#input-time').pickadate(); $('#content-form').ajaxForm({ url: path + '/ajax/exam/exam.php', dataType: 'json', type: 'get', beforeSubmit: function() { $('body').showLoading(); }, success: function(result) { if ((result != null) && result.state === 'success') { Root.Router.navigate('list/' + Root.List.Model.pageIndex, { replace: true, trigger: true }); } $('body').hideLoading(); }, error: function() { return $('body').hideLoading(); } }); } }); Root.Main = { Banners: {}, Best: {}, Description: {} }; Root.List = {}; Root.Content = {}; Root.Main.Banners.Model = new Main.Collections.Banner(); Root.Main.Best.Model = new Main.Collections.Best(); Root.Main.Description.Model = new Main.Models.Description(); Root.Main.Model = new Main.Model(Root.Main.Banners.Model, Root.Main.Best.Model, Root.Main.Description.Model); Root.List.Model = new List.Collection(); Root.Content.Model = new List.Model(); Root.Main.Banners.View = new Main.Views.Banner({ model: Root.Main.Banners.Model }); Root.Main.Best.View = new Main.Views.Best({ model: Root.Main.Best.Model }); Root.Main.Description.View = new Main.Views.Description({ model: Root.Main.Description.Model }); Root.List.View = new List.View({ model: Root.List.Model }); Root.Content.View = new Content.View({ model: Root.Content.Model }); Router = Backbone.Router.extend({ routes: { '': 'tomain', 'list/:pageindex': 'tolist', 'content(/:id)': 'tocontent', 'delete/:id': 'delete' } }); Root.Router = new Router(); Root.Router.on('route:tomain', function() { $('.wrap>h2>a').hide(); $('#exam-main').show(); $('#dashboard-widgets-wrap').hide(); $('#content-enter').hide(); Root.Main.Model.fetch({ success: function(result) { Root.Main.Description.View.render(); return $('#exam-setting-submit').bind('click', function() { $('body').showLoading(); return $.ajax({ url: path + '/ajax/exam/set-exam-intro.php', dataType: 'json', data: { id: Root.Main.Model.get('id'), banners: Root.Main.Banners.Model.toJSON(), best: Root.Main.Best.Model.toJSON(), description: Root.Main.Description.Model.toJSON() }, type: 'get', success: function(result) { $('body').hideLoading(); if (result.result === 'success') { alert('success'); } else { alert('failed'); } }, error: function() { $('body').hideLoading(); } }); }); } }); }); Root.Router.on('route:tolist', function(pageIndex) { var links; $('#exam-main').hide(); $('#dashboard-widgets-wrap').show(); $('#content-enter').hide(); $('.wrap>h2>a').eq(0).show(); links = $('.wrap>h2>a').eq(1).hide().attr('href', '#list/' + pageIndex); Root.List.Model.pageIndex = parseInt(pageIndex); return Root.List.Model.fetch({ reset: true, success: function() { if ((Root.List.Model.models[0] != null) && (Root.List.Model.models[0].attributes.sum != null)) { Root.List.Model.pageSum = Root.List.Model.models[0].attributes.sum; } return Root.List.View.render(); } }); }); Root.Router.on('route:delete', function(id) { var data; data = { type: 'delete', id: id }; return $.ajax({ url: path + '/ajax/exam/exam.php', data: data, dataType: 'json', type: 'get', success: function(result) { if (result.state === 'success') { return Root.Router.navigate('list/' + Root.List.Model.pageIndex, { replace: true, trigger: true }); } } }); }); Root.Router.on('route:tocontent', function(id) { $('#exam-main').hide(); $('#dashboard-widgets-wrap').hide(); $('#content-enter').show(); $('.wrap>h2>a').show(); if (id != null) { return $.ajax({ url: path + '/ajax/exam/exam.php', data: { type: 'fetch', id: id }, dataType: 'json', type: 'get', success: function(result) { if (result.id != null) { result.type = 'edit'; Root.Content.Model.set(result); return Root.Content.View.render(); } } }); } else { Root.Content.Model.clear(); Root.Content.Model.set({ type: 'add' }); Root.Content.View.render(); } }); return Backbone.history.start(); }); }); }).call(this); <file_sep>/js-config.php <script src="<?php echo plugins_url('',__FILE__); ?>/js/sea.js"></script> <script src="<?php echo plugins_url('',__FILE__); ?>/js/seajs-css.js"></script> <script src="<?php echo plugins_url('',__FILE__); ?>/js/showLoading/jquery.showLoading.min.js"></script> <script> var path = '<?php echo plugins_url('',__FILE__); ?>'; var Root = {}; $ = jQuery; if(moduleName) { seajs.config({ paths: { 'base': path+'/js', 'fun': path+'/js/module/'+moduleName }, alias: { 'handlebars': 'base/handlebars.runtime.min.js' } }); if (extraCss) { for (var i=0;i<extraCss.length;i++) { seajs.use('base/'+extraCss[i]); } } seajs.use('fun/main',function() { console.log('ready'); }); } </script><file_sep>/ajax/course/classes-issue.php <?php /* { toptype : [ { id : 1 title : 'abroad', sectype : [ { id : 1 title : 'yasi', update_time : '2014.12.21', desc : 'there are 3 people signing recently' },... ] },... ] } */ require(dirname(__FILE__).'/../../../../../wp-load.php'); class obj{} $data = new obj; $args = array( 'parent' => get_cat_ID('course'), 'orderby' => 'name', 'hide_empty' => false ); $rec = get_categories($args); $rec_child = array(); for ($i=0;$i<count($rec);$i++) { $targs = array( 'parent' => $rec[$i]->term_id, 'orderby' => 'name', 'hide_empty' => false ); array_push($rec_child,get_categories($targs)); } $data->toptype =array(); for ($i=0;$i<count($rec);$i++) { $element = new obj; $element->id = $rec[$i]->term_id; if ($rec[$i]->name == 'e') { $element->student = 1; } $element->title = urldecode($rec[$i]->slug); $element->sectype = array(); for ($j=0;$j<count($rec_child[$i]);$j++) { $ele = new obj; $ele->id = $rec_child[$i][$j]->term_id; $ele->title = urldecode($rec_child[$i][$j]->slug); $ele->update_time = "2014.12.21"; $ele->desc = "最近有3个学生报名"; array_push($element->sectype, $ele); } array_push($data->toptype, $element); } echo json_encode($data); ?> <file_sep>/js/module/common/utils.js (function() { define(function(require, exports, module) { var Utils; Utils = {}; Utils.initSelectImage = function(button, target, callback) { return button.click(function() { var custom_file_frame; custom_file_frame = wp.media.frames.customHeader = wp.media({ title: "上传或选择图片", library: { type: 'image' }, button: { text: "使用选中图片" }, multiple: false }); custom_file_frame.on('select', function() { var attachment; attachment = custom_file_frame.state().get('selection').first().toJSON(); target.val(attachment.url); if (callback != null) { return callback(target.val()); } }); custom_file_frame.open(); return false; }); }; return Utils; }); }).call(this); <file_sep>/main.php <div class="wrap"> <h2>首页设置</h2> <div id="dashboard-widgets-wrap"> <div class="setting-wrapper"> <h4>插图(图片建议:1120×350)<input type="button" id="banner_add" class="button" value="增加"></h4> <div id="setting-banner"></div> </div> <div class="setting-wrapper"> <h4>近期更新插图(图片建议:380×200)</h4> <div id="setting-recent"></div> </div> <input type="button" id="home-setting-submit" class="button" value="保存设置"> </div> </div> <div class="clear"></div> <?php wp_enqueue_media(); ?> <script type="text/javascript"> var moduleName = 'home'; var extraCss =['showLoading/showLoading.css']; </script> <?php include 'js-config.php' ?> <?php <file_sep>/js/module/source/main.js (function() { define(function(require, exports, module) { var $; $ = jQuery; $(function() { var Backbone, Content, List, Router, Type; Backbone = require('backbone'); require('base/template/source'); Type = {}; List = {}; Content = {}; Type.Model = Backbone.Model.extend({ defaults: { type: [{}, {}, {}, {}] }, url: path + '/ajax/source/sources-issue.php' }); List.Model = Backbone.Model.extend({ defaults: { name: '', size: '', link: '', hot: 0, upload: '', desc: '' } }); List.Collection = Backbone.Collection.extend({ model: List.Model, pageIndex: 0, pageSum: 0, sectypeid: void 0, url: function() { return path + '/ajax/source/get-some-sources.php?page_pos=' + this.pageIndex + (this.sectypeid != null ? '&sec_type=' + this.sectypeid : void 0); } }); Type.View = Backbone.View.extend({ template: JST['source/template/source/main.hbs'], el: $('#dashboard-widgets-wrap'), events: { 'click .handlediv': 'panelswitch' }, initialize: function() { this.listenTo(this.model, 'change', this.render); }, render: function() { var tmp; $('#content-editor-preload').hide(); this.$el.html(''); tmp = { lefttype: this.model.attributes.type }; this.$el.append(this.template(tmp)); }, panelswitch: function(e) { var panel; panel = $(e.currentTarget).parent(); if (panel.hasClass('closed')) { panel.removeClass('closed'); } else { panel.addClass('closed'); } } }); List.View = Backbone.View.extend({ template: JST['source/template/source/list.hbs'], el: $('#dashboard-widgets-wrap'), pageindex: 1, pagesum: 1, initialize: function() {}, render: function() { var num, tmp, _i, _ref; $('#content-editor-preload').hide(); tmp = { row: this.model.length, pageIndex: this.model.pageIndex + 1, pageSum: this.model.pageSum }; tmp.list = []; for (num = _i = 0, _ref = this.model.length; 0 <= _ref ? _i < _ref : _i > _ref; num = 0 <= _ref ? ++_i : --_i) { tmp.list.push(this.model.models[num].attributes); } this.$el.html(''); this.$el.append(this.template(tmp)); this.afterRender(); }, afterRender: function() { var prefix; prefix = '#list/sectype' + this.model.sectypeid + '/'; $('.first-page').attr('href', prefix + '0'); $('.pre-page').attr('href', prefix + (this.model.pageIndex < 1 ? 0 : this.model.pageIndex - 1)); if (this.model.pageSum === 0) { $('.next-page').attr('href', prefix + '0'); } else { $('.next-page').attr('href', prefix + (this.model.pageIndex >= this.model.pageSum - 1 ? this.model.pageSum - 1 : this.model.pageIndex + 1)); } return $('.last-page').attr('href', prefix + (this.model.length > 0 ? this.model.pageSum - 1 : 0)); } }); Content.View = Backbone.View.extend({ template: JST['source/template/source/content.hbs'], el: $('#content-enter'), initialize: function() { this.listenTo(this.model, 'change', this.render); }, render: function() { $('#dashboard-widgets-wrap').html(''); this.$el.html(this.template(this.model.attributes)); $('#content-editor-preload iframe').css('height', '500px'); $('#content-editor-preload').show(); if (this.model.get('description') != null) { tinymce.activeEditor.setContent(this.model.get('description')); } $('#content-form').ajaxForm({ url: path + '/ajax/source/source.php', dataType: 'json', type: 'get', beforeSubmit: function() { $('body').showLoading(); }, success: function(result) { if ((result != null) && result.state === 'success') { Root.Router.navigate('list/sectype' + Root.List.Model.sectypeid + '/' + Root.List.Model.pageIndex, { replace: true, trigger: true }); } $('body').hideLoading(); }, error: function() { $('body').hideLoading(); } }); } }); Root.Main = {}; Root.List = {}; Root.Content = {}; Root.Main.Model = new Type.Model(); Root.List.Model = new List.Collection(); Root.Content.Model = new List.Model(); Root.Main.View = new Type.View({ model: Root.Main.Model }); Root.List.View = new List.View({ model: Root.List.Model }); Root.Content.View = new Content.View({ model: Root.Content.Model }); Router = Backbone.Router.extend({ routes: { '': 'tomain', 'list/sectype:sectypeid/:pageindex': 'tolist', 'content(/:id)': 'tocontent', 'delete/:id': 'delete' } }); Root.Router = new Router(); Root.Router.on('route:tomain', function() { $('.wrap a').hide(); return Root.Main.Model.fetch(); }); Root.Router.on('route:tolist', function(sectypeid, pageIndex) { var links; links = $('.wrap>h2>a'); links.eq(0).show(); links.eq(1).hide(); links.eq(1).attr('href', '#list/sectype' + sectypeid + '/' + pageIndex); Root.List.Model.sectypeid = sectypeid; Root.List.Model.pageIndex = parseInt(pageIndex); return Root.List.Model.fetch({ reset: true, success: function(result) { if ((Root.List.Model.models[0] != null) && (Root.List.Model.models[0].attributes.sum != null)) { Root.List.Model.pageSum = Root.List.Model.models[0].attributes.sum; } return Root.List.View.render(); } }); }); Root.Router.on('route:tocontent', function(id) { $('.wrap a').show(); if (id != null) { return $.ajax({ url: path + '/ajax/source/source.php', data: { type: 'fetch', id: id }, dataType: 'json', type: 'get', success: function(result) { if (result.id != null) { result.type = 'edit'; result.sec_type = Root.List.Model.sectypeid; Root.Content.Model.set(result); return Root.Content.View.render(); } } }); } else { Root.Content.Model.clear(); Root.Content.Model.set({ type: 'add', sec_type: Root.List.Model.sectypeid, description: '' }); return Root.Content.View.render(); } }); Root.Router.on('route:delete', function(id) { var data; data = { type: 'delete', id: id }; return $.ajax({ url: path + '/ajax/source/source.php', data: data, dataType: 'json', type: 'get', success: function(result) { if (result.state === 'success') { return Root.Router.navigate('list/sectype' + Root.List.Model.sectypeid + '/' + Root.List.Model.pageIndex, { replace: true, trigger: true }); } } }); }); Root.Router.on('route:savecontent', function() { return Root.Content.View.render(); }); Backbone.history.start(); }); }); }).call(this);
4dc1e482df9379bb64e1ece2e994c5d65daab46c
[ "JavaScript", "Markdown", "PHP" ]
26
PHP
LeoJiaXin/uestc_lang_backend
e9df0348ad3e01d151458d4df986c3eff444d881
0c9135059c8db3f1cf5f1c16ae00b3567b1ca46f
refs/heads/main
<repo_name>OlafGarcia4/Word-Counter<file_sep>/README.md # Word Counter In this program, it takes a string and organizes them by the frequenzy they appear on from most to least, using *ctrl+D* to run after the set of strings have been added Main.java - Scans the string the user inputs - Creates a map to add the words - Prints the frequnecy e WordCount.java - Evalutes if the string has already been accounted and increases the key value of the Map DescendingCount.java - Evaluates the size of the keys and organizes them using java Comparator This code can easily be changed to read from a file or a website, alternatively it can also be used to output the top unique words in that said input method. <file_sep>/src/DescendingCount.java import java.util.Comparator; import java.util.Map; public class DescendingCount implements Comparator<Map.Entry<String, Integer>> { public int compare(final Map.Entry<String, Integer> l, final Map.Entry<String, Integer> r) { if (l.getValue() > r.getValue()) { return -1; } if (l.getValue() < r.getValue()) { return 1; } else { return 0; } } }
79cb032932e8fe91e707bc31e68d08808edc2d2d
[ "Markdown", "Java" ]
2
Markdown
OlafGarcia4/Word-Counter
7fc98b334548cbaae322633f281d2d70de7283ef
9e5e9bea75f806994bed5452efa6b981308a76f5
refs/heads/master
<file_sep>class Style < ActiveRecord::Base self.inheritance_column = :_type_disabled has_many :items def to_s "type: #{type}, name: #{name}, wholesale_price: #{wholesale_price.to_f}, retail_price: #{retail_price.to_f}" end end <file_sep>class ReportService def report(batch_id) items = Item.where(:clearance_batch_id => batch_id) File.open("reports/clearance#{Time.now.to_i}.txt", 'w') do |file| items.each do |item| file.write(item.to_s<<", "<<item.style.to_s<<"\n") end end end end<file_sep>class ItemsController < ApplicationController def show group_by = params[:group_by_var].to_s @items = group_by == "" ? Item.all : Item.all.order(group_by) end def index @new_item = Item.new @style_arr = [] Style.all.each { |style| @style_arr << [style.name, style.id] } end def add @new_item = Item.new(user_params) @new_item.save session[:items_to_clearance] ||= [] session[:items_to_clearance] << @new_item.id redirect_to index_path end def clearance clearancing_status = ClearancingService.new.process_items(session[:items_to_clearance]) session[:items_to_clearance] = nil clearance_batch = clearancing_status.clearance_batch flash[:notice],flash[:alert] = clearance_batch.create_messages(clearancing_status) redirect_to index_path end private def user_params params.require(:item).permit(:size, :color, :status, :price_sold, :sold_at, :style_id) end end <file_sep># Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Rails.application.load_tasks task :package do changed_files = `git status --porcelain`.split("\n") abort "You have local changes:\n#{changed_files.join("\n")}" unless changed_files.empty? chdir("..") do command = "zip -x take-home-challenge-next-level/tmp/cache/\\* -x take-home-challenge-next-level/.git/\\* -x take-home-challenge-next-level/RUBRIC.md -r take-home-challenge.zip take-home-challenge-next-level/*" sh command do |ok,res| raise "Problem running #{command}" unless ok end end end <file_sep>class ClearanceBatchesController < ApplicationController def index @clearance_batches = ClearanceBatch.all end def create clearancing_status = ClearancingService.new.process_file(params[:csv_batch_file].tempfile) clearance_batch = clearancing_status.clearance_batch flash[:notice],flash[:alert] = clearance_batch.create_messages(clearancing_status) redirect_to action: :index end end <file_sep>require 'rails_helper' describe Item do describe "#perform_clearance!" do let(:wholesale_price) { 100 } let(:item) { FactoryGirl.create(:item, style: FactoryGirl.create(:style, wholesale_price: wholesale_price)) } before do item.clearance! item.reload end it "should mark the item status as clearanced" do expect(item.status).to eq("clearanced") end it "should set the price_sold as 75% of the wholesale_price" do expect(item.price_sold).to eq(BigDecimal.new(wholesale_price) * BigDecimal.new("0.75")) end context "wholesale_price is less than $5" do let(:wholesale_price) { 4 } let(:item2) { FactoryGirl.create(:item, style: FactoryGirl.create(:style, wholesale_price: wholesale_price, type: "Pants")) } before do item2.clearance! item2.reload end it "should set clearanced price to $5 if they get set lower than $5" do expect(item2.price_sold.to_i).to eq(5) end end context 'wholesale_price is $2' do let(:wholesale_price) { 1 } let(:item3) { FactoryGirl.create(:item, style: FactoryGirl.create(:style, wholesale_price: wholesale_price, type: "Sweater")) } before do item3.clearance! item3.reload end it "should set clearanced price to $2 if if it's lower than $2" do expect(item3.price_sold.to_i).to eq(2) end end end end <file_sep>source "https://rubygems.org" gem "rails", "4.1.1" gem "sqlite3" gem "sass-rails", "~> 4.0.3" gem "uglifier", ">= 1.3.0" gem "coffee-rails", "~> 4.0.0" gem "jquery-rails" gem "bootstrap-sass", "~> 3.2.0" gem "sdoc", "~> 0.4.0", group: :doc group :test, :development do gem "spring" gem "rspec-rails" gem "factory_girl_rails" gem "capybara" gem "database_cleaner", git: "<EMAIL>:bmabey/database_cleaner.git" gem "ruby_css_lint" gem "selenium-webdriver" end <file_sep>class ClearanceBatch < ActiveRecord::Base has_many :items def create_messages(clearancing_status) alert_messages = [] flash_notice = nil if self.persisted? flash_notice = "#{items.count} items clearanced in batch #{id}" else alert_messages << "No new clearance batch was added" end if clearancing_status.errors.any? alert_messages << "#{clearancing_status.errors.count} item ids raised errors and were not clearanced" clearancing_status.errors.each {|error| alert_messages << error } end flash_alert = alert_messages.join("<br/>") if alert_messages.any? [flash_notice,flash_alert] end end <file_sep>class Item < ActiveRecord::Base CLEARANCE_PRICE_PERCENTAGE = BigDecimal.new("0.75") belongs_to :style belongs_to :clearance_batch validates :size, :color, presence: true scope :sellable, -> { where(status: 'sellable') } before_save :fix_price def clearance! update_attributes!(status: 'clearanced', price_sold: style.wholesale_price * CLEARANCE_PRICE_PERCENTAGE) end def to_s "id: #{id}, clearance_batch_id: #{clearance_batch_id}, size: #{size}, color: #{color}, status: #{status}, price_sold: #{price_sold}, sold_at: #{sold_at}" end private def fix_price if status == 'clearanced' if (price_sold.to_i < 5) && (["Pants", "Dress"].include? style.type) update_attributes!(price_sold: 5) elsif price_sold.to_i < 2 update_attributes!(price_sold: 2) end end end end <file_sep># Problem testing master branch We need to clearance inventory from time to time. Certain items don't sell through to our clients, so every month, we collect certain unsold items and sell them to a third party vendor for a portion of their wholesale price. This repository is a bare-bones application that meets that need, but it's in need of some enhancements, which we'd like you provide. # Vocabulary _Items_ refer to individual pieces of clothing. So, if we have two of the exact same type of jeans, we have two items. Items are grouped by _style_, so the two aforementioned items would have the same style. Important data about an item is: * size * color * status - sellable, not sellable, sold, clearanced * price sold * date sold A style's important data is: * wholesale price * retail price * type - pants, shirts, dresses, skirts, other * name The _users_ of this application are warehouse employees (not developers). They have a solid understanding the business process they must carry out and look to our software to support them. # Requirements This application currently handles the clearance task in a very basic way. A spreadsheet containing a list of item ids is uploaded and those items are clearanced as a batch. Items can only be sold at clearance if their status is 'sellable'. When the item is clearanced, we sell it at 75% of the wholesale price, and record that as "price sold". You should be able to play around with the app by uploading the CSV file in this repository against the database in `db/development.sqlite3` to see how it currently works. We'd like you to make some improvements, specifically: - We're selling some items for less than we'd like, so we want to set a minimum price for items whose clearance discount is too low. For pants and dresses, ensure they don't sell for less than $5. For all other items the minimum price is $2. - The vendor buying the items on clearance needs to know what they've just purchased, so please provide a report for each batch about what items were clearanced. - Users should be able to browse items and see them grouped by status or by batch. - Finally, we'd like to avoid requiring that users create a spreadsheet and upload it, and instead handle this process directly in the app. Since they can scan an item's barcode into any text field (as if typed directly by a keyboard), we'd like to try allowing them to create batches and clearancing them simply by entering item IDs. We'd want to support both methods of clearancing batches for the time being. You can assume the barcode scanner works just like a computer keyboard, so if your solution works by entering text with a keyboard, it will be fine for the purposes described here, i.e. don't worry about barcodes. # Tech Specs: - Rails 4.1 - Ruby 2.1 - SQLite preferred, Postgres OK - Anything can be changed if you think it's needed, including database schema, Rails config, whatever # Some other guidance * DO NOT HESITATE TO REFACTOR where appropriate * If you need to make an assumption about a vague requirement, feel free, just state what it is. <file_sep>Rails.application.routes.draw do get 'items/show' post 'items/show' get 'items/index' post 'items/index' match 'items/add' => "items#add", via: :post match 'items/index' => "items#index", :as => :index, via: [:get, :post] match 'items/clearance' => "items#clearance", :as => :clearance, via: [:get, :post] match 'items/show' => "items#show", :as => :items_listing, via: [:get, :post] resources :clearance_batches, only: [:index, :create] root to: "clearance_batches#index" end
07b40e64b8e72eb6e3bfa625d92391a102ff89ae
[ "Markdown", "Ruby" ]
11
Ruby
chadwickdonald/stitchfix-take-home-challenge
6eebdbaf4e33017802133fd0b51e20a465bd3641
fc71180d188eed2f1e43df1b4c68795a34505185
refs/heads/master
<repo_name>hunterwb/no-constructors<file_sep>/noconstructors-javac-maven-example/src/main/java/Example.java import com.hunterwb.noconstructors.NoConstructors; @NoConstructors public class Example {}<file_sep>/noconstructors-bytebuddy-gradle-example/src/main/java/Example2.java public class Example2 {} <file_sep>/noconstructors-javac-gradle-example/build.gradle group 'com.hunterwb.noconstructors' version '0.1.0-SNAPSHOT' apply plugin: 'java' repositories { mavenLocal() } configurations { process } dependencies { implementation "com.hunterwb.noconstructors:noconstructors:${project.version}" process "com.hunterwb.noconstructors:noconstructors-javac-plugin:${project.version}" } compileJava { options.annotationProcessorPath = configurations.process options.compilerArgs.addAll(['--release', '6']) options.compilerArgs.add('-Xplugin:NoConstructorsPlugin') }<file_sep>/noconstructors-bytebuddy-gradle-example/settings.gradle rootProject.name = 'noconstructors-bytebuddy-gradle-example'<file_sep>/noconstructors-bytebuddy-plugin/src/main/java/com/hunterwb/noconstructors/bytebuddy/NoConstructorsPlugin.java package com.hunterwb.noconstructors.bytebuddy; import com.hunterwb.noconstructors.NoConstructors; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.build.Plugin; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.description.field.FieldList; import net.bytebuddy.description.method.MethodList; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.implementation.Implementation; import net.bytebuddy.jar.asm.AnnotationVisitor; import net.bytebuddy.jar.asm.ClassVisitor; import net.bytebuddy.jar.asm.MethodVisitor; import net.bytebuddy.jar.asm.Opcodes; import net.bytebuddy.pool.TypePool; import net.bytebuddy.utility.OpenedClassReader; public final class NoConstructorsPlugin implements Plugin { @Override public boolean matches(TypeDescription target) { return target.getDeclaredAnnotations().isAnnotationPresent(NoConstructors.class); } @Override public DynamicType.Builder<?> apply( DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassFileLocator classFileLocator ) { return builder.visit(new AsmVisitorWrapper.AbstractBase() { @Override public ClassVisitor wrap( TypeDescription instrumentedType, ClassVisitor classVisitor, Implementation.Context implementationContext, TypePool typePool, FieldList<FieldDescription.InDefinedShape> fields, MethodList<?> methods, int writerFlags, int readerFlags ) { return new ClassVisitor(OpenedClassReader.ASM_API, classVisitor) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access | Opcodes.ACC_FINAL, name, signature, superName, interfaces); } @Override public AnnotationVisitor visitAnnotation( String descriptor, boolean visible ) { return "Lcom/hunterwb/noconstructors/NoConstructors;".equals(descriptor) ? null : super.visitAnnotation(descriptor, visible); } @Override public MethodVisitor visitMethod( int access, String name, String descriptor, String signature, String[] exceptions ) { return "<init>".equals(name) ? null : super.visitMethod(access, name, descriptor, signature, exceptions); } }; } }); } @Override public void close() {} } <file_sep>/noconstructors-javac-gradle-example/settings.gradle rootProject.name = 'noconstructors-javac-gradle-example'<file_sep>/README.md # no-constructors [![Build Status](https://img.shields.io/circleci/project/github/hunterwb/no-constructors.svg)](https://circleci.com/gh/hunterwb/no-constructors) If a class contains no constructors, a [default constructor](https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.8.9) is implicitly added ```java public class Example {} ``` ```console $ javap Example.class public class Example { public Example(); } ``` The `@NoConstructors` annotation and corresponding build plugin prevent the default constructor from being added ```java @NoConstructors public class Example {} ``` ```console $ javap Example.class public final class Example {} ```<file_sep>/noconstructors-bytebuddy-gradle-example/build.gradle group 'com.hunterwb.noconstructors' version '0.1.0-SNAPSHOT' buildscript { repositories { mavenCentral() } dependencies { classpath 'net.bytebuddy:byte-buddy-gradle-plugin:1.9.5' } } apply plugin: 'java' apply plugin: 'net.bytebuddy.byte-buddy' repositories { mavenLocal() } configurations { process } dependencies { implementation "com.hunterwb.noconstructors:noconstructors:${project.version}" process "com.hunterwb.noconstructors:noconstructors-bytebuddy-plugin:${project.version}" } compileJava { options.compilerArgs.addAll(['--release', '6']) } byteBuddy { initialization { entryPoint = 'REDEFINE' } transformation { plugin = 'com.hunterwb.noconstructors.bytebuddy.NoConstructorsPlugin' classPath = configurations.process } }
d4de308fea3797e1658d12560c2603d6315261c3
[ "Markdown", "Java", "Gradle" ]
8
Java
hunterwb/no-constructors
100650cf9754c4aa2e341b1636dde741bd532831
551a502f8900c6a86c31993eb5646a536f76b1af
refs/heads/master
<repo_name>abhiomkar/abhiomkar-next<file_sep>/README.md # abhiomkar-next ## Deploy Push changes to GitHub for deploying to prod: ``` git commit -am "changes" git push origin HEAD # deploys to prod ``` Preview deploy before pushing changes: ``` npx vercel ``` You can also deploy to prod without pushing to GitHub: ``` vercel --prod ``` <file_sep>/components/layout.js import Head from 'next/head'; import Header from './header'; const gaAnalyticsTrackCode = ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-7271166-2');`; const Layout = (props) => ( <div className='main-container'> <Head> <title><NAME></title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta charSet="utf-8" /> <link rel="icon" href="/static/favicon.ico" /> {/* <!-- Global site tag (gtag.js) - Google Analytics --> */} <script async src='https://www.googletagmanager.com/gtag/js?id=UA-7271166-2'></script> <script dangerouslySetInnerHTML={{ __html: gaAnalyticsTrackCode}} /> </Head> <Header /> <div className={`body-content ${props.fullWidth ? 'full-width' : ''}`}> {props.children} </div> </div> ); export default Layout; <file_sep>/pages/index.js import Layout from '../components/layout'; import ReactMarkdown from 'react-markdown'; const markdown = ` My name is **<NAME>**. I'm an Indian he/him living in Bangalore, India (Previously worked at New York City and Chennai). I was born in Telangana, India and studied Computer Science of Engineering at _Koneru Lakshmaiah College of Engineering_ near Vijayawada, India. Work ---- I'm currently working at Google as UX Engineer. Previously at Akamai Technologies & HCL Technologies. More details at [Linkedin](https://www.linkedin.com/in/abhiomkar). Code ---- I believe writing good code is as important as a good design. I've expertise in front-end engineering. See my work and open source contribution at [Github](https://github.com/abhiomkar). See [/projects](/projects) for my little hacks. Photography ----------- I'm a self-taught photographer specialized in Creative Candid Moments, Weddings, Portraits, Travel & Nature. I started my own venture as a part-time freelancer in creative candid wedding photography while ago. I shot weddings of various traditions all over india including simple and big fat weddings. See photo gallery at [/photography](/photography). I love to travel and explore new places, I take photos to make world look beautiful. I design & code to make the world a better place. :) `; const Home = () => ( <Layout> <section className='container' data-deploy-version-check="1"> <div className='home-container'> <ReactMarkdown children={markdown} /> </div> </section> </Layout> ); export default Home; <file_sep>/pages/debug.js const Debug = (props) => ( <pre>{JSON.stringify(props.data)}</pre> ); Debug.getInitialProps = async function (context) { return {data: context.query}; }; export default Debug; <file_sep>/pages/projects.js import Layout from '../components/layout'; const Project = (props) => ( <Layout> <div className='container project-container'> <h1 className='title'>Projects</h1> {props.projects.map((project) => { return (<ProjectCard project={project} key={project.url}></ProjectCard>); })} <a className='view-all-link' href='https://github.com/abhiomkar'> View All <span className='view-all-icon'>&#8250;</span> </a> </div> </Layout> ); const ProjectCard = (props) => ( <div className='item'> <a className='item-body' href={props.project.url}> <div className='item-name'> {props.project.name} </div> <div className='item-description'> {props.project.description} </div> </a> <div className='item-footer'> {props.project.homepage && (<a className='item-action-button' href={props.project.homepage}>Go to App</a>)} <a className='item-action-button' href={props.project.url}>Source code</a> </div> </div> ); const projectList = [{ url: 'https://github.com/abhiomkar/chessboard-io', description: 'Chessboard Multiplayer', name: 'chessboard-io', }, { url: 'https://github.com/abhiomkar/portfoliojs', description: 'jQuery plugin for your beautiful portfolio images with ' + 'horizontal scrolling', name: 'portfoliojs', homepage: 'http://portfoliojs.com/', }, { url: 'https://github.com/abhiomkar/pip-save', description: 'bringing npm like behavior to pip including init & save', name: 'pip-save', homepage: 'http://abhiomkar.github.io/pip-save/', }, { url: 'https://github.com/abhiomkar/whois-home', description: 'Get a push notification on your iPhone/Android when ' + 'someone enters or leaves your home.', name: 'whois-home', }, { url: 'https://github.com/abhiomkar/raspberrypi-mac', description: 'Setup RaspberryPi on Mac', name: 'raspberrypi-mac', }, { url: 'https://github.com/abhiomkar/save-martian', description: 'Communicate with astronaut <NAME> - The Martian ' + 'using hexadecimal system with Pathfinder. from NASA.', name: 'save-martian', homepage: 'http://abhiomkar.github.io/save-martian/', }, { url: 'https://github.com/abhiomkar/Minimality', description: 'Minimal wordpress theme for real programmers & hackers.', name: 'Minimality', }, { url: 'https://github.com/abhiomkar/good-quotes', description: 'Google Chrome Extension to replace new tab with ' + 'inspirational quotes.', name: 'good-quotes', homepage: 'http://bit.ly/chrome-good-quotes', }, { url: 'https://github.com/abhiomkar/pingpong-app', description: 'Pingpong game with Phaser.js', name: 'pingpong-app', homepage: 'http://abhiomkar.github.io/pingpong-app/', }, { url: 'https://github.com/abhiomkar/gallerly.js', description: 'Google Images like photo gallery with pure JavaScript', name: 'gallery.js', homepage: 'http://gallery-js.now.sh/', }, ]; export default () => (<Project projects={projectList} />); <file_sep>/next.config.js module.exports = { i18n: { locales: ['en-US', 'en-IN'], defaultLocale: 'en-US', }, }
c1d4202c6b9f467ff948265539671a54ffd02489
[ "Markdown", "JavaScript" ]
6
Markdown
abhiomkar/abhiomkar-next
6b0cb4b32871736fc213a5b610fca3c20cfc04ed
aabefb3d6c9d798d8912c1b0d2e8600816ffa0a2
refs/heads/master
<repo_name>h4nyu/react-state-sandbox<file_sep>/src/store.ts import { useState } from 'react' import { createContainer } from 'unstated-next' import { Map } from 'immutable' function useStoreA () { const [name, setName] = useState('') return { name, setName } } export const StoreA = createContainer(useStoreA) function useStoreB () { const [name, setName] = useState('') return { name, setName } } export const StoreB = createContainer(useStoreB) export type User = { id:string, name: string } export type Users = Map<string, User>; function useDataStore () { const [users, setUsers] = useState<Users>(Map()) const fetch = async () => { setUsers(Map({ a: { id: 'a', name: 'aa' }, b: { id: 'b', name: 'bb' } })) } return { users, fetch } } export const DataStore = createContainer(useDataStore) <file_sep>/Dockerfile FROM node:14-slim WORKDIR /srv
288ee579d04fad4773a4da9d730ac7ab5e562b40
[ "TypeScript", "Dockerfile" ]
2
TypeScript
h4nyu/react-state-sandbox
9ed1a8075e53adbcd7155efc637ac0d53566cfa0
500429dd19240079b71137964e779679d0ba0084
refs/heads/master
<file_sep>const router = require('express').Router() const { getSavedTodos, createTodo, updateTodo, getMovies, getGames, getTv, getBooks} = require('../../controllers/todo-controller') router .route('/') .get(getSavedTodos) .post(createTodo) // .put(updateTodo) router .route('/movies') .get(getMovies) router .route('/games') .get(getGames) router .route('/tv') .get(getTv) router .route('/books') .get(getBooks) router .route('/update/') .put(updateTodo) module.exports = router<file_sep>const { Todos } = require('../models') // route or retrieving todos const getSavedTodos = (req, res) => { Todos.find({}) .then(dbTodoData => res.json(dbTodoData)) .catch(err => { console.log(err); res.json(err) }) } //get movies const getMovies = (req, res) => { Todos.find({"typeTodo": "movie"}) .then(dbTodoData => res.json(dbTodoData)) .catch(err => { console.log(err); res.json(err) }) } // get games const getGames = (req, res) => { Todos.find({"typeTodo": "game"}) .then(dbTodoData => res.json(dbTodoData)) .catch(err => { console.log(err); res.json(err) }) } // get tv const getTv = (req, res) => { Todos.find({"typeTodo": "tv"}) .then(dbTodoData => res.json(dbTodoData)) .catch(err => { console.log(err); res.json(err) }) } // get books const getBooks = (req, res) => { Todos.find({"typeTodo": "book"}) .then(dbTodoData => res.json(dbTodoData)) .catch(err => { console.log(err); res.json(err) }) } // route for creating todos const createTodo = (req, res) => { Todos.create(req.body) .then(dbTodoData => res.json(dbTodoData)) .catch(err => { console.log(err); res.json(err); }) } // route for updating list items const updateTodo = async(req, res) => { if(!req.body){ return res.status(400).send({ message: "requested content is empty" }) } Todos.findByIdAndUpdate(req.body._id, { titleTodo: req.body.titleTodo, typeTodo: req.body.typeTodo, completed: req.body.completed }, {new: true}) .then(dbData => { if(!dbData){ return res.status(404).send({ message: "item not found with matching id" }) } res.send(dbData) }).catch(err => { if(err) console.log(err) }) } module.exports = { getSavedTodos, createTodo, updateTodo, getMovies, getGames, getTv, getBooks }<file_sep>const router = require('express').Router(); const todoRoutes = require('./todo-routes') router.use('/todos', todoRoutes) module.exports = router<file_sep>import React, { Component } from 'react' // import ThemeProvider from '@material-ui/styles/ThemeProvider/ThemeProvider' import Container from '@material-ui/core/Container' import MovieList from '../Components/movieList' import NavBar from '../Components/NavBar/' export class Movie extends Component { render() { return ( <React.Fragment> <Container maxWidth='sm' > <NavBar /> <h1>Movies</h1> <MovieList /> </Container> </React.Fragment> ) } } export default Movie <file_sep>const mongoose = require('mongoose') const { Schema } = mongoose; const todoSchema = new Schema ({ titleTodo: { type: String, default: "title" }, typeTodo: { type: String, default: "type" }, completed: { type: Boolean, default: false }, date: { type: Date, default: Date.now } }) const Todos = mongoose.model('todo', todoSchema) module.exports = Todos<file_sep>import axios from 'axios' export const getSavedTodos = () => { return axios.get('/') }; export const createTodo = todoData => { return axios.post('/', todoData) }; export const updateTodo = todoData => { return axios.put('/update/', todoData) }<file_sep>import React, { Component } from 'react' import Movie from './Movie' import Create from './CreateTodo' class Index extends Component { state = { category: 'movie' } render(){ const { category } = this.state switch(category){ case 'movie': return( <Movie /> ) case 'tv': return( <h1>tv</h1> ) case 'book': return( <h1>books</h1> ) case 'game': return( <h1>games</h1> ) case 'create': return( <Create /> ) default: return( <h2>this is the default</h2> ) } } } export default Index<file_sep>import React, { Component } from 'react' import Container from '@material-ui/core/Container' import SubmitForm from '../Components/SubmitForm' export class Create extends Component { render() { return ( <div> <Container maxWidth="md"> <SubmitForm /> </Container> </div> ) } } export default Create
a4541d1cdc2c62e1668046e9903f41307e73ba50
[ "JavaScript" ]
8
JavaScript
Jonahkarew/vigilant-rotary-phone
30395ce8cf984582d5dc1835abc208518c00ea61
69568dfc35ae793241c1341f97edb702712d71db
refs/heads/master
<file_sep># MSL [![Codacy Badge](https://api.codacy.com/project/badge/Grade/d8d6542435654914aa7ccdd11125ac99)](https://app.codacy.com/app/abhinavtk97/MSL?utm_source=github.com&utm_medium=referral&utm_content=abhinavtk97/MSL&utm_campaign=Badge_Grade_Dashboard) Mace Super League Live Scores and Fixtures <file_sep>package in.ac.mace.abhinavtk.mpl; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Toast; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import in.ac.mace.abhinavtk.mpl.pojo.Match; public class MatchHistory extends Activity implements MatchAdapter.OnItemClickListener { private FirebaseFirestore db = FirebaseFirestore.getInstance(); private CollectionReference matchreference = db.collection("Matches"); private MatchAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_match_history); setUpRecyclerView(); } private void setUpRecyclerView(){ Query query =matchreference.orderBy("datetime"); FirestoreRecyclerOptions<Match> options = new FirestoreRecyclerOptions.Builder<Match>() .setQuery(query,Match.class) .build(); adapter = new MatchAdapter(options); RecyclerView recyclerView = findViewById(R.id.recycler_view1); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); Log.d("firebase","setup"); adapter.setOnItemClickListener(this); } @Override protected void onStart(){ super.onStart(); adapter.startListening(); Log.d("firebase","start listen"); } @Override protected void onStop(){ super.onStop(); adapter.stopListening(); Log.d("firebase","stop listen"); } @Override public void onItemClick(DocumentSnapshot documentSnapshot, int position) { if(documentSnapshot.get("over")!=null) { if ((boolean) documentSnapshot.get("over")) { Intent intent = new Intent(MatchHistory.this, MatchDetails.class); intent.putExtra("snapshot", documentSnapshot.getId()); intent.putExtra("team1",documentSnapshot.get("team1").toString()); intent.putExtra("team2",documentSnapshot.get("team2").toString()); startActivity(intent); }else { Toast.makeText(MatchHistory.this,"Match not started",Toast.LENGTH_LONG).show(); } } } } <file_sep>package in.ac.mace.abhinavtk.mpl; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.firebase.firestore.DocumentSnapshot; import java.text.SimpleDateFormat; import in.ac.mace.abhinavtk.mpl.pojo.Match; public class MatchAdapter extends FirestoreRecyclerAdapter<Match,MatchAdapter.MatchHolder> { private OnItemClickListener listener; public MatchAdapter(@NonNull FirestoreRecyclerOptions<Match> options) { super(options); } SimpleDateFormat mydateformat = new SimpleDateFormat("d MMM yyyy",java.util.Locale.getDefault()); @Override protected void onBindViewHolder(@NonNull MatchHolder holder, int position, @NonNull Match model) { if(model.isOver()){ holder.team1goal.setText(String.valueOf(model.getTeam1goal())); holder.team2goal.setText(String.valueOf(model.getTeam2goal())); holder.team1stat.setText(model.getTeam1stat()); holder.team2stat.setText(model.getTeam2stat()); } holder.datetime.setText(mydateformat.format(model.getDatetime())); if(model.isLive()){ holder.live.setVisibility(View.VISIBLE); }else { holder.live.setVisibility(View.GONE); } int t1=0,t2=0; switch (model.getTeam1()){ case "Club De Dinkan":t1=R.drawable.dink; break; case "Bellaries FC" : t1=R.drawable.bell; break; case "Real Manavalan FC":t1=R.drawable.manav; break; case "Ponjikkara FC": t1=R.drawable.ponji; break; case "FC Marakkar":t1=R.drawable.mara; break; case "Chekuthans FC":t1=R.drawable.che;break; case "Dashamoolam FC":t1=R.drawable.dasha;break; case "Karakkambi FC":t1=R.drawable.kara;break; } switch (model.getTeam2()){ case "Club De Dinkan":t2=R.drawable.dink; break; case "Bellaries FC" : t2=R.drawable.bell; break; case "Real Manavalan FC":t2=R.drawable.manav; break; case "Ponjikkara FC": t2=R.drawable.ponji; break; case "FC Marakkar":t2=R.drawable.mara; break; case "Chekuthans FC":t2=R.drawable.che;break; case "Dashamoolam FC":t2=R.drawable.dasha;break; case "Karakkambi FC":t2=R.drawable.kara;break; } holder.team1logo.setImageResource(t1); holder.team2logo.setImageResource(t2); holder.team1name.setText(model.getTeam1().toUpperCase()); holder.team2name.setText(model.getTeam2().toUpperCase()); } @NonNull @Override public MatchHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_match,viewGroup,false); return new MatchHolder(v); } class MatchHolder extends RecyclerView.ViewHolder { TextView team1goal; TextView team2goal; TextView datetime; TextView team1stat; TextView team2stat; ProgressBar live; ImageView team1logo; ImageView team2logo; TextView team1name; TextView team2name; public MatchHolder(final View itemView){ super(itemView); team1goal = itemView.findViewById(R.id.team1goal); team2goal = itemView.findViewById(R.id.team2goal); datetime = itemView.findViewById(R.id.datetime); team1stat = itemView.findViewById(R.id.team1stat); team2stat = itemView.findViewById(R.id.team2stat); live = itemView.findViewById(R.id.live); team1logo = itemView.findViewById(R.id.team1logo); team2logo = itemView.findViewById(R.id.team2logo); team1name = itemView.findViewById(R.id.team1name); team2name = itemView.findViewById(R.id.team2name); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getAdapterPosition(); if(position!=RecyclerView.NO_POSITION && listener!=null){ listener.onItemClick(getSnapshots().getSnapshot(position),position); } } }); } } public interface OnItemClickListener{ void onItemClick(DocumentSnapshot documentSnapshot,int position); } public void setOnItemClickListener(OnItemClickListener listener){ this.listener=listener; } } <file_sep>package in.ac.mace.abhinavtk.mpl; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import in.ac.mace.abhinavtk.mpl.pojo.MatchData; public class MatchDataAdapter extends FirestoreRecyclerAdapter<MatchData,MatchDataAdapter.MatchHolder> { public MatchDataAdapter(@NonNull FirestoreRecyclerOptions<MatchData> options) { super(options); } @Override protected void onBindViewHolder(@NonNull MatchHolder holder, int position, @NonNull MatchData model) { holder.message.setText(model.getMessage()); int t1=0,t2=0; switch (model.getTeam()){ case "Club De Dinkan":t1=R.drawable.dink; break; case "Bellaries FC" : t1=R.drawable.bell; break; case "Real Manavalan FC":t1=R.drawable.manav; break; case "Ponjikkara FC": t1=R.drawable.ponji; break; case "FC Marakkar":t1=R.drawable.mara; break; case "Chekuthans FC":t1=R.drawable.che;break; case "Dashamoolam FC":t1=R.drawable.dasha;break; case "Karakkambi FC":t1=R.drawable.kara;break; } switch (model.getHeading()){ case "Red Card":t2=R.drawable.red; break; case "Yellow Card" : t2=R.drawable.yellow; break; case "Goal":t2=R.drawable.goal; break; } holder.logodata.setImageResource(t1); holder.infodata.setImageResource(t2); holder.heading.setText(model.getHeading()); holder.description.setText(model.getDescription()); } @NonNull @Override public MatchHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_data,viewGroup,false); return new MatchHolder(v); } class MatchHolder extends RecyclerView.ViewHolder { TextView heading; TextView description; TextView message; ImageView logodata; ImageView infodata; public MatchHolder(View itemView){ super(itemView); message = itemView.findViewById(R.id.team1data); heading = itemView.findViewById(R.id.heading); description = itemView.findViewById(R.id.description); logodata = itemView.findViewById(R.id.team1logodata); infodata = itemView.findViewById(R.id.team1infodata); Log.d("fir","start"); } } } <file_sep>package in.ac.mace.abhinavtk.mpl; import android.app.NotificationManager; import android.content.Context; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseMessaging extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage){ Log.d("Recived FCM", String.valueOf(remoteMessage.getData())); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,"MSLNOTI"); mBuilder.setSmallIcon(R.drawable.ic_stat_picsart_02_03_01_21_52); mBuilder.setContentTitle(remoteMessage.getData().get("head")); mBuilder.setContentText(remoteMessage.getData().get("message")); mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0,mBuilder.build()); } } <file_sep>package in.ac.mace.abhinavtk.mpl.pojo; public class StatisticData { private String name; private int number; private String team; public StatisticData(){ //empty } public StatisticData(String name, int number,String team) { this.name = name; this.number = number; this.team=team; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } } <file_sep>package in.ac.mace.abhinavtk.mpl; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import mehdi.sakout.aboutpage.AboutPage; public class About extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View aboutPage = new AboutPage(this) .isRTL(false) .setDescription("MSL Live \n For Mar Athanasius College of Engineering") .addGroup("Connect with us") .addInstagram("mace_footballteam") .addGroup("About Developer") .addEmail("<EMAIL>") .addInstagram("abhinav.tk") .addGitHub("abhinavtk97") .create(); setContentView(aboutPage); } }
cf339d6f4f363b9ac46af2686df6b142db87bef6
[ "Markdown", "Java" ]
7
Markdown
abhinavtk97/MSL
31048d8da88d7d27e0284cf7086baf5445861e7e
3657f972a3f9dcf003d16b1902490d285c996705
refs/heads/main
<file_sep>//named class // class rectangle{ // constructor(width, height){ // this.width = width // this.height = height // } // } // //unnamed class // console.log(rectangle .name) // let rectangle2 = class { // constructor(height,width){ // this.height=height // this.width=width // } // } //prototype method class rectangle { constructor(width, height){ this.width = width this.height = height } get area(){ return this.calArea() } calArea(){ return this.width*this.height } } var square = new rectangle(3,5) console.log(square.area)
c148994bbbb7f6f020532c43b0aec75cb8cc0302
[ "JavaScript" ]
1
JavaScript
duyvt7/10-days-of-JavaScript
4c5e56f296c64b4ff43652182942e9d8b5fe07fc
963082430fb66de0bafd39214569bd7d765c22bd
refs/heads/master
<repo_name>amrutsabale/portfolio-spa<file_sep>/src/components/Footer.js /* eslint-disable jsx-a11y/anchor-is-valid */ import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faLinkedin, faGithub, faTwitter, faMedium, } from "@fortawesome/free-brands-svg-icons"; const Footer = () => { return ( <div className="footer"> <div className="container"> <div className="row justify-content-center"> <div className="col-lg-6 col-md-12 col-sm-12 align-items-center my-3"> <div className="row justify-content-center"> <FontAwesomeIcon onClick={() => window.open("https://www.linkedin.com/in/amrut-sabale/") } className="footer-icon" icon={faLinkedin} size="2x" /> <FontAwesomeIcon onClick={() => window.open("https://twitter.com/amrutsabale")} className="footer-icon" icon={faTwitter} size="2x" /> <FontAwesomeIcon onClick={() => window.open("https://github.com/amrutsabale")} className="footer-icon" icon={faGithub} size="2x" /> <FontAwesomeIcon onClick={() => window.open("https://amrutsabale.medium.com/")} className="footer-icon" icon={faMedium} size="2x" /> </div> </div> </div> <div className="footer-end-text justify-content-center"> <p className="pt-3 text-center"> Year {new Date().getFullYear()}&nbsp;Amrut Sabale </p> </div> </div> </div> ); }; export default Footer; <file_sep>/src/components/Portfolio.js /* eslint-disable jsx-a11y/anchor-is-valid */ import React from "react"; import spotify from "../images/spotify-clone.png"; import covidTracker from "../images/covid-19-tracker.png"; import portfolio from "../images/portfolio.png"; import devConnector from "../images/dev-connector.png"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSearchPlus } from "@fortawesome/free-solid-svg-icons"; import { PopupboxManager, PopupboxContainer } from "react-popupbox"; import "react-popupbox/dist/react-popupbox.css"; const Portfolio = () => { // Spotify const openPopupboxSpotify = () => { const content = ( <> <div className="image-popupbox-container"> <img className="portfolio-image-popupbox" src={spotify} alt="Spotify Clone Project..." /> </div> <h6 className="my-2 font-weight-bold">Spotify-Clone</h6> <p> Basic Spotify Web App Clone build using React Context-api and Spotify Real-time API. Project fetches real user spotify account data using axios call. Build is designed using Material-UI & CSS FlexBox.Deployed using Firebase. </p> <b>Demo:</b>{" "} <a className="hyper-link" onClick={() => window.open("https://spotify-clone-d4f4c.web.app/", "_blank") } > https://spotify-clone-d4f4c.web.app/ </a> <br /> <b>GitHub:</b>{" "} <a className="hyper-link" onClick={() => window.open("https://github.com/amrutsabale/spotify-app-clone") } > https://github.com/amrutsabale/spotify-app-clone </a> </> ); PopupboxManager.open({ content }); }; // covid-19-tracker const openPopupboxCovidTracker = () => { const content = ( <> <div className="image-popupbox-container"> <img className="portfolio-image-popupbox" src={covidTracker} alt="covid-19-tracker App Project..." /> </div> <h6 className="my-2 font-weight-bold">Covid-19 Tracker</h6> <p> Covid-19 Tracker is ReactJs webapp which tracks Realtime Covid-19 cases day to day. Build uses realtime Covid-19 Cases API for open Covid Disease Data. UI is designed using CSS flexBox & Material-UI. Data is compared & displayed using ChartJS. Countries wise cases tracking is represented in Map using react-leaflet library. </p> <b>Demo:</b>{" "} <a className="hyper-link" onClick={() => window.open("https://covid-19-tracker-5f51a.web.app", "_blank") } > https://covid-19-tracker-5f51a.web.app </a> <br /> <b>GitHub:</b>{" "} <a className="hyper-link" onClick={() => window.open( "https://github.com/amrutsabale/covid-19-tracker", "_blank" ) } > https://github.com/amrutsabale/covid-19-tracker </a> </> ); PopupboxManager.open({ content }); }; // Portfolio Project const openPopupboxPortfolio = () => { const content = ( <> <div className="image-popupbox-container"> <img className="portfolio-image-popupbox" src={portfolio} alt="Portfolio Project..." /> </div> <h6 className="my-2 font-weight-bold">Portfolio-React </h6> <p> Portfolio Project implemented using React. Responsive website is designed using Bootstrap & fontawesome. Given particles effect & text typing effect to create beutiful UI using react-particles-js & react-typed libraries. Implemented full-fledge contact form which sends email notification using emailjs. </p> <b>Demo:</b>{" "} <a className="hyper-link" onClick={() => window.open("https://amrut-sabale-portfolio.web.app", "_blank") } > https://amrut-sabale-portfolio.web.app </a> <br /> <b>GitHub:</b>{" "} <a className="hyper-link" onClick={() => window.open( "https://github.com/amrutsabale/portfolio-spa", "_blank" ) } > https://github.com/amrutsabale/portfolio-spa </a> </> ); PopupboxManager.open({ content }); }; // dev-connector const openPopupboxDevConnector = () => { const content = ( <> <div className="image-popupbox-container"> <img className="portfolio-image-popupbox" src={devConnector} alt="Dev-connector React Project..." /> </div> <h6 className="my-2 font-weight-bold">Dev-Connector </h6> <p> Build an in depth full stack Social Network Application using Node.js, Express, React, Redux and MongoDB along with ES6+. </p> <b>Demo:</b>{" "} <a className="hyper-link" onClick={() => window.open("https://dev-connector-spa.herokuapp.com/", "_blank") } > https://dev-connector-spa.herokuapp.com </a> <br /> <b>GitHub:</b>{" "} <a className="hyper-link" onClick={() => window.open( "https://github.com/amrutsabale/dev-connector", "_blank" ) } > https://github.com/amrutsabale/dev-connector </a> </> ); PopupboxManager.open({ content }); }; return ( <div id="portfolio" className="portfolio-wrapper"> <div className="container"> <h1 className="text-uppercase text-center py-5">projects</h1> <div className="image-box-wrapper row justify-content-center"> <div className="portfolio-image-box" onClick={openPopupboxCovidTracker} > <img className="portfolio-image" src={covidTracker} alt="Covid-19 Tracker Project..." /> <div className="overflow"></div> <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} /> </div> <div className="portfolio-image-box" onClick={openPopupboxDevConnector} > <img className="portfolio-image" src={devConnector} alt="Dev-connector React Project..." /> <div className="overflow"></div> <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} /> </div> <div className="portfolio-image-box" onClick={openPopupboxPortfolio}> <img className="portfolio-image" src={portfolio} alt="Portfolio React and Material UI Project..." /> <div className="overflow"></div> <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} /> </div> <div className="portfolio-image-box" onClick={openPopupboxSpotify}> <img className="portfolio-image" src={spotify} alt="Spotify Clone Project..." /> <div className="overflow"></div> <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} /> </div> </div> </div> <PopupboxContainer {...{ titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 500, }} /> </div> ); }; export default Portfolio; <file_sep>/src/components/Header.js import React from "react"; import Typed from "react-typed"; import { Link } from "react-scroll"; const Header = () => { return ( <div className="header-wrapper"> <div className="main-info"> <h1><NAME></h1> <Typed className="typed-text" strings={[ "ReactJs Developer", "Frontend Software Engineer", "I Love JavaScript", ]} typeSpeed={40} backSpeed={60} loop /> <Link smooth={true} to={"contact"} href="#" className="btn-main-offer"> Contact me </Link> </div> </div> ); }; export default Header;
bfcf10740fd7418fd7fb8e1e29040d54abbad42c
[ "JavaScript" ]
3
JavaScript
amrutsabale/portfolio-spa
1e343b0b74266f00afb370f2d1559bb6ed5a5593
228a9de17c7119480d89d628962a2283ea9f550a
refs/heads/master
<repo_name>stella-h/spinning-bunny<file_sep>/scripts/script.js var stage = new PIXI.Stage(0x66FF99); var renderer = new PIXI.autoDetectRenderer(400,300); //check for webGL support, otherwise canvas document.body.appendChild(renderer.view); requestAnimFrame( animate ); var texture = PIXI.Texture.fromImage("bunny.png"); //texture from image path var bunny = new PIXI.Sprite(texture); // anchor point for sprite bunny.anchor.x = 0.5; bunny.anchor.y = 0.5; bunny.position.x = 190; bunny.position.y = 150; stage.addChild(bunny); function animate(){ requestAnimFrame( animate ); bunny.rotation += 0.1; renderer.render(stage); }
b241ccd8f1e14efdd3eb951be69c38d79ba958be
[ "JavaScript" ]
1
JavaScript
stella-h/spinning-bunny
1a591f4b1f80f568be46214522d9a86e4faf2872
70959105d8b33edbd72d8617f48d684de60afc21
refs/heads/master
<repo_name>odrevet/Chess-Wii<file_sep>/source/cui_engine.h #ifndef ENGINE_H #define ENGINE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include "engines/firstchess/core.h" #include "engines/TSCP/defs.h" #include "engines/TSCP/data.h" #include "engines/TSCP/protos.h" typedef enum E_ENGINE{ FIRSTCHESS, TSCP, GNUCHESS4 }ENGINE; /** * glu goes here * */ bool calculate_coords(char coords[5], char newcoord[5], ENGINE engine); #endif <file_sep>/source/cui_cursor.c #include "cui_cursor.h" void cui_cursor_display(cui_cursor* cursor) { int draw_index=0; if(cursor->is_grabbing){ draw_index=1; } GRRLIB_DrawImg(cursor->x, cursor->y, cursor->tex[draw_index], 1, 1, 1, 0xFFFFFFFF); } void cui_cursor_update(cui_cursor* cursor, int x, int y, int angle) { cursor->x = x; cursor->y = y; if(cursor->is_grabbing){ cursor->hotspot_x = cursor->x + 12; cursor->hotspot_y = cursor->y + 12; }else{ cursor->hotspot_x = cursor->x + 12; cursor->hotspot_y = cursor->y + 5; } cursor->angle = angle; } <file_sep>/source/cui_game.h #ifndef CUI_GAME_H #define CUI_GAME_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <stdarg.h> #include <gccore.h> #include <ogcsys.h> #include <fat.h> #include <wiiuse/wpad.h> #include <grrlib.h> #include <gcmodplay.h> #include <aesndlib.h> #include "cui_board.h" #include "cui_cursor.h" ir_t ir; AESNDPB *voice; MODPlay play; typedef struct t_cui_game{ ENGINE engine; cui_board *board; cui_cursor *cursor; GRRLIB_texImg *tex_wallpaper; //options bool is_mute; int volume_music; int volume_effects; u32 piece_color1; u32 piece_color2; }cui_game; void cui_game_update_cursor(cui_cursor* cursor); ///////////////////////////////////////////////////////// void GRRLIB_PrintfTTF2(int x, int y, GRRLIB_ttfFont *myFont, unsigned int fontSize, const u32 color, const char *string, ...); #endif <file_sep>/source/cui_tile.h #ifndef CUI_TILE_H #define CUI_TILE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <stdarg.h> #include <gccore.h> #include <ogcsys.h> typedef struct t_cui_tile{ u32 color; }cui_tile; void cui_tile_set_color(cui_tile* tile, u32 color, float delay); void cui_tile_set_color_back_to_normal(cui_tile* tile, float delay); #endif <file_sep>/source/cui_tile.c #include "cui_tile.h" void cui_tile_set_color(cui_tile* tile, u32 color, float delay) { tile->color = color; } <file_sep>/source/engines/firstchess/core.c #include "core.h" int FIRSTCHESS_piece[64] = { ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK }; int FIRSTCHESS_color[64] = { BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE }; void Gen_Push(int from, int dest, int type, MOVE * pBuf, int *pMCount) { MOVE move; move.from = from; move.dest = dest; move.type = type; pBuf[*pMCount] = move; *pMCount = *pMCount + 1; } void Gen_PushNormal(int from, int dest, MOVE * pBuf, int *pMCount) { Gen_Push(from, dest, MOVE_TYPE_NORMAL, pBuf, pMCount); } void Gen_PushPawn(int from, int dest, MOVE * pBuf, int *pMCount) { if (dest > 7 && dest < 56) Gen_Push(from, dest, MOVE_TYPE_NORMAL, pBuf, pMCount); else { Gen_Push(from, dest, MOVE_TYPE_PROMOTION_TO_QUEEN, pBuf, pMCount); Gen_Push(from, dest, MOVE_TYPE_PROMOTION_TO_ROOK, pBuf, pMCount); Gen_Push(from, dest, MOVE_TYPE_PROMOTION_TO_BISHOP, pBuf, pMCount); Gen_Push(from, dest, MOVE_TYPE_PROMOTION_TO_KNIGHT, pBuf, pMCount); } } int Gen(int current_side, MOVE * pBuf) { int i, k, y, FIRSTCHESS_ROW, FIRSTCHESS_COL, movecount; movecount = 0; for (i = 0; i < 64; i++) /* Scan all board */ if (FIRSTCHESS_color[i] == current_side) { switch (FIRSTCHESS_piece[i]) { case PAWN: FIRSTCHESS_COL = FIRSTCHESS_COL(i); FIRSTCHESS_ROW = FIRSTCHESS_ROW(i); if (current_side == BLACK) { if (FIRSTCHESS_color[i + 8] == EMPTY) Gen_PushPawn(i, i + 8, pBuf, &movecount); if (FIRSTCHESS_ROW == 1 && FIRSTCHESS_color[i + 8] == EMPTY && FIRSTCHESS_color[i + 16] == EMPTY) Gen_PushNormal(i, i + 16, pBuf, &movecount); if (FIRSTCHESS_COL && FIRSTCHESS_color[i + 7] == WHITE) Gen_PushNormal(i, i + 7, pBuf, &movecount); if (FIRSTCHESS_COL < 7 && FIRSTCHESS_color[i + 9] == WHITE) Gen_PushNormal(i, i + 9, pBuf, &movecount); } else { if (FIRSTCHESS_color[i - 8] == EMPTY) Gen_PushPawn(i, i - 8, pBuf, &movecount); if (FIRSTCHESS_ROW == 6 && FIRSTCHESS_color[i - 8] == EMPTY && FIRSTCHESS_color[i - 16] == EMPTY) Gen_PushNormal(i, i - 16, pBuf, &movecount); if (FIRSTCHESS_COL && FIRSTCHESS_color[i - 9] == BLACK) Gen_PushNormal(i, i - 9, pBuf, &movecount); if (FIRSTCHESS_COL < 7 && FIRSTCHESS_color[i - 7] == BLACK) Gen_PushNormal(i, i - 7, pBuf, &movecount); } break; case QUEEN: /* == BISHOP+ROOK */ case BISHOP: for (y = i - 9; y >= 0 && FIRSTCHESS_COL(y) != 7; y -= 9) { /* go left up */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } for (y = i - 7; y >= 0 && FIRSTCHESS_COL(y) != 0; y -= 7) { /* go right up */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } for (y = i + 9; y < 64 && FIRSTCHESS_COL(y) != 0; y += 9) { /* go right down */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } for (y = i + 7; y < 64 && FIRSTCHESS_COL(y) != 7; y += 7) { /* go right down */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } if (FIRSTCHESS_piece[i] == BISHOP) break; /* FALL THROUGH FOR QUEEN {I meant to do that!} ;-) */ case ROOK: FIRSTCHESS_COL = FIRSTCHESS_COL(i); for (k = i - FIRSTCHESS_COL, y = i - 1; y >= k; y--) { /* go left */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } for (k = i - FIRSTCHESS_COL + 7, y = i + 1; y <= k; y++) { /* go right */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } for (y = i - 8; y >= 0; y -= 8) { /* go up */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } for (y = i + 8; y < 64; y += 8) { /* go down */ if (FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); if (FIRSTCHESS_color[y] != EMPTY) break; } break; case KNIGHT: FIRSTCHESS_COL = FIRSTCHESS_COL(i); y = i - 6; if (y >= 0 && FIRSTCHESS_COL < 6 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); y = i - 10; if (y >= 0 && FIRSTCHESS_COL > 1 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); y = i - 15; if (y >= 0 && FIRSTCHESS_COL < 7 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); y = i - 17; if (y >= 0 && FIRSTCHESS_COL > 0 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); y = i + 6; if (y < 64 && FIRSTCHESS_COL > 1 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); y = i + 10; if (y < 64 && FIRSTCHESS_COL < 6 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); y = i + 15; if (y < 64 && FIRSTCHESS_COL > 0 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); y = i + 17; if (y < 64 && FIRSTCHESS_COL < 7 && FIRSTCHESS_color[y] != current_side) Gen_PushNormal(i, y, pBuf, &movecount); break; case KING: FIRSTCHESS_COL = FIRSTCHESS_COL(i); if (FIRSTCHESS_COL && FIRSTCHESS_color[i - 1] != current_side) Gen_PushNormal(i, i - 1, pBuf, &movecount); /* left */ if (FIRSTCHESS_COL < 7 && FIRSTCHESS_color[i + 1] != current_side) Gen_PushNormal(i, i + 1, pBuf, &movecount); /* right */ if (i > 7 && FIRSTCHESS_color[i - 8] != current_side) Gen_PushNormal(i, i - 8, pBuf, &movecount); /* up */ if (i < 56 && FIRSTCHESS_color[i + 8] != current_side) Gen_PushNormal(i, i + 8, pBuf, &movecount); /* down */ if (FIRSTCHESS_COL && i > 7 && FIRSTCHESS_color[i - 9] != current_side) Gen_PushNormal(i, i - 9, pBuf, &movecount); /* left up */ if (FIRSTCHESS_COL < 7 && i > 7 && FIRSTCHESS_color[i - 7] != current_side) Gen_PushNormal(i, i - 7, pBuf, &movecount); /* right up */ if (FIRSTCHESS_COL && i < 56 && FIRSTCHESS_color[i + 7] != current_side) Gen_PushNormal(i, i + 7, pBuf, &movecount); /* left down */ if (FIRSTCHESS_COL < 7 && i < 56 && FIRSTCHESS_color[i + 9] != current_side) Gen_PushNormal(i, i + 9, pBuf, &movecount); /* right down */ break; default: puts("FIRSTCHESS_piece type unknown"); assert(false); } } return movecount; } int Eval() { int value_FIRSTCHESS_piece[6] = {VALUE_PAWN, VALUE_KNIGHT, VALUE_BISHOP, VALUE_ROOK, VALUE_QUEEN, VALUE_KING}; int i, score = 0; for (i = 0; i < 64; i++) { if (FIRSTCHESS_color[i] == WHITE) score += value_FIRSTCHESS_piece[FIRSTCHESS_piece[i]]; else if (FIRSTCHESS_color[i] == BLACK) score -= value_FIRSTCHESS_piece[FIRSTCHESS_piece[i]]; } if (side == WHITE) return score; return -score; } int IsInCheck(int current_side) { int k, h, y, FIRSTCHESS_ROW, FIRSTCHESS_COL, xside; xside = (WHITE + BLACK) - current_side; /* opposite current_side, who may be checking */ /* Find King */ for (k = 0; k < 64; k++) if (FIRSTCHESS_piece[k] == KING && FIRSTCHESS_color[k] == current_side) break; FIRSTCHESS_ROW = FIRSTCHESS_ROW(k), FIRSTCHESS_COL = FIRSTCHESS_COL(k); /* Check attacking of Knight */ if (FIRSTCHESS_COL > 0 && FIRSTCHESS_ROW > 1 && FIRSTCHESS_color[k - 17] == xside && FIRSTCHESS_piece[k - 17] == KNIGHT) return 1; if (FIRSTCHESS_COL < 7 && FIRSTCHESS_ROW > 1 && FIRSTCHESS_color[k - 15] == xside && FIRSTCHESS_piece[k - 15] == KNIGHT) return 1; if (FIRSTCHESS_COL > 1 && FIRSTCHESS_ROW > 0 && FIRSTCHESS_color[k - 10] == xside && FIRSTCHESS_piece[k - 10] == KNIGHT) return 1; if (FIRSTCHESS_COL < 6 && FIRSTCHESS_ROW > 0 && FIRSTCHESS_color[k - 6] == xside && FIRSTCHESS_piece[k - 6] == KNIGHT) return 1; if (FIRSTCHESS_COL > 1 && FIRSTCHESS_ROW < 7 && FIRSTCHESS_color[k + 6] == xside && FIRSTCHESS_piece[k + 6] == KNIGHT) return 1; if (FIRSTCHESS_COL < 6 && FIRSTCHESS_ROW < 7 && FIRSTCHESS_color[k + 10] == xside && FIRSTCHESS_piece[k + 10] == KNIGHT) return 1; if (FIRSTCHESS_COL > 0 && FIRSTCHESS_ROW < 6 && FIRSTCHESS_color[k + 15] == xside && FIRSTCHESS_piece[k + 15] == KNIGHT) return 1; if (FIRSTCHESS_COL < 7 && FIRSTCHESS_ROW < 6 && FIRSTCHESS_color[k + 17] == xside && FIRSTCHESS_piece[k + 17] == KNIGHT) return 1; /* Check horizontal and vertical lines for attacking of Queen, Rook, King */ /* go down */ y = k + 8; if (y < 64) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] == EMPTY) for (y += 8; y < 64; y += 8) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } /* go left */ y = k - 1; h = k - FIRSTCHESS_COL; if (y >= h) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] == EMPTY) for (y--; y >= h; y--) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } /* go right */ y = k + 1; h = k - FIRSTCHESS_COL + 7; if (y <= h) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] == EMPTY) for (y++; y <= h; y++) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } /* go up */ y = k - 8; if (y >= 0) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] == EMPTY) for (y -= 8; y >= 0; y -= 8) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == ROOK)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } /* Check diagonal lines for attacking of Queen, Bishop, King, Pawn */ /* go right down */ y = k + 9; if (y < 64 && FIRSTCHESS_COL(y) != 0) { if (FIRSTCHESS_color[y] == xside) { if (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP) return 1; if (current_side == BLACK && FIRSTCHESS_piece[y] == PAWN) return 1; } if (FIRSTCHESS_piece[y] == EMPTY) for (y += 9; y < 64 && FIRSTCHESS_COL(y) != 0; y += 9) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } /* go left down */ y = k + 7; if (y < 64 && FIRSTCHESS_COL(y) != 7) { if (FIRSTCHESS_color[y] == xside) { if (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP) return 1; if (current_side == BLACK && FIRSTCHESS_piece[y] == PAWN) return 1; } if (FIRSTCHESS_piece[y] == EMPTY) for (y += 7; y < 64 && FIRSTCHESS_COL(y) != 7; y += 7) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } /* go left up */ y = k - 9; if (y >= 0 && FIRSTCHESS_COL(y) != 7) { if (FIRSTCHESS_color[y] == xside) { if (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP) return 1; if (current_side == WHITE && FIRSTCHESS_piece[y] == PAWN) return 1; } if (FIRSTCHESS_piece[y] == EMPTY) for (y -= 9; y >= 0 && FIRSTCHESS_COL(y) != 7; y -= 9) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } /* go right up */ y = k - 7; if (y >= 0 && FIRSTCHESS_COL(y) != 0) { if (FIRSTCHESS_color[y] == xside) { if (FIRSTCHESS_piece[y] == KING || FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP) return 1; if (current_side == WHITE && FIRSTCHESS_piece[y] == PAWN) return 1; } if (FIRSTCHESS_piece[y] == EMPTY) for (y -= 7; y >= 0 && FIRSTCHESS_COL(y) != 0; y -= 7) { if (FIRSTCHESS_color[y] == xside && (FIRSTCHESS_piece[y] == QUEEN || FIRSTCHESS_piece[y] == BISHOP)) return 1; if (FIRSTCHESS_piece[y] != EMPTY) break; } } return 0; } int MakeMove(MOVE m) { int r; hist[hdp].m = m; hist[hdp].cap = FIRSTCHESS_piece[m.dest]; FIRSTCHESS_piece[m.dest] = FIRSTCHESS_piece[m.from]; FIRSTCHESS_piece[m.from] = EMPTY; FIRSTCHESS_color[m.dest] = FIRSTCHESS_color[m.from]; FIRSTCHESS_color[m.from] = EMPTY; if (m.type >= MOVE_TYPE_PROMOTION_TO_QUEEN) { /* Promotion */ switch (m.type) { case MOVE_TYPE_PROMOTION_TO_QUEEN: FIRSTCHESS_piece[m.dest] = QUEEN; break; case MOVE_TYPE_PROMOTION_TO_ROOK: FIRSTCHESS_piece[m.dest] = ROOK; break; case MOVE_TYPE_PROMOTION_TO_BISHOP: FIRSTCHESS_piece[m.dest] = BISHOP; break; case MOVE_TYPE_PROMOTION_TO_KNIGHT: FIRSTCHESS_piece[m.dest] = KNIGHT; break; default: puts("impossible to get here..."); assert(false); } } ply++; hdp++; r = !IsInCheck(side); side = (WHITE + BLACK) - side; /* After making move, give turn to * opponent */ return r; } void TakeBack() { side = (WHITE + BLACK) - side; hdp--; ply--; FIRSTCHESS_piece[hist[hdp].m.from] = FIRSTCHESS_piece[hist[hdp].m.dest]; FIRSTCHESS_piece[hist[hdp].m.dest] = hist[hdp].cap; FIRSTCHESS_color[hist[hdp].m.from] = side; if (hist[hdp].cap != EMPTY) FIRSTCHESS_color[hist[hdp].m.dest] = (WHITE + BLACK) - side; else FIRSTCHESS_color[hist[hdp].m.dest] = EMPTY; if (hist[hdp].m.type >= MOVE_TYPE_PROMOTION_TO_QUEEN) /* Promotion */ FIRSTCHESS_piece[hist[hdp].m.from] = PAWN; } int Search(int alpha, int beta, int depth, MOVE * pBestMove) { int i, value, havemove, movecnt; MOVE moveBuf[200], tmpMove; nodes++; /* visiting a node, count it */ havemove = 0; pBestMove->type = MOVE_TYPE_NONE; movecnt = Gen(side, moveBuf); /* generate all moves for current position */ /* loop through the moves */ for (i = 0; i < movecnt; ++i) { if (!MakeMove(moveBuf[i])) { TakeBack(); continue; } havemove = 1; if (depth - 1 > 0) /* If depth is still, continue to search deeper */ value = -Search(-beta, -alpha, depth - 1, &tmpMove); else /* If no depth left (leaf node), go to evalute that position */ value = Eval(); TakeBack(); if (value > alpha) { /* This move is so good and caused a cutoff */ if (value >= beta) return beta; alpha = value; *pBestMove = moveBuf[i]; /* so far, current move is the best reaction * for current position */ } } if (!havemove) { /* If no legal moves, that is checkmate or * stalemate */ if (IsInCheck(side)) return -MATE + ply; /* add ply to find the longest path to lose or shortest path to win */ else return 0; } return alpha; } MOVE ComputerThink(int max_depth) { MOVE m; int score; /* reset some values before searching */ ply = 0; nodes = 0; /* search now */ score = Search(-MATE, MATE, max_depth, &m); /* after searching, print results */ printf("Search result: move = %c%d%c%d; nodes = %d, score = %d\n", 'a' + FIRSTCHESS_COL(m.from), 8 - FIRSTCHESS_ROW(m.from), 'a' + FIRSTCHESS_COL(m.dest), 8 - FIRSTCHESS_ROW(m.dest), nodes, score ); return m; } <file_sep>/source/egg.h #ifndef EGG_H #define EGG_H #include <stdbool.h> #include <wiiuse/wpad.h> bool egg_check_s1_code(u32 pressed, u32 released); bool egg_check_k_code(u32 pressed, u32 released); #endif <file_sep>/source/egg.c #include "egg.h" bool egg_check_s1_code(u32 pressed, u32 released) { static int valid_nb=0; if(pressed >= 0x0004 && pressed <= 0x1000){ switch (valid_nb){ case 0:if(pressed & WPAD_BUTTON_UP)valid_nb++; else valid_nb=0;break; case 1:if(pressed & WPAD_BUTTON_DOWN)valid_nb++; else valid_nb=0;break; case 2:if(pressed & WPAD_BUTTON_LEFT)valid_nb++;else valid_nb=0;break; case 3:if(pressed & WPAD_BUTTON_RIGHT)valid_nb++; else valid_nb=0;break; case 4:if(pressed & WPAD_BUTTON_B)valid_nb++; else valid_nb=0;break; case 5:if(pressed & WPAD_BUTTON_A)valid_nb++; else valid_nb=0;break; case 6:if(pressed & WPAD_BUTTON_PLUS)valid_nb++; else valid_nb=0;break; } } if(valid_nb==7){ valid_nb = 0; return true; } else return false; } bool egg_check_k_code(u32 pressed, u32 released) { static int valid_nb=0; if(pressed >= 0x0004 && pressed <= 0x1000){ switch (valid_nb){ case 0:if(pressed & WPAD_BUTTON_UP)valid_nb++; else valid_nb=0;break; case 1:if(pressed & WPAD_BUTTON_UP)valid_nb++; else valid_nb=0;break; case 2:if(pressed & WPAD_BUTTON_DOWN)valid_nb++; else valid_nb=0;break; case 3:if(pressed & WPAD_BUTTON_DOWN)valid_nb++; else valid_nb=0;break; case 4:if(pressed & WPAD_BUTTON_LEFT)valid_nb++;else valid_nb=0;break; case 5:if(pressed & WPAD_BUTTON_RIGHT)valid_nb++; else valid_nb=0;break; case 6:if(pressed & WPAD_BUTTON_LEFT)valid_nb++;else valid_nb=0;break; case 7:if(pressed & WPAD_BUTTON_RIGHT)valid_nb++; else valid_nb=0;break; case 8:if(pressed & WPAD_BUTTON_B)valid_nb++; else valid_nb=0;break; case 9:if(pressed & WPAD_BUTTON_A)valid_nb++; else valid_nb=0;break; } } if(valid_nb==10){ valid_nb = 0; return true; } else return false; } <file_sep>/source/cui_cursor.h #ifndef CUI_CURSOR #define CUI_CURSOR #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <gccore.h> #include <wiiuse/wpad.h> #include <grrlib.h> typedef struct t_cui_cursor{ GRRLIB_texImg *tex[2]; //0 is pointing, 1 is grabbing, bool is_grabbing; int x; int y; int hotspot_x; int hotspot_y; int angle; }cui_cursor; void cui_cursor_display(cui_cursor* cursor); void cui_cursor_update(cui_cursor* cursor, int x, int y, int angle); #endif <file_sep>/source/cui_game.c #include "cui_game.h" void cui_game_update_cursor(cui_cursor* cursor) { WPAD_IR(0, &ir); WPAD_ScanPads(); cui_cursor_update(cursor, ir.x, ir.y, ir.angle); } //////////////////////////////////////////////////// void GRRLIB_PrintfTTF2(int x, int y, GRRLIB_ttfFont *myFont, unsigned int fontSize, const u32 color, const char *string, ...) { if(myFont == NULL || string == NULL) return; char tmp[1024]; va_list argp; va_start(argp, string); size_t length = vsprintf(tmp, string, argp) + 1; va_end(argp); wchar_t *utf32 = (wchar_t*)malloc(length * sizeof(wchar_t)); if(utf32) { length = mbstowcs(utf32, tmp, length); if(length > 0) { utf32[length] = L'\0'; GRRLIB_PrintfTTFW(x, y, myFont, utf32, fontSize, color); } free(utf32); } } <file_sep>/source/UI/button.c #include "button.h" void UI_InitBtn(UI_button* p_button, int x, int y, char* text) { p_button->x=x; p_button->y=y; p_button->over=false; p_button->click=false; p_button->scale = 1; p_button->text_color=0X000000FF; if(text){ p_button->text = (char*)strdup(text); }else p_button->text=NULL; p_button->on_in = UI_button_on_in_default; p_button->on_out = UI_button_on_out_default; p_button->on_click = UI_button_on_click_default; p_button->hotkey = 8; } void UI_DrawBtn(UI_button* p_button) { GRRLIB_DrawImg(p_button->x, p_button->y, p_button->img, 0, p_button->scale, p_button->scale, 0xFFFFFFFF); if(p_button->text){ int txt_w = GRRLIB_WidthTTF (p_button->font, p_button->text, 16); GRRLIB_PrintfTTF (p_button->x + p_button->img->w / 2 - txt_w / 2, p_button->y + p_button->img->h / 2 - 16 / 2, p_button->font, p_button->text, 16, p_button->text_color); } } void UI_UpdateBtn(UI_button* p_button, int cursor_x, int cursor_y, int hotkey) { if(GRRLIB_PtInRect(p_button->x, p_button->y, p_button->img->w * p_button->scale, p_button->img->h * p_button->scale, cursor_x, cursor_y)){ if(hotkey == p_button->hotkey){ p_button->click=true; }else p_button->click=false; if(!p_button->over){ p_button->over = true; if(p_button->on_in){ p_button->on_in(p_button); } } } else{ if(p_button->over){ p_button->over = false; if(p_button->on_out){ p_button->on_out(p_button); } } } } void* UI_button_on_in_default(void* arg){ UI_button* p_button = (UI_button*)arg; p_button->text_color=0xFF0000FF; p_button->scale = 1.3; if(voice) AESND_PlayVoice(voice, VOICE_STEREO16, hit, hit_size, VOICE_FREQ48KHZ, 1, false); return NULL; } void* UI_button_on_out_default(void* arg){ UI_button* p_button = (UI_button*)arg; p_button->text_color=0x000000FF; p_button->scale = 1; return NULL; } void* UI_button_on_click_default(void* arg){ UI_button* p_button = (UI_button*)arg; p_button->text_color=0x00FF00FF; return NULL; } <file_sep>/source/filelist.h #ifndef _FILELIST_H_ #define _FILELIST_H_ #include <gccore.h> extern const u8 font_ttf[]; extern const u32 font_ttf_size; extern const u8 bg_music_ogg[]; extern const u32 bg_music_ogg_size; extern const u8 button_over_pcm[]; extern const u32 button_over_pcm_size; extern const u8 button_click_pcm[]; extern const u32 button_click_pcm_size; extern const u8 wall_jpg[]; extern const u32 wall_jpg_size; extern const u8 button_png[]; extern const u32 button_png_size; extern const u8 button_over_png[]; extern const u32 button_over_png_size; extern const u8 button_large_png[]; extern const u32 button_large_png_size; extern const u8 button_large_over_png[]; extern const u32 button_large_over_png_size; extern const u8 dialogue_box_png[]; extern const u32 dialogue_box_png_size; extern const u8 bg_options_png[]; extern const u32 bg_options_png_size; extern const u8 bg_options_entry_png[]; extern const u32 bg_options_entry_png_size; extern const u8 folder_png[]; extern const u32 folder_png_size; extern const u8 bg_file_selection_png[]; extern const u32 bg_file_selection_png_size; extern const u8 bg_file_selection_entry_png[]; extern const u32 bg_file_selection_entry_png_size; extern const u8 scrollbar_png[]; extern const u32 scrollbar_png_size; extern const u8 scrollbar_arrowup_png[]; extern const u32 scrollbar_arrowup_png_size; extern const u8 scrollbar_arrowup_over_png[]; extern const u32 scrollbar_arrowup_over_png_size; extern const u8 scrollbar_arrowdown_png[]; extern const u32 scrollbar_arrowdown_png_size; extern const u8 scrollbar_arrowdown_over_png[]; extern const u32 scrollbar_arrowdown_over_png_size; extern const u8 scrollbar_box_png[]; extern const u32 scrollbar_box_png_size; extern const u8 scrollbar_box_over_png[]; extern const u32 scrollbar_box_over_png_size; extern const u8 keyboard_textbox_png[]; extern const u32 keyboard_textbox_png_size; extern const u8 keyboard_key_png[]; extern const u32 keyboard_key_png_size; extern const u8 keyboard_key_over_png[]; extern const u32 keyboard_key_over_png_size; extern const u8 keyboard_mediumkey_png[]; extern const u32 keyboard_mediumkey_png_size; extern const u8 keyboard_mediumkey_over_png[]; extern const u32 keyboard_mediumkey_over_png_size; extern const u8 keyboard_largekey_png[]; extern const u32 keyboard_largekey_png_size; extern const u8 keyboard_largekey_over_png[]; extern const u32 keyboard_largekey_over_png_size; extern const u8 player1_point_png[]; extern const u32 player1_point_png_size; extern const u8 player2_point_png[]; extern const u32 player2_point_png_size; extern const u8 player1_grab_png[]; extern const u32 player1_grab_png_size; extern const u8 player2_grab_png[]; extern const u32 player2_grab_png_size; extern const u8 chess_classic_png[]; extern const u32 chess_classic_png_size; extern const u8 move_pcm[]; extern const u32 move_pcm_size; #endif <file_sep>/source/UI/button.h #ifndef UI_BUTTON #define UI_BUTTON #include <stdbool.h> #include <gccore.h> #include <ogcsys.h> #include <fat.h> #include <wiiuse/wpad.h> #include <grrlib.h> #include <grrlib/GRRLIB__inline.h> #include <gcmodplay.h> #include <aesndlib.h> #include "../cui_game.h" #include "../sounds/hit.h" typedef struct t_UI_button{ char* text; u32 text_color; GRRLIB_texImg* img; GRRLIB_ttfFont* font; int x; int y; bool over; bool click; u32 hotkey; float scale; void*(*on_in)(void*); void*(*on_out)(void*); void*(*on_click)(void*); }UI_button; void UI_InitBtn(UI_button* p_button, int x, int y, char* text); void UI_DrawBtn(UI_button* p_button); void UI_UpdateBtn(UI_button* p_button, int cursor_x, int cursor_y, int hotkey); //Callback functions by default void* UI_button_on_in_default(void* arg); void* UI_button_on_out_default(void* arg); void* UI_button_on_click_default(void* arg); #endif <file_sep>/source/cui_piece.h #ifndef CUI_PIECE_H #define CUI_PIECE_H #include <stdbool.h> typedef struct t_cui_piece{ bool color; bool display; bool is_dragged; }cui_piece; /** * Display an animation of the piece moving througt tiles * */ void cui_piece_move_to(cui_piece* piece, int from, int to); #endif <file_sep>/source/cui_board.c #include "cui_board.h" void cui_board_init(cui_board* board) { unsigned int i; unsigned int x=0, y=0; for (i = 0; i < CUI_TILE_NB; i++) { bool is_white = (x%2?false:true); if(y%2)is_white=!is_white; u32 tile_color = is_white? board->tile_color1 : board->tile_color2; cui_tile_set_color(&board->tile[i], tile_color, 3); if ((i & 7) == 7){ y++; x=0; }else x++; } } void cui_board_read_core(cui_board *board, ENGINE engine) { int i; switch(engine){ case FIRSTCHESS: { for (i=0; i < CUI_TILE_NB; i++) { if(FIRSTCHESS_piece[i] != EMPTY){ board->piece[i]=FIRSTCHESS_piece[i]; board->color[i]=FIRSTCHESS_color[i]; }else{ board->piece[i] = CUI_EMPTY; board->color[i] = CUI_EMPTY; } } } break; case TSCP: { for (i=0; i < CUI_TILE_NB; i++) { board->piece[i]=piece[i]; if(color[i] == 1){ board->color[i]=CUI_BLACK; }else if (color[i] == 6){ board->color[i]=CUI_EMPTY; }else if (color[i] == 0){ board->color[i]=CUI_WHITE; } } } break; } } void cui_board_display(cui_board *board, GRRLIB_texImg* tex_pieces, GRRLIB_texImg* tex_tile, GRRLIB_ttfFont* font, int cursor_x, int cursor_y){ unsigned int i; unsigned int x=0, y=0; int offset_x = 140; int offset_y = 80; for(i=0;i<8;i++){ char board_alpha[2] = {i + 'A'}; GRRLIB_PrintfTTF (i*40+offset_x+20, offset_y + 8*40 + 16/2, font, board_alpha, 16, 0xFFFFFFFF); } for (i = 0; i < CUI_TILE_NB; i++) { u32 tile_color; if(x == cursor_x && y == cursor_y){ tile_color = 0x223388FF; }else tile_color = board->tile[i].color; GRRLIB_DrawImg(x*40+offset_x, y*40+offset_y, tex_tile, 0, 1, 1, tile_color); if ((i & 7) == 7){ char board_num[2]; snprintf(board_num, 2, "%d", 8-y); GRRLIB_PrintfTTF (offset_x - 20, y*40+offset_y + 16/2, font, board_num, 16, 0xFFFFFFFF); y++; x=0; }else{ x++; } } x=y=0; offset_x++; offset_y = 11; for (i = 0; i < CUI_TILE_NB; i++) { if (board->piece[i] != CUI_EMPTY){ u32 piece_color = (board->color[i] == CUI_WHITE ? board->piece_color1 : board->piece_color2); GRRLIB_DrawPart(x*40+offset_x, y*40+offset_y, board->piece[i]*40, 0, 40, 100, tex_pieces, 0, 1, 1, piece_color); } if ((i & 7) == 7){ y++; x=0; }else x++; } } void cui_board_demo(cui_board *board, GRRLIB_texImg* tex_pieces, GRRLIB_texImg* tex_tile, GRRLIB_ttfFont* font){ unsigned int i; unsigned int x=0, y=0; int offset_x = 140; int offset_y = 80; srand ( time(NULL) ); for (i = 0; i < CUI_TILE_NB; i++) { u32 color1 = rand() % 0x0000FF88; u32 color2 = rand() % 0x0000FF88; bool is_white = (x%2?false:true); if(y%2)is_white=!is_white; u32 tile_color = is_white? color1 : color2; GRRLIB_DrawImg(x*40+offset_x, y*40+offset_y, tex_tile, 0, 1, 1, tile_color); if ((i & 7) == 7){ char board_num[2]; snprintf(board_num, 2, "%d", 8-y); y++; x=0; }else{ x++; } } } void cui_board_update(cui_board *p_board, char coords[5]) { //p_board->piece[64]; //p_board->color[64]; } <file_sep>/source/cui_menu.h #ifndef CUI_MENU_H #define CUI_MENU_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <stdarg.h> #include <gccore.h> #include <ogcsys.h> #include <fat.h> #include <wiiuse/wpad.h> #include <grrlib.h> #include <gcmodplay.h> #include <aesndlib.h> #include "filelist.h" #include "cui_game.h" #include "cui_engine.h" #include "cui_board.h" #include "cui_cursor.h" #include "egg.h" #include "sounds/bg_music.h" #include "sounds/warp.h" #include "UI/button.h" #include "cui_menu_option.h" typedef enum e_cui_menu{ CUI_MENU_MAIN, CUI_MENU_PLAY, CUI_MENU_OPTION, CUI_MENU_OPTION_GENERAL, CUI_MENU_OPTION_GFX, CUI_MENU_OPTION_SND, CUI_MENU_CREDITS, CUI_MENU_PAUSE, CUI_MENU_HOME, CUI_MENU_EXIT }cui_menu; cui_menu menu_main(cui_game* p_game); cui_menu menu_play(cui_game* p_game); cui_menu menu_pause(cui_game* p_game); cui_menu menu_home(cui_game* p_game); cui_menu menu_exit(cui_game* p_game); cui_menu menu_credits(cui_game* p_game); #endif <file_sep>/source/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <stdarg.h> #include <gccore.h> #include <ogcsys.h> #include <fat.h> #include <wiiuse/wpad.h> #include <grrlib.h> #include <gcmodplay.h> #include <aesndlib.h> #include "filelist.h" #include "cui_engine.h" #include "cui_board.h" #include "cui_cursor.h" #include "egg.h" #include "sounds/bg_music.h" #include "UI/button.h" #include "cui_menu.h" s8 HWButton = -1; #define BURST_SIZE 5760 #define NUM_BUFFERS 18 static void *buffers[NUM_BUFFERS]; static u8 play_buffer; static int queued; static bool active; static void aesnd_callback(AESNDPB *pb, u32 state) { if (state == VOICE_STATE_STREAM) { if (queued > 0) { AESND_SetVoiceBuffer(pb, buffers[play_buffer], BURST_SIZE); play_buffer = (play_buffer + 1) % NUM_BUFFERS; queued -= BURST_SIZE; } else { AESND_SetVoiceStop(pb, true); active = false; } } } int main(int argc, char **argv) { GRRLIB_Init(); // Initialise the attached controllers WPAD_Init(); WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR); // Initialise the audio subsystem AESND_Init(NULL); MODPlay_Init(&play); MODPlay_SetMOD(&play,bg_music); MODPlay_SetVolume(&play,63,63); MODPlay_Start(&play); cui_cursor cursor; cursor.tex[0]=GRRLIB_LoadTexture(player1_point_png); cursor.tex[1]=GRRLIB_LoadTexture(player1_grab_png); cursor.is_grabbing=false; cui_board board; ENGINE engine = FIRSTCHESS; if(engine == TSCP){ int i; for (i=0; i < CUI_TILE_NB; i++) { board.piece[i]=init_piece[i]; if(init_color[i] == 1){ board.color[i]=CUI_BLACK; }else if (init_color[i] == 6){ board.color[i]=CUI_EMPTY; }else if (init_color[i] == 0){ board.color[i]=CUI_WHITE; } } init_hash(); init_board(); open_book(); gen(); } cui_board_read_core(&board, engine); GRRLIB_SetBackgroundColour(0x030, 0x30, 0x42, 0xFF); board.tile_color1 = 0xAAAAAAFF; board.tile_color2 = 0x444444FF; board.piece_color1 = 0xAAAAAAFF; board.piece_color2 = 0x444444FF; cui_board_init(&board); cui_game game; game.board = &board; game.engine = engine; game.cursor = &cursor; game.is_mute = false; GRRLIB_texImg *tex_wallpaper = GRRLIB_LoadTexture(wall_jpg); game.tex_wallpaper = tex_wallpaper; voice = AESND_AllocateVoice(aesnd_callback); AESND_SetVoiceVolume(voice, 0xFF, 0xFF); AESND_SetVoiceStream(voice, true); cui_menu current_state = CUI_MENU_MAIN; while(current_state != CUI_MENU_EXIT) { switch(current_state){ case CUI_MENU_MAIN: current_state=menu_main(&game);break; case CUI_MENU_PLAY: current_state=menu_play(&game);break; case CUI_MENU_OPTION:current_state=menu_option(&game);break; case CUI_MENU_OPTION_GENERAL:current_state=menu_option_general(&game);break; case CUI_MENU_OPTION_GFX:current_state=menu_option_gfx(&game);break; case CUI_MENU_OPTION_SND:current_state=menu_option_snd(&game);break; case CUI_MENU_CREDITS:current_state=menu_credits(&game);break; case CUI_MENU_PAUSE:current_state=menu_pause(&game);break; case CUI_MENU_HOME:current_state=menu_home(&game);break; case CUI_MENU_EXIT:current_state=menu_exit(&game);break; default:break; } } GRRLIB_FreeTexture(tex_wallpaper); GRRLIB_FreeTexture(cursor.tex[0]); GRRLIB_FreeTexture(cursor.tex[1]); GRRLIB_Exit(); return 0; } <file_sep>/source/engines/firstchess/core.h #ifndef CORE_H #define CORE_H /* FirstChess - Freeware, by <NAME> Version: beta */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /* **************************************************************************** * Some definitions * **************************************************************************** */ #define PAWN 0 #define KNIGHT 1 #define BISHOP 2 #define ROOK 3 #define QUEEN 4 #define KING 5 #define EMPTY 6 #define WHITE 0 #define BLACK 1 #define VALUE_PAWN 100 #define VALUE_KNIGHT 300 #define VALUE_BISHOP 300 #define VALUE_ROOK 500 #define VALUE_QUEEN 900 #define VALUE_KING 10000 #define MATE 10000 /* equal value of King, losing King==mate */ #define FIRSTCHESS_COL(pos) ((pos)&7) #define FIRSTCHESS_ROW(pos) (((unsigned)pos)>>3) /* **************************************************************************** * Board representation and main varians * **************************************************************************** */ /* Board representation */ extern int FIRSTCHESS_piece[64]; extern int FIRSTCHESS_color[64]; int side; /* side to move, value = BLACK or WHITE */ /* For move generation */ #define MOVE_TYPE_NONE 0 #define MOVE_TYPE_NORMAL 1 #define MOVE_TYPE_CASTLE 2 #define MOVE_TYPE_ENPASANT 3 #define MOVE_TYPE_PROMOTION_TO_QUEEN 4 #define MOVE_TYPE_PROMOTION_TO_ROOK 5 #define MOVE_TYPE_PROMOTION_TO_BISHOP 6 #define MOVE_TYPE_PROMOTION_TO_KNIGHT 7 typedef struct tag_MOVE { int from, dest, type; } MOVE; /* For storing all moves of game */ typedef struct tag_HIST { MOVE m; int cap; } HIST; HIST hist[6000]; /* Game length < 6000 */ int hdp; /* Current move order */ /* For searching */ int nodes; /* Count all visited nodes when searching */ int ply; /* ply of search */ /* **************************************************************************** * Move generator * * Lack: no enpassant, no castle * **************************************************************************** */ void Gen_Push(int from, int dest, int type, MOVE * pBuf, int *pMCount); void Gen_PushNormal(int from, int dest, MOVE * pBuf, int *pMCount); /* Pawn can promote */ void Gen_PushPawn(int from, int dest, MOVE * pBuf, int *pMCount); /* Gen all moves of current_side to move and push them to pBuf, return number of moves */ int Gen(int current_side, MOVE * pBuf); /* **************************************************************************** * Evaluation for current position - main "brain" function * * Lack: almost no knowlegde * **************************************************************************** */ int Eval(); /* **************************************************************************** * Make and Take back a move, IsInCheck * **************************************************************************** */ /* Check and return 1 if side is in check */ int IsInCheck(int current_side); int MakeMove(MOVE m); /* undo what MakeMove did */ void TakeBack(); /* **************************************************************************** * Search function - a typical alphabeta, main search function * * Lack: no any technique for move ordering * **************************************************************************** */ int Search(int alpha, int beta, int depth, MOVE * pBestMove); MOVE ComputerThink(int max_depth); #ifdef __cplusplus } #endif #endif <file_sep>/source/cui_piece.c #include "cui_piece.h" void cui_piece_move_to(cui_piece* piece, int from, int to) { } <file_sep>/source/cui_menu_option.c #include "cui_menu_option.h" enum e_cui_menu menu_option(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; bool done=false; GRRLIB_ttfFont* font = GRRLIB_LoadTTF(font_ttf, font_ttf_size); /* UI_button button_general; UI_InitBtn(&button_general, 280, 120, "General"); button_general.img = GRRLIB_LoadTexture(button_png); button_general.font = font; */ UI_button button_graphics; UI_InitBtn(&button_graphics, 280, 200, "Graphics"); button_graphics.img = GRRLIB_LoadTexture(button_png); button_graphics.font = font; UI_button button_sounds; UI_InitBtn(&button_sounds, 280, 280, "Sounds"); button_sounds.img = GRRLIB_LoadTexture(button_png); button_sounds.font = font; UI_button button_return; UI_InitBtn(&button_return, 400, 400, "Return"); button_return.img = GRRLIB_LoadTexture(button_png); button_return.font = font; while(!done){ cui_game_update_cursor(p_game->cursor); u32 pressed = WPAD_ButtonsDown(0); //UI_UpdateBtn(&button_general, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_graphics, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_sounds, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_return, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); /*if(button_general.click){ done=true; next_state=CUI_MENU_OPTION_GENERAL; }*/ if(button_graphics.click){ done=true; next_state=CUI_MENU_OPTION_GFX; } if(button_sounds.click){ done=true; next_state=CUI_MENU_OPTION_SND; } if(button_return.click){ done=true; next_state=CUI_MENU_MAIN; } if ( pressed & WPAD_BUTTON_HOME ){ if(!p_game->is_mute)AESND_Pause(true); if(menu_home(p_game) == CUI_MENU_EXIT){done=true;next_state=CUI_MENU_EXIT;} if(!p_game->is_mute)AESND_Pause(false); } //UI_DrawBtn(&button_general); UI_DrawBtn(&button_graphics); UI_DrawBtn(&button_sounds); UI_DrawBtn(&button_return); cui_cursor_display(p_game->cursor); GRRLIB_Render(); } GRRLIB_FreeTexture(button_graphics.img);free(button_graphics.text); GRRLIB_FreeTexture(button_sounds.img);free(button_sounds.text); GRRLIB_FreeTexture(button_return.img);free(button_return.text); GRRLIB_FreeTTF(font); //GRRLIB_F(font); return next_state; } enum e_cui_menu menu_option_gfx(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; bool done=false; u32 option_tile_color_1 = p_game->board->tile_color1; u32 option_tile_color_2 = p_game->board->tile_color2; u32 option_piece_color_1 = p_game->board->piece_color1; u32 option_piece_color_2 = p_game->board->piece_color2; GRRLIB_texImg *tex_tile = GRRLIB_LoadTexture(keyboard_key_png); GRRLIB_texImg *tex_pieces = GRRLIB_LoadTexture(chess_classic_png); GRRLIB_texImg *tex_up = GRRLIB_LoadTexture(scrollbar_arrowup_png); GRRLIB_texImg *tex_down = GRRLIB_LoadTexture(scrollbar_arrowdown_png); GRRLIB_ttfFont* font = GRRLIB_LoadTTF(font_ttf, font_ttf_size); int i,j; UI_button button_color[4][8]; //tile 1, tile 2, piece 1, piece 2 | R-+, G-+, B-+, A-+, for(i=0;i<4;i++){ for(j=0;j<8;j++){ UI_InitBtn(&button_color[i][j], 120 + j*64, 64 + i*80, NULL); button_color[i][j].img = j%2==0?tex_down:tex_up; } } UI_button button_return; UI_InitBtn(&button_return, 500, 400, "apply"); button_return.img = GRRLIB_LoadTexture(button_png); button_return.font = font; UI_button button_cancel; UI_InitBtn(&button_cancel, 350, 400, "cancel"); button_cancel.img = GRRLIB_LoadTexture(button_png); button_cancel.font = font; while(!done){ cui_game_update_cursor(p_game->cursor); u32 pressed = WPAD_ButtonsDown(0); u32* color_to_modify=NULL; u32 mask; for(i=0;i<4;i++){ for(j=0;j<8;j++){ UI_UpdateBtn(&button_color[i][j], p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); if(button_color[i][j].click){ switch(i){ case 0:color_to_modify = &option_tile_color_1;break; case 1:color_to_modify = &option_tile_color_2;break; case 2:color_to_modify = &option_piece_color_1;break; case 3:color_to_modify = &option_piece_color_2;break; } if(j==0 || j==1)mask=0x06000000; if(j==2 || j==3)mask=0x00060000; if(j==4 || j==5)mask=0x00000600; if(j==6 || j==7)mask=0x00000006; *color_to_modify+=j%2==0?-mask:mask; } } } UI_UpdateBtn(&button_cancel, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_return, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); if(button_return.click){ if((option_tile_color_1 != p_game->board->tile_color1) || (option_tile_color_2 != p_game->board->tile_color2)){ p_game->board->tile_color1 = option_tile_color_1; p_game->board->tile_color2 = option_tile_color_2; cui_board_init(p_game->board); } if(option_tile_color_1 != p_game->board->piece_color1)p_game->board->piece_color1=option_piece_color_1; if(option_tile_color_2 != p_game->board->piece_color2)p_game->board->piece_color2=option_piece_color_2; done=true; next_state=CUI_MENU_MAIN; } if(button_cancel.click){ done=true; next_state=CUI_MENU_MAIN; } if ( pressed & WPAD_BUTTON_HOME ){ if(!p_game->is_mute)AESND_Pause(true); if(menu_home(p_game) == CUI_MENU_EXIT){done=true;next_state=CUI_MENU_EXIT;} if(!p_game->is_mute)AESND_Pause(false); } GRRLIB_DrawImg(380, 80+140, tex_tile, 0, 2, 2, option_tile_color_1); GRRLIB_DrawImg(380, 180+140, tex_tile, 0, 2, 2, option_tile_color_2); GRRLIB_DrawImg(380+80, 80+140, tex_tile, 0, 2, 2, option_tile_color_2); GRRLIB_DrawImg(380+80, 180+140, tex_tile, 0, 2, 2, option_tile_color_1); GRRLIB_DrawImg(380+160, 80+140, tex_tile, 0, 2, 2, option_tile_color_1); GRRLIB_DrawImg(380+160, 180+140, tex_tile, 0, 2, 2, option_tile_color_2); GRRLIB_DrawImg(380, 80, tex_pieces, 0, 2, 2, option_piece_color_2); GRRLIB_DrawImg(380, 180, tex_pieces, 0, 2, 2, option_piece_color_1); GRRLIB_PrintfTTF (145, 0, font, "RED GREEN BLUE ALPHA", 20, 0xFFFFFFFF); GRRLIB_PrintfTTF (15, 40, font, "Tiles color #1", 20, 0xFFFFFFFF); GRRLIB_PrintfTTF (15, 40+80, font, "Tiles color #2", 20, 0xFFFFFFFF); GRRLIB_PrintfTTF (15, 40+80*2, font, "Pieces color #1", 20, 0xFFFFFFFF); GRRLIB_PrintfTTF (15, 40+80*3, font, "Pieces color #2", 20, 0xFFFFFFFF); for(i=0;i<4;i++){ for(j=0;j<8;j++){ UI_DrawBtn(&button_color[i][j]); } } UI_DrawBtn(&button_return); UI_DrawBtn(&button_cancel); GRRLIB_Line(235, 25, 235, 350, 0xFFFFFFFF); GRRLIB_Line(235+64*2, 25, 235+64*2, 350, 0xFFFFFFFF); GRRLIB_Line(235+64*4, 25, 235+64*4, 350, 0xFFFFFFFF); GRRLIB_Line(235+64*6, 25, 235+64*6, 350, 0xFFFFFFFF); cui_cursor_display(p_game->cursor); GRRLIB_Render(); } GRRLIB_FreeTexture(tex_tile); GRRLIB_FreeTexture(tex_pieces); GRRLIB_FreeTexture(tex_up); GRRLIB_FreeTexture(tex_down); GRRLIB_FreeTTF(font); free(button_return.text); free(button_cancel.text); return next_state; } enum e_cui_menu menu_option_snd(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; bool done=false; GRRLIB_ttfFont* font = GRRLIB_LoadTTF(font_ttf, font_ttf_size); GRRLIB_texImg *tex_btn = GRRLIB_LoadTexture(button_png); UI_button button_sounds; UI_InitBtn(&button_sounds, 200, 280, "Mute"); button_sounds.img = tex_btn; button_sounds.font = font; UI_button button_return; UI_InitBtn(&button_return, 400, 400, "Return"); button_return.img = tex_btn; button_return.font = font; int i; UI_button button_type[4]; for(i=0;i<4;i++){ char text[7]; sprintf(text, "TYPE %c", 'A'+i); UI_InitBtn(&button_type[i], 50+150*i, 100, text); button_type[i].img = tex_btn; button_type[i].font = font; } while(!done){ cui_game_update_cursor(p_game->cursor); u32 pressed = WPAD_ButtonsDown(0); for(i=0;i<4;i++){ UI_UpdateBtn(&button_type[i], p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); } UI_UpdateBtn(&button_sounds, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_return, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); for(i=0;i<4;i++){ if(button_type[i].click){ switch(i){ case 0:MODPlay_SetMOD(&play,bg_music);MODPlay_Start(&play);break; case 1:MODPlay_SetMOD(&play,bg_music_b);MODPlay_Start(&play);break; case 2:MODPlay_SetMOD(&play,bg_music_c);MODPlay_Start(&play);break; case 3:MODPlay_SetMOD(&play,bg_music_d);MODPlay_Start(&play);break; } } } if(button_sounds.click){ p_game->is_mute = !p_game->is_mute; AESND_Pause(p_game->is_mute); } if(button_return.click){ done=true; next_state=CUI_MENU_MAIN; } if ( pressed & WPAD_BUTTON_HOME ){ if(!p_game->is_mute)AESND_Pause(true); if(menu_home(p_game) == CUI_MENU_EXIT){done=true;next_state=CUI_MENU_EXIT;} if(!p_game->is_mute)AESND_Pause(false); } for(i=0;i<4;i++){ UI_DrawBtn(&button_type[i]); } UI_DrawBtn(&button_sounds); UI_DrawBtn(&button_return); cui_cursor_display(p_game->cursor); GRRLIB_Render(); } free(button_sounds.text); free(button_return.text); free(button_type[0].text); free(button_type[1].text); free(button_type[2].text); free(button_type[3].text); GRRLIB_FreeTexture(tex_btn); GRRLIB_FreeTTF(font); return next_state; } enum e_cui_menu menu_option_general(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; return next_state; } <file_sep>/source/cui_engine.c #include "cui_engine.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <time.h> #include <sys/timeb.h> // get_ms() returns the milliseconds elapsed since midnight, // January 1, 1970. #include <sys/timeb.h> #include <sys/time.h> int getTime() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } BOOL ftime_ok = FALSE; // does ftime return milliseconds? int get_ms() {/* struct timeb timebuffer; ftime(&timebuffer); if (timebuffer.millitm != 0) ftime_ok = TRUE; return (timebuffer.time * 1000) + timebuffer.millitm; */ ftime_ok = TRUE; return getTime(); } // parse the move s (in coordinate notation) and return the move's // index in gen_dat, or -1 if the move is illegal int parse_move(char *s) { int from, to, i; // make sure the string looks like a move if (s[0] < 'a' || s[0] > 'h' || s[1] < '0' || s[1] > '9' || s[2] < 'a' || s[2] > 'h' || s[3] < '0' || s[3] > '9') return -1; from = s[0] - 'a'; from += 8 * (8 - (s[1] - '0')); to = s[2] - 'a'; to += 8 * (8 - (s[3] - '0')); for (i = 0; i < first_move[1]; ++i) if (gen_dat[i].m.b.from == from && gen_dat[i].m.b.to == to) { // if the move is a promotion, handle the promotion piece; // assume that the promotion moves occur consecutively in // gen_dat. if (gen_dat[i].m.b.bits & 32) switch (s[4]) { case 'N': return i; case 'B': return i + 1; case 'R': return i + 2; default: // assume it's a queen return i + 3; } return i; } // didn't find the move return -1; } // move_str returns a string with move m in coordinate notation char *move_str(move_bytes m) { static char str[6]; char c; if (m.bits & 32) { switch (m.promote) { case KNIGHT: c = 'n'; break; case BISHOP: c = 'b'; break; case ROOK: c = 'r'; break; default: c = 'q'; break; } sprintf(str, "%c%d%c%d%c", COL(m.from) + 'a', 8 - ROW(m.from), COL(m.to) + 'a', 8 - ROW(m.to), c); } else sprintf(str, "%c%d%c%d", COL(m.from) + 'a', 8 - ROW(m.from), COL(m.to) + 'a', 8 - ROW(m.to)); return str; } bool calculate_coords(char coords[5], char newcoord[5], ENGINE engine) { switch(engine){ case FIRSTCHESS: { int from, dest, i; int computer_side; int max_depth; // max depth to search MOVE moveBuf[200]; int movecnt; side = WHITE; max_depth = 7; hdp = 0; // maybe the user entered a move? from = coords[0] - 'a'; from += 8 * (8 - (coords[1] - '0')); dest = coords[2] - 'a'; dest += 8 * (8 - (coords[3] - '0')); ply = 0; movecnt = Gen(side, moveBuf); // loop through the moves to see if it's legal for (i = 0; i < movecnt; i++){ if (moveBuf[i].from == from && moveBuf[i].dest == dest) { if (FIRSTCHESS_piece[from] == PAWN && (dest < 8 || dest > 55)) { // Promotion move? switch (coords[4]) { case 'q': moveBuf[i].type = MOVE_TYPE_PROMOTION_TO_QUEEN; break; case 'r': moveBuf[i].type = MOVE_TYPE_PROMOTION_TO_ROOK; break; case 'b': moveBuf[i].type = MOVE_TYPE_PROMOTION_TO_BISHOP; break; case 'n': moveBuf[i].type = MOVE_TYPE_PROMOTION_TO_KNIGHT; break; default: puts("promoting to a McGuffin..., I'll give you a queen"); moveBuf[i].type = MOVE_TYPE_PROMOTION_TO_QUEEN; } } if (!MakeMove(moveBuf[i])) { TakeBack(); }else{ MOVE bestMove = ComputerThink(max_depth); MakeMove(bestMove); } break; } } break; } case TSCP: { int m = parse_move(coords); if (m == -1 || !makemove(gen_dat[m].m.b)){ //break; } else { ply = 0; gen(); } // think about the move and make it think(1); /*if (!pv[0][0].u) { break; }*/ makemove(pv[0][0].b); ply = 0; gen(); } break; } return true; } <file_sep>/source/cui_board.h #ifndef CUI_BOARD_H #define CUI_BOARD_H #include <gccore.h> #include <fat.h> #include <wiiuse/wpad.h> #include <grrlib.h> #include "cui_engine.h" #include "cui_board.h" #include "cui_tile.h" #include "engines/firstchess/core.h" #define CUI_TILE_NB 64 #define CUI_WHITE 0 #define CUI_BLACK 1 #define CUI_EMPTY 420 typedef struct t_cui_board{ int piece[64]; int color[64]; u32 tile_color1; u32 tile_color2; u32 piece_color1; u32 piece_color2; cui_tile tile[64]; }cui_board; void cui_board_init(cui_board* board); /** * Read the internal variable of a given engine to set the cui board * Should be used once, for initialisation, and eventually to redraw * in some special cases (board editor...) * */ void cui_board_read_core(cui_board *board, ENGINE engine); void cui_board_display(cui_board *board, GRRLIB_texImg* tex_pieces, GRRLIB_texImg* tex_tile, GRRLIB_ttfFont* font, int cursor_x, int cursor_y); void cui_board_demo(cui_board *board, GRRLIB_texImg* tex_pieces, GRRLIB_texImg* tex_tile, GRRLIB_ttfFont* font); /** * Update the cui board according the coords * */ void cui_board_update(cui_board *board, char coords[5]); #endif <file_sep>/source/cui_menu_option.h #ifndef CUI_MENU_OPTION_H #define CUI_MENU_OPTION_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <stdarg.h> #include <gccore.h> #include <ogcsys.h> #include <fat.h> #include <wiiuse/wpad.h> #include <grrlib.h> #include <gcmodplay.h> #include <aesndlib.h> #include "filelist.h" #include "cui_game.h" #include "cui_engine.h" #include "cui_board.h" #include "cui_cursor.h" #include "egg.h" #include "sounds/bg_music.h" #include "sounds/bg_music_b.h" #include "sounds/bg_music_c.h" #include "sounds/bg_music_d.h" #include "sounds/warp.h" #include "UI/button.h" #include "cui_menu.h" enum e_cui_menu menu_option(cui_game* p_game); enum e_cui_menu menu_option_general(cui_game* p_game); enum e_cui_menu menu_option_gfx(cui_game* p_game); enum e_cui_menu menu_option_snd(cui_game* p_game); #endif <file_sep>/source/cui_menu.c #include "cui_menu.h" cui_menu menu_main(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; bool done=false; GRRLIB_ttfFont* font = GRRLIB_LoadTTF(font_ttf, font_ttf_size); GRRLIB_texImg *tex_pieces = GRRLIB_LoadTexture(chess_classic_png); GRRLIB_texImg *tex_tile = GRRLIB_LoadTexture(keyboard_key_png); GRRLIB_texImg *tex_btn = GRRLIB_LoadTexture(button_png); UI_button button_newgame; UI_InitBtn(&button_newgame, 280, 120, "New game"); button_newgame.img = tex_btn; button_newgame.font = font; UI_button button_options; UI_InitBtn(&button_options, 280, 200, "Options"); button_options.img = tex_btn; button_options.font = font; UI_button button_credit; UI_InitBtn(&button_credit, 280, 280, "credit"); button_credit.img = tex_btn; button_credit.font = font; while(!done){ cui_game_update_cursor(p_game->cursor); u32 pressed = WPAD_ButtonsDown(0); GRRLIB_PrintfTTF (5, 5, font, "ChessUI", 96, 0x424242FF); UI_UpdateBtn(&button_newgame, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_options, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_credit, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); if(button_newgame.click){ done=true; next_state=CUI_MENU_PLAY; } if(button_options.click){ done=true; next_state=CUI_MENU_OPTION; } if(button_credit.click){ done=true; next_state=CUI_MENU_CREDITS; } if ( pressed & WPAD_BUTTON_HOME ){ if(!p_game->is_mute)AESND_Pause(true); if(menu_home(p_game) == CUI_MENU_EXIT){done=true;next_state=CUI_MENU_EXIT;} if(!p_game->is_mute)AESND_Pause(false); } if ( pressed & WPAD_BUTTON_A ){ if(voice) AESND_PlayVoice(voice, VOICE_STEREO16, button_click_pcm, button_click_pcm_size, VOICE_FREQ48KHZ, 1, false); } cui_board_demo(p_game->board, tex_pieces, tex_tile, font); UI_DrawBtn(&button_newgame); UI_DrawBtn(&button_options); UI_DrawBtn(&button_credit); cui_cursor_display(p_game->cursor); GRRLIB_Render(); } GRRLIB_FreeTTF(font); GRRLIB_FreeTexture(tex_btn); free(button_newgame.text); free(button_options.text); free(button_credit.text); return next_state; } cui_menu menu_play(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; bool done=false; GRRLIB_texImg *tex_pieces = GRRLIB_LoadTexture(chess_classic_png); GRRLIB_texImg *tex_tile = GRRLIB_LoadTexture(keyboard_key_png); GRRLIB_ttfFont* font = GRRLIB_LoadTTF(font_ttf, font_ttf_size); bool is_debug = false; char coords[5]; char calculated_coords[5]; strcpy(coords, "d2d20"); strcpy(calculated_coords, "d2d20"); while(!done){ WPAD_IR(0, &ir); WPAD_ScanPads(); u32 pressed = WPAD_ButtonsDown(0); u32 released = WPAD_ButtonsUp(0); if(egg_check_s1_code(pressed, released)){ is_debug = true; p_game->board->tile_color1 = 0xc66300FF; p_game->board->tile_color2 = 0x632100FF; p_game->board->piece_color1 = 0x4242CCFF; p_game->board->piece_color2 = 0x444411FF; cui_board_init(p_game->board); if(voice) AESND_PlayVoice(voice, VOICE_STEREO8, warp, warp_size, VOICE_FREQ32KHZ, 1, false); } if ( pressed & WPAD_BUTTON_HOME ){ if(!p_game->is_mute)AESND_Pause(true); if(menu_home(p_game) == CUI_MENU_EXIT){done=true;next_state=CUI_MENU_EXIT;} if(!p_game->is_mute)AESND_Pause(false); } if ( pressed & WPAD_BUTTON_MINUS){ switch(menu_option(p_game)){ case CUI_MENU_OPTION_GFX:menu_option_gfx(p_game);break; case CUI_MENU_OPTION_SND:menu_option_snd(p_game);break; default:break; } } int index_offset_x = (p_game->cursor->hotspot_x - 40 / 2)/ 40 - 140 / 40; int index_offset_y = p_game->cursor->hotspot_y / 40 - 80 / 40; if (pressed & WPAD_BUTTON_B) { p_game->cursor->is_grabbing = true; if(index_offset_x >= 0 && index_offset_x < 8 && index_offset_y >= 0 && index_offset_y < 8){ coords[0] = 'a' + index_offset_x; coords[1] = '8' - index_offset_y; } } else if(released & WPAD_BUTTON_B){ p_game->cursor->is_grabbing = false; if(index_offset_x >= 0 && index_offset_x < 8 && index_offset_y >= 0 && index_offset_y < 8){ coords[2] = 'a' + index_offset_x; coords[3] = '8' - index_offset_y; coords[4] = 0; if(voice) AESND_PlayVoice(voice, VOICE_STEREO16, move_pcm, move_pcm_size, VOICE_FREQ48KHZ, 1, false); if(calculate_coords(coords, calculated_coords, p_game->engine)){ cui_board_read_core(p_game->board, p_game->engine); } } } cui_cursor_update(p_game->cursor, ir.x, ir.y, ir.angle); if(p_game->tex_wallpaper)GRRLIB_DrawImg(0, -50, p_game->tex_wallpaper, 1, 1, 1, 0XFFFFFFFF); cui_board_display(p_game->board, tex_pieces, tex_tile, font, index_offset_x, index_offset_y); cui_cursor_display(p_game->cursor); if(is_debug){ GRRLIB_PrintfTTF (20, 00, font, coords, 16, 0x424242FF); GRRLIB_PrintfTTF2 (20, 20, font, 16, 0xFFFFFFFF, "x:%.2f y:%.2f", ir.x, ir.y); GRRLIB_PrintfTTF2 (20, 40, font, 16, 0xFFFFFFFF, "x:%.2f y:%.2f", ir.x/40, ir.y/40); GRRLIB_PrintfTTF2 (20, 60, font, 16, 0xFFFFFFFF, "x:%d y:%d", index_offset_x, index_offset_y); GRRLIB_PrintfTTF (20, 80, font, p_game->cursor->is_grabbing?"GRAB":"POINT", 16, 0xFFFFFFFF); GRRLIB_Rectangle(p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, 4, 4, 0xFF4242FF, 1); } GRRLIB_Render(); } GRRLIB_FreeTexture(tex_pieces); GRRLIB_FreeTexture(tex_tile); GRRLIB_FreeTTF(font); return next_state; } cui_menu menu_credits(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; bool done=false; GRRLIB_ttfFont* font = GRRLIB_LoadTTF(font_ttf, font_ttf_size); UI_button button_return; UI_InitBtn(&button_return, 400, 400, "Return"); button_return.img = GRRLIB_LoadTexture(button_png); button_return.font = font; while(!done){ cui_game_update_cursor(p_game->cursor); u32 pressed = WPAD_ButtonsDown(0); UI_UpdateBtn(&button_return, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); GRRLIB_PrintfTTF2 (20, 60, font, 20, 0xFFFFFFFF, "%s", "ChessUi -- a chess interface for Wii --"); GRRLIB_PrintfTTF2 (20, 80, font, 20, 0xFFFFFFFF, "%s", "Presented & programmed by TheDrev"); GRRLIB_PrintfTTF2 (20, 100, font, 20, 0xFFFFFFFF, "%s", "Using the FirstChess engine by <NAME> "); GRRLIB_PrintfTTF2 (20, 120, font, 20, 0xFFFFFFFF, "%s", "and piece graphismes by Wapcaplet"); GRRLIB_PrintfTTF2 (20, 140, font, 20, 0xFFFFFFFF, "%s", "and also the GRRLIB graphic library"); GRRLIB_PrintfTTF2 (20, 160, font, 20, 0xFFFFFFFF, "%s", "see http://wiibrew.org/wiki/Chessui for more details"); if(button_return.click){ done=true; next_state=CUI_MENU_MAIN; } if ( pressed & WPAD_BUTTON_HOME ){ if(!p_game->is_mute)AESND_Pause(true); if(menu_home(p_game) == CUI_MENU_EXIT){done=true;next_state=CUI_MENU_EXIT;} if(!p_game->is_mute)AESND_Pause(false); } UI_DrawBtn(&button_return); cui_cursor_display(p_game->cursor); GRRLIB_Render(); } GRRLIB_FreeTTF(font); free(button_return.text); GRRLIB_FreeTexture(button_return.img); return next_state; } cui_menu menu_pause(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; return next_state; } cui_menu menu_home(cui_game* p_game) { cui_menu next_state = CUI_MENU_MAIN; bool done=false; GRRLIB_ttfFont* font = GRRLIB_LoadTTF(font_ttf, font_ttf_size); UI_button button_loader; UI_InitBtn(&button_loader, 200, 200, "Loader"); button_loader.img = GRRLIB_LoadTexture(button_png); button_loader.font = font; UI_button button_menu; UI_InitBtn(&button_menu, 400, 200, "Wii menu"); button_menu.img = GRRLIB_LoadTexture(button_png); button_menu.font = font; while(!done) { GRRLIB_FillScreen(0x000000FF); GRRLIB_PrintfTTF (15, 0, font, "HOME Menu", 96, 0xFFFFFFFF); GRRLIB_Line(0, 100, 640, 100, 0xFFFFFFFF); UI_DrawBtn(&button_loader); UI_DrawBtn(&button_menu); cui_cursor_display(p_game->cursor); cui_game_update_cursor(p_game->cursor); u32 pressed = WPAD_ButtonsDown(0); UI_UpdateBtn(&button_loader, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); UI_UpdateBtn(&button_menu, p_game->cursor->hotspot_x, p_game->cursor->hotspot_y, pressed & WPAD_BUTTON_A); if ( pressed & WPAD_BUTTON_HOME ){ done = true; } if(button_loader.click){ done=true; next_state=CUI_MENU_EXIT; } if(button_menu.click){ SYS_ResetSystem(SYS_RETURNTOMENU, 0, 0); } GRRLIB_Render(); } GRRLIB_FreeTexture(button_loader.img); GRRLIB_FreeTexture(button_menu.img); free(button_loader.text); free(button_menu.text); return next_state; } cui_menu menu_exit(cui_game* p_game) { cui_menu next_state = CUI_MENU_EXIT; exit(0); return next_state; }
8815c948838e08f415d308aac1a0b04ffbd6b634
[ "C" ]
24
C
odrevet/Chess-Wii
3f6d3319893dced5bf7ffa1abb8db69d08ccd782
973a423f108bf6245ce2be64f59fdf3f87b7c0f2
refs/heads/master
<repo_name>bkleinbaum/leaflet2hw<file_sep>/js/script.js var pizzaIcon = L.icon({ iconUrl: 'images/pizza.png', iconSize: [32, 37], shadowSize: [50, 64], shadowAnchor: [4, 62], popupAnchor: [-3, -76] }); var beerIcon = L.icon({ iconUrl: 'images/bar.png', iconSize: [32, 37], shadowSize: [50, 64], shadowAnchor: [4, 62], popupAnchor: [-3, -76] }); var WeatherUp = L.marker([40.679855, -73.967743], {icon:beerIcon}).bindPopup("Weather Up"); var BklynSocial = L.marker([40.680405, -73.994415], {icon:beerIcon}).bindPopup("Brooklyn Social"); var WXOU = L.marker([40.7353829, -74.0059682], {icon:beerIcon}).bindPopup("Radio Bar"); var Sophies = L.marker([40.724842, -73.983788], {icon:beerIcon}).bindPopup("Sophie's"); var DutchKills = L.marker([40.7478994, -73.9401146], {icon:beerIcon}).bindPopup("Dutch Kill's"); var bars = L.layerGroup([WeatherUp, BklynSocial, WXOU, Sophies, DutchKills]); var Johns = L.marker([40.7315956, -74.0032746], {icon: pizzaIcon}).bindPopup("John's of Bleecker Street"), JoePat = L.marker([40.6130654, -74.1221964], {icon: pizzaIcon}).bindPopup("Joe and Pat's"), LandB = L.marker([40.5944187, -73.9812993], {icon: pizzaIcon}).bindPopup("L&B Spumoni Gardens"), Zero = L.marker([40.8546312, -73.8884278], {icon: pizzaIcon}).bindPopup("Zero Otto Nove"), Speedy = L.marker([40.687481,  -73.96006], {icon: pizzaIcon}).bindPopup("Speedy Romeo's"); var pizza = L.layerGroup([Johns, JoePat, LandB, Zero, Speedy]); var overlays = { "Bars" : bars, "Pizza": pizza }; var map = L.map('map', { center:[40.7820015, -73.8317032], zoom: 10, layers: pizza }); L.tileLayer('http://{s}.tiles.mapbox.com/v3/examples.map-i875mjb7/{z}/{x}/{y}.png', { maxZoom: 18 }).addTo(map); L.control.layers(overlays).addTo(map); var info = L.control(); info.onAdd = function (map) { this._div = L.DomUtil.create('div', 'info'); this.update(); return this._div; }; info.update = function (props) { this._div.innerHTML = '<h4>Best Pizza and Bars in NYC</h4>' }; info.addTo(map);
c0b1838999ebd54769375cd46cb2ec70b8461bb1
[ "JavaScript" ]
1
JavaScript
bkleinbaum/leaflet2hw
6a10b14e4e03f1c1fd4b399b407f1665f14a4826
312a620425fd2b25035792269e4041ff3bc95d18
refs/heads/master
<repo_name>Coopersino/wf1<file_sep>/index.js var sum = require('./modules/sum.js'), guard = require('./modules/guard.js'); console.log(sum(13,22)); console.log(guard('Dima'));
a80d34caa6f9526efd555c362686bacd678ebb94
[ "JavaScript" ]
1
JavaScript
Coopersino/wf1
1a0e292b91a2dc1c884f94f7437be7b91daca126
3efd9e800912992710827f2a9009543f68f59456
refs/heads/master
<repo_name>den59k/def<file_sep>/libs/onceCipher.js const convert = (char) => { let ch = null; switch (char) { case 32: ch = 32; break; case 33: ch = 33; break; case 46: ch = 34; break; case 44: ch = 35; break; case 63: ch = 36; break; default: if(char < 1000) ch = char-48+37; else ch = char - 1040; } if(ch < 0 || ch > 46) ch = 32; return ch; } const unConvert = (char) => { let ch = null; switch (char) { case 32: ch = 32; break; case 33: ch = 33; break; case 34: ch = 46; break; case 35: ch = 44; break; case 36: ch = 63; break; default: if(char > 32) ch = char-37+48; else ch = char + 1040; } return ch; } export const encrypt = (input, key) => { let output = ''; const _input = input.toUpperCase(); for(let i = 0; i < input.length; i++){ const k = convert(_input.charCodeAt(i)); const k2 = convert(key.charCodeAt(i)); let k3 = k+k2; if(k3 > 46) k3 -= 46; console.log(unConvert(k3)); output += String.fromCharCode(unConvert(k3)); } return output; } export const decrypt = (input, key) => { let output = ''; const _input = input.toUpperCase(); for(let i = 0; i < input.length; i++){ const k = convert(_input.charCodeAt(i)); const k2 = convert(key.charCodeAt(i)); let k3 = k-k2; if(k3 < 0) k3 += 46; console.log(unConvert(k3)); output += String.fromCharCode(unConvert(k3)); } return output; }<file_sep>/pages/laba5/index.jsx import { useState, useRef } from 'react' import Layout from 'components/layout.jsx' import { LibInput, RippleButton, Picker } from 'components/inputs.jsx' import sha1 from 'js-sha1'; import _ from 'lodash' import { MdFileUpload } from 'react-icons/md' import { generateKeys, encrypt, decrypt } from 'libs/rsa.js' import { generatePrime, fastModularExponentiation } from 'libs/tools.js' import style from 'styles/laba.module.sass' function zeroPad (num) { if(num.length <= 8) return "00000000".slice(num.length) + num; //Мы должны будем дополнить нашу строку нулями слева else return "0000000000000000".slice(num.length)+num; } const Laba1Page = (props) => { const [ values, setValues ] = useState(''); const onChange = (obj) => { if("input" in obj){ const binary = []; for (var i = 0; i < obj.input.length; i++) binary.push(zeroPad(obj.input[i].charCodeAt(0).toString(2))); const str = binary.join(""); let k = 0; let n = 1; let hamming = []; while(k < str.length){ if(hamming.length < n-1){ const end = k+n-1-hamming.length; for(let i = k; i < Math.min(end, str.length); i++){ hamming.push(str[i]); } k = end; } if(k < str.length) hamming.push(0); n *= 2; } n = 1; const controlBits = []; while(n < hamming.length){ const a = 0; for(let i = n-1; i < hamming.length; i+=n*2) for(let j = 0; j < n; j++) a += hamming[i+j] === '1'; controlBits.push(a); n *= 2; } obj.controlBits = controlBits; n = 1; for(let i = 0; i < controlBits.length; i++){ hamming[n-1] = controlBits[i]%2; n *= 2; } obj.hamming = hamming.join(""); obj.binary = binary; obj.error = 0; } let error = 0; if(obj.hamming){ let n = 1; while(n < obj.hamming.length){ const a = 0; for(let i = n-1; i < obj.hamming.length; i+=n*2) for(let j = 0; j < n; j++) a += obj.hamming[i+j] === '1'; if(a%2 === 1) error += n; n*= 2; } let str = ""; let array = []; n = 1; for(let i = 1; i < obj.hamming.length+1; i++){ if(i === n){ n*=2; continue; } str += (i !== error)? obj.hamming[i-1]: (obj.hamming[i-1]==='1'?'0': '1'); //Инвертируем ошибочный бит if(str.length === 8){ array.push(parseInt(str, 2)); str =""; } } obj.error = error; obj.str = String.fromCharCode(...array); } setValues(Object.assign({}, values, obj)); } return ( <Layout title="Код Хэмминга" sub="Лабораторная работа 5" > <main className={style.main} style={{width: "500px"}}> <LibInput label="Строка (UTF-8)" name="input" onChange={onChange}/> <div className={style.field}> <div className={style.name}>Бинарное представление</div> <div className={style.value}>{values.binary && values.binary.join(" ")}</div> </div> <div className={style.field}> <div className={style.name}>Контрольные значения</div> <div className={style.value}>{values.controlBits && values.controlBits.join(", ")}</div> </div> <textarea className={style.textArea} rows="3" placeholder="Текст + Код хэмминга" onChange={(e) => onChange({hamming: e.target.value})} value={values.hamming}> </textarea> <div>{values.error === 0? "В строке нет ошибок": ("Ошибка в символе "+values.error)}</div> <div className={style.field}> <div className={style.name}>Восстановленная строка</div> <div className={style.value} style={{fontSize: "16px"}}>{values.str}</div> </div> </main> </Layout> ); } export default Laba1Page;<file_sep>/pages/index.jsx import Head from 'next/head' import Link from 'next/link' import Layout from 'components/layout.jsx' import _ from 'lodash' import style from 'styles/laba.module.sass' const links = []; for(let i = 1; i <= 8; i++) links.push({to: "/laba"+i, title: "Лабораторная работа "+i}); export default function Home() { return ( <Layout title="Защита информации" sub="Лабораторные работы" > <main className={style.main} style={{width: "400px"}}> {links.map(item => ( <Link key={item.to} href={item.to}> <a>{item.title}</a> </Link> ))} </main> </Layout> ) } <file_sep>/pages/laba4/index.jsx import { useState, useRef } from 'react' import Layout from 'components/layout.jsx' import { LibInput, RippleButton, Picker } from 'components/inputs.jsx' import sha1 from 'js-sha1'; import _ from 'lodash' import { MdFileUpload } from 'react-icons/md' import { generateKeys, encrypt, decrypt } from 'libs/rsa.js' import { generatePrime, fastModularExponentiation } from 'libs/tools.js' import style from 'styles/laba.module.sass' const initialPermutation = []; for(let i = 0; i < 32; i++) initialPermutation.push(i); _.shuffle(initialPermutation); const keyPermutation = []; for(let i = 0; i < 16; i++) keyPermutation.push(i); _.shuffle(keyPermutation); function cycled (int){ //Циклический сдвиг вправо return (int >> 1) + ((int & 1) << 15); } function cipher (int, _key, cycles){ let newInt = 0; for(let i = 0; i < initialPermutation.length; i++) newInt += ((int >> i & 1) << initialPermutation[i]); //Здесь мы получаем нужный бит и сдвигаем его на нужную позицию перестановки let l0 = newInt >>> 16; let r0 = (newInt & ~(~0 << 16)); //Ну что сказать - здесь мы делим число на две части let key = 0; for(let i = 0; i < keyPermutation.length; i++) key += ((_key >> i & 1) << keyPermutation[i]); for(let i = 0; i < cycles; i++){ key = cycled(key); const a = l0; l0 = l0 ^ key ^ r0; r0 = a; } const _newInt = (l0 << 16) + r0; let finalInt = 0; for(let i = 0; i < initialPermutation.length; i++) finalInt += ((_newInt >> initialPermutation[i] & 1) << i); return finalInt; } function decypher (int, _key, cycles){ let newInt = 0; for(let i = 0; i < initialPermutation.length; i++) newInt += ((int >> i & 1) << initialPermutation[i]); //Здесь мы получаем нужный бит и сдвигаем его на нужную позицию перестановки let l0 = (newInt >>> 16) | 0; let r0 = (newInt & ~(~0 << 16)); //Ну что сказать - здесь мы делим число на две части let key = 0; for(let i = 0; i < keyPermutation.length; i++) key += ((_key >> i & 1) << keyPermutation[i]); const keyArr = []; for(let i = 0; i < cycles; i++){ key = cycled(key); keyArr.push(key); } for(let i = 0; i < cycles; i++){ key = keyArr[cycles-i-1]; const a = r0; r0 = r0 ^ key ^ l0; l0 = a; } const _newInt = (l0 << 16) + r0; let finalInt = 0; for(let i = 0; i < initialPermutation.length; i++) finalInt += ((_newInt >> initialPermutation[i] & 1) << i); return finalInt; } const dataArray = []; for(let i = 1; i < 16; i++) dataArray.push(i); const Laba1Page = (props) => { const [ values, setValues ] = useState(''); const onChange = (obj) => { setValues(Object.assign({}, values, obj)); } const fileRef = useRef(null); const file2Ref = useRef(null); const aRef = useRef(null); const onFileChange = (e) => { const file = e.target.files[0]; if(!file) return; let reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = () => { const buffer = reader.result; const view = new DataView(buffer); const key = parseInt(values.key, 16); const outputBuffer = new ArrayBuffer(Math.ceil(view.byteLength/4)*4); const outputView = new DataView(outputBuffer); for(let i = 0; i < view.byteLength/4; i++){ if(i*4+4 > view.byteLength){ let newInt = 0; for(let j = 0; j < view.byteLength-i*4; j++) newInt = (newInt << 8) + view.getUint8(i*4+j); outputView.setUint32(i*4, cipher(newInt, key, values.cycles)); }else outputView.setUint32(i*4, cipher(view.getUint32(i*4), key, values.cycles)); } const blob = new Blob([outputView.buffer], {type: "application/octet-binary"}); const url = URL.createObjectURL(blob); aRef.current.href = url; aRef.current.click(); }; e.target.value = ""; } const onFile2Change = (e) => { const file = e.target.files[0]; if(!file) return; let reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = () => { const buffer = reader.result; const view = new DataView(buffer); const key = parseInt(values.key, 16); const outputBuffer = new ArrayBuffer(Math.ceil(view.byteLength/4)*4); const outputView = new DataView(outputBuffer); for(let i = 0; i < view.byteLength/4; i++){ if(i*4+4 > view.byteLength){ let newInt = 0; for(let j = 0; j < view.byteLength-i*4; j++) newInt = (newInt << 8) + view.getUint8(i*4+j); outputView.setUint32(i*4, decypher(newInt, key, values.cycles)); }else outputView.setUint32(i*4, decypher(view.getUint32(i*4), key, values.cycles)); } const blob = new Blob([outputView.buffer], {type: "application/octet-binary"}); const url = URL.createObjectURL(blob); aRef.current.href = url; aRef.current.click(); }; e.target.value = ""; } return ( <Layout title="Блочное шифрование DES" sub="Лабораторная работа 4" > <main className={style.main} style={{width: "400px"}}> <div className={style.pair}> <div>Циклов:</div> <Picker onChange={onChange} name="cycles" width="50px" data={dataArray}/> <LibInput label="Ключ (hex) - 16бит" name="key" onChange={onChange}/> </div> <input type="file" hidden={true} ref={fileRef} onChange={onFileChange}/> <input type="file" hidden={true} ref={file2Ref} onChange={onFile2Change}/> <RippleButton style={{flexGrow: '1'}} onClick={() => fileRef.current.click()}><MdFileUpload/> Зашифровать файл</RippleButton> <RippleButton style={{flexGrow: '1'}} onClick={() => file2Ref.current.click()}><MdFileUpload/> Расшифровать файл</RippleButton> <a ref={aRef} download="file.bin"></a> </main> </Layout> ); } export default Laba1Page;<file_sep>/components/layout.jsx import Head from 'next/head' import style from 'styles/layout.module.sass' const Layout = (props) => { return ( <div className={style.layout}> <Head> <title>{props.title}</title> <meta name="viewport" content="initial-scale=1, width=device-width" /> </Head> <div className={style.title}> <h2>{props.sub}</h2> <h1>{props.title}</h1> </div> <div className={style.content}> {props.children} </div> </div> ); } export default Layout;<file_sep>/pages/laba2/index.jsx import { useState, useRef } from 'react' import Layout from 'components/layout.jsx' import { LibInput, RippleButton, Picker } from 'components/inputs.jsx' import { FaLock, FaUnlock, FaCodepen, FaSuperpowers } from 'react-icons/fa' import { GiRegeneration } from 'react-icons/gi' import { generateKeys, encrypt, decrypt } from 'libs/rsa.js' import { generatePrime } from 'libs/tools.js' import style from 'styles/laba.module.sass' let keys = null; const dataArray = []; for(let i = 3; i < 50; i+=3) dataArray.push(i); const convert = (str) => { const arr = [0, 0]; if(str.length % 2 === 0) str = "0"+str; for(let i = 0; i < str.length; i+=2){ const k = parseInt("0x"+str[i]+str[i+1]); arr.push(k); } return String.fromCharCode(...arr); } let array = []; const Laba1Page = (props) => { const [ outputValue, setOutputValue ] = useState(''); const [ pq, setPq ] = useState({p: 0n, q: 0n}); const [ privateKey, setPrivateKey ] = useState(null); const [ publicKey, setPublicKey ] = useState(null); const [values, setValues] = useState({text: '', cipherText: ''}); const generate = () => { const size = values.size || 3; setPq({ p: generatePrime(size), q: generatePrime(size) }) } const generateKey = () => { keys = generateKeys(pq.p, pq.q); console.log(keys); const privateKeyStr = window.btoa(convert(keys.private.d.toString(16)) + convert(keys.private.n.toString(16))); const publicKeyStr = window.btoa(convert(keys.public.e.toString(16)) + convert(keys.public.n.toString(16))); setPrivateKey(privateKeyStr); setPublicKey(publicKeyStr); } const onChange = (e) => { setValues(Object.assign({}, values, e)); } const _encrypt = () => { if(values.text.length === 0) return; console.log(values.text); const arr = encrypt(values.text, keys.public); array = arr; const cipherText = array.map(i => i.toString(16)).join("\n"); setValues(Object.assign({}, values, {cipherText} )); } const _decrypt = () => { if(values.cipherText.length === 0) return; const _arr = values.cipherText.split("\n").map(str => BigInt("0x"+str)); const decrypted = decrypt(_arr, keys.private); console.log(decrypted); setValues(Object.assign({}, values, {text: decrypted} )); } return ( <Layout title="Алгоритм RSA" sub="Лабораторная работа 2"> <main className={style.main}> <div className={style.pair}> <div>Байт:</div> <Picker onChange={onChange} name="size" width="50px" data={dataArray}/> <RippleButton style={{flexGrow: '1'}} onClick={generate}><FaCodepen/> Сгенерировать пару чисел</RippleButton> </div> <div className={style.pair}> {Object.keys(pq).map(key => ( <div className={style.field} key={key}> <div className={style.name}>{key}</div> <div className={style.value}>{pq[key].toString()}</div> </div> ))} </div> {pq.p > 0 && pq.q > 0 && (<RippleButton style={{flexGrow: '1'}} onClick={generateKey}><FaSuperpowers/> Сгенерировать ключ</RippleButton>)} {publicKey && privateKey && ( <div className={style.pair}> <div className={style.column}> <div className={style.field}> <div className={style.name}>Публичный ключ RSA</div> <div className={style.value}>{publicKey}</div> </div> <RippleButton onClick={_encrypt}><FaLock/> Зашифровать открытым ключом</RippleButton> <textarea className={style.textArea} rows="6" placeholder="Исходный Текст" onChange={(e) => onChange({text: e.target.value})} value={values.text}> </textarea> </div> <div className={style.column}> <div className={style.field}> <div className={style.name}>Приватный ключ RSA</div> <div className={style.value}>{privateKey}</div> </div> <RippleButton onClick={_decrypt}><FaUnlock/> Расшифровать закрытым ключом</RippleButton> <textarea className={style.textArea} rows="6" placeholder="Шифрованный текст" onChange={(e) => onChange({cipherText: e.target.value})} value={values.cipherText}> </textarea> </div> </div> )} </main> </Layout> ); } export default Laba1Page;<file_sep>/libs/rsa.js const { calcSecretExponent, fastModularExponentiation, generatePrime } = require('./tools.js') export function generateKeys (p, q) { const n = p*q; const euler = (p-1n)*(q-1n); const e = 17n; const d = calcSecretExponent(e, euler); return { public: {e, n}, private: {d, n} }; } //Разбиваем строку на блоки export const encrypt = (str, publicKey) => { const size = publicKey.n.toString(16).length-4; console.log(size); let k = 1n; let m = 0n; let array = []; let s = 0; for(let i = 0; i < str.length; i++){ m = m + BigInt(str.charCodeAt(i)) * k; k *= 65536n; s += 4; if(s >= size){ array.push(m); k = 1n; s = 0; m = 0n; } } if(s >= 0) array.push(m); const {e, n} = publicKey; const arr = []; for(let i = 0; i < array.length; i++){ const a = fastModularExponentiation(array[i], e, n); arr.push(a); } let outString = ""; for(let i = 0; i < array.length; i++){ let q = array[i]; while(q > 0){ outString += String.fromCharCode(Number(q%65536n)); q /= 65536n; } } console.log(outString); return arr; } export const decrypt = (arr, privateKey) => { const {d, n} = privateKey; console.log(d, n); let outString = ""; for(let i = 0; i < arr.length; i++){ let q = fastModularExponentiation(arr[i], d, n); console.log(q); while(q > 0){ outString += String.fromCharCode(Number(q%65536n)); q /= 65536n; } } return outString; } /* let d; let n; let e = 17n; do{ const p = generatePrime(); const q = generatePrime(); console.log(p); console.log(q); n = p*q; const euler = (p-1n)*(q-1n); e = 17n; d = calcSecretExponent(e, euler); }while(d == -1); const str = "Привет, как у тебя дела? Что делаешь такое интересное?"; const arr = []; for(let i = 0; i < str.length; i++){ const a = fastModularExponentiation(BigInt(str.charCodeAt(i)), e, n); arr.push(a); } console.log(d); console.log(arr); const arr2 = []; for(let i = 0; i < arr.length; i++){ const b = fastModularExponentiation(arr[i], d, n); console.log(b); arr2.push(Number(b)); } console.log(String.fromCharCode(...arr2));*/<file_sep>/pages/laba8/index.jsx import { useState, useRef } from 'react' import Layout from 'components/layout.jsx' import { LibInput, RippleButton, Picker } from 'components/inputs.jsx' import sha1 from 'js-sha1'; import _ from 'lodash' import { MdSpellcheck, MdLock } from 'react-icons/md' import { generateKeys, encrypt, decrypt } from 'libs/rsa.js' import { generatePrime, fastModularExponentiation } from 'libs/tools.js' import style from 'styles/laba.module.sass' const round = (i, max) => { while(i >= max) i -= max; return i; } const Laba1Page = (props) => { const [ values, setValues ] = useState({cycles: 2}); const onChange = (obj) => { const newVal = Object.assign({}, values, obj); if(newVal.text && newVal.gamma && newVal.gamma.length > 0){ let ciphered = ""; for(let i = 0; i < newVal.text.length; i++){ ciphered = ciphered + String.fromCharCode(newVal.text.charCodeAt(i) ^ newVal.gamma[round(i, newVal.gamma.length)]); } newVal.ciphered = ciphered; } setValues(newVal); } const generateGamma = () => { const str = values.text; const arr = []; for(let i = 0; i < str.length; i++) arr.push(_.random(0, 256, false)); onChange({gamma: arr, gammaStr: arr.map(i => i.toString(16)).join('') }); } const cipher = () => { } return ( <Layout title="Метод гаммирования" sub="Лабораторная работа 8" > <main className={style.main} style={{width: "400px"}}> <LibInput label="Исходный текст" name="text" onChange={onChange} className="auto"/> <RippleButton style={{flexGrow: '1'}} onClick={generateGamma}><MdLock/> Сгенерировать гамму</RippleButton> <div className={style.field}> <div className={style.name}>Гамма (HEX)</div> <div className={style.value}>{values.gammaStr}</div> </div> <div className={style.field}> <div className={style.name}>Результат шифрования (XOR)</div> <div className={style.value}>{values.ciphered}</div> </div> </main> </Layout> ); } export default Laba1Page;<file_sep>/pages/laba3/index.jsx import { useState, useRef } from 'react' import Layout from 'components/layout.jsx' import { LibInput, RippleButton, Picker } from 'components/inputs.jsx' import sha1 from 'js-sha1'; import { FaLock, FaUnlock, FaCodepen, FaSuperpowers } from 'react-icons/fa' import { GiRegeneration } from 'react-icons/gi' import { generateKeys, encrypt, decrypt } from 'libs/rsa.js' import { generatePrime, fastModularExponentiation } from 'libs/tools.js' import style from 'styles/laba.module.sass' let keys = null; const dataArray = []; for(let i = 3; i < 50; i+=3) dataArray.push(i); let array = []; const Laba1Page = (props) => { const [ outputValue, setOutputValue ] = useState(''); const [ pq, setPq ] = useState({p: 0n, g: 0n, x: 0n}); const [ privateKey, setPrivateKey ] = useState(null); const [ publicKey, setPublicKey ] = useState(null); const [values, setValues] = useState({text: '', sign: ''}); const generate = () => { const size = values.size || 3; const p = generatePrime(size); const g = generatePrime(size/2); const x = generatePrime(size/2); const y = fastModularExponentiation(g, x, p); const k = 257n; const a = fastModularExponentiation(g, k, p); setPq({ p, g, x, y, k, a }); } const onSign = () => { const message = values.text; const { p, g, x, y, k, a } = pq; const __M = sha1(message); const M = BigInt("0x"+__M); const _M = (x*a) % (p-1n); let delta = M-_M; if(delta < 0) delta = delta + (p-1n); for(let i = 0; i < 2000; i++){ if(delta % k == 0) break; delta += (p-1n); } const b = delta/k; console.log(a); setValues(Object.assign({}, values, { hash: __M, sign: a.toString(16)+"\n"+b.toString(16) })) } const onChange = (e) => { setValues(Object.assign({}, values, e)); } const checkSign = () => { const message = values.text; const { y, g, p } = pq; const sign = values.sign.split("\n"); const a = BigInt("0x"+sign[0]); const b = BigInt("0x"+sign[1]); const __M = sha1(message); const M = BigInt("0x"+__M); const x1 = fastModularExponentiation(y, a, p); const x2 = fastModularExponentiation(a, b, p); const x3 = fastModularExponentiation(g, M, p); console.log(x3); console.log((x1*x2) % p); setValues(Object.assign({}, values, {check: (x3 === (x1*x2) % p)})); } return ( <Layout title="Подпись Эль-Гамаля" sub="Лабораторная работа 3"> <main className={style.main}> <div className={style.pair}> <div>Байт:</div> <Picker onChange={onChange} name="size" width="50px" data={dataArray}/> <RippleButton style={{flexGrow: '1'}} onClick={generate}><FaCodepen/> Сгенерировать числа и посчитать ключ</RippleButton> </div> <div className={style.pair} style={{flexWrap: "wrap"}}> {Object.keys(pq).map(key => ( <div className={style.field} key={key}> <div className={style.name}>{key}</div> <div className={style.value}>{pq[key].toString(16)}</div> </div> ))} </div> <textarea className={style.textArea} rows="6" placeholder="Исходный Текст" onChange={(e) => onChange({text: e.target.value})} value={values.text}> </textarea> <RippleButton style={{flexGrow: '1'}} onClick={onSign}><FaSuperpowers/> Подписать</RippleButton> <div className={style.field}> <div className={style.name}>Хэш сообщения (SHA1)</div> <div className={style.value}>{values.hash}</div> </div> <textarea className={style.textArea} rows="2" placeholder="Подпись" onChange={(e) => onChange({sign: e.target.value})} value={values.sign}> </textarea> <RippleButton style={{flexGrow: '1'}} onClick={checkSign}><FaSuperpowers/> Проверить подпись</RippleButton> <div className={style.field}> <div className={style.name}>Результат проверки</div> <div className={style.value}>{values.check?"Подпись верна" : "Подпись не верна"}</div> </div> </main> </Layout> ); } export default Laba1Page;<file_sep>/pages/laba6/index.jsx import { useState, useRef } from 'react' import Layout from 'components/layout.jsx' import { LibInput, RippleButton, Picker } from 'components/inputs.jsx' import sha1 from 'js-sha1'; import _ from 'lodash' import { MdFileUpload } from 'react-icons/md' import { generateKeys, encrypt, decrypt } from 'libs/rsa.js' import { generatePrime, fastModularExponentiation } from 'libs/tools.js' import style from 'styles/laba.module.sass' function setTable(item, table, str=""){ if(item.children){ setTable(item.children[0], table, str+"0") setTable(item.children[1], table, str+"1") }else table.set(item.key, str || "0"); } const Laba6Page = (props) => { const [ values, setValues ] = useState(''); const onChange = (obj) => { if(obj.input){ const chars = new Map(); for(let i = 0; i < obj.input.length; i++){ const a = obj.input[i]; chars.set(a, (chars.get(a) || 0) + 1); } let array = []; for(let [key, value] of chars.entries()) array.push({key, count: value}); while(array.length > 1){ array = _.sortBy(array, ['count']); const newArr = array.slice(2); newArr.push({ count: array[0].count+ array[1].count, children: array.slice(0, 2) }); array = newArr; } const table = new Map(); setTable(array[0], table); let tableStr = ""; for(let [key, value] of table) tableStr += key+":"+value + " "; obj.tableStr = tableStr; let archiveStr = ""; for(let i = 0; i < obj.input.length; i++) archiveStr += table.get(obj.input[i]); obj.archiveStr = archiveStr; let hexStr = ""; let _str = ""; for(let i = archiveStr.length-1; i >= 0; i--){ _str = archiveStr[i]+_str; if(_str.length === 8){ hexStr = parseInt(_str, 2).toString(16) + hexStr; _str = ""; } } if(_str) hexStr = parseInt(_str, 2).toString(16) + hexStr; obj.hexStr = hexStr; const arr = []; let cursor = 1; while(cursor <= hexStr.length){ let c = cursor; let str = ""; const condition = (hexStr[c] === hexStr[c-1]) while((hexStr[c] === hexStr[c-1]) === condition && c < hexStr.length && c-cursor < 16) c++; if(condition || c === hexStr.length) c+=1; arr.push(hexStr.slice(cursor-1, c-1)); cursor = c; } obj.RLE = arr; obj.RLEstr = arr.map(item => (item.length <= 1 || item[0] !== item[1])?("0"+item.length.toString(16)+item): (item.length.toString(16)+item[0]) ).join(""); } setValues(Object.assign({}, values, obj)); } return ( <Layout title="Методы сжатия информации" sub="Лабораторная работа 6" > <main className={style.main} style={{width: "500px"}}> <LibInput label={"Исходный текст - "+(values.input?values.input.length: 0)+" байт"} name="input" onChange={onChange}/> <div className={style.field}> <div className={style.name}>Таблица символов</div> <div className={style.value}>{values.tableStr}</div> </div> <div className={style.field}> <div className={style.name}>Сжатая строка (Хаффман)</div> <div className={style.value}>{values.archiveStr}</div> </div> <div className={style.field}> <div className={style.name}>Сжатая строка (Хаффман) - HEX - {values.hexStr?(Math.ceil(values.hexStr.length/2)): 0} байт</div> <div className={style.value}>{values.hexStr}</div> </div> <div className={style.field}> <div className={style.name}>Блоки RLE для сжатия</div> <div className={style.value}>{values.RLE && values.RLE.join(", ")}</div> </div> <div className={style.field}> <div className={style.name}>Блоки RLE для сжатия - {values.RLEstr?(Math.ceil(values.RLEstr.length/2)): 0} байт</div> <div className={style.value}>{values.RLEstr}</div> </div> </main> </Layout> ); } export default Laba6Page;
c9886510e08341014c352cbdc9f721603e231ff3
[ "JavaScript" ]
10
JavaScript
den59k/def
b3b5c2a341f60c894570dc545ab09dd58f68d3fd
5f9155e158132dfa9e35e235d60b0bb90674e1e8
refs/heads/master
<repo_name>theonesuperdave/sandbox<file_sep>/KarmaWithMocha/specRunner.js var karma = window.__karma__; var tests = []; if (karma) { // take all of the files harvested from the karma // setup, and push them as dependencies to requireJS for (var file in karma.files) { if (karma.files.hasOwnProperty(file)) { if (/spec\.js$/.test(file)) { tests.push(file); } } } } requirejs.config({ baseUrl: '/base/js', paths: { should: '../node_modules/should/should', sinon: '../node_modules/sinon/lib/sinon' }, deps: tests, shim: { 'sinon': { exports: 'sinon'} }, // This allows us to run karma or mocha directly callback: function () { if (karma) { karma.start(); } return; } }); define('sinon', function () { return sinon; }); define('should', function () { return should; }); // This piece is needed if running mocha stand-alone if (karma == undefined) { // a bit tedious to make this file list dynamic, but it's possible // since we are using grunt to kick off mocha: // http://tbusser.net/articles/js-unit-testing-part-01/ require([ 'specs/sample-basic.spec.js', //'specs/sample-requireJS.spec.js' // not ready for prime-time; mocha config doesn't like requireJS right now ], function () { mocha.run(); }); } <file_sep>/team-city-setup/Dockerfile FROM jetbrains/teamcity-agent:latest-windowsservercore ADD NodeJsInstaller.ps1 /Windows/Temp/NodeJsInstaller.ps1 RUN powershell -executionpolicy bypass C:\Windows\Temp\NodeJsInstaller.ps1 -RunNative<file_sep>/README.md # sandbox I play a lot here. Tech research, proof-of-concepts, etc. It's like a playground for nerds. ### RivetsJS Just a basic web app using rivets ### RivetsJSConDurandalJS An implementation of DurandalJS using RivetsJS for everything but the compose binding. Several variations of data-binding and AMD modules are in play. ### KarmaWithMocha This is a simple setup using Karma for the test framework and Mocha as the test runner. Since requireJS is a thing, there is the config and example of that as well. Grunt is also an option for running Mocha here, but it doesn't play well with requireJS, so examples are limited. ### SupertestWithMocha This one is the same tech stack as `KarmaWithMocha`, only adding `supertest` on top of it for API calls. The result is a light-weight, performant test kit which can be used for various integration/API tests. The output can be piped to a CI/CD server or other dashboard for visibility and monitoring. ### json-config-transform I needed a simple console app to transform config files written in `JSON`. This one is a basic one written using .Net Core 2.0. The source file contents are iterated over, replacing any matching content present in a target file of the same structure. Values are replaced, and outputted for use in the necessary services. ### jest-the-basics In this sample, we setup `Jest` to run unit tests against our JavaScript modules. Everything runs under NodeJS and can mock out API calls and other dependencies as well as report code coverage for the tests. Nothing fancy, just a kind of starter kit which shows how to get started testing either client- or server-side code. <file_sep>/rivetsJS/Scripts/index-partial.js // This type of declaration is not working for some reason //var indexPartial = function() { // this.title = 'STAR WARS'; // this.message = 'We\'re doomed'; // this.message2 = 'It\'s not my fault. They told me they fixed it!'; // this.click = function() { // if (this.title === '') { // this.title = this.message2; // this.message2 = ''; // } // else { // this.message2 = this.title; // this.title = ''; // } // } //} var indexPartial = { title: 'STAR WARS', message: 'blah', messages: [ 'We\'re doomed', 'It\'s not my fault. They told me they fixed it!'], click: function () { if (indexPartial.message === indexPartial.messages[0]) { indexPartial.message = indexPartial.messages[1]; } else { indexPartial.message = indexPartial.messages[0]; } } }<file_sep>/SupertestWithMocha/integration-tests/describe-sample-auth.spec.js const request = require('supertest'); const express = require('express'); const should = require('should'); describe('sample - auth', () => { let app = express(); before(() => { app.get('/endpoint/secured', function (request, response) { let apiKey = '42'; let isAuthorized = request.header('X-API-Key') === apiKey; if (isAuthorized) { response.status(200).json({ name: '<NAME>', lightsaberColor: 'purple' }); } else { response.sendStatus(401); } }); }); it('should be authorized', async () => { let apiKey = '42'; await request(app) .get('/endpoint/secured') .set('X-API-Key', apiKey) .expect('Content-Type', /json/) .expect(200) .expect(/M<NAME>/); }); it('should be UNauthorized', async () => { await request(app) .get('/endpoint/secured') .expect(401); }); });<file_sep>/rivetsJSConDurandalJS/App/viewmodels/nav.js define(['durandal/app', 'plugins/router', 'rivets'], function (app, router, rivets) { var nav = { title: app.title, router: router, firstRoute: function() { return nav.router.navigationModel()[0].hash; }, activate: function () { }, binding: function () { nav.rivetsBinding = rivets.bind($('#nav'), { vm: nav }); }, compositionComplete: function () { }, deactivated: function () { nav.rivetsBinding.unbind(); }, detached: function () { nav.rivetsBinding.unbind(); } } return nav; });<file_sep>/rivetsJSConDurandalJS/App/viewmodels/evenMorePart1.js define(['rivets'], function (rivets) { var evenMorePart1 = { images: ['../../Content/images/rivets-sample1.jpg', '../../Content/images/rivets-sample2.jpg', '../../Content/images/rivets-sample3.jpg'], activate: function () { }, binding: function () { evenMorePart1.rivetsBinding = rivets.bind($('#evenMorePart1'), { vm: evenMorePart1 }); }, compositionComplete: function () { }, deactivated: function () { evenMorePart1.rivetsBinding.unbind(); }, detached: function () { evenMorePart1.rivetsBinding.unbind(); } } return evenMorePart1; });<file_sep>/rivetsJSConDurandalJS/App/viewmodels/home.js define(['rivets'], function (rivets) { var home = { rivetsBinding: {}, title: 'What is a rivet?', toggleOptions: ['Take the rivet challenge!', 'Just show me the answer already...'], toggle: function () { return home.toggleOptions[0]; }, // a little shady, but it works... clickToggle: function() { if (home.showQuestion) { home.toggle = home.toggleOptions[0]; } else { home.toggle = home.toggleOptions[1]; } home.clickQuestion(); }, showQuestion: false, doNotShowQuestion: function () { return home.showQuestion === false; }, clickQuestion: function() { home.showQuestion = !home.showQuestion; }, questionOptions: [{ id: 1, value: 'A type of frog only found on Corellia?' }, { id: 2, value: 'A permanent mechanical fastener?' }, { id: 3, value: 'The name of the long-lost sword of King Authur? ' }], activate: function() { }, binding: function() { home.rivetsBinding = rivets.bind($('#home'), { vm: home }); }, compositionComplete: function() { }, deactivated: function() { home.rivetsBinding.unbind(); }, detached: function () { home.rivetsBinding.unbind(); } } return home; });<file_sep>/jest-the-basics/index.js var target = () => { blah = 42; oops = null; motto = "May the Force be with you..."; jedis = [ 'Yoda', 'Windu', 'Obi-Wan']; opposite = (input) => { return !input; } boom = () => { throw new Error('blah blah blah. bad. blah.'); } return { blah: blah, oops: oops, motto: motto, jedis: jedis, opposite: opposite, boom: boom }; } module.exports = target();<file_sep>/KarmaWithMocha/js/target.js define([], function () { var target = (function () { var _this = this; function Target() { this.goalsScored = 0; } Target.prototype.gol = function () { return 'gooooooooooooooolazo'; }; Target.prototype.scoreGoal = function () { this.goalsScored++; }; Target.prototype.scoreGoalDelayed = function () { var _this = this; window.setInterval(function () { _this.goalsScored++; }, 1000); // delay for a second in real time }; Target.prototype.goalCount = function () { return this.goalsScored; }; return Target; })(); return new target(); });<file_sep>/json-config-transform/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Newtonsoft; using Newtonsoft.Json.Linq; namespace docker_config_transform { class Program { static void Main(string[] args) { // Generate the EXE for this project: 'dotnet publish -c Release -r win10-x64' // Usage: 'json-config-transform.exe -sourceFile .\config-source.json -targetFile .\config-target.json -targetOutputFile .\config-modified.json' // CLI Arg format: -[arg name] [value] // Parse them in pairs. var argPairs = new Dictionary<string, string>(); for(int index=0; index < args.Length; index += 2) { argPairs.Add(args[index], args[index+1]); } if (argPairs.ContainsKey("-sourceFile") == false || argPairs.ContainsKey("-targetFile") == false || argPairs.ContainsKey("-targetFile") == false) { Console.WriteLine("A required file was not specified. Please provide '-sourceFile', '-targetFile', and '-targetOutputFile' values."); return; } var sourceFile = argPairs["-sourceFile"]; var targetFile = argPairs["-targetFile"]; var targetOutputFile = argPairs["-targetOutputFile"]; // var sourceFile = @".\config-source.json"; // var targetFile = @".\config-target.json"; // var targetOutputFile = @".\config-modified.json"; // Here is the RegEx for HCL files in case they are needed at some point. // var appSettingsRegEx = "(APPSETTING_.*)=(.*)"; // var connStrRegEx = "(CONNSTR_.*)=(.*)"; JObject sourceConfigAsJObject = JObject.Parse(File.ReadAllText(sourceFile)); JObject targetConfigAsJObject = JObject.Parse(File.ReadAllText(targetFile)); TransformJObject(sourceConfigAsJObject, targetConfigAsJObject); File.WriteAllText(targetOutputFile, sourceConfigAsJObject.ToString()); // Console.ReadLine(); } private static void TransformJObject(JObject sourceConfigAsJObject, JObject targetConfigAsJObject) { var sourceJsonPath = sourceConfigAsJObject.Path; foreach (var item in sourceConfigAsJObject) { var itemToModify = sourceConfigAsJObject[item.Key]; if (itemToModify is JValue) { var mergeConfigItem = targetConfigAsJObject.SelectToken(item.Value.Path); itemToModify = mergeConfigItem; sourceConfigAsJObject[item.Key] = itemToModify; } else if (itemToModify is JObject) { TransformJObject(itemToModify as JObject, targetConfigAsJObject); } else if (itemToModify is JArray) { // Handles arrays of only values or only objects, but not a mix of the two var arrayModified = new JArray(); var arrayContainerModified = new JObject(new JProperty(item.Key, arrayModified)); foreach (var arrayItem in itemToModify) { if (arrayItem is JValue) { var result = TransformJArrayItem(arrayItem, targetConfigAsJObject, itemToModify); sourceConfigAsJObject[item.Key] = new JArray(new JValue[] { result }); arrayModified.Add(result); } else { TransformJObject(arrayItem as JObject, targetConfigAsJObject); } } } } } private static JValue TransformJArrayItem(JToken arrayItem, JObject targetConfigAsJObject, JToken itemToModify) { return targetConfigAsJObject.SelectToken(itemToModify.Path).First as JValue; } } } <file_sep>/SupertestWithMocha/integration-tests/describe-sample.spec.js var request = require('supertest'); var express = require('express'); var should = require('should'); describe('sample', () => { var app = express(); before(() => { app.get('/jedi/mace', function (request, response) { response.status(200).json({ name: '<NAME>', lightsaberColor: 'purple' }); }); }); it('should get Mace Windu', async () => { await request(app) .get('/jedi/mace') .expect('Content-Type', /json/) .expect(200) .expect(/Mace Windu/); }); it('should have purple lightsaber', async () => { let response = await request(app) .get('/jedi/mace') .expect('Content-Type', /json/) .expect(200) .expect(/lightsaberColor.*purple/); response.body.lightsaberColor.should.be.equal('purple'); }); });<file_sep>/KarmaWithMocha/specs/sample-sinon.spec.js define(['sinon', 'target'], function (sinon, target) { describe('sample-sinonJS', function () { before(function () { // Karma creates this global __html__ property that will hold all //// of our HTML so we can populate the body during our tests if (window.__html__) { document.body.innerHTML = window.__html__['specRunner.html']; } }); describe('sinon', function () { it('sinon-not-null', function () { var result = sinon !== null && sinon !== undefined; result.should.be.true(); }); it('sinon-spy-target', function () { var callbackScoreGoal = sinon.spy(target, 'scoreGoal'); var callbackGoalCount = sinon.spy(target, 'goalCount'); target.scoreGoal(callbackScoreGoal); callbackScoreGoal.calledOn(target).should.be.true(); callbackGoalCount.called.should.be.false(); target.scoreGoal.restore(); target.goalCount.restore(); }); it('sinon-stub-target', function () { var targetStub = sinon.stub(target); targetStub.goalCount.returns(3); targetStub.scoreGoal.returns(); targetStub.scoreGoal(); targetStub.goalCount().should.be.equal(3); targetStub.scoreGoal.called.should.be.true(); targetStub.goalCount.restore(); targetStub.scoreGoal.restore(); }); it('sinon-mock-target', function () { var targetMock = sinon.mock(target); targetMock.expects('goalCount').atLeast(1).returns(1); target.goalCount(); targetMock.verify(); targetMock.restore(); }); }); }); });<file_sep>/rivetsJSConDurandalJS/App/viewmodels/rivetUses.js define([], function () { var rivetUses = { title: 'What rivets can be used for', blah: 'this is just here to determine if rivetsJS is binding to everything in the view-model or just what is used in the view' } return rivetUses; });<file_sep>/KarmaWithMocha/specs/sample-requireJS.spec.js define(['sinon', 'target'], function (sinon, target) { describe('sample-requireJS', function () { before(function () { // Karma creates this global __html__ property that will hold all // of our HTML so we can populate the body during our tests if (window.__html__) { document.body.innerHTML = window.__html__['specRunner.html']; } }); beforeEach(function () { target.goalsScored = 0; }); describe('target', function () { it('scoreGoal', function () { target.scoreGoal(); target.goalCount().should.be.equal(1); target.scoreGoal(); target.goalCount().should.be.equal(2); }); it('gol', function () { var message = target.gol(); message.should.be.equal('gooooooooooooooolazo'); }); it('scoreGoalDelayed', function () { var fakeClock = sinon.useFakeTimers(); target.scoreGoalDelayed(); fakeClock.tick(1001); // advance 'real time' past the interval inside target target.goalCount().should.be.equal(1); fakeClock.restore(); }); }); }); });<file_sep>/SupertestWithMocha/README.md # Instructions and Setup 1. Install NodeJS (and npm) * Run `npm install` * To run the tests simply run this from anything that can run cmds: `npm run integration` # A Brief History of Everything 1. [NodeJS] (https://nodejs.org/dist/latest-v4.x/docs/api/) - provides the core plumbing for managing web requests and responses. * [Supertest] (https://github.com/visionmedia/supertest) - a framework which sits on top of NodeJS for managing web requests and responses. Additionally, it provides the core assertions against the responses received from the API. * [Mocha] (https://mochajs.org/) - a test framework--_similar to MSpec_--which gives some structure to how we write the tests. * [Should] (http://shouldjs.github.io/) - an assertion framework which helps us assert against errors. * [Express] (https://expressjs.com/en/4x/api.html) - a simple web server host for NodeJS. # What's in this project * A simple web server hosted in ExpressJS. We use this as the target for our tests * Mocha drives the process and executes our tests * Supertest is used on top of the NodeJS plumbing for sending web requests to our server * `integration` in the `package.json` file is a script which provides and alias to kick off our test suite <file_sep>/KarmaWithMocha/gruntfile.js module.exports = function (grunt) { var port = 8000; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), connect: { server: { options: { port: port, livereload: true, debug: true, base: '..', open: { target: 'http://localhost:' + port, appName: 'chrome' } } } }, watch: { all: { options: { livereload: true }, files: [ './specs/specRunner.js', './specs/**/*.spec.js', './specs/**/specRunner.html', './App/**/*.ts', 'gruntfile.js' ], tasks: ['jshint', 'mocha'] } }, mocha: { all: ['./specRunner.html'], options: { reporter: 'Spec', ui: 'bdd', ignoreLeaks: false, log: true, logErrors: true, //run: true // this is handled in the specRunner.js files: './specs/**/*.spec.js' } }, karma: { options: { // Configuration options that tell Karma how to run configFile: 'karma.conf.js' }, dev: { browsers: ['PhantomJS'], // On our local environment we want to test all the things! //browsers: ['Chrome', 'Firefox', 'PhantomJS'] //autoWatch: true, singleRun: true }, // For production, that is to say, our CI environment, we'll // run tests once in PhantomJS browser. prod: { singleRun: true, browsers: ['PhantomJS'] } }, debug: { }, sample: { options: { files: './specs/**/*.spec.js' } } }); //grunt.task.registerTask('default', ['mocha']); grunt.task.registerTask('watch', ['connect', 'watch', 'mocha']); grunt.task.registerTask('mocha', ['mocha:all']); grunt.task.registerTask('karma', ['karma:dev']); grunt.task.registerTask('sample', ['sample'], function () { console.log('sample running...'); var options = this.options(); console.log(options); var tests = grunt.file.expand(options.files).map(function (file) { return file; }); //mocha.tests = tests; grunt.option('tests', tests); console.log(tests); }); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-karma'); }; <file_sep>/InnoSetup/Inno-WindowsService/README.md # Inno Setup [Inno Setup](http://www.jrsoftware.org/isinfo.php) is a free installer for Windows programs. First introduced in 1997, Inno Setup today rivals and even surpasses many commercial installers in feature set and stability. For first-time users, the easiest way to get started is to download and run the **QuickStart Pack**. It comes with a file editor (_Inno Setup Studio_) and a handy utility to get things going manually. ## QuickStart Pack The [Inno Setup QuickStart Pack](http://www.jrsoftware.org/isdl.php#qsp) includes Inno Setup itself and additionally includes an option to install the **Inno Script Studio** script editor. This script editor is not official and is not required for general usage, but make Inno Setup easier to use. See the Third-Party Files page for more information. The Inno Setup QuickStart Pack also includes an option to download and install official encryption support. #### Practical Usage Overall, it's very well built, intuitive, and only opinionated where it needs to be. There is a lot of stuff out of the box, but it is easily extended in a few ways. The recommended customization is using Pascal Script built into the `[Code]` section of the file. This is great if you want to bring back the 1980's, but I've found it easier to implement and maintain by running scripts from the `[Run]` and/or `[Uninstall]` sections. Since we are targeting Windows machines, it's easy enough to plug in Powershell scripts or simply Windows CLI. #### Automation In order to expedite generation of the installer for code changes, it is now generated automatically for each successful build. This is done as a Visual Studio post-build event: `"$(ProjectDir)install\Inno Setup 5\iscc" "$(ProjectDir)install\*.iss"` The Inno Setup Compiler is included in the `install` directory of the Windows Service project. We simply call this from the command-line to create the installer using the `.iss` file present for the product. ## Resources [Inno Setup Help](http://www.jrsoftware.org/ishelp/) [Example .iss file](https://github.com/jrsoftware/issrc/blob/master/Examples/CodeDlg.iss) [Command -Line Compiler Execution](http://www.jrsoftware.org/ishelp/index.php?topic=compilercmdline) <file_sep>/rivetsJSConDurandalJS/App/viewmodels/evenMorePart2.js // DurandalJS Singleton define(['durandal/app', 'plugins/router', 'rivets'], function (app, router, rivets) { return { goodPermission: 'can do stuff', badPermission: 'barf', map: [{ id: 1, value: 'bg-info' }, { id: 2, value: 'bg-success' }], // This is a map of known type\category\etc. numbers to come CSS class; ideally, this would be some dictionary implementation where the key could be anything id: 2, // This would be the key into the collection defined above in the 'map' init: function() { var self = this; // Setup a container object that matches the 'interface' to the input arg for our custom binder. Yucky, but it works with this object literal style. self.mapContainer = { id: self.id, map: self.map } return self; }, activate: function() { }, binding: function() { var self = this; self.rivetsBinding = rivets.bind($('#evenMorePart2'), { vm: self }); }, compositionComplete: function() { }, deactivated: function() { var self = this; self.unbindRivetsIfNecessary(); }, detached: function() { var self = this; self.unbindRivetsIfNecessary(); }, unbindRivetsIfNecessary: function() { var self = this; if (self.rivetsBinding) { self.rivetsBinding.unbind(); } } }.init(); });<file_sep>/rivetsJSConDurandalJS/App/viewmodels/more.js // DurandalJS Transient define(['viewmodels/rivetTypes', 'viewmodels/rivetUses', 'rivets'], function (types, uses, rivets) { var more = (function () { function more() {} more.prototype.activate = function() { } more.prototype.binding = function () { more.typesBinding = rivets.bind($('#types'), { types: types }); more.usesBinding = rivets.bind($('#uses'), { uses: uses }); } more.prototype.compositionComplete = function () { } more.prototype.deactivated = function () { more.typesBinding.unbind(); more.usesBinding.unbind(); } more.prototype.detached = function () { more.typesBinding.unbind(); more.usesBinding.unbind(); } return more; })(); return more; });<file_sep>/KarmaWithMocha/README.md # Instructions and Setup 1. Install NodeJS * Install base dependencies (npm) - (FRESH INSTALL ONLY) * [Require](https://www.npmjs.com/package/karma-requirejs) * [Grunt](http://gruntjs.com/installing-grunt)~ * [Karma](http://karma-runner.github.io/1.0/intro/installation.html) * [PhantomJS](https://github.com/karma-runner/karma-phantomjs-launcher) * [Mocha](https://www.npmjs.com/package/karma-mocha) * Setup Grunt CLI~ - `npm install -g grunt-cli` * Setup Karma CLI - `npm install -g karma-cli` * [Optional] Add global node modules to PATH environment variable (Windows only): `%AppData%\npm` * Run: `npm install` * Create and configure the karma.conf.js * Configure frameworks * Add necessary files and/or patterns * App * Specs * requireJS config (include this in the browser) * Configure any preprocessors (*.html) * Configure browsers to be used in testing * Setup autoWatch or singleRun * Create and configure the gruntfile.js~ * Create test harness (*.html) * Setup the file to be created below as the 'data-main' for requireJS * Include lib dependencies * Don't forget the div for mocha: `<div id="mocha"></div>` * Add config (*.js) - this is where we setup requireJS and such * baseUrl: '/base' - Karma serves up all file to this location (base/[app] to match existing source files) * Add the following snippet to add all test files as a requireJS dependency ```javascript var tests = []; if (window.__karma__) { for (var file in window.__karma__.files) { if (window.__karma__.files.hasOwnProperty(file)) { if (/specs\.js$/.test(file)) { tests.push(file); } } } } ``` * Add the 'tests' above as a dependency to requireJS config (`deps: tests,`) * Setup any necessary requireJS paths and/or shims Ex. ```javascript paths: { should: 'node_modules/should/should', sinon: 'node_modules/sinon/lib/sinon' }, shim: { 'sinon': { exports: 'sinon'} }, ``` ~_Optional Step: if using the grunt task runner_ _Mocha doesn't play very well directly with requireJS_ <file_sep>/rivetsJSConDurandalJS/App/rivetsJSCustomBindings.js define(['user', 'rivets'], function (user, rivets) { var rivetsJSCustomBindings = { init: function () { rivets.binders.haspermission = function (element, value) { $(element).css('display', user.hasPermission(value) ? 'inherit' : 'none'); }; rivets.binders.setcssforinputvalue = { routine: function (element, value) { var map = value.map; if (map) { var css = null; for (var index = 0; index < map.length; index++) { if (map[index].id === value.id) { css = map[index].value; break; } } if (css) { $(element).addClass(css); } } } }; rivets.binders.setTextForInputValue = { routine: function (element, value) { var map = value.map; if (map) { var text = null; for (var index = 0; index < map.length; index++) { if (map[index].id === value.id) { text = map[index].value; break; } } if (text) { $(element).text(text); } } } }; } } return rivetsJSCustomBindings; });<file_sep>/momentJSLocales/Scripts/locale/moment-es.js moment.locale('es', { months: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "augosto", "septiembre", "octubre", "noviembre", "diciembre"], weekdays: ["domingo", "lunes", "martes", "miercoles", "jueves", "viernes", "sabado"], longDateFormat: { LT: "HH:mm", LTS: "HH:mm:ss", L: "DD/MM/YYYY", LL: "D MMMM YYYY", LLL: "D MMMM YYYY LT", LLLL: "dddd D MMMM YYYY LT" }, calendar: { sameDay: "[mismo dia] LT", nextDay: '[dia siguente] LT', nextWeek: 'dddd [proxima semana] LT', lastDay: '[dia pasada] LT', lastWeek: 'dddd [semana pasada] LT', sameElse: 'L' }, relativeTime: { future: "futuro %s", past: "pasado %s", s: "segundo", m: "un minuto", mm: "%d minutos", h: "una hora", hh: "%d horas", d: "un dia", dd: "%d dias", M: "un mes", MM: "%d meses", y: "un ano", yy: "%d anos" }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } });<file_sep>/rivetsJSConDurandalJS/App/user.js define([], function () { var user = { permissions: ['can do stuff', 'can do more stuff'], hasPermission: function(permission) { for (var index = 0; index < user.permissions.length; index++) { if (user.permissions[index] === permission) { return true; } } return false; } } return user; });
af20e32f6ad5dc0eb2f01190f17d67d0cc60eaf3
[ "JavaScript", "C#", "Dockerfile", "Markdown" ]
24
JavaScript
theonesuperdave/sandbox
7ef91041b5610044bc5b04a1e4df8e9487706687
7ba33ada5aae4dda7883801a708244baed641b0d
refs/heads/master
<repo_name>monkeysuffrage/deathbycaptcha<file_sep>/lib/deathbycaptcha/version.rb module DeathByCaptcha VERSION = "4.1.2" API_VERSION = "DBC/Ruby v4.1.0" end <file_sep>/lib/deathbycaptcha.rb require 'deathbycaptcha/version' require 'deathbycaptcha/config' require 'deathbycaptcha/error' require 'deathbycaptcha/client' require 'deathbycaptcha/http_client' require 'deathbycaptcha/socket_client' module DeathByCaptcha end
894c087a2f834775fa2d399c05409b6269478f22
[ "Ruby" ]
2
Ruby
monkeysuffrage/deathbycaptcha
e48d5b0db71c19f384eed8d5d2d98311d163d0e6
b8f62ae49a3680ad02cc9d8423bffbdd3d6ef4e2
refs/heads/master
<file_sep># demo-login-firebase <file_sep>interface ProfileState { id: string; username: string; email: string; fullName: string; permissions: string[]; language: string; isLoggedIn: boolean; rememberMe: boolean; token: string; } export default ProfileState; <file_sep>import ProfileState from './state'; export { ProfileState }; <file_sep>import { SagaMiddleware } from 'redux-saga'; import loginPageSaga from './ui/login-page/saga'; import profileSaga from './profile/saga'; const runSagas = (sagaMiddleware: SagaMiddleware<{}>) => { sagaMiddleware.run(loginPageSaga); sagaMiddleware.run(profileSaga); }; export default runSagas; <file_sep>import config from './config'; import * as express from 'express'; import firebase from 'firebase'; import * as bodyparser from 'body-parser'; import loginRouter from './modules/login/loginRouter'; const cors = require('cors'); const serviceAccount = require('./serviceAccountKey/serviceaccount.json'); import * as admin from 'firebase-admin'; const bootstrap = async () => { const server = express(); server.use(cors({ origin: true })); firebase.initializeApp(config.auth); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: 'https://test-a1c39.firebaseio.com' }); const db = admin.firestore(); server.set('db', db); // server.use((req, res, next) => { // res.header('Access-Control-Allow-Origin', '*'); // res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); // next(); // }); server.use(bodyparser.urlencoded({ extended: true })); server.use(bodyparser.json()); server.use('/api/', loginRouter); server.use(express.static('public')); server.listen(config.app.port, (error, respond) => { if (error) { // tslint:disable-next-line:no-console console.log(error); } else { // tslint:disable-next-line:no-console console.log(`running on port ${config.app.port}`); } }); }; bootstrap(); <file_sep>import firebase from 'firebase'; const isAuth = async (req, res, next) => { await firebase.auth().onAuthStateChanged((user) => { if (!user) { return res.status(404).send('You are not login'); } }); next(); }; export default isAuth; <file_sep>import { MiddlewareAPI } from 'redux'; import { AppState } from '..'; import { UPDATE_USER_PROFILE, CLEAR_USER_PROFILE } from '../profile/action'; const TokenKey = 'token'; const localStorageMiddleware = ({ getState, }: MiddlewareAPI<any>) => next => action => { const returnValue = next(action); if (localStorage) { if (action.type === UPDATE_USER_PROFILE) { const state: AppState = getState(); if (state.profile.token) { localStorage.setItem(TokenKey, state.profile.token); } } else if (action.type === CLEAR_USER_PROFILE) { localStorage.removeItem(TokenKey); } } return returnValue; }; export default localStorageMiddleware; export { TokenKey }; <file_sep>const config = { apiUrls: 'http://localhost:3001/api/' }; export default config; <file_sep>import { LoginWithEmail, loginWithEmail, loginInProgress, loginSuccessfully, loginError, LoginWithFb, loginWithFb, LoginWithGg, loginWithGg } from './action'; import { put, all, takeEvery } from 'redux-saga/effects'; // import axios from 'axios'; // import config from '../../../config/config'; import { message } from 'antd'; import { updateUserProfile } from '../../profile/action'; import { push } from 'react-router-redux'; import { RouteUrls } from '../../../routes/routes.constant'; import firebase from 'firebase'; function* loginWithEmailWorker(action: LoginWithEmail): any { try { yield put(loginInProgress()); try { const signIn = yield firebase.auth() .signInWithEmailAndPassword(action.payload.username, action.payload.password); if (signIn) { yield put(loginSuccessfully()); message.success('Login Successfully'); const getIdToken = yield firebase.auth().currentUser!.getIdToken(/* forceRefresh */ true); yield put(updateUserProfile(getIdToken, false)); yield put(push(RouteUrls.Main)); } else { yield put(loginError(signIn.message)); message.error(signIn.data.message); } // const response = yield axios.post( // config.apiUrls + 'signin', // { // email: action.payload.username, // password: <PASSWORD>.payload.<PASSWORD> // } // ); // if (response.data.user) { // yield put(loginSuccessfully()); // message.success('Login Successfully'); // yield put(updateUserProfile(response.data.user.stsTokenManager.accessToken, false)); // yield put(push(RouteUrls.Main)); // } else { // yield put(loginError(response.data.message)); // message.error(response.data.message); // } } catch (error) { message.error('Login failed'); // tslint:disable-next-line:no-console console.log(error); } } catch (error) { // tslint:disable-next-line:no-console console.log(error); } } function* loginWithFbWorker(action: LoginWithFb): any { try { const provider = new firebase.auth.FacebookAuthProvider(); firebase.auth().languageCode = 'en_EN'; try { yield put(loginInProgress()); const response = yield firebase.auth().signInWithPopup(provider); if (response.credential) { yield put(loginSuccessfully()); message.success('Login Successfully'); const getIdToken = yield firebase.auth().currentUser!.getIdToken(/* forceRefresh */ true); yield put(updateUserProfile(getIdToken, false)); yield put(push(RouteUrls.Main)); } } catch (err) { yield put(loginError(err.message)); message.error(err.message); // tslint:disable-next-line:no-console console.log(err); } } catch (error) { message.error(error); } } function* loginWithGgWorker(action: LoginWithGg): any { try { const provider = new firebase.auth.GoogleAuthProvider(); try { yield put(loginInProgress()); const response = yield firebase.auth().signInWithPopup(provider); if (response.credential) { yield put(loginSuccessfully()); message.success('Login Successfully'); const getIdToken = yield firebase.auth().currentUser!.getIdToken(/* forceRefresh */ true); yield put(updateUserProfile(getIdToken, false)); yield put(push(RouteUrls.Main)); } } catch (err) { yield put(loginError(err.message)); message.error('Login failed'); // tslint:disable-next-line:no-console console.log(err); } } catch (error) { message.error(error); } } /******************************************************************************/ /******************************* WATCHERS *************************************/ /******************************************************************************/ export default function* loginPageSaga(): any { yield all([ takeEvery(loginWithEmail, loginWithEmailWorker), takeEvery(loginWithFb, loginWithFbWorker), takeEvery(loginWithGg, loginWithGgWorker), ]); } <file_sep>import { handleActions } from 'redux-actions'; import { ProfileState } from '.'; import { UpdateUserProfile, ClearUserProfile, CLEAR_USER_PROFILE, UPDATE_USER_PROFILE, CheckForLogIn, CHECK_FOR_LOG_IN, } from './action'; // import * as admin from 'firebase-admin'; import jwt_decode from 'jwt-decode'; export interface Token { uid: string; username: string; email: string; name: string; permissions: string[]; language: string; exp?: number; iat?: number; user_id: string; } // const decodeToken = async (token: any) => { // try { // const response = await admin.auth().verifyIdToken(token); // // tslint:disable-next-line:no-console // console.log(response); // return response; // } catch (error) { // // tslint:disable-next-line:no-console // console.log(error); // return null; // } // }; const defaultState: ProfileState = { id: '', isLoggedIn: false, rememberMe: false, token: '', username: '', email: '', fullName: '', permissions: [], language: '', }; const checkForLogInReducer = ( state: ProfileState, action: CheckForLogIn ) => { return { ...state, }; }; const updateUserProfileReducer = ( state: ProfileState, action: UpdateUserProfile, ) => { const data: Token = jwt_decode(action.payload.token) as any; // tslint:disable-next-line:no-console console.log(data); return { ...state, id: data.uid ? data.uid : data.user_id, isLoggedIn: true, rememberMe: action.payload.rememberMe || false, token: action.payload.token, email: data.email, fullName: data.name, permissions: data.permissions, language: data.language ? data.language : 'en', }; }; const clearUserProfileReducer = ( state: ProfileState, action: ClearUserProfile, ) => { return { ...defaultState }; }; const profileReducer = handleActions<ProfileState, any>( { [UPDATE_USER_PROFILE]: updateUserProfileReducer, [CLEAR_USER_PROFILE]: clearUserProfileReducer, [CHECK_FOR_LOG_IN]: checkForLogInReducer }, defaultState, ); export { profileReducer }; <file_sep>const defaultConfig = { app: { port: 3001, }, auth: { apiKey: '<KEY>', authDomain: 'test-a1c39.firebaseapp.com', databaseURL: 'https://test-a1c39.firebaseio.com', projectId: 'test-a1c39', storageBucket: 'test-a1c39.appspot.com', messagingSenderId: '703565782455' } }; export default defaultConfig; <file_sep>import * as _ from 'lodash'; import defaultConfig from './default.config'; const config = _.merge({}, defaultConfig); export default config; <file_sep>import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; import * as express from 'express'; import * as cors from 'cors'; const app = express(); app.use(cors({ origin: true })); // Start writing Firebase Functions // https://firebase.google.com/docs/functions/typescript admin.initializeApp(functions.config().firebase); const db = admin.firestore(); app.get('/getAllDocument', async (request, response) => { try { const activites = await db.collection('activites'); const snapshot = await activites.get(); if (!snapshot) { console.log('No document collection'); return; } const usersList = []; snapshot.forEach((item) => { usersList.push(item); }); console.log('hey') response.send(usersList); } catch (error) { console.log(error); } }); app.get('/', (req, res) => { res.send('hey') }); app.get('/createActivitesCol', (request, response) => { for (let i = 0; i < 5; i++) { const usersRef = db.collection('activites').doc(); usersRef.set({ username: 'user' + i, distance: Math.floor(Math.random() * (2000 - 1)) + 1, id: usersRef.id, date: new Date }).then((doc) => { if (!doc || i >= 5) { console.log('User is not created'); return; } response.send(doc); }).catch((error) => { console.log(error); }); } }); app.get('/createLeaderBoardCol', (request, response) => { for (let i = 0; i < 5; i++) { const usersRef = db.collection('leaderboard').doc(); usersRef.set({ username: 'user' + i, distance: Math.floor(Math.random() * (2000 - 1)) + 1, id: usersRef.id, date: '' }).then((doc) => { if (!doc) { console.log('User is not created'); return; } console.log(doc); }).catch((error) => { console.log(error); }); } }); // export const getAllDocument = functions.https.onRequest((request, response) => { // const leaderBoard = db.collection('leaderboard'); // leaderBoard.get() // .then((snapshot) => { // if (!snapshot) { // console.log('No document collection'); // return; // } // const usersList = []; // snapshot.forEach((item) => { // usersList.push(item); // }); // response.send(usersList); // }) // .catch((error) => { // console.log(error); // }); // }); // export const updateUser = functions.https.onRequest((request, response) => { // response.send(request.body); // // db.collection('activites').doc().get() // // .then(doc => { // // if (!doc.exists) { // // console.log('No user with current id'); // // return; // // } // // console.log(doc.data()); // // }).catch(error => { // // console.log(error); // // }); // }); // export const createActivitesCol = functions.https.onRequest((request, response) => { // for (let i = 0; i < 5; i++) { // const usersRef = db.collection('activites').doc(); // usersRef.set({ // username: 'user' + i, // distance: Math.floor(Math.random() * (2000 - 1)) + 1, // id: usersRef.id, // date: new Date // }).then((doc) => { // if (!doc || i >= 5) { // console.log('User is not created'); // return; // } // response.send(doc); // }).catch((error) => { // console.log(error); // }); // } // }); // export const createLeaderBoardCol = functions.https.onRequest((request, response) => { // for (let i = 0; i < 5; i++) { // const usersRef = db.collection('leaderboard').doc(); // usersRef.set({ // username: 'user' + i, // distance: Math.floor(Math.random() * (2000 - 1)) + 1, // id: usersRef.id, // date: '' // }).then((doc) => { // if (!doc) { // console.log('User is not created'); // return; // } // console.log(doc); // }).catch((error) => { // console.log(error); // }); // } // }); exports.app = functions.https.onRequest(app);<file_sep>interface AppSettingsState { language: string; isTranslating: boolean; apiUrl: string; clientUrl: string; maxPageSize: number; gridPage: { defaultPageSize: number; pageSizes: number[]; }; } export default AppSettingsState; <file_sep>interface LoginPageState { state: number; username: string; errorMessage: string; callbackUrl: string; isBusy: boolean; } export default LoginPageState; <file_sep>// import { RouteUrls } from '../../routes/routes.constant'; // import { push } from 'react-router-redux'; import { put, all, takeEvery } from 'redux-saga/effects'; import { // logout, checkForLogIn, clearUserProfile, logout } from './action'; import firebase from 'firebase'; import { push } from 'react-router-redux'; import { RouteUrls } from '../../routes/routes.constant'; import { message } from 'antd'; // import { AppState } from '..'; function* logoutWorker(): any { try { yield firebase.auth().signOut(); message.success('Sign Out Successfully'); // const username = ((yield select()) as AppState).profile.username; yield put(clearUserProfile()); // yield put(loginWithUsername(username)); yield put(push(RouteUrls.Login)); } catch (error) { // tslint:disable-next-line:no-console console.log(error); } } function* checkForLogInWorker(): any { try { yield firebase.auth().onAuthStateChanged((user) => { // tslint:disable-next-line:no-console // console.log(user); }); // const isLoggedIn = yield fetch('http://localhost:3001/api/user'); // // tslint:disable-next-line:no-console // console.log(isLoggedIn); } catch (error) { // tslint:disable-next-line:no-console console.log(error); } } /******************************************************************************/ /******************************* WATCHERS *************************************/ /******************************************************************************/ export default function* profileSaga(): any { yield all([ takeEvery(logout, logoutWorker), takeEvery(checkForLogIn, checkForLogInWorker) ]); } <file_sep>import { createAction } from 'redux-actions'; export interface LoginParams { username: string; password: string; } // =================================== // login with username export const LOGIN_WITH_EMAIL = 'LOGGIN_PAGE/LOGIN_WITH_EMAIL'; export type LOGIN_WITH_EMAIL = typeof LOGIN_WITH_EMAIL; export const LOGIN = 'LOGGIN_PAGE/LOGIN'; export type LOGIN = typeof LOGIN; export const LOGIN_IN_PROGRESS = 'LOGGIN_PAGE/LOGIN_IN_PROGRESS'; export type LOGIN_IN_PROGRESS = typeof LOGIN_IN_PROGRESS; export const LOGIN_SUCCESSFULLY = 'LOGGIN_PAGE/LOGIN_SUCCESSFULLY'; export type LOGIN_SUCCESSFULLY = typeof LOGIN_SUCCESSFULLY; export const LOGIN_ERROR = 'LOGGIN_PAGE/LOGIN_ERROR'; export type LOGIN_ERROR = typeof LOGIN_ERROR; export interface LoginWithEmail { type: LOGIN_WITH_EMAIL; payload: LoginParams; } export interface LoginInProgress { type: LOGIN_IN_PROGRESS; } export interface LoginSuccessfully { type: LOGIN_SUCCESSFULLY; } export interface LoginError { type: LOGIN_ERROR; payload: { errorMessage: string }; error: boolean; } export const loginWithEmail = createAction( LOGIN_WITH_EMAIL, (loginParams: LoginParams) => ({ ...loginParams, }) ); export const loginInProgress = createAction( LOGIN_IN_PROGRESS ); export const loginSuccessfully = createAction(LOGIN_SUCCESSFULLY); export const loginError = createAction(LOGIN_ERROR); // =================================== // login with fb & gg export const LOGIN_WITH_FB = 'LOGGIN_PAGE/LOGIN_WITH_FB'; export type LOGIN_WITH_FB = typeof LOGIN_WITH_FB; export interface LoginWithFb { type: LOGIN_WITH_FB; } export const loginWithFb = createAction(LOGIN_WITH_FB); export interface LoginWithGg { type: LOGIN_WITH_GG; } export const LOGIN_WITH_GG = 'LOGGIN_PAGE/LOGIN_WITH_GG'; export type LOGIN_WITH_GG = typeof LOGIN_WITH_GG; export const loginWithGg = createAction(LOGIN_WITH_GG); export type LoginPageAction = |LoginWithEmail | LoginInProgress | LoginSuccessfully | LoginError | LoginWithFb | LoginWithGg; <file_sep>import LoginPageState from './state'; import { LoginWithEmail, LOGIN_WITH_EMAIL, LoginInProgress, LoginSuccessfully, LoginError, LOGIN_IN_PROGRESS, LOGIN_SUCCESSFULLY, LOGIN_ERROR, LoginWithFb, LOGIN_WITH_FB, LOGIN_WITH_GG } from './action'; import { handleActions } from 'redux-actions'; const initialState = { state: 0, username: '', errorMessage: '', callbackUrl: '', isBusy: false }; const loginWithEmailReducer = ( state: LoginPageState, action: LoginWithEmail, ) => { return { ...state, isBusy: false, errorMessage: '' }; }; const loginInProgressReducer = ( state: LoginPageState, action: LoginInProgress, ) => { return { ...state, isBusy: true, errorMessage: '' }; }; const loginSuccessfullyReducer = ( state: LoginPageState, action: LoginSuccessfully, ) => { return { ...state, isBusy: false, errorMessage: '' }; }; const loginErrorReducer = ( state: LoginPageState, action: LoginError, ) => { return { ...state, isBusy: false, errorMessage: action.payload.errorMessage }; }; const loginWithFbReducer = ( state: LoginPageState, action: LoginWithFb, ) => { return { ...state, isBusy: false, }; }; const loginWithGgReducer = ( state: LoginPageState, action: LoginWithFb, ) => { return { ...state, isBusy: false, }; }; const loginPageReducer = handleActions<LoginPageState, any>( { [LOGIN_WITH_FB]: loginWithFbReducer, [LOGIN_WITH_GG]: loginWithGgReducer, [LOGIN_WITH_EMAIL]: loginWithEmailReducer, [LOGIN_IN_PROGRESS]: loginInProgressReducer, [LOGIN_SUCCESSFULLY]: loginSuccessfullyReducer, [LOGIN_ERROR]: loginErrorReducer }, { ...initialState } ); export { loginPageReducer }; <file_sep>import { Router as ExpressRouter } from 'express'; const Router = ExpressRouter(); import firebase from 'firebase/app'; import isAuth from 'helpers/isAuth'; import * as admin from 'firebase-admin'; // const db = admin.firestore(); Router.get('/login', (req, res) => { res.send('login api'); }); Router.post('/createuser', (req, res) => { firebase.auth().createUserWithEmailAndPassword(req.body.email, req.body.password) .then((resolve) => { res.send(resolve); }) .catch((error) => { res.send(error); // tslint:disable-next-line:no-console console.log(error); }); }); Router.get('/user', isAuth, (req, res) => { const user = firebase.auth().currentUser; if (user != null) { res.send(user); } }); Router.post('/signin', (req, res) => { firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password) .then((resolve) => { res.send(resolve); }) .catch((error) => { res.send(error); }); }); Router.get('/logout', isAuth, (req, res) => { firebase.auth().signOut().then((resolve) => { // tslint:disable-next-line:no-console console.log(resolve); res.send(resolve); }).catch((error) => { // tslint:disable-next-line:no-console console.log(error); res.send(error); }); }); Router.get('/testfirecloud', async (req, res) => { const db = req.app.get('db'); // const setAlan = aTuringRef.set({ // first: 'Alan', // middle: 'Mathison', // last: 'Turing', // born: 1912 // }); for (let i = 0; i < 5; i++) { const usersRef = await db .collection('leaderboard').doc('user' + i); await usersRef.set({ username: 'user' + i, ranking: Math.floor(Math.random() * (100 - 1)) + 1 }); } try { const Users = await db.collection('leaderboard').get(); const usersList = []; Users.forEach((item) => { usersList.push(item.data()); }); res.send(usersList); } catch (error) { // tslint:disable-next-line:no-console console.log(error); } }); export default Router; <file_sep>import firebase from 'firebase/app'; import { TokenKey } from './redux/middlewares/local-storage.middleware'; import { store } from './redux/store'; import { updateUserProfile, checkForLogIn } from './redux/profile/action'; const bootstrap = async () => { try { const config = { apiKey: '<KEY>', authDomain: 'test-a1c39.firebaseapp.com', databaseURL: 'https://test-a1c39.firebaseio.com', projectId: 'test-a1c39', storageBucket: 'test-a1c39.appspot.com', messagingSenderId: '703565782455' }; await firebase.initializeApp(config); if (localStorage) { const currentToken = localStorage.getItem(TokenKey); store.dispatch(checkForLogIn()); // try { // } catch (error) { // // tslint:disable-next-line:no-console // console.log(error); // } store.dispatch(updateUserProfile(currentToken!, true)); } } catch (err) { // tslint:disable-next-line:no-console // console.log('can not load configuration', err); return; } }; export default bootstrap; <file_sep>import { ProfileState } from './profile'; import LoginPageState from './ui/login-page/state'; interface AppState { profile: ProfileState; ui: { loginPage: LoginPageState; }; } export { AppState }; <file_sep>import { createAction } from 'redux-actions'; export const UPDATE_USER_PROFILE = 'PROFILE/UPDATE_USER_PROFILE'; export type UPDATE_USER_PROFILE = typeof UPDATE_USER_PROFILE; export const CLEAR_USER_PROFILE = 'PROFILE/CLEAR_USER_PROFILE'; export type CLEAR_USER_PROFILE = typeof CLEAR_USER_PROFILE; export const UPDATE_TOKEN = 'PROFILE/UPDATE_TOKEN'; export type UPDATE_TOKEN = typeof UPDATE_TOKEN; export const LOGOUT = 'PROFILE/LOGOUT'; export type LOGOUT = typeof LOGOUT; export const CHECK_FOR_LOG_IN = 'PROFILE/CHECK_FOR_LOG_IN'; export type CHECK_FOR_LOG_IN = typeof CHECK_FOR_LOG_IN; export interface CheckForLogIn { type: CHECK_FOR_LOG_IN; } const checkForLogIn = createAction(CHECK_FOR_LOG_IN); export interface UpdateUserProfile { type: UPDATE_USER_PROFILE; payload: { token: string; rememberMe?: boolean; }; } export interface ClearUserProfile { type: CLEAR_USER_PROFILE; } export interface Logout { type: LOGOUT; } const updateUserProfile = createAction( UPDATE_USER_PROFILE, (token: string, rememberMe: boolean) => ({ token, rememberMe }), ); const clearUserProfile = createAction(CLEAR_USER_PROFILE); const logout = createAction(LOGOUT); export { updateUserProfile, clearUserProfile, logout, checkForLogIn }; <file_sep>import Routes from './routes'; import LoginPage from './Login/LoginPage'; // import RegisterPage from './Register/RegisterPage'; import Page400 from './Error/Page400/Page400'; import Page403 from './Error/Page403/Page403'; import Page500 from './Error/Page500/Page500'; // import MainPage from './Main/MainPage'; // import Static from './Static/StaticHomePage'; export { Routes, LoginPage, Page400, Page403, Page500 }; <file_sep>import { AppState } from './state'; export { AppState }; <file_sep>import { compose, createStore as reduxCreateStore, combineReducers, applyMiddleware } from 'redux'; import createSagaMiddleware from 'redux-saga'; import { routerReducer, routerMiddleware } from 'react-router-redux'; import createHistory from 'history/createBrowserHistory'; import { AppState } from './state'; import runSagas from './saga'; import { loginPageReducer } from './ui/login-page/reducer'; import { profileReducer } from './profile/reducer'; import localStorageMiddleware from './middlewares/local-storage.middleware'; const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const sagaMiddleware = createSagaMiddleware(); const history = createHistory(); const historyRouterMiddleware = routerMiddleware(history); // create store const store = reduxCreateStore<AppState>( combineReducers({ profile: profileReducer, ui: combineReducers({ loginPage: loginPageReducer, }), router: routerReducer, }), composeEnhancers( applyMiddleware( historyRouterMiddleware, sagaMiddleware, localStorageMiddleware ) ) ); runSagas(sagaMiddleware); export { store, history }; <file_sep>export class RouteUrls { public static readonly Login: string = '/login'; public static readonly Register: string = '/register'; public static readonly Page400: string = '/error/400'; public static readonly Page403: string = '/error/403'; public static readonly Page500: string = '/error/500'; public static readonly Main: string = '/main'; public static readonly Profile: string = '/main/profile'; }
fea8cea3cff0b333981a4d3ccfb3b31c5dc86232
[ "Markdown", "TypeScript" ]
26
Markdown
duyanhv/demo-login-firebase
a9a01a551b0510adb4664dc51a67ab97fdfade57
69cd746790fb2d812d4fdcebeccae13c01e81f66
refs/heads/master
<repo_name>nikhilenmudi/orderchief<file_sep>/src/main/java/com/orderchief/domain/Vendor.java package com.orderchief.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.ColumnResult; import javax.persistence.Entity; import javax.persistence.EntityResult; import javax.persistence.FieldResult; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SqlResultSetMapping; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonManagedReference; @Entity @Table(name="vendor") public class Vendor { @Id @Column(name="VENDOR_ID") @GeneratedValue protected int vendorId; @OneToMany(cascade=javax.persistence.CascadeType.ALL,mappedBy="vendor") @Column(name="Product") @JsonManagedReference("Product-list") protected List<Product> product = new ArrayList<Product>(); @Column(name="VENDOR_NAME") protected String vendorName; @Column(name="COUNTER") protected int waitingNumber; @Column(name="VENDOR_LATITUDE") protected double vendorLatitude; @Column(name="VENDOR_LONGITUDE") protected double vendorLongitude; @Transient protected double distance; @Column(name="LOGO") protected String logo; @JsonIgnore @OneToMany(cascade=javax.persistence.CascadeType.ALL,mappedBy="vendor") @Column(name="CURRENTORDERS") protected List<Order> currentorders = new ArrayList<Order>(); public List<Order> getCurrentorders() { return currentorders; } public void setCurrentorders(List<Order> currentorders) { this.currentorders = currentorders; } public String getVendorName() { return vendorName; } public void setVendorName(String vendorName) { this.vendorName = vendorName; } public int getWaitingNumber() { return waitingNumber; } public void setWaitingNumber(int waitingNumber) { this.waitingNumber = waitingNumber; } public int getVendorId() { return vendorId; } public void setVendorId(int vendorId) { this.vendorId = vendorId; } public List<Product> getProduct() { return product; } public void setProduct(List<Product> product) { this.product = product; } public double getVendorLatitude() { return vendorLatitude; } public void setVendorLatitude(double vendorLatitude) { this.vendorLatitude = vendorLatitude; } public double getVendorLongitude() { return vendorLongitude; } public void setVendorLongitude(double vendorLongitude) { this.vendorLongitude = vendorLongitude; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } } <file_sep>/src/main/java/com/orderchief/domain/ProductOption.java package com.orderchief.domain; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity @Table(name="productoption") public class ProductOption{ @Id @Column(name="product_option_id") @GeneratedValue protected int productOptionId; @ManyToOne() @JsonBackReference("Product-option") protected Product product; @Column(name="ProductTopping") private String topping; @Column(name="price") protected BigDecimal baseprice; public int getProductOptionId() { return productOptionId; } public void setProductOptionId(int productOptionId) { this.productOptionId = productOptionId; } public BigDecimal getBaseprice() { return baseprice; } public void setBaseprice(BigDecimal baseprice) { this.baseprice = baseprice; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public String getTopping() { return topping; } public void setTopping(String topping) { this.topping = topping; } } <file_sep>/src/main/java/com/orderchief/server/OrderController.java package com.orderchief.server; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import com.orderchief.domain.Order; import com.orderchief.domain.Vendor; import com.orderchief.forms.PaymentForm; import com.orderchief.service.OrderService; import com.orderchief.util.OrderItem; @Controller public class OrderController { @Autowired private OrderService orderService; @ResponseBody @RequestMapping(value = "/submitorder/{userGcmKey}" , method = RequestMethod.POST, headers = "Accept=application/*" ) public void submitOrder(@PathVariable String userGcmKey, @RequestBody List<OrderItem> jsonOrders, HttpServletResponse response){ System.out.println("the size is"+jsonOrders.size()); this.orderService.saveOrder(userGcmKey, jsonOrders); System.out.println("the size is"+jsonOrders.size()); response.setStatus(HttpServletResponse.SC_OK); } @RequestMapping(value = "/orderready", method = RequestMethod.POST) public void orderReady(@RequestParam String regId, HttpServletResponse response){ //System.out.println("The server key is "+ apiKey); System.out.println("User key is "+ regId); // OrderReadyMsg orderReadyMsg = new OrderReadyMsg(); // orderReadyMsg.createData("This is awesome", "Achieved this awesomeness"); // orderReadyMsg.addRegId(regId); // SendToGCM.post(apiKey, orderReadyMsg); RestTemplate restTemplate = new RestTemplate(); String url = "https://android.googleapis.com/gcm/send?=&="; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Authorization", "key=<KEY>"); requestHeaders.set("Content-type", "application/x-www-form-urlencoded"); MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>(); postParams.add("registration_id",regId); String data = "Your Order at is ready. Kindly Visit the Store"; postParams.add("data", data); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParams, requestHeaders); ResponseEntity<String> re = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); System.out.println(re.getBody()); response.setStatus(HttpServletResponse.SC_OK); } @RequestMapping(value = "/getOrders/{vendorId}", method = RequestMethod.GET) public @ResponseBody List<Order> getOrders(@PathVariable int vendorId){ List<Order> orders = orderService.getOrdersForVendor(vendorId); System.out.println(orders.size()); return orders; } @RequestMapping(value = "/getOrderItems/{orderId}", method = RequestMethod.GET) public @ResponseBody List<OrderItem> getOrderItems(@PathVariable int orderId){ List<OrderItem> orderItems = orderService.getOrderItems(orderId); System.out.println(orderItems.size()); return orderItems; } @RequestMapping(value = "/ordercomplete", method = RequestMethod.POST) public void orderComplete(@RequestParam int completedOrderId, HttpServletResponse response){ System.out.println("completing order"+completedOrderId); this.orderService.completeOrder(completedOrderId); response.setStatus(HttpServletResponse.SC_OK); } @RequestMapping(value = "/processPayment/{complexKey}", method = RequestMethod.POST, headers = "Accept=application/*") public void processPayment(@PathVariable String complexKey, @RequestBody List<OrderItem> jsonOrders, HttpServletResponse response){ System.out.println("Received order processing size of "+jsonOrders.size()); System.out.println("Token number " + complexKey); String[] paymentInfo = complexKey.split("\\s+"); String userGcmKey = paymentInfo[0]; String paymentToken = paymentInfo[1]; boolean payStatus = this.orderService.processPayment(paymentToken,jsonOrders); System.out.println("The payment was "+payStatus); if(payStatus){ System.out.println("Payment Successful -- inserting order!!"); this.orderService.saveOrder(userGcmKey, jsonOrders); } response.setStatus(HttpServletResponse.SC_OK); } } <file_sep>/README.md ORDERCHIEF Required tools - Spring STS 3.4 Spring Release - 4.0.2 Hibernate 4.3.1 Maven MySQL 5.x Checkout as "Maven Project"<file_sep>/src/main/java/com/orderchief/dao/ProductOptionDAO.java package com.orderchief.dao; import com.orderchief.domain.ProductOption; public interface ProductOptionDAO { public ProductOption getProductOptionById(int id); } <file_sep>/src/main/java/com/orderchief/forms/PaymentForm.java package com.orderchief.forms; public class PaymentForm { private String cardNumber; private String cardName; private int cvc; private int expDate; public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } public int getCvc() { return cvc; } public void setCvc(int cvc) { this.cvc = cvc; } public int getExpDate() { return expDate; } public void setExpDate(int expDate) { this.expDate = expDate; } } <file_sep>/src/main/java/com/orderchief/dao/ProductSubOptionDaoImpl.java package com.orderchief.dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.orderchief.domain.ProductSubOption; @Repository public class ProductSubOptionDaoImpl implements ProductSubOptionDAO { @PersistenceContext(unitName = "ocPersistenceUnit") EntityManager em; @Override public ProductSubOption getProductSubOptionById(int id) { return em.find(ProductSubOption.class, id); } } <file_sep>/src/main/java/com/orderchief/domain/ProductSubOption.java package com.orderchief.domain; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity @Table(name="prod_sub_option") public class ProductSubOption { @Id @Column(name="product_sub_option_id") @GeneratedValue protected int productSubOptionId; @Column(name="product_size") protected String size; @JsonBackReference("Product-suboption") @ManyToOne() @JoinColumn(name="productId") protected Product product; @Column(name="price") protected BigDecimal baseprice; public BigDecimal getBaseprice() { return baseprice; } public void setBaseprice(BigDecimal baseprice) { this.baseprice = baseprice; } public int getProductSubOptionId() { return productSubOptionId; } public void setProductSubOptionId(int productSubOptionId) { this.productSubOptionId = productSubOptionId; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } } <file_sep>/src/main/java/com/orderchief/service/MenuService.java package com.orderchief.service; import java.util.List; import com.orderchief.domain.Product; public interface MenuService { public List<Product> getMenuById(int VendorId); } <file_sep>/src/main/java/com/orderchief/service/VendorServiceImpl.java package com.orderchief.service; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.orderchief.dao.VendorDao; import com.orderchief.domain.UserVendor; import com.orderchief.domain.Vendor; @Service public class VendorServiceImpl implements VendorService { @Autowired private VendorDao vendorDao; @Transactional @Override public List<Vendor> getListOfVendors() { List<Vendor> vendors = vendorDao.getListOfVendors(); return vendors; } @Transactional @Override public List<Vendor> getVendorsListByLocation(double latitude, double longitude) { List<Vendor> vendors = this.vendorDao.getListByLocation(latitude, longitude); for(Vendor vendor : vendors){ System.out.println("The distance is "+ vendor.getDistance()); } return vendors; } @Override @Transactional public UserVendor authenticateVendor(String loginKey) { String[] loginInfo = loginKey.split("\\s+"); String username = loginInfo[0]; String password = loginInfo[1]; UserVendor user = this.vendorDao.checkVendor(username, password); boolean loginStatus = false; if(user != null){ return user; } return null; } } <file_sep>/src/main/java/com/orderchief/service/VendorService.java package com.orderchief.service; import java.util.List; import com.orderchief.domain.UserVendor; import com.orderchief.domain.Vendor; public interface VendorService { public List<Vendor> getListOfVendors(); public List<Vendor> getVendorsListByLocation(double latitude, double longitude); public UserVendor authenticateVendor(String loginKey); } <file_sep>/src/main/webapp/WEB-INF/pages/test1.js $(document).ready(function() { $.ajax({ url: "http://localhost:8080/server/getVendors" }).then(function(data, status, jqxhr) { alert(data[0].vendorId); }); });<file_sep>/src/main/java/com/orderchief/dao/VendorDaoImpl.java package com.orderchief.dao; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import javax.persistence.ColumnResult; import javax.persistence.EntityManager; import javax.persistence.EntityResult; import javax.persistence.FieldResult; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.SqlResultSetMapping; import org.springframework.stereotype.Repository; import com.orderchief.domain.ProductSubOption; import com.orderchief.domain.UserVendor; import com.orderchief.domain.Vendor; @Repository public class VendorDaoImpl implements VendorDao { @PersistenceContext(unitName = "ocPersistenceUnit") EntityManager em; @SuppressWarnings("unchecked") @Override public List<Vendor> getListOfVendors() { List<Vendor> result = em.createQuery("from "+Vendor.class.getName()).getResultList(); return result; } @Override public List<Vendor> getListByLocation(double latitude, double longitude) { List<Vendor> vendors = new ArrayList<Vendor>(); Query query = em.createNativeQuery("SELECT vendor.VENDOR_ID, ( 6371 * acos( cos( radians(45.422) ) * " +"cos( radians( VENDOR_LATITUDE ) ) * cos( radians( VENDOR_LONGITUDE ) - radians(-75.66) )" +" + sin( radians(45.422) ) * sin(radians(VENDOR_LATITUDE)) ) )" +" AS distance FROM vendor HAVING distance < 10 ORDER BY distance"); List<Object[]> vendorObjects = (List<Object[]>)query.getResultList(); BigDecimal bd; for(Object[] obj : vendorObjects){ Vendor vendor = this.findById(Integer.parseInt(obj[0].toString())); bd = new BigDecimal(Float.parseFloat(obj[1].toString())); bd = bd.setScale(2, RoundingMode.HALF_UP); vendor.setDistance(bd.doubleValue()); vendors.add(vendor); } if(vendors!= null & vendors.size() > 0){ return vendors; } else{ return null; } } @Override public Vendor findById(int id) { return em.find(Vendor.class, id); } @Override public UserVendor checkVendor(String userName, String password) { Query query = em.createQuery("from UserVendor where login=:username and password =:password"); query.setParameter("username", userName); query.setParameter("password", password); UserVendor user = (UserVendor) query.getSingleResult(); if(user != null){ return user; } return null; } // public ProductSubOption getPS(){ // ProductSubOption result1 = (ProductSubOption)em.createQuery("from "+ProductSubOption.class.getName()+" where productId=?").getSingleResult(); // return result1; // } } <file_sep>/src/main/java/com/orderchief/dao/ProductSubOptionDAO.java package com.orderchief.dao; import com.orderchief.domain.ProductSubOption; public interface ProductSubOptionDAO { public ProductSubOption getProductSubOptionById(int id); }
86af638280edc0b6168a038f6d06bbe23888520b
[ "Markdown", "Java", "JavaScript" ]
14
Java
nikhilenmudi/orderchief
b68519bf8d210ad51ff89a200f00388f6c0c48e9
b366fbdfff3745abd0b17aafdd047deade2663c2
refs/heads/master
<repo_name>hyunjungpp/practice<file_sep>/src/Thread/ThreadTest.java package Thread; class ThreadClass implements Runnable{ public void run(){ System.out.println("thread is running..."); } } public class ThreadTest { public static void main(String[] args) { ThreadClass t1 = new ThreadClass(); Thread tt1 = new Thread(t1); tt1.start(); try { tt1.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>/src/Sync/SyncTest2.java package Sync; class StaticPrint implements Runnable{ private static int i= 0; // static 권장 노노 @Override public void run() { show(); } public void show() { // 전역변수를 공유한다. 동시에 자원에 접근한다. for (; i < 100; i++) { if ((Thread.currentThread()).getName().equals("a")) { System.out.println("[A" + i + "]"); } else if ((Thread.currentThread()).getName().equals("b")) { System.out.println("[B" + i + "]"); } else if ((Thread.currentThread()).getName().equals("c")) { System.out.println("[C" + i + "]"); } } } public void show2() {//한 스레드가 들어온다. synchronized (StaticPrint.class) { //synchronized있고 없고 차이.(없으면 스레들이 자원을 동시에 나눠 먹어서, 엉망으로 된다....ㅠ) for (; i < 100; i++) { if ((Thread.currentThread()).getName().equals("a")) { System.out.println("[A" + i + "]"); } else if ((Thread.currentThread()).getName().equals("b")) { System.out.println("[B" + i + "]"); } else if ((Thread.currentThread()).getName().equals("c")) { System.out.println("[C" + i + "]"); } } } } } class StaticPrint2 implements Runnable{ /* * 스레드가 같은 자원을 공유하기(멤버 변수 공유) */ private int i= 0; @Override public void run() { show(); } public void show() { for (; i < 100; i++) { if ((Thread.currentThread()).getName().equals("a")) { System.out.println("[A" + i + "]"); } else if ((Thread.currentThread()).getName().equals("b")) { System.out.println("[B" + i + "]"); } else if ((Thread.currentThread()).getName().equals("c")) { System.out.println("[C" + i + "]"); } } } } public class SyncTest2 { public static void main(String[] args) { /*StaticPrint s1 = new StaticPrint(); StaticPrint s2 = new StaticPrint(); StaticPrint s3 = new StaticPrint(); Thread t1 = new Thread(s1,"a"); Thread t2 = new Thread(s2,"b"); Thread t3 = new Thread(s3,"c"); t1.start(); t2.start(); t3.start();*/ //case2 하나의 Runnable생성 후 여러개 thread생성 //3개의 스레드가 멤버변수를 공유 한다. StaticPrint2 ss1 = new StaticPrint2(); Thread tt1 = new Thread(ss1,"a"); Thread tt2 = new Thread(ss1,"b"); Thread tt3 = new Thread(ss1,"c"); tt1.start(); tt2.start(); tt3.start(); } } <file_sep>/src/Socket/EX/Ex_Client.java package Socket.EX; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class Ex_Client { /* * test.exe파일을 서버에게 전송한다. */ public static void main(String[] args) throws UnknownHostException, IOException { Socket s = new Socket("127.0.0.1", 9090); java.io.OutputStream out = s.getOutputStream(); byte[] buffer = new byte[4096]; int readLen; //get all the files from a directory FileInputStream inputStream = new FileInputStream("test.exe"); while((readLen = inputStream.read(buffer)) != -1) { out.write(buffer,0,readLen); } inputStream.close(); s.close(); System.out.println("test.exe"+" is sent."); } } <file_sep>/src/Sync/SyncTest.java package Sync; import java.util.concurrent.locks.ReentrantLock; class ThreadClass implements Runnable{ String name; public ThreadClass(String name) { this.name = name; } static ReentrantLock lock = new ReentrantLock(); @Override public void run() { lock.lock(); try { System.out.println(name); for (int i = 0; i < 30; i++) { System.out.print(i + " "); } System.out.println(); } finally { lock.unlock(); } } } public class SyncTest { public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new ThreadClass("Thread1")); Thread t2 = new Thread(new ThreadClass("Thread2")); t1.start(); t2.start(); ThreadClass.lock.lock(); try { System.out.println("Main"); for (int i = 0; i < 30; i++) { System.out.print(i + " "); } System.out.println(); } finally { ThreadClass.lock.unlock(); } t1.join(); t2.join(); } } <file_sep>/src/Socket/EX/Ex_Server.java package Socket.EX; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; class ThreadClass implements Runnable{ ServerSocket listener; @Override public void run() { final int BUF_SIZE = 512; int recvLen; byte[] buffer = new byte[BUF_SIZE]; try { listener = new ServerSocket(9090); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { while (true) { Socket s = listener.accept(); InputStream input = s.getInputStream(); int cnt = 0; while ((recvLen = input.read(buffer, 0, BUF_SIZE)) != -1) { FileOutputStream fw = new FileOutputStream("recvTest.exe", true); fw.write(buffer, cnt, recvLen); fw.close(); } input.close(); System.out.println("recvTest.exe is received."); } } catch (IOException e) { //e.printStackTrace(); } finally { try { listener.close(); } catch (IOException e) { //e.printStackTrace(); } } } } public class Ex_Server { /* * 클라이언트로부터 파일을 받고 "QUIT"입력까지 대기한다. */ public static void main(String[] args) throws InterruptedException { ThreadClass m1 = new ThreadClass(); Thread t1 = new Thread(m1); t1.start(); String message; Scanner scan = new Scanner(System.in); while (true) { message = scan.nextLine(); System.out.println(message); if (message.equals("q")) { try { t1.join(); scan.close(); break; } catch (InterruptedException e) { e.printStackTrace(); } } } } }
66495c795c3f19003cc8812305a8a755a31d936f
[ "Java" ]
5
Java
hyunjungpp/practice
964fe206a6204bbab2b2e2c3a71e218e3a277226
947e5a5eea20c8c68d824a119de140f5178c705a
refs/heads/master
<file_sep>from datetime import datetime # for date for result dir from multiprocessing import Pool # non-distributed parallellism from time import time # timing from progress.bar import Bar # progress indicators import os # for mkdir import os.path # for path manipulation import yaml # for loading experiment files import sys # for path, exit import shutil # file copying import logging # for logging, duh import argparse # CLI import itertools # imap and count import scoop # for distributed parallellism from boolnet.exptools.learn_boolnet import learn_bool_net import boolnet.exptools.config_tools as cfg def initialise_logging(settings, result_dir): ''' sets up logging with user defined level. ''' level_dict = {'warning': logging.WARNING, 'info': logging.INFO, 'debug': logging.DEBUG, 'none': logging.ERROR} log_filename = os.path.join(result_dir, 'log') # default to 'none' log_level = level_dict[settings.get('debug_level', 'warning')] logging.basicConfig(filename=log_filename, level=log_level) def parse_arguments(): parser = argparse.ArgumentParser(description='') parser.add_argument('experiment', type=argparse.FileType('r'), help='experiment config filename.') parser.add_argument('-n', '--numprocs', metavar='N', type=int, default=8, choices=range(0, 17), help='how many parallel processes to use (give 0 for ' 'scoop).') parser.add_argument('-r', '--result-dir', type=str, metavar='dir', default='experiments/results', help='directory to store results in (in own subdir).') parser.add_argument('-b', '--batch-mode', action='store_true', help='suppress progress bars.') return parser.parse_args() def create_result_dir(base_dir, exp_name): ''' Generates a new timestamped directory for the results and copies the experiment script, experiment file and git hash into it.''' # make directory for the results result_dir = os.path.join(base_dir, '{}_{}_'.format( exp_name, datetime.now().strftime('%y-%m-%d'))) # find the first number i such that 'Results_datetime_i' is not # already a directory and make that new directory result_dir += next(str(i) for i in itertools.count() if not os.path.isdir(result_dir + str(i))) os.makedirs(result_dir) # return the directory name for the results to go in return result_dir def initialise(args): ''' This is responsible for setting up the output directory, checking the git repo isn't dirty and setting up logging.''' # Check version if sys.version_info.major != 3: sys.exit("Requires python 3.") # load experiment file settings = yaml.load(args.experiment, Loader=yaml.CSafeLoader) # create result directory result_dir = create_result_dir(args.result_dir, settings['name']) # copy experiment config into results directory shutil.copy(args.experiment.name, result_dir) return settings, result_dir def run_tasks(tasks, num_processes, out_stream, batch_mode): out_stream.write('[') if num_processes == 1: run_sequential(tasks, out_stream, batch_mode) elif num_processes < 1: run_scooped(tasks, out_stream, batch_mode) else: # Run the actual learning as a parallel process run_parallel(tasks, num_processes, out_stream, batch_mode) out_stream.write(']') def run_parallel(tasks, num_processes, out_stream, batch_mode): ''' runs the given configurations ''' suffix_fmt = 'completed: %(index)d/%(max)d | elapsed: %(elapsed)ds | eta: %(eta)ds' with Pool(processes=num_processes) as pool: if not batch_mode: bar = Bar('Parallelised ({})'.format(num_processes), max=len(tasks), suffix=suffix_fmt) bar.update() # uses unordered map to ensure results are dumped as soon as available for i, result in enumerate(pool.imap_unordered(learn_bool_net, tasks)): cfg.dump_results_partial(result, out_stream, i == 0) if not batch_mode: bar.next() if not batch_mode: bar.finish() def scoop_worker_wrapper(*args, **kwargs): import traceback try: # call to actual worker code return learn_bool_net(*args, **kwargs) except: type, value, tb = sys.exc_info() lines = traceback.format_exception(type, value, tb) print(''.join(lines)) raise def run_scooped(tasks, out_stream, batch_mode): ''' runs the given configurations ''' suffix_fmt = 'completed: %(index)d/%(max)d | elapsed: %(elapsed)ds | eta: %(eta)ds' if not batch_mode: bar = Bar('Scooped', max=len(tasks), suffix=suffix_fmt) bar.update() # uses unordered map to ensure results are dumped as soon as available for i, result in enumerate(scoop.futures.map_as_completed( scoop_worker_wrapper, tasks)): cfg.dump_results_partial(result, out_stream, i == 0) if not batch_mode: bar.next() if not batch_mode: bar.finish() def run_sequential(tasks, out_stream, batch_mode): ''' runs the given configurations ''' suffix_fmt = 'completed: %(index)d/%(max)d | elapsed: %(elapsed)ds | eta: %(eta)ds' if not batch_mode: bar = Bar('Sequential', max=len(tasks), suffix=suffix_fmt) bar.update() # map gives an iterator so results are dumped as soon as available for i, result in enumerate(map(learn_bool_net, tasks)): cfg.dump_results_partial(result, out_stream, i == 0) if not batch_mode: bar.next() if not batch_mode: bar.finish() # ############################## MAIN ####################################### # def main(): start_time = time() args = parse_arguments() settings, result_dir = initialise(args) # initialise logging initialise_logging(settings, result_dir) try: print('Directories initialised.') print('Results in: ' + result_dir + '\n') # generate learning tasks try: configurations = cfg.generate_configurations(settings, args.batch_mode) print('Done: {} configurations generated.'.format( len(configurations))) tasks = cfg.generate_tasks(configurations, args.batch_mode) print('Done: {} tasks generated.\n'.format(len(tasks))) except cfg.ValidationError as err: print(err) print('\nExperiment aborted.') print('Result directory will still exist: {}'.format(result_dir)) logging.shutdown() return result_filename = os.path.join(result_dir, 'results.json') with open(result_filename, 'w') as results_stream: # Run the actual learning as a parallel process run_tasks(tasks, args.numprocs, results_stream, args.batch_mode) total_time = time() - start_time print('Runs completed in {}s.'.format(total_time)) finally: logging.shutdown() if __name__ == '__main__': main() <file_sep>import operator import numpy as np from pytest import fixture from numpy.testing import assert_array_equal as assert_array_equal import boolnet.bintools.operator_iterator as opit class TestIterators: @fixture(params=[ opit.ZeroIncIterator, opit.UnaryANDIncIterator, opit.UnaryORIncIterator, opit.ANDIncIterator, opit.ORIncIterator, opit.AddIncIterator, opit.SubIncIterator, opit.MulIncIterator]) def include_iterator(self, request): return request.param @fixture(params=[ opit.ZeroExcIterator, opit.UnaryANDExcIterator, opit.UnaryORExcIterator, opit.ANDExcIterator, opit.ORExcIterator, opit.AddExcIterator, opit.SubExcIterator, opit.MulExcIterator]) def exclude_iterator(self, request): return request.param @fixture(params=np.random.randint(2, 100, 5)) def index_harness(self, request): max_index = request.param num_indices = np.random.randint(max_index-1, max_index) in_indices = np.random.choice(max_index, size=num_indices, replace=False) in_indices = np.array(np.sort(in_indices), dtype=np.uint64) ex_indices = np.array([i for i in range(max_index) if i not in in_indices]) return (in_indices, ex_indices, max_index) def test_include_indices(self, include_iterator, index_harness): indices, _, _ = index_harness expected = np.array(indices, copy=True) actual = np.array(list(include_iterator(indices, 2)))[:, 0] assert_array_equal(expected, actual) def test_exclude_indices(self, exclude_iterator, index_harness): indices, expected, max_index = index_harness actual = np.array(list(exclude_iterator(indices, 2, max_index)))[:, 0] assert_array_equal(expected, actual) class TestExampleIteratorFactory: @fixture(params=[ (opit.AND, operator.__and__), (opit.OR, operator.__or__), (opit.ADD, operator.add), (opit.SUB, operator.sub), (opit.MUL, operator.mul) ]) def binary_op(self, request): return request.param @fixture(params=[ (opit.ZERO, lambda x, m: 0), (opit.UNARY_OR, lambda x, m: int(x > 0)), (opit.UNARY_AND, lambda x, m: int(x == m - 1)) ]) def unary_op(self, request): return request.param @fixture(params=list(range(1, 7))) def operand_width(self, request): return request.param def test_operator_factory_include(self, binary_op, operand_width): operator_id, operator_function = binary_op Nb = int(operand_width) upper = 2**Nb max_indices = 2**(2*Nb) Ne = np.random.randint(min(100, max_indices)) indices = np.random.choice(max_indices, Ne, replace=False) indices = np.array(indices, dtype=np.uint64) factory = opit.OpExampleIterFactory(indices, Nb, operator_id, False) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = operator_function(int(i // upper), int(i % upper)) if expected_out < 0: expected_out += upper assert expected_out == tgt def test_operator_factory_exclude(self, binary_op, operand_width): Nb = operand_width upper = 2**Nb N = 2**(2*Nb) Ne = np.random.randint(min(100, N)) ex_indices = np.random.choice(N, Ne, replace=False) ex_indices = np.array(ex_indices, dtype=np.uint64) indices = (i for i in range(N) if i not in ex_indices) factory = opit.OpExampleIterFactory(ex_indices, Nb, binary_op[0], True) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = binary_op[1](int(i // upper), int(i % upper)) if expected_out < 0: expected_out += upper assert expected_out == tgt def test_unary_operator_factory_include(self, unary_op, operand_width): Nb = int(operand_width) N = 2**Nb Ne = np.random.randint(min(100, N)) indices = np.random.choice(N, Ne, replace=False) indices = np.array(indices, dtype=np.uint64) factory = opit.OpExampleIterFactory(indices, Nb, unary_op[0], False) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = unary_op[1](i, N) assert expected_out == tgt def test_unary_operator_factory_exclude(self, unary_op, operand_width): Nb = operand_width N = 2**Nb Ne = np.random.randint(min(100, N)) ex_indices = np.sort(np.random.choice(N, Ne, replace=False)) ex_indices = np.array(ex_indices, dtype=np.uint64) indices = (i for i in range(N) if i not in ex_indices) factory = opit.OpExampleIterFactory(ex_indices, Nb, unary_op[0], True) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = unary_op[1](i, N) assert expected_out == tgt <file_sep>from random import random from math import exp from copy import copy from itertools import chain, repeat from collections import deque, namedtuple import operator as op import numpy as np import networkx as nx import sys import logging OptimiserResult = namedtuple('OptimiserResult', [ 'representation', 'error', 'best_iteration', 'iteration', 'restarts']) def stepped_exp_decrease(init_temp, rate, num_temps, steps_per_temp): return chain.from_iterable(repeat(t, steps_per_temp) for t in geometric(init_temp, rate, num_temps)) def geometric(a, r, n): val = a for i in range(n): yield val val *= r class RestartLocalSearch: def initialise(self, parameters): # unpack options try: self.guiding_function = parameters['guiding_function'] if parameters['minimise']: self.is_as_good = op.le self.is_better = op.lt else: self.is_as_good = op.ge self.is_better = op.gt self.stopping_condition = parameters['stopping_condition'] self.return_option = parameters.get('return', 'best') # self.max_restarts = parameters.get('max_restarts', 0) self.max_restarts = parameters.get('max_restarts', 0) self.reached_stopping_condition = False except KeyError: print('Optimiser parameters missing!', file=sys.stderr) raise def move(self, state): state.move_to_random_neighbour() def undo_move(self, state): state.revert_move() def _optimise(self, state): raise NotImplemented def run(self, state, parameters): # unpack options self.initialise(parameters) # original_state = state.representation() for i in range(self.max_restarts + 1): # state.set_representation(original_state) step_result = self._optimise(state) if self.reached_stopping_condition: break elif i < self.max_restarts: state.randomise() return OptimiserResult( representation=step_result.representation, error=step_result.error, best_iteration=step_result.best_iteration, iteration=step_result.iteration, restarts=i) class HC(RestartLocalSearch): def initialise(self, parameters): super().initialise(parameters) try: self.max_iterations = parameters['max_iterations'] except KeyError: print('Optimiser parameters missing!', file=sys.stderr) raise def _optimise(self, state): # Calculate initial error error = self.guiding_function(state) # error = evaluator.function_value(self.guiding_function) # set up aspiration criteria best_iteration = 0 self.reached_stopping_condition = False # optimisation loop for iteration in range(self.max_iterations): # Stop on user defined condition if self.stopping_condition(state): self.reached_stopping_condition = True break # perform random move self.move(state) # calculate error for new state new_error = self.guiding_function(state) # new_error = evaluator.function_value(self.guiding_function) # Determine whether to accept the new state if self.accept(new_error, error): error = new_error best_iteration = iteration else: self.undo_move(state) # In any case, clear the move history to save memory # and prevent accidentally undoing accepted moves later state.clear_history() return OptimiserResult( representation=state.representation, error=error, best_iteration=best_iteration, iteration=iteration, restarts=None) def accept(self, new_error, current_error): if self.is_as_good(new_error, current_error): return True class LAHC(RestartLocalSearch): def initialise(self, parameters): super().initialise(parameters) try: self.cost_list_len = parameters['cost_list_length'] self.max_iterations = parameters['max_iterations'] except KeyError: print('Optimiser parameters missing!', file=sys.stderr) raise def _optimise(self, state): # Calculate initial error error = self.guiding_function(state) # set up aspiration criteria best_error = error best_representation = copy(state.representation) best_iteration = 0 # initialise cost list self.costs = deque(repeat(error, self.cost_list_len)) if self.stopping_condition(state): self.reached_stopping_condition = True return OptimiserResult( representation=best_representation, error=best_error, best_iteration=0, iteration=0, restarts=None) else: self.reached_stopping_condition = False # optimisation loop for iteration in range(self.max_iterations): # perform random move self.move(state) # calculate error for new state new_error = self.guiding_function(state) # Keep best state seen if new_error < best_error: best_error = new_error best_representation = copy(state.representation) best_iteration = iteration # Stop on user defined condition if self.stopping_condition(state): self.reached_stopping_condition = True break # Determine whether to accept the new state if self.accept(new_error, error): error = new_error else: self.undo_move(state) # Clear the move history to save memory and prevent accidentally # undoing accepted moves later state.clear_history() if self.return_option == 'last': best_representation = copy(state.representation) return OptimiserResult( representation=best_representation, error=best_error, best_iteration=best_iteration, iteration=iteration, restarts=None) def accept(self, new_error, current_error): oldest_error = self.costs.popleft() if (self.is_as_good(new_error, current_error) or self.is_better(new_error, oldest_error)): self.costs.append(new_error) return True else: self.costs.append(current_error) return False class LAHC_perc(LAHC): def initialise(self, parameters): super().initialise(parameters) try: self.perc_period = parameters['percolation_period'] except KeyError: print('Optimiser parameters missing!', file=sys.stderr) raise def _build_digraph(self, state): G = nx.DiGraph() Ni = state.Ni G.add_nodes_from(range(Ni)) edges = [] for g, gate in enumerate(state.gates): edges.append((gate[0], g + Ni)) edges.append((gate[1], g + Ni)) G.add_edges_from(edges) return G def _percolate(self, state): Ni, No = state.Ni, state.No gates = np.array(state.gates) G = self._build_digraph(state) connected = np.array(state.connected_sources()) # build a network with only the connected nodes remaining G.remove_nodes_from(np.flatnonzero(connected == 0)) G_percolated = nx.convert_node_labels_to_integers(G) percolated_nodes = G_percolated.reverse().adjacency_list() # double any singleton entries for i in range(len(percolated_nodes)): if len(percolated_nodes[i]) == 1: percolated_nodes[i].append(percolated_nodes[i][0]) percolated_internal_nodes = percolated_nodes[Ni:-No] percolated_output_nodes = percolated_nodes[-No:] new_gates = np.array(gates) Ng_prc_internal = len(percolated_internal_nodes) # swap the the activation functions around prc_gate_idxs = np.flatnonzero(connected[Ni:-No]) oth_gate_idxs = np.flatnonzero(connected[Ni:-No] == 0) new_gates[:Ng_prc_internal, 2] = gates[prc_gate_idxs, 2] new_gates[Ng_prc_internal:-No, 2] = gates[oth_gate_idxs, 2] new_gates[Ng_prc_internal:-No, 2] = gates[oth_gate_idxs, 2] # copy the internal percolated nodes into the first block new_gates[:Ng_prc_internal, :2] = np.array(percolated_internal_nodes) # copy the percolated outputs back into the last No positions new_gates[-No:, :2] = np.array(percolated_output_nodes) state.set_gates(new_gates) def _optimise(self, state): # Calculate initial error error = self.guiding_function(state) # set up aspiration criteria best_error = error best_representation = copy(state.representation) best_iteration = 0 # initialise cost list self.costs = deque(repeat(error, self.cost_list_len)) if self.stopping_condition(state): self.reached_stopping_condition = True return OptimiserResult( representation=best_representation, error=best_error, best_iteration=0, iteration=0, restarts=None) else: self.reached_stopping_condition = False # optimisation loop for iteration in range(self.max_iterations): if iteration % self.perc_period == self.perc_period - 1: self._percolate(state) # perform random move self.move(state) # calculate error for new state new_error = self.guiding_function(state) # Keep best state seen if new_error < best_error: best_error = new_error best_representation = copy(state.representation) best_iteration = iteration # Stop on user defined condition if self.stopping_condition(state): self.reached_stopping_condition = True break # Determine whether to accept the new state if self.accept(new_error, error): error = new_error else: self.undo_move(state) # Clear the move history to save memory and prevent accidentally # undoing accepted moves later state.clear_history() if self.return_option == 'last': best_representation = copy(state.representation) return OptimiserResult( representation=best_representation, error=best_error, best_iteration=best_iteration, iteration=iteration, restarts=None) def accept(self, new_error, current_error): oldest_error = self.costs.popleft() if (self.is_as_good(new_error, current_error) or self.is_better(new_error, oldest_error)): self.costs.append(new_error) return True else: self.costs.append(current_error) return False class SA(RestartLocalSearch): def accept(self, old_error, new_error, temperature): delta = abs(new_error - old_error) if self.is_better(new_error, old_error): delta *= -1 # DETERMINISTIC # return delta < -temperature or 0 <= delta < temperature # STOCHASTIC # Accept when dE is non-negative or with probability P = e^(-dE/T) return (delta <= 0) or (temperature > 0 and random() < exp(-delta/temperature)) def initialise(self, parameters): super().initialise(parameters) try: self.num_temps = parameters['num_temps'] self.steps_per_temp = parameters['steps_per_temp'] self.init_temp = parameters['init_temp'] self.temp_rate = parameters['temp_rate'] except KeyError: print('Optimiser parameters missing!', file=sys.stderr) raise self.temperatures = stepped_exp_decrease( self.init_temp, self.temp_rate, self.num_temps, self.steps_per_temp) def _optimise(self, state): # Calculate initial error error = self.guiding_function(state) # Setup aspiration criteria best_error = error best_representation = copy(state.representation) best_iteration = 0 best_error_for_temp = error last_temp = self.init_temp # so we can check for temp changes self.reached_stopping_condition = False # annealing loop for iteration, temp in enumerate(self.temperatures): # Log error on new temperature if logging best_error_for_temp = min(best_error_for_temp, error) if last_temp != temp: logging.debug('temp: %f best_err:%f ', last_temp, best_error_for_temp) best_error_for_temp = error last_temp = temp # perform random move self.move(state) # calculate error for new state new_error = self.guiding_function(state) # Keep best state seen if new_error < best_error: best_representation = copy(state.representation) best_error = new_error best_iteration = iteration # Stop on user defined condition if self.stopping_condition(state): self.reached_stopping_condition = True break # Determine whether to accept the new state if self.accept(error, new_error, temp): error = new_error else: self.undo_move(state) # In any case, clear the move history to save memory # and prevent accidentally undoing accepted moves later state.clear_history() if self.return_option == 'last': best_representation = copy(state.representation) return OptimiserResult( representation=best_representation, error=best_error, best_iteration=best_iteration, iteration=iteration, restarts=None) <file_sep>from copy import copy from collections import namedtuple import numpy as np import bitpacking.packing as pk import minfs.feature_selection as mfs import boolnet.bintools.functions as fn from boolnet.utils import PackedMatrix, order_from_rank, inverse_permutation from boolnet.network.networkstate import BNState from time import time LearnerResult = namedtuple('LearnerResult', [ 'network', 'partial_networks', 'best_errors', 'best_iterations', 'final_iterations', 'target_order', 'feature_sets', 'restarts', 'optimisation_time', 'other_time']) def fn_value_stop_criterion(func_id, name, limit=None): if limit is None: limit = fn.optimum(func_id) if fn.is_minimiser(func_id): return lambda state: state.function_value(name) <= limit else: return lambda state: state.function_value(name) >= limit class BasicLearner: def _setup(self, optimiser, parameters): # Gate generation self.gate_generator = parameters['gate_generator'] self.node_funcs = parameters['network']['node_funcs'] self.budget = parameters['network']['Ng'] # Instance self.problem_matrix = parameters['training_set'] self.Ni = self.problem_matrix.Ni self.No = self.problem_matrix.No self.input_matrix, self.target_matrix = np.split( self.problem_matrix, [self.Ni]) self.Ne = self.problem_matrix.Ne # Optimiser self.optimiser = optimiser self.opt_params = copy(parameters['optimiser']) gf_name = self.opt_params['guiding_function'] self.guiding_fn_id = fn.function_from_name(gf_name) self.guiding_fn_params = self.opt_params.get( 'guiding_function_parameters', {}) self.opt_params['minimise'] = fn.is_minimiser(self.guiding_fn_id) # convert shorthands for target order if parameters['target_order'] == 'lsb': self.target_order = np.arange(self.No, dtype=np.uintp) elif parameters['target_order'] == 'msb': self.target_order = np.arange(self.No, dtype=np.uintp)[::-1] elif parameters['target_order'] == 'random': self.target_order = np.random.permutation(self.No).astype(np.uintp) elif parameters['target_order'] == 'auto': self.target_order = None # this key is only required if auto-targetting self.mfs_metric = parameters['minfs_selection_metric'] else: self.target_order = np.array(parameters['target_order'], dtype=np.uintp) # Optional minfs solver time limit self.minfs_params = parameters.get('minfs_solver_params', {}) self.minfs_solver = parameters.get('minfs_solver', 'cplex') # add functor for evaluating the guiding func self.guiding_fn_eval_name = 'guiding' self.opt_params['guiding_function'] = lambda x: x.function_value( self.guiding_fn_eval_name) # Check if user supplied a stopping condition condition = self.opt_params.get('stopping_condition', None) if condition and condition[0] != 'guiding': limit = condition[1] self.stopping_fn_eval_name = 'stop' self.stopping_fn_id = fn.function_from_name(condition[0]) if len(condition) > 2: self.stopping_fn_params = condition[2] else: self.stopping_fn_params = {} else: if condition: limit = condition[1] self.stopping_fn_eval_name = self.guiding_fn_eval_name self.stopping_fn_id = self.guiding_fn_id self.stopping_fn_params = self.guiding_fn_params limit = None self.opt_params['stopping_condition'] = fn_value_stop_criterion( self.stopping_fn_id, self.stopping_fn_eval_name, limit) # check parameters if self.guiding_fn_id not in fn.scalar_functions(): raise ValueError('Invalid guiding function: {}'.format(gf_name)) if max(self.node_funcs) > 15 or min(self.node_funcs) < 0: raise ValueError('\'node_funcs\' must come from [0, 15]: {}'. format(self.node_funcs)) def run(self, optimiser, parameters): t0 = time() self._setup(optimiser, parameters) if self.target_order is None: # determine the target order by ranking feature sets mfs_features = pk.unpackmat(self.input_matrix, self.Ne) mfs_targets = pk.unpackmat(self.target_matrix, self.Ne) # use external solver for minFS rank, feature_sets = mfs.ranked_feature_sets( mfs_features, mfs_targets, self.mfs_metric, self.minfs_solver, self.minfs_params) # randomly pick from possible exact orders self.target_order = order_from_rank(rank) # build the network state gates = self.gate_generator(self.budget, self.Ni, self.No, self.node_funcs) # reorder problem matrix outputs = self.problem_matrix[-self.No:, :] outputs[:] = outputs[self.target_order, :] state = BNState(gates, self.problem_matrix) # add the guiding function to be evaluated state.add_function(self.guiding_fn_id, self.guiding_fn_eval_name, self.guiding_fn_params) # add the stopping function to be evaluated if (self.stopping_fn_eval_name is not None and self.stopping_fn_eval_name != self.guiding_fn_eval_name): state.add_function(self.stopping_fn_id, self.stopping_fn_eval_name, self.stopping_fn_params) t1 = time() # run the optimiser opt_result = self.optimiser.run(state, self.opt_params) t2 = time() # undo ordering inverse_order = inverse_permutation(self.target_order) outputs[:] = outputs[inverse_order, :] gates = np.array(opt_result.representation.gates) out_gates = gates[-self.No:, :] out_gates[:] = out_gates[inverse_order, :] opt_result.representation.set_gates(gates) return LearnerResult( network=opt_result.representation, best_errors=[opt_result.error], best_iterations=[opt_result.best_iteration], final_iterations=[opt_result.iteration], restarts=[opt_result.restarts], target_order=self.target_order, feature_sets=None, partial_networks=[], optimisation_time=t2-t1, other_time=t1-t0) <file_sep>import time import random import logging import re import numpy as np import bitpacking.packing as pk import boolnet.bintools.functions as fn import boolnet.bintools.example_generator as gen import boolnet.network.networkstate as ns import boolnet.utils as utils import boolnet.learners as learners import boolnet.optimisers as optimisers import boolnet.exptools.fastrand as fastrand import boolnet.exptools.config_filtering as cf OPTIMISERS = { 'SA': optimisers.SA(), 'LAHC': optimisers.LAHC(), 'LAHC_perc': optimisers.LAHC_perc(), 'HC': optimisers.HC(), } LEARNERS = { 'basic': learners.BasicLearner() } def seed_rng(seed): # if seed is None this will use OS randomness source to generate a seed if seed is None: random.seed() seed = random.randint(1, 2**32) np.random.seed(seed) fastrand.seed(seed) return seed def random_network(Ng, Ni, No, node_funcs): # generate random feedforward network gates = np.empty(shape=(Ng, 3), dtype=np.int32) for g in range(Ng): # don't allow connecting outputs together gates[g, 0] = np.random.randint(min(g, Ng - No) + Ni) gates[g, 1] = np.random.randint(min(g, Ng - No) + Ni) gates[:, 2] = np.random.choice(node_funcs, size=Ng) return gates def build_training_set(mapping): if mapping['type'] == 'raw_split': trg_indices = mapping.get('training_indices', None) if trg_indices is not None: return utils.sample_packed(mapping['training_set'], trg_indices) else: return mapping['training_set'] elif mapping['type'] == 'raw_unsplit': return utils.sample_packed(mapping['matrix'], mapping['training_indices']) elif mapping['type'] == 'operator': indices = mapping['training_indices'] operator = mapping['operator'] Nb = mapping['Nb'] No = mapping['No'] return gen.packed_from_operator(indices, Nb, No, operator) def add_noise(mapping, rate): Ne, No = mapping.Ne, mapping.No num_flips = int(np.round(mapping.Ne * rate)) if num_flips == 0: # rather than complicating code to handle 0 flips return 0 effective_rate = num_flips / Ne noise_mask = np.zeros((Ne, No), dtype=np.uint8) noise_mask[-num_flips:, :] = 1 for i in range(No): np.random.shuffle(noise_mask[:, i]) noise_mask = pk.packmat(noise_mask) # XOR will flip all bits where the noise mask is '1' mapping[-No:, :] = np.bitwise_xor(mapping[-No:, :], noise_mask).astype(mapping.dtype) return effective_rate def learn_bool_net(parameters): start_time = time.monotonic() seed = seed_rng(parameters['learner'].get('seed', None)) # if no given seed then store to allow reporting in results parameters['learner']['seed'] = seed learner_params = parameters['learner'] optimiser_params = parameters['learner']['optimiser'] training_set = build_training_set(parameters['mapping']) if 'add_noise' in parameters['data']: rate = add_noise(training_set, parameters['data']['add_noise']) parameters['actual_noise'] = rate learner_params['training_set'] = training_set learner_params['gate_generator'] = random_network # Handle flexible network size if str(learner_params['network']['Ng']).endswith('n'): n = int(str(learner_params['network']['Ng'])[:-1]) Ng = n * training_set.No learner_params['network']['Ng'] = Ng learner = LEARNERS[learner_params['name']] optimiser = OPTIMISERS[optimiser_params['name']] setup_end_time = time.monotonic() # learn the network learner_result = learner.run(optimiser, learner_params) learning_end_time = time.monotonic() results = build_result_map(parameters, learner_result) end_time = time.monotonic() # add timing results if parameters.get('verbose_timing'): results['setup_time'] = setup_end_time - start_time results['result_time'] = end_time - learning_end_time results['total_time'] = end_time - start_time results['learning_time'] = learning_end_time - setup_end_time return results def build_states(mapping, gates, objectives): ''' objectives should be a list of (func_id, ordering, name) tuples.''' if mapping['type'] == 'raw_split': trg_indices = mapping.get('training_indices', None) test_indices = mapping.get('test_indices', None) M_trg = mapping['training_set'] M_test = mapping['test_set'] if trg_indices is not None: M_trg = utils.sample_packed(M_trg, mapping['training_indices']) if test_indices is not None: M_test = utils.sample_packed(M_test, mapping['test_indices']) S_trg = ns.BNState(gates, M_trg) S_test = ns.BNState(gates, M_test) elif mapping['type'] == 'raw_unsplit': M = mapping['matrix'] trg_indices = mapping['training_indices'] test_indices = mapping['test_indices'] if test_indices is None: M_trg, M_test = utils.partition_packed(M, trg_indices) else: M_trg = utils.sample_packed(M, trg_indices) M_test = utils.sample_packed(M, test_indices) S_trg = ns.BNState(gates, M_trg) S_test = ns.BNState(gates, M_test) elif mapping['type'] == 'operator': trg_indices = mapping['training_indices'] test_indices = mapping['test_indices'] op = mapping['operator'] Nb = mapping['Nb'] No = mapping['No'] # window_size = mapping['window_size'] S_trg = ns.state_from_operator(gates, trg_indices, Nb, No, op) if test_indices is None: S_test = ns.state_from_operator(gates, trg_indices, Nb, No, op, exclude=True) else: S_test = ns.state_from_operator(gates, test_indices, Nb, No, op) else: raise ValueError('Invalid mapping type: {}'.format(mapping['type'])) # add functions to be later called by name for func, name, params in objectives: S_trg.add_function(func, name, params=params) S_test.add_function(func, name, params=params) return S_trg, S_test def build_result_map(parameters, learner_result): guiding_function = fn.function_from_name( parameters['learner']['optimiser']['guiding_function']) guiding_function_params = parameters['learner']['optimiser'].get( 'guiding_function_parameters', {}) final_network = learner_result.network gates = final_network.gates # build evaluators for training and test data objective_functions = [ (guiding_function, 'guiding', guiding_function_params), (fn.E1, 'e1', {}), (fn.E1_MCC, 'e1_mcc', {}), (fn.CORRECTNESS, 'correctness', {}), (fn.PER_OUTPUT_ERROR, 'per_output_error', {}), (fn.PER_OUTPUT_MCC, 'per_output_mcc', {})] train_state, test_state = build_states( parameters['mapping'], gates, objective_functions) results = { 'Ni': final_network.Ni, 'No': final_network.No, 'Ng': final_network.Ng, 'best_step': learner_result.best_iterations, 'steps': learner_result.final_iterations, 'best_err': learner_result.best_errors, 'trg_error': train_state.function_value('e1'), 'trg_cor': train_state.function_value('correctness'), 'trg_mcc': train_state.function_value('e1_mcc'), 'trg_err_gf': train_state.function_value('guiding'), 'test_error': test_state.function_value('e1'), 'test_cor': test_state.function_value('correctness'), 'test_mcc': test_state.function_value('e1_mcc'), 'test_err_gf': test_state.function_value('guiding'), 'Ne': train_state.Ne, 'tgt_order': np.array(learner_result.target_order, dtype=np.uintp), 'opt_time': learner_result.optimisation_time, 'other_time': learner_result.other_time } # Optional results if parameters.get('record_final_net', True): results['final_net'] = np.array(final_network.gates) if parameters.get('record_intermediate_nets', False): for i, net in enumerate(learner_result.partial_networks): key = 'net_{}'.format(i) results[key] = np.array(net.gates) if learner_result.feature_sets is not None: for strata, strata_f_sets in enumerate(learner_result.feature_sets): for target, fs in enumerate(strata_f_sets): # only record FSes if they exist if fs is not None: key = 'fs_s{}_t{}'.format(strata, target) results[key] = fs if learner_result.restarts is not None: results['restarts'] = learner_result.restarts if 'actual_noise' in parameters: results['actual_noise'] = parameters['actual_noise'] # multi-part results for bit, v in enumerate(train_state.function_value('per_output_error')): key = 'trg_err_tgt_{}'.format(bit) results[key] = v for bit, v in enumerate(test_state.function_value('per_output_error')): key = 'test_err_tgt_{}'.format(bit) results[key] = v for bit, v in enumerate(train_state.function_value('per_output_mcc')): key = 'trg_mcc_tgt_{}'.format(bit) results[key] = v for bit, v in enumerate(test_state.function_value('per_output_mcc')): key = 'test_mcc_tgt_{}'.format(bit) results[key] = v # for bit, v in enumerate(final_network.max_node_depths()): # key = 'max_depth_tgt_{}'.format(bit) # results[key] = v if 'notes' in parameters: results['notes'] = ''.join(parameters['notes'].values()) # handle requests to log keys log_keys = parameters.get('log_keys', []) # strip out warning flags log_keys_just_paths = [[k, v] for k, _, v in log_keys] # match dict paths to given patterns and pull out corresponding values passed_through_params = cf.filter_keys(parameters, log_keys_just_paths) # Generate warnings for reserved keys - needs to run before merging dicts for key, _, _ in log_keys: if key in results: logging.warning( 'log_keys: %s ignored - reserved key.', key) # Generating warnings for missing but required patterns for key, required, pattern in log_keys: # handle keys that contain insert positions if '{}' in key: checker = re.compile(key.format('.*')).fullmatch else: checker = re.compile(key).fullmatch # check at least one key in the result dict matches the given key if required and all(checker(k) is None for k in passed_through_params): logging.warning(('log_keys: %s is required but does not match any ' 'path in the configuration.'), pattern) # merge dictionaries, giving preference to results ahead of parameters passed_through_params.update(results) return passed_through_params <file_sep>import operator import os.path import numpy as np from pytest import fixture from numpy.testing import assert_array_equal as assert_array_equal from bitpacking.packing import packed_type, packmat import boolnet.bintools.operator_iterator as opit from boolnet.bintools.example_generator import ( packed_from_operator, PackedExampleGenerator) class TestIterators: @fixture(params=[ opit.ZeroIncIterator, opit.UnaryANDIncIterator, opit.UnaryORIncIterator, opit.ANDIncIterator, opit.ORIncIterator, opit.AddIncIterator, opit.SubIncIterator, opit.MulIncIterator]) def include_iterator(self, request): return request.param @fixture(params=[ opit.ZeroExcIterator, opit.UnaryANDExcIterator, opit.UnaryORExcIterator, opit.ANDExcIterator, opit.ORExcIterator, opit.AddExcIterator, opit.SubExcIterator, opit.MulExcIterator]) def exclude_iterator(self, request): return request.param @fixture(params=np.random.randint(2, 100, 5)) def index_harness(self, request): max_index = request.param num_indices = np.random.randint(max_index-1, max_index) in_indices = np.random.choice(max_index, size=num_indices, replace=False) in_indices = np.array(np.sort(in_indices), dtype=np.uint64) ex_indices = np.array([i for i in range(max_index) if i not in in_indices]) return (in_indices, ex_indices, max_index) def test_include_indices(self, include_iterator, index_harness): indices, _, _ = index_harness expected = np.array(indices, copy=True) actual = np.array(list(include_iterator(indices, 2)))[:, 0] assert_array_equal(expected, actual) def test_exclude_indices(self, exclude_iterator, index_harness): indices, expected, max_index = index_harness actual = np.array(list(exclude_iterator(indices, 2, max_index)))[:, 0] assert_array_equal(expected, actual) class TestExampleIteratorFactory: @fixture(params=[ (opit.AND, operator.__and__), (opit.OR, operator.__or__), (opit.ADD, operator.add), (opit.SUB, operator.sub), (opit.MUL, operator.mul) ]) def binary_op(self, request): return request.param @fixture(params=[ (opit.ZERO, lambda x, m: 0), (opit.UNARY_OR, lambda x, m: int(x > 0)), (opit.UNARY_AND, lambda x, m: int(x == m - 1)) ]) def unary_op(self, request): return request.param @fixture(params=list(range(1, 7))) def operand_width(self, request): return request.param def test_operator_factory_include(self, binary_op, operand_width): operator_id, operator_function = binary_op Nb = int(operand_width) upper = 2**Nb max_indices = 2**(2*Nb) Ne = np.random.randint(min(100, max_indices)) indices = np.random.choice(max_indices, Ne, replace=False) indices = np.array(indices, dtype=np.uint64) factory = opit.OpExampleIterFactory(indices, Nb, operator_id, False) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = operator_function(int(i // upper), int(i % upper)) if expected_out < 0: expected_out += upper assert expected_out == tgt def test_operator_factory_exclude(self, binary_op, operand_width): Nb = operand_width upper = 2**Nb N = 2**(2*Nb) Ne = np.random.randint(min(100, N)) ex_indices = np.random.choice(N, Ne, replace=False) ex_indices = np.array(ex_indices, dtype=np.uint64) indices = (i for i in range(N) if i not in ex_indices) factory = opit.OpExampleIterFactory( ex_indices, Nb, binary_op[0], True) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = binary_op[1](int(i // upper), int(i % upper)) if expected_out < 0: expected_out += upper assert expected_out == tgt def test_unary_operator_factory_include(self, unary_op, operand_width): Nb = int(operand_width) max_indices = 2**Nb Ne = np.random.randint(min(100, max_indices)) indices = np.random.choice(max_indices, Ne, replace=False) indices = np.array(indices, dtype=np.uint64) factory = opit.OpExampleIterFactory(indices, Nb, unary_op[0], False) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = unary_op[1](i, max_indices) assert expected_out == tgt def test_unary_operator_factory_exclude(self, unary_op, operand_width): Nb = operand_width N = 2**Nb Ne = np.random.randint(min(100, N)) ex_indices = np.sort(np.random.choice(N, Ne, replace=False)) ex_indices = np.array(ex_indices, dtype=np.uint64) indices = (i for i in range(N) if i not in ex_indices) factory = opit.OpExampleIterFactory( ex_indices, Nb, unary_op[0], True) for i, (inp, tgt) in zip(indices, iter(factory)): assert i == inp expected_out = unary_op[1](i, N) assert expected_out == tgt class TestExampleGenerator: op_map = {'add': opit.ADD, 'sub': opit.SUB, 'mul': opit.MUL} cache = dict() @fixture(params=['add4.npz', 'add8.npz', 'sub4.npz', 'sub8.npz', 'mul2.npz', 'mul3.npz', 'mul4.npz', 'mul6.npz', 'mul2f.npz', 'mul3f.npz', 'mul4f.npz', 'mul6f.npz']) def file_func_inst(self, request, test_location): return test_location, request.param @fixture(params=[True, False]) def exclude(self, request): return request.param def load_file_func_instance(self, instance): location, name = instance fname = os.path.join(location, 'functions', name) if fname not in self.cache: with np.load(fname) as data: inp = data['input_matrix'] tgt = data['target_matrix'] self.cache[fname] = (inp, tgt) inp = np.array(self.cache[fname][0], copy=True) tgt = np.array(self.cache[fname][1], copy=True) return self.op_map[name[:3]], inp, tgt def build_generator_instance(self, instance, exclude): op, inp, tgt = self.load_file_func_instance(instance) Ne, Ni = inp.shape _, No = tgt.shape indices = np.random.choice(Ne, min(100, Ne-1), replace=False) indices = np.sort(indices) inp = inp[indices, :] tgt = tgt[indices, :] inp_p = packmat(inp) tgt_p = packmat(tgt) if exclude: indices = [i for i in range(Ne) if i not in indices] indices = np.array(indices, dtype=packed_type) factory = opit.OpExampleIterFactory( indices, Ni//2, op, Ne if exclude else 0) gen = PackedExampleGenerator(factory, No) return (gen, inp_p, tgt_p) @fixture(params=[0, np.random.rand(), 1]) def block_fraction(self, request): return request.param def test_packed_generation(self, file_func_inst, exclude, block_fraction): generator_instance = self.build_generator_instance( file_func_inst, exclude) generator, expected_inp, expected_tgt = generator_instance actual_inp = np.zeros_like(expected_inp) actual_tgt = np.zeros_like(expected_tgt) Ni, cols = expected_inp.shape No, _ = expected_tgt.shape block_width = np.round(cols * block_fraction) block_width = int(np.clip(block_width, 1, cols)) i = 0 while generator: generator.next_examples(actual_inp[:, i: i + block_width], actual_tgt[:, i: i + block_width]) i += block_width assert_array_equal(expected_inp, actual_inp) assert_array_equal(expected_tgt, actual_tgt) def test_packed_from_operator_inc(self, file_func_inst, exclude): op, inp, tgt = self.load_file_func_instance(file_func_inst) Ne, Ni = inp.shape _, No = tgt.shape indices = np.random.choice(Ne, min(100, Ne-1), replace=False) indices = np.sort(indices) indices = np.array(indices, dtype=packed_type) if exclude: expected_indices = [i for i in range(Ne) if i not in indices] expected_indices = np.array(expected_indices, dtype=packed_type) else: expected_indices = indices expected = packmat(np.hstack(( inp[expected_indices, :], tgt[expected_indices, :]))) actual = packed_from_operator(indices, Ni//2, No, op, exclude) assert_array_equal(expected, actual) <file_sep>import numpy as np import bitpacking.packing as pk class PackedMatrix(np.ndarray): def __new__(cls, input_array, Ne, Ni=0): # Input array is an already formed ndarray instance # We first cast to be our class type obj = np.asarray(input_array).view(cls) # add the new attribute to the created instance obj.Ne = Ne obj.Ni = Ni # Finally, we must return the newly created object: return obj def __array_finalize__(self, obj): if obj is None: return self.Ne = getattr(obj, 'Ne', None) self.Ni = getattr(obj, 'Ni', None) @property def No(self): return self.shape[0] - self.Ni def split(self): return np.split(self, [self.Ni]) def __reduce__(self): # Get the parent's __reduce__ tuple pickled_state = super(PackedMatrix, self).__reduce__() # Create our own tuple to pass to __setstate__ new_state = pickled_state[2] + (self.Ne, self.Ni) # Return a tuple that replaces the parent's __setstate__ with our own return (pickled_state[0], pickled_state[1], new_state) def __setstate__(self, state): self.Ne = state[-2] # Set the info attribute self.Ni = state[-1] # Set the info attribute # Call the parent's __setstate__ with the other tuple elements. super(PackedMatrix, self).__setstate__(state[0:-2]) def partition_packed(matrix, indices): M_trg, M_test = pk.partition_columns(matrix, matrix.Ne, indices) # return the PackedMatrix types to provide meta-data Ne = indices.shape[0] training_matrix = PackedMatrix(M_trg, Ne=Ne, Ni=matrix.Ni) test_matrix = PackedMatrix(M_test, Ne=matrix.Ne-Ne, Ni=matrix.Ni) return training_matrix, test_matrix def sample_packed(matrix, indices, invert=False): sample = pk.sample_columns(matrix, matrix.Ne, indices, invert) Ne = matrix.Ne - indices.size if invert else indices.size return PackedMatrix(sample, Ne=Ne, Ni=matrix.Ni) def unpack(packed_matrix, transpose=True): return pk.unpackmat(packed_matrix, packed_matrix.Ne, transpose=transpose) def inverse_permutation(permutation): inverse = np.zeros_like(permutation) for i, p in enumerate(permutation): inverse[p] = i return inverse def rank_with_ties_broken(ranking_with_ties): new_ranking = np.zeros_like(ranking_with_ties) ranks, counts = np.unique(ranking_with_ties, return_counts=True) for rank, count in zip(ranks, counts): indices = np.where(ranking_with_ties == rank) perm = np.random.permutation(count) + rank new_ranking[indices] = perm return new_ranking def order_from_rank(ranking_with_ties): ''' Converts a ranking with ties into an ordering, breaking ties with uniform probability.''' ranking_without_ties = rank_with_ties_broken(ranking_with_ties) # orders and rankings are inverse when no ties are present return inverse_permutation(ranking_without_ties) <file_sep>import yaml # for loading experiment files import argparse # CLI import boolnet.exptools.config_tools as config_tools def main(): parser = argparse.ArgumentParser(description='Config file tester - to help' ' debug config file problems ' 'w/o running experiments.') parser.add_argument('experiment', type=argparse.FileType('r'), help='experiment config filename.') parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-r', '--result-dir', type=str, metavar='dir', default='experiments/results', help='directory to store results in (in own subdir).') args = parser.parse_args() # load experiment file settings = yaml.load(args.experiment, Loader=yaml.CSafeLoader) # test generation of tasks try: configurations = config_tools.generate_configurations(settings, False) print('{} configurations.'.format(len(configurations))) tasks = config_tools.generate_tasks(configurations, False) print('{} tasks.'.format(len(tasks))) except config_tools.ValidationError as err: print() print(err) print('\nExperiment config is NOT valid.') return print('\nExperiment config is valid.') if args.verbose: print('\nConfigurations:') for cfg in configurations: print() print(cfg) if __name__ == '__main__': main() <file_sep>from voluptuous import ( Schema, message, All, Any, Range, IsDir, ALLOW_EXTRA, In, Optional, Required, Exclusive, Length, Invalid) import boolnet.bintools.functions as fn import re def conditionally_required(trigger_key, trigger_val, required_key): ''' if trigger_key = trigger_val then required_key must be present.''' def validator(d): required = (trigger_key in d and d[trigger_key] == trigger_val) if required and required_key not in d: raise Invalid('\'{}\' = \'{}\' requires \'{}\'.'.format( trigger_key, trigger_val, required_key)) # Return the dictionary return d return validator def conditionally_forbidden(trigger_key, trigger_val, required_key): ''' if trigger_key = trigger_val then required_key must NOT be present.''' def validator(d): required = (trigger_key in d and d[trigger_key] == trigger_val) if required and required_key in d: raise Invalid('\'{}\' = \'{}\' forbids \'{}\'.'.format( trigger_key, trigger_val, required_key)) # Return the dictionary return d return validator @message('Must be a permutation.') def permutation(l): assert (min(l) == 0 and max(l) == len(l) - 1 and len(set(l)) == len(l)) return l def integer_multiplier_string(msg=None): def f(v): if re.fullmatch("[1-9][0-9]*n", str(v)): return str(v) else: raise Invalid(msg or ("invalid integer multiplier string")) return f guiding_functions = fn.scalar_function_names() seed_schema = Any(None, str, All(int, Range(min=0))) data_schema = Any( # generated from operator Schema({ 'type': 'generated', 'operator': str, 'bits': All(int, Range(min=1)), Optional('out_width'): All(int, Range(min=1)), Optional('window_size'): All(int, Range(min=1)), Optional('add_noise'): Range(min=0.0), # Optional('targets'): [All(int, Range(min=0))], }, required=True), # read from file Schema({ 'type': 'file', 'filename': str, Optional('dir'): IsDir(), Optional('add_noise'): Range(min=0.0), Optional('targets'): [All(int, Range(min=0))], }, required=True), # pre-split, read from file Schema({ 'type': 'split', 'training_filename': str, 'test_filename': str, Optional('dir'): IsDir(), Optional('add_noise'): Range(min=0.0), Optional('targets'): [All(int, Range(min=0))], }, required=True) ) sampling_schema = Any( # randomly generated Schema({ 'type': 'generated', 'Ns': All(int, Range(min=1)), 'Ne': All(int, Range(min=1)), 'seed': seed_schema, Optional('test'): All(int, Range(min=0)) }, required=True), # read from file Schema({ 'type': 'file', 'filename': str, Optional('test'): str, Optional('dir'): IsDir(), # allow for now, but don't force Optional('seed'): seed_schema, }, required=True), # given in config file Schema({ 'type': 'given', 'indices': [[All(int, Range(min=0))]], Optional('test'): [[All(int, Range(min=0))]], # allow for now, but don't force Optional('seed'): seed_schema, }, required=True), # blank - data is already split Schema({'type': 'blank'}, required=True) ) network_schema = All( Schema({ 'method': 'generated', 'Ng': Any(All(int, Range(min=1)), integer_multiplier_string()), 'node_funcs': [All(int, Range(min=0, max=15))] }, required=True), # Schema({ # 'method': 'given', # 'gates': [All([All(int, Range(min=0))], Length(min=3, max=3))], # }) ) stopping_condition_schema = Any(['guiding', float], [In(guiding_functions), float]) optimiser_schema = Any( # Simulated Annealing Schema({ 'name': 'SA', 'num_temps': All(int, Range(min=1)), 'init_temp': Range(min=0.0), 'temp_rate': Range(min=0.0, max=1.0), 'steps_per_temp': All(int, Range(min=1)), 'guiding_function': In(guiding_functions), Optional('guiding_function_parameters'): Schema({}, extra=ALLOW_EXTRA), Optional('return'): In(['best', 'last']), Optional('stopping_condition'): stopping_condition_schema, Optional('max_restarts'): All(int, Range(min=0)) }, required=True), # Hill Climbing Schema({ 'name': 'HC', 'max_iterations': All(int, Range(min=1)), 'guiding_function': In(guiding_functions), Optional('guiding_function_parameters'): Schema({}, extra=ALLOW_EXTRA), Optional('return'): In(['best', 'last']), Optional('stopping_condition'): stopping_condition_schema, Optional('max_restarts'): All(int, Range(min=0)) }, required=True), # Late-Acceptance Hill Climbing Schema({ 'name': 'LAHC', 'cost_list_length': All(int, Range(min=1)), 'max_iterations': All(int, Range(min=1)), 'guiding_function': In(guiding_functions), Optional('guiding_function_parameters'): Schema({}, extra=ALLOW_EXTRA), Optional('return'): In(['best', 'last']), Optional('stopping_condition'): stopping_condition_schema, Optional('max_restarts'): All(int, Range(min=0)) }, required=True), # LAHC with periodic percolation Schema({ 'name': 'LAHC_perc', 'cost_list_length': All(int, Range(min=1)), 'max_iterations': All(int, Range(min=1)), 'percolation_period': All(int, Range(min=1)), 'guiding_function': In(guiding_functions), Optional('guiding_function_parameters'): Schema({}, extra=ALLOW_EXTRA), Optional('return'): In(['best', 'last']), Optional('stopping_condition'): stopping_condition_schema, Optional('max_restarts'): All(int, Range(min=0)) }, required=True) ) fs_selection_metric_schema = Any( 'cardinality>first', 'cardinality>random', 'cardinality>entropy', 'cardinality>feature_diversity', 'cardinality>pattern_diversity') minfs_params_schema = Any( # CPLEX Schema({ Optional('time_limit'): Range(min=0.0), }), # Meta-RaPS Schema({ Optional('iterations'): All(int, Range(min=1)), Optional('improvement_iterations'): All(int, Range(min=1)), Optional('search_magnitude'): All(float, Range(min=0, max=1)), Optional('priority'): All(float, Range(min=0, max=1)), Optional('restriction'): All(float, Range(min=0, max=1)), Optional('improvement'): All(float, Range(min=0, max=1)) }), ) target_order_schema = Any('auto', 'msb', 'lsb', 'random', All(list, permutation)) learner_schema = Schema( All( Schema({ 'name': 'basic', 'network': network_schema, 'optimiser': optimiser_schema, 'target_order': target_order_schema, Required('seed', default=None): Any( None, All(int, Range(min=0))), Optional('minfs_solver'): Any('cplex', 'greedy', 'raps'), Optional('minfs_solver_params'): minfs_params_schema, Optional('minfs_selection_metric'): fs_selection_metric_schema, }, required=True), conditionally_required( 'minfs_masking', True, 'minfs_selection_metric'), conditionally_required( 'target_order', 'auto', 'minfs_selection_metric'), ) ) log_keys_schema = Schema( [All(Schema([], extra=ALLOW_EXTRA), Length(min=3, max=3))] ) instance_schema = Schema({ 'data': data_schema, 'learner': learner_schema, 'sampling': sampling_schema, 'log_keys': log_keys_schema, Optional('notes'): Schema({}, extra=ALLOW_EXTRA), Optional('verbose_errors'): bool, Optional('verbose_timing'): bool, Optional('record_final_net'): bool, Optional('record_intermediate_nets'): bool, }, required=True) # ########## Schemata for base configs ########## # list_msg = '\'list\' must be a sequence of mappings.' prod_msg = '\'product\' must be a length 2 sequence of sequences of mappings.' experiment_schema = Schema({ 'name': str, # Must be any dict 'base_config': Schema({}, extra=ALLOW_EXTRA), # only one of 'list_config' or 'product_config' are allowed # Must be a list of dicts Exclusive('list', 'config', msg=list_msg): All( Schema([{}], extra=ALLOW_EXTRA), Length(min=1)), # Must be a length 2 list of lists of dicts Exclusive('product', 'config', msg=prod_msg): All([ All(Schema([{}], extra=ALLOW_EXTRA), Length(min=1))], Length(min=2, max=2)), # optional level of debug logging Optional('debug_level'): In(['none', 'warning', 'info', 'debug']), }, required=True) <file_sep>from bitpacking import packing as pk from boolnet.bintools.functions import function_from_name import numpy as np from boolnet.bintools.biterror import EVALUATORS def test_function_value(error_matrix_harness): Ne = error_matrix_harness['Ne'] E = error_matrix_harness['packed error matrix'] T = np.zeros_like(E) No, _ = E.shape for test in error_matrix_harness['tests']: order = test['order'] func_id = function_from_name(test['function']) expected = test['value'] if order == 'lsb': order = np.arange(No, dtype=np.uintp) elif order == 'msb': order = np.arange(No, dtype=np.uintp)[::-1] E_ = E[order, :] T_ = T[order, :] eval_class = EVALUATORS[func_id] error_evaluator = eval_class(Ne, No) actual = error_evaluator.evaluate(E_, T_) np.testing.assert_array_almost_equal(actual, expected) def test_e3_general(): E = np.array([[1, 0, 1, 1, 0], [0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 1, 1, 0], [0, 0, 1, 1, 0]], dtype=np.uint8) # E = np.array([[1, 0, 1, 1, 1], # [0, 0, 0, 0, 0], # [0, 1, 1, 1, 1], # [0, 1, 1, 1, 1], # [0, 1, 1, 1, 1], # [0, 1, 1, 1, 1], # [0, 0, 0, 0, 1], # [0, 0, 1, 1, 1], # [0, 0, 1, 1, 1]], dtype=np.uint8) Ne, No = E.shape Ep = pk.packmat(E) Tp = np.zeros_like(Ep) eval_class = EVALUATORS[function_from_name('e3_general')] dependencies = [[], [], [0, 1], [0, 1, 2], [0, 1, 2]] error_evaluator = eval_class(Ne, No, dependencies) actual = error_evaluator.evaluate(Ep, Tp) np.testing.assert_array_almost_equal(actual, 27/45) def test_e6_general(): E = np.array([[0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1]], dtype=np.uint8) # E = np.array([[0, 0, 1, 1, 1, 0], # [0, 0, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 0], # [0, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 0], # [0, 0, 1, 1, 1, 1], # [0, 0, 1, 1, 1, 0], # [0, 0, 1, 1, 1, 1]], dtype=np.uint8) Ne, No = E.shape Ep = pk.packmat(E) Tp = np.zeros_like(Ep) eval_class = EVALUATORS[function_from_name('e6_general')] dependencies = [[], [], [0, 1], [0, 1, 2], [0, 1, 2], [0]] error_evaluator = eval_class(Ne, No, dependencies) actual = error_evaluator.evaluate(Ep, Tp) np.testing.assert_array_almost_equal(actual, 36/54) # @pytest.mark.python # def test_error(error_matrix_harness, function): # from BoolNet.BitError import function_value # actual = function_value(error_matrix_harness['error matrix'], function) # expected = error_matrix_harness[function_name(function)] # assert np.array_equal(actual, expected) # @pytest.mark.gpu # def test_error_gpu(error_matrix_harness, function): # import pycuda.driver as cuda # import pycuda.autoinit # from BoolNet.BitErrorGPU import function_value_gpu, IMPLEMENTED_METRICS # err_mat = error_matrix_harness['error matrix'] # d_error_mat = cuda.mem_alloc(err_mat.nbytes) # d_scratch_mat = cuda.mem_alloc(err_mat.shape[0] * 4) # Ne, No = err_mat.shape # Ne, No = np.int32(Ne), np.int32(No) # cuda.memcpy_htod(d_error_mat, err_mat) # expected = error_matrix_harness[function_name(function)] # if function in IMPLEMENTED_METRICS: # actual = function_value_gpu(d_error_mat, d_scratch_mat, Ne, No, function) # assert np.array_equal(actual, expected) # else: # with pytest.raises(NotImplementedError): # function_value_gpu(d_error_mat, d_scratch_mat, Ne, No, function) # d_scratch_mat.free() # d_error_mat.free() <file_sep>from copy import deepcopy from collections import MutableMapping from progress.bar import Bar import voluptuous as vol import numpy as np import os import json import random import boolnet.exptools.config_schemata as sch import boolnet.bintools.operator_iterator as op from boolnet.utils import PackedMatrix def get_seed(key): ''' Keeps a registry of seeds for each key, if given a new key get_seed() generates a new seed for that key, but if given an existing key it returns that seed. Allows any number of named seeds.''' if 'registry' not in get_seed.__dict__: # first call, create the registry get_seed.registry = {} if key not in get_seed.registry: # non-existant key, generate a seed random.seed() # use default randomness source to get a seed get_seed.registry[key] = random.randint(1, 2**32-1) return get_seed.registry[key] # to signal schema validation failure # (with custom message formatting) class ValidationError(Exception): pass class ExperimentJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj) def dump_results_partial(results, stream, first): if not first: stream.write(',') json.dump(results, stream, cls=ExperimentJSONEncoder) stream.write('\n') # ensure data is written to disk immediately stream.flush() os.fsync(stream.fileno()) def update_nested(d, u): ''' this updates a dict with another where the two may contain nested dicts themselves (or more generally nested mutable mappings). ''' for k, v in u.items(): if isinstance(v, MutableMapping): r = update_nested(d.get(k, {}), v) d[k] = r else: # preference to second mapping if k exists in d d[k] = u[k] return d def build_filename(params, extension, key='filename'): ''' complicated filename helper.''' filename = params[key] location = params.get('dir', None) # if 'filename' is absolute then ignore 'dir' if location and not os.path.isabs(params[key]): filename = os.path.join(location, params[key]) # add extension if missing if os.path.splitext(filename)[-1] == '': filename += extension return filename def load_samples(params, N, Ni, Nt=None): if params['type'] == 'given': training_indices = np.array(params['indices'], dtype=np.uintp) if 'test' in params: test_indices = np.array(params['test'], dtype=np.uintp) else: test_indices = [None]*training_indices.shape[0] if params['type'] == 'file': filename = build_filename(params, '.npy') training_indices = np.load(filename) if 'test' in params: filename = build_filename(params, '.npy', 'test') test_indices = np.load(filename) else: test_indices = [None]*training_indices.shape[0] elif params['type'] == 'generated': # this provided seed allows us to generate the same set # of training indices across multiple configurations Ns = params['Ns'] Ne = params['Ne'] s = params['seed'] if isinstance(s, str): # s is actually a name s = get_seed(s) params['seed'] = s random.seed(s) if 'test' in params: Ne_test = params['test'] if Nt is None: # combined training and test data all_indices = np.array([ random.sample(range(N), Ne+Ne_test) for i in range(Ns)]) training_indices, test_indices = np.hsplit(all_indices, [Ne]) else: # separate training and test data training_indices = np.array([ random.sample(range(N), Ne) for i in range(Ns)]) test_indices = np.array([ random.sample(range(N), Ne_test) for i in range(Ns)]) else: training_indices = np.array([ random.sample(range(N), Ne) for i in range(Ns)]) test_indices = [None]*Ns return training_indices, test_indices def load_dataset(settings): data_settings = settings['data'] dtype = data_settings['type'] if dtype == 'file': instance, N, Ni = file_instance(data_settings) elif dtype == 'split': instance, N, Ni, Nt = split_instance(data_settings) elif dtype == 'generated': instance, N, Ni = generated_instance(data_settings) # check for problematic case problematic = (dtype == 'split' and settings['sampling']['type'] == 'blank' and 'test' not in settings['sampling']) if problematic: raise ValueError('Cannot use implicit test sampling with split data.') # Only handle sampling if necessary if dtype == 'split': if settings['sampling']['type'] == 'blank': return [instance] else: training_indices, test_indices = load_samples( settings['sampling'], N, Ni, Nt) else: training_indices, test_indices = load_samples( settings['sampling'], N, Ni) contexts = [] for trg, test in zip(training_indices, test_indices): context = instance.copy() context.update({'training_indices': trg, 'test_indices': test}) contexts.append(context) return contexts def file_instance(params): filename = build_filename(params, '.npz') with np.load(filename) as dataset: Mp = dataset['matrix'] # Ne in the dataset is the full number of examples which we are # referring to herein as 'N' to differentiate from the sample size N = dataset['Ne'] Ni = dataset['Ni'] if 'targets' in params: Tp = Mp[Ni:, :] Tp = Tp[params['targets'], :] Mp = np.vstack((Mp[:Ni, :], Tp)) instance = { 'type': 'raw_unsplit', 'matrix': PackedMatrix(Mp, N, Ni) } return instance, N, Ni def split_instance(params): trg_filename = build_filename(params, '.npz', key='training_filename') test_filename = build_filename(params, '.npz', key='test_filename') with np.load(trg_filename) as train, np.load(test_filename) as test: Mp_trg = train['matrix'] Mp_test = test['matrix'] Ne_trg, Ne_test = train['Ne'], test['Ne'] Ni = train['Ni'] assert test['Ni'] == Ni if 'targets' in params: Tp_trg = Mp_trg[Ni:, :] Tp_trg = Tp_trg[params['targets'], :] Mp_trg = np.vstack((Mp_trg[:Ni, :], Tp_trg)) Tp_test = Mp_test[Ni:, :] Tp_test = Tp_test[params['targets'], :] Mp_test = np.vstack((Mp_test[:Ni, :], Tp_test)) instance = { 'type': 'raw_split', 'training_set': PackedMatrix(Mp_trg, Ne_trg, Ni), 'test_set': PackedMatrix(Mp_test, Ne_test, Ni) } return instance, Ne_trg, Ni, Ne_test def generated_instance(params): Nb = params['bits'] operator = op.operator_from_name(params['operator']) instance = { 'type': 'operator', 'operator': operator, 'Nb': Nb, 'No': params.get('out_width', Nb), # defaults to operand width 'window_size': params.get('window_size', 4) # arbitrary default } Ni = op.num_operands(operator) * Nb return instance, 2**Ni, Ni # def handle_initial_network(settings): # net_settings = settings['learner']['network'] # net_method = net_settings['method'] # if net_method == 'given': # data_dir = settings['data']['dir'] # filename = net_settings['file'] # index = net_settings['index'] # with open(join(data_dir, filename)) as f: # gates = np.array(json.load(f)[index], dtype=np.uint32) # net_settings['initial_gates'] = gates def validate_schema(config, schema, config_num, msg): try: schema(config) except vol.MultipleInvalid as err: msg = ('Experiment instance {} invalid: {}\nerror: {}\npath: {}\n' '\nConfig generation aborted.').format( config_num + 1, err, err.error_message, err.path) raise ValidationError(msg) def split_variables_from_base(settings): # configuration sub-dicts are popped try: variable_sets = settings['list'] except KeyError: try: products = settings['product'] # build merged mappings for each pair from products variable_sets = [update_nested(deepcopy(d1), d2) for d2 in products[1] for d1 in products[0]] except KeyError: print('Warning: no variable configuration found.\n') variable_sets = [{}] return variable_sets, settings['base_config'] def insert_default_log_keys(settings): defaults = [ ['learner', True, ['learner', 'name']], ['learner_seed', True, ['learner', 'seed']], ['config_num', True, ['configuration_number']], ['trg_set_num', True, ['training_set_number']], ['tfs', True, ['learner', 'network', 'node_funcs']], ['guiding_function', True, ['learner', 'optimiser', 'guiding_function']], ['given_tgt_order', True, ['learner', 'target_order']], ['sample_seed', False, ['sampling', 'seed']], ['fs_sel_metric', False, ['learner', 'minfs_selection_metric']], ['fs_masking', False, ['learner', 'minfs_masking']], ['fs_timelimit', False, ['learner', 'minfs_time_limit']], ['fs_solver', False, ['learner', 'minfs_solver']], ['opt_{}', False, ['learner', 'optimiser', '.*']], ] # give preference to user log_keys defaults.extend(settings['base_config'].get('log_keys', [])) settings['base_config']['log_keys'] = defaults return settings def generate_configurations(settings, batch_mode): # validate the given schema try: sch.experiment_schema(settings) except vol.MultipleInvalid as err: raise ValidationError( 'Top-level config invalid: {}\nerror: {}\npath: {}'.format( err, err.error_message, err.path)) # insert default log_keys values into base config insert_default_log_keys(settings) # the configurations approach involves having a multiple config dicts and # updating them with each element of the configurations list or product variable_sets, base_settings = split_variables_from_base(settings) # Build up the configuration list configurations = [] if not batch_mode: bar = Bar('Generating configurations', max=len(variable_sets), suffix='%(index)d/%(max)d : %(eta)ds') bar.update() try: for config_num, variables in enumerate(variable_sets): # keep contexts isolated context = deepcopy(base_settings) # update the settings dict with the values for this configuration update_nested(context, variables) # check the given config is a valid experiment validate_schema(context, sch.instance_schema, config_num, variables) # record the config number for debugging context['configuration_number'] = config_num # !!REMOVED!! load initial network from file if required # handle_initial_network(context) # load the data for this configuration instances = load_dataset(context) configurations.append((context, instances)) if not batch_mode: bar.next() finally: # clean up progress bar before printing anything else if not batch_mode: bar.finish() return configurations def generate_tasks(configurations, batch_mode): # Build up the task list tasks = [] if not batch_mode: bar = Bar('Generating training tasks', max=len(configurations), suffix='%(index)d/%(max)d : %(eta)ds') bar.update() try: for context, instances in configurations: # for each sample for i, instance in enumerate(instances): task = deepcopy(context) task['mapping'] = instance task['training_set_number'] = i tasks.append(task) if not batch_mode: bar.next() finally: # clean up progress bar before printing anything else if not batch_mode: bar.finish() return tasks <file_sep>Code and data for the paper "Multi-Label Curricula via Minimum Feature Selection: a Case Study in Boolean Networks" ## Setup To install requirements from PYPI run: ~~~~ pip install -r requirements.txt ~~~~ Depends on two other projects [bitpacking (v1.0)](https://github.com/shannonfenn/bitpacking/releases/tag/v1.0) and [minfs (v1.0)](https://github.com/shannonfenn/minfs/releases/tag/v1.0) which need to be available on the python path. ## Use To run use: `python runexp.y <path-to-experiment-config>` The experiments are implemented as yaml configs, see config_schema.py for the schema definition (note that the configs include relative paths to their relevant dataset and sample files, these may need to be updated depending on your directory structure). Other commandline parameters can be given, use `python runexp.y -h` to see more. Config files can be tested without running the actual experiment using: `python check_config.y <path-to-experiment-config>` which has similar arguments. ## Tests Unit tests are implemented using pytest: ~~~~ pip install pytest py.test -x ~~~~
7e23e5990047ee53ff208a178941bddacc9e627f
[ "Markdown", "Python" ]
12
Python
shannonfenn/Multi-Label-Curricula-via-Minimum-Feature-Selection
060dbc2700d4fb29f919dfdb371706bb562f10fe
4b2b44a9dfdce95a4ad4048e9076faa727bcb69b
refs/heads/master
<repo_name>Ishank-811/portfolio-website<file_sep>/main.js // function hidden(){ // let btn1= document.querySelectorAll("#graphic-btn"); // let para= document.querySelectorAll(".category-hidden"); // //btn1= addEventListener("click", function(){ // if(para.style.display=='none'){ // para.style.display='block'; // console.log("hello"); // } // else{ // para.style.display='block' ; // } //}) $(document).ready(function (){ $('#graphic-btn').click(function(){ $('.category-active').css({display:'none'}); console.log("graphic show") }); $('#graphic-btn').click(function(){ $('.category-hidden').css({display:'block'}) console.log("work hidden") }); $('#graphic-btn').click(function(){ $('.category-hidden2').css({display:'none'}); console.log("graphic hidden"); }); $('#work-btn').click(function(){ $('.category-active').css({display:'block'}); }); $('#work-btn').click(function(){ $('.category-hidden').css({display:'none'}); }); $('#work-btn').click(function(){ $('.category-hidden2').css({display:'none'}); console.log("graphic hidden"); }); $('#react-btn').click(function(){ $('.category-active').css({display:'none'}); console.log("work hidden") }); $('#react-btn').click(function(){ $('.category-hidden').css({display:'none'}); console.log("graphic hidden"); }); $('#react-btn').click(function(){ $('.category-hidden2').css({display:'block'}); console.log("react show"); }); });
f7867fb889ec92d8cf73d7a401c8a9a8dcd29dee
[ "JavaScript" ]
1
JavaScript
Ishank-811/portfolio-website
1b2eb1cc752d3e21a4b2d762edbb52c4b4218b54
864360e3a7ff140c736d6f22c66c68b288c4f2a0
refs/heads/master
<file_sep>class ProjectsController < ApplicationController respond_to :json def index respond_with(Project.all) end end
e76e4d461fa6f87189584af3dfdbae86cb869cf4
[ "Ruby" ]
1
Ruby
jlovell/buggy
549924a6cc65d194ed239bc7d6ff784773470ec8
16d585f02e6b976e33f4afc4cd640df7fb01663d
refs/heads/master
<repo_name>CNUClasses/9_NetworkCheck<file_sep>/app/src/main/java/com/example/keith/a9_network_connectioncheck/ConnectivityCheck.java package com.example.keith.a9_network_connectioncheck; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectivityCheck { private Context context; ConnectivityCheck(Context context) { this.context = context; } public boolean isNetworkReachable() { NetworkInfo current = getNetworkInfo(); return (current == null)?false:(current.getState() == NetworkInfo.State.CONNECTED); } public boolean isWifiReachable() { NetworkInfo current = getNetworkInfo(); return (current == null)?false:(current.getType() == ConnectivityManager.TYPE_WIFI); } private NetworkInfo getNetworkInfo() { ConnectivityManager mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return mManager.getActiveNetworkInfo(); } }
8a6bf2f5376ccc465216e6135cb9291ae55ad786
[ "Java" ]
1
Java
CNUClasses/9_NetworkCheck
b472e98f5427b87e035edaff5d8638c97d92b5a0
229decdf14e55ff8adbd617ff6e764f3ca74e639
refs/heads/master
<file_sep>package com.dexesttp.hkxpack.hkxwriter.object; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.List; import com.dexesttp.hkxpack.descriptor.HKXEnumResolver; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.descriptor.members.HKXMemberTemplate; import com.dexesttp.hkxpack.hkx.data.DataExternal; import com.dexesttp.hkxpack.hkx.data.DataInternal; import com.dexesttp.hkxpack.hkxwriter.object.array.HKXArrayMemberHandler; import com.dexesttp.hkxpack.hkxwriter.object.array.HKXArrayPointerMemberHandler; import com.dexesttp.hkxpack.hkxwriter.object.callbacks.HKXMemberCallback; import com.dexesttp.hkxpack.hkxwriter.utils.PointerObject; public class HKXMemberHandlerFactory { private final RandomAccessFile outFile; private final HKXEnumResolver enumResolver; private final List<DataInternal> data1List; private final List<PointerObject> data2List; private List<HKXMemberCallback> memberCallbacks; /** * Creates a {@link HKXMemberHandlerFactory}. * @param outFile the {@link File} to write into. * @param enumResolver the {@link HKXEnumResolver} to use to resolve enums. * @param data1List the list of {@link DataInternal} to fill while solving an array or a string. * @param data2List the list of {@link DataExternal} to fill while solving pointers. * @throws FileNotFoundException if there was a problem opening a conenction to the given {@link File}. */ public HKXMemberHandlerFactory(File outFile, HKXEnumResolver enumResolver, List<DataInternal> data1List, List<PointerObject> data2List, List<HKXMemberCallback> memberCallbacks) throws FileNotFoundException { this(new RandomAccessFile(outFile, "rw"), enumResolver, data1List, data2List, memberCallbacks); } private HKXMemberHandlerFactory(RandomAccessFile outFile, HKXEnumResolver enumResolver, List<DataInternal> data1List, List<PointerObject> data2List, List<HKXMemberCallback> memberCallbacks) { this.outFile = outFile; this.enumResolver = enumResolver; this.data1List = data1List; this.data2List = data2List; this.memberCallbacks = memberCallbacks; } /** * Clones the factory, but changes the memberCallback queue. * @param memberCallbacks then new {@link HKXMemberCallback} list ot use. * @return the cloned {@link HKXMemberHandlerFactory}. */ public HKXMemberHandlerFactory clone(List<HKXMemberCallback> memberCallbacks) { return new HKXMemberHandlerFactory(outFile, enumResolver, data1List, data2List, memberCallbacks); } /** * Creates the {@link HKXMemberHandler} relevant to the given {@link HKXMemberTemplate}. * @param memberTemplate the {@link HKXMemberTemplate} to base the {@link HKXMemberHandler} on. * @return the relevant {@link HKXMemberHandler}. */ public HKXMemberHandler create(HKXType vtype, long offset) { switch(vtype.getFamily()) { case DIRECT: case COMPLEX: return new HKXDirectMemberHandler(outFile, offset); case ENUM: return new HKXEnumMemberHandler(outFile, offset, enumResolver); case STRING: return new HKXStringMemberHandler(outFile, offset, data1List); case POINTER: return new HKXPointerMemberHandler(offset, data2List); case OBJECT: return new HKXObjectMemberHandler(offset, this, memberCallbacks); case ARRAY: return new HKXArrayMemberHandler(outFile, offset, data1List, this); default: throw new IllegalArgumentException("Unknown type : " + vtype); } } /** * Creates a APMH to handle pointer stacking at array initialization but the filling of the pointeronly at array writing. * @return a brand new {@link HKXArrayPointerMemberHandler}. */ public HKXArrayPointerMemberHandler createAPMH() { return new HKXArrayPointerMemberHandler(data2List); } /** * Close this {@link HKXMemberHandlerFactory}. * @throws IOException if there was a problem closing the connection to the {@link File}. */ public void close() throws IOException { outFile.close(); } } <file_sep>package com.dexesttp.hkxpack.hkx.data; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkx.header.SectionData; import com.dexesttp.hkxpack.resources.ByteUtils; /** * Interface on the Data1 section of a HKX File. */ public class Data1Interface { private RandomAccessFile file; private SectionData header; private int lastPos = -1; /** * Connect this {@link Data1Interface} to a {@link File}. * @param file the {@link File} to connect to. * @param dataHeader the {@link SectionData} relative to the Data section. * @throws FileNotFoundException if the {@link File} couldn't be opened. */ public void connect(File file, SectionData dataHeader) throws FileNotFoundException { this.file = new RandomAccessFile(file, "rw"); this.header = dataHeader; } /** * Read a given Internal data component from the file. * @param pos the position of the wanted {@link DataInternal} component. * @return the read {@link DataInternal}. * @throws IOException if the file couldn't be read. * @throws InvalidPositionException if the requested position was outside the Data1 section. */ public DataInternal read(int pos) throws IOException, InvalidPositionException { DataInternal data = new DataInternal(); long dataPos = header.data1 + pos * 0x08; if(pos < 0 || dataPos > header.data2) throw new InvalidPositionException("DATA_1", pos ); file.seek(header.offset + dataPos); byte[] dataLine = new byte[4]; file.read(dataLine); data.from = ByteUtils.getLong(dataLine); if(data.from > header.offset + header.data1) throw new InvalidPositionException("DATA_1", pos ); file.read(dataLine); data.to = ByteUtils.getLong(dataLine); this.lastPos = pos; return data; } /** * Writes the given Internal data to the file, at the given position. * @param pos the position to write the data to. * @param internal the {@link DataInternal} to write. * @return the position of the end of the {@link DataInternal}. * @throws IOException if there was a problem while writing to the file. */ public long write(int pos, DataInternal internal) throws IOException { long dataPos = header.data1 + pos * 0x08; file.seek(header.offset + dataPos); file.write(ByteUtils.fromLong(internal.from, 4)); file.write(ByteUtils.fromLong(internal.to, 4)); return dataPos + 0x08; } /** * Reads the next element from the Data1 section. * @return The requested {@link DataInternal} * @throws IOException if there was a problem reading the file. * @throws InvalidPositionException If the next element doesn't exist. */ public DataInternal readNext() throws IOException, InvalidPositionException { return read(++lastPos); } /** * Cancel reading the next element. */ public void backtrack() { lastPos--; } /** * Close this {@link Data1Interface} connection with the {@link File}. * @throws IOException */ public void close() throws IOException { file.close(); } } <file_sep>package com.dexesttp.hkxpack.hkx.header.internals.versions; import com.dexesttp.hkxpack.hkx.header.internals.HeaderDescriptor; public class HeaderDescriptor_v11 extends HeaderDescriptor { { version = new byte[] {11, 0, 0, 0}; extras = new byte[] {8, 1, 0, 1}; verName = new byte[] {'h', 'k', '_', '2', '0', '1', '4', '.', '1', '.', '0', '-', 'r', '1'}; extras_v11 = new byte[] {21, 0}; padding_v11 = new byte[] {16, 0}; } public byte[] padding = new byte[] {20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; } <file_sep>package com.dexesttp.hkxpack.hkxwriter.exceptions; public class WrongInputCastException extends Exception { private static final long serialVersionUID = 6483999356904172141L; public WrongInputCastException(String message) { super(message); } public WrongInputCastException(Throwable e) { super(e); } public WrongInputCastException(String message, Throwable e) { super(message, e); } } <file_sep>package com.dexesttp.hkxpack.hkxwriter.object.callbacks; import java.io.IOException; import java.util.List; import com.dexesttp.hkxpack.hkx.data.DataInternal; public class HKXBaseArrayMemberCallback implements HKXMemberCallback { private final HKXArrayMemberCallback callbackProcessor; private final List<DataInternal> data1; private final DataInternal arrData; public HKXBaseArrayMemberCallback(HKXArrayMemberCallback callbackProcessor, List<DataInternal> data1, DataInternal arrData) { this.callbackProcessor = callbackProcessor; this.data1 = data1; this.arrData = arrData; } @Override public long process(List<HKXMemberCallback> memberCallbacks, long position) throws IOException { arrData.to = position; data1.add(arrData); return callbackProcessor.process(memberCallbacks, position); } } <file_sep>package com.dexesttp.hkxpack.hkxreader.member.arrays; import com.dexesttp.hkxpack.descriptor.HKXDescriptor; import com.dexesttp.hkxpack.descriptor.HKXDescriptorFactory; import com.dexesttp.hkxpack.descriptor.exceptions.ClassFileReadError; import com.dexesttp.hkxpack.descriptor.members.HKXMemberTemplate; import com.dexesttp.hkxpack.hkxreader.HKXObjectReader; import com.dexesttp.hkxpack.hkxreader.HKXReaderConnector; import com.dexesttp.hkxpack.hkxreader.PointerNameGenerator; import com.dexesttp.hkxpack.l10n.SBundle; public class HKXArrayContentsReaderFactory { private HKXReaderConnector connector; private HKXDescriptorFactory descriptorFactory; private HKXObjectReader objectReader; private PointerNameGenerator pointerNameGenerator; public HKXArrayContentsReaderFactory(HKXReaderConnector connector, HKXDescriptorFactory descriptorFactory, HKXObjectReader objectReader, PointerNameGenerator pointerNameGenerator) { this.connector = connector; this.descriptorFactory = descriptorFactory; this.objectReader = objectReader; this.pointerNameGenerator = pointerNameGenerator; } public HKXArrayContentsReader get(HKXMemberTemplate template) throws ClassFileReadError { switch(template.vsubtype.getFamily()) { case DIRECT: case COMPLEX: return new HKXDirectArrayContentsReader(connector, template.vsubtype); case STRING: return new HKXStringArrayContentsReader(connector, template.vsubtype); case OBJECT: HKXDescriptor descriptor = descriptorFactory.get(template.target); return new HKXObjectArrayContentsReader(objectReader, descriptorFactory, descriptor); case POINTER: return new HKXPointerArrayContentsReader(connector, pointerNameGenerator); default: throw new IllegalArgumentException(SBundle.getString("error.hkx.read.subtype") + template.vsubtype); } } } <file_sep>package com.dexesttp.hkxpack.cli.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Parse arguments into {@link Options}.<br /> * {@link #addOption(String, int)} adds an option catching a specific number of arguments.<br /> * {@link #addOption(String)} adds an option catcing all arguments following it.<br /> * {@link #parse(String...)} parse arguments into {@link Options}. */ public class ArgsParser { /** * Contains a list of {@link Options} associated with their argument catcher size. */ private class OptionList extends HashMap<String, Integer> { private static final long serialVersionUID = 7529991519923957630L; void add(String option, int numberOfArgs) { this.put(option, numberOfArgs); } void add(String option) { this.put(option, -1); } } /** * Contains the result of {@link ArgsParser#parse(String...)}.<br /> * use {@link #get(String, int)} to get the n-th argument of a given option<br /> * use {@link #exists(String)} to check if an option was detected. */ public class Options extends HashMap<String, List<String>> { private static final long serialVersionUID = -9078055964913056347L; /** * Retrieve the option-catched argument described by {@code position}. * @param optionName the option name to retrieve from * @param position the position of the arg to retrieve. * @return the given arg */ public String get(String optionName, int position) { try { return this.get(optionName).get(position); } catch(Exception e) { return ""; } } /** * Returns true if the given {@code optionName} exists. * @param optionName the option to test the existence of. */ public boolean exists(String optionName) { return this.containsKey(optionName); } } private OptionList optionList = new OptionList(); /** * Adds an option catching an unlimited number of arguments. * @param optionName the name of the argument to add. */ public void addOption(String optionName) { optionList.add(optionName); } /** * Adds an option catching exacty {@code optionSize} arguments. * @param optionName the name of the option to add * @param optionSize the number of arguments to catch */ public void addOption(String optionName, int optionSize) { optionList.add(optionName, optionSize); } /** * Parse arguments into {@link Options}. * @param args the arguments to parse. * @return the {@link Options} object. * @throws WrongSizeException */ public Options parse(String... args) throws WrongSizeException { Options res = new Options(); String optionName = ""; res.put(optionName, new ArrayList<>()); int countdown = -1; for(String arg : args) { if(countdown == 0) optionName = ""; countdown--; if(optionList.containsKey(arg)) { if(countdown >= 0) throw new WrongSizeException(); optionName = arg; countdown = optionList.get(arg); if(!res.containsKey(optionName)) res.put(optionName, new ArrayList<>()); } else { res.get(optionName).add(arg); } } return res; } } <file_sep>package com.dexesttp.hkxpack.hkxwriter.utils; import java.util.HashMap; import java.util.Map; import com.dexesttp.hkxpack.hkx.data.DataExternal; public class PointerResolver { private Map<String, Long> map = new HashMap<>(); public void add(String name, long position) { map.put(name, position); } public DataExternal resolve(PointerObject object) { if(!map.keySet().contains(object.to)) return null; DataExternal res = new DataExternal(); res.section = 0x02; res.from = object.from; res.to = map.get(object.to); return res; } } <file_sep>package com.dexesttp.hkxpack.hkxreader.member; import java.io.IOException; import java.io.RandomAccessFile; import com.dexesttp.hkxpack.data.HKXData; import com.dexesttp.hkxpack.data.members.HKXArrayMember; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.hkx.data.Data1Interface; import com.dexesttp.hkxpack.hkx.data.DataInternal; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkx.types.MemberSizeResolver; import com.dexesttp.hkxpack.hkxreader.HKXReaderConnector; import com.dexesttp.hkxpack.hkxreader.member.arrays.HKXArrayContentsReader; import com.dexesttp.hkxpack.resources.ByteUtils; public class HKXArrayMemberReader implements HKXMemberReader { private final HKXReaderConnector connector; private final String name; private final HKXType subtype; private final HKXArrayContentsReader internals; private final long memberOffset; HKXArrayMemberReader(HKXReaderConnector connector, String name, HKXType subtype, HKXArrayContentsReader internals, long offset) { this.connector = connector; this.name = name; this.subtype = subtype; this.internals = internals; this.memberOffset = offset; } @Override public HKXMember read(long classOffset) throws IOException, InvalidPositionException { final int memberSize = (int) MemberSizeResolver.getSize(HKXType.TYPE_ARRAY); RandomAccessFile file = connector.data.setup(classOffset + memberOffset); byte[] b = new byte[memberSize]; file.read(b); HKXArrayMember result = new HKXArrayMember(name, HKXType.TYPE_ARRAY, subtype); int arrSize = getSizeComponent(b); if(arrSize > 0) { Data1Interface data1 = connector.data1; DataInternal arrValue = data1.readNext(); assert(arrValue.from == classOffset + memberOffset); for(int i = 0; i < arrSize; i++ ) { HKXData data = internals.getContents(arrValue.to, i); result.add(data); } } return result; } private int getSizeComponent(byte[] b) { byte[] newB = new byte[]{b[8], b[9], b[10], b[11]}; return ByteUtils.getInt(newB); } } <file_sep>package com.dexesttp.hkxpack.hkx.data; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkx.header.SectionData; import com.dexesttp.hkxpack.resources.ByteUtils; /** * Interface on the Data2 section of a HKX file. */ public class Data2Interface { private RandomAccessFile file; private SectionData header; private int lastPos = -1; /** * Connect this {@link Data2Interface} to a {@link File}. * @param file the {@link File} to connect to. * @param dataHeader the {@link SectionData} relative to the Data section. * @throws FileNotFoundException if the {@link File} couldn't be opened. */ public void connect(File file, SectionData data1) throws FileNotFoundException { this.file = new RandomAccessFile(file, "rw"); this.header = data1; } /** * Read a given External data component from the file. * @param pos the position of the wanted {@link DataExternal} component. * @return the read {@link DataExternal}. * @throws IOException if the file couldn't be read. * @throws InvalidPositionException if the requested position was outside the Data2 section. */ public DataExternal read(int pos) throws IOException, InvalidPositionException { DataExternal data = new DataExternal(); long dataPos = header.data2 + pos * 0x0C; if(pos < 0 || dataPos > header.data3) throw new InvalidPositionException("DATA_2", pos ); file.seek(header.offset + dataPos); byte[] dataLine = new byte[4]; file.read(dataLine); data.from = ByteUtils.getLong(dataLine); file.read(dataLine); data.section = ByteUtils.getInt(dataLine); if(data.section > header.offset + header.data1) throw new InvalidPositionException("DATA_2", pos ); file.read(dataLine); data.to = ByteUtils.getLong(dataLine); lastPos = pos; return data; } /** * Write a given External data to the file at the given position. * @param pos the position to write the external data at. * @param data the {@link DataExternal} to write. * @return the position as section offset of the end of the written {@link DataExternal}. * @throws IOException if there was a problem writing to the file. */ public long write(int pos, DataExternal data) throws IOException { long dataPos = header.data2 + pos * 0x0C; file.seek(header.offset + dataPos); file.write(ByteUtils.fromLong(data.from, 4)); file.write(ByteUtils.fromLong(data.section, 4)); file.write(ByteUtils.fromLong(data.to, 4)); return dataPos + 0x0C; } /** * Reads the next element from the Data2 section. * @return The requested {@link DataExternal} * @throws IOException if there was a problem reading the file. * @throws InvalidPositionException If the next element doesn't exist. */ public DataExternal readNext() throws IOException, InvalidPositionException { return read(++lastPos); } /** * Cancel reading the next element. */ public void backtrack() { lastPos--; } /** * Close this {@link Data2Interface} connection with the {@link File}. * @throws IOException */ public void close() throws IOException { file.close(); } } <file_sep>package com.dexesttp.hkxpack.data.members; import java.util.ArrayList; import java.util.List; import com.dexesttp.hkxpack.data.HKXData; import com.dexesttp.hkxpack.descriptor.enums.HKXType; public class HKXArrayMember implements HKXMember { private String name; private HKXType type; private HKXType subtype; private List<HKXData> contents; public HKXArrayMember(String name, HKXType type, HKXType subtype) { this.name = name; this.type = type; this.subtype = subtype; this.contents = new ArrayList<>(); } public HKXType getSubType() { return subtype; } public void add(HKXData data) { if(subtype != HKXType.TYPE_NONE && data.getType() != subtype) throw new IllegalArgumentException("Array data type is defined as : " + subtype + " while the given argument is " + data.getType()); this.contents.add(data); } public HKXData get(int pos) { return contents.get(pos); } public List<HKXData> contents() { return this.contents; } @Override public String getName() { return name; } @Override public HKXType getType() { return type; } } <file_sep>package com.dexesttp.hkxpack.hkx.types; import com.dexesttp.hkxpack.data.members.HKXDirectMember; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.resources.ByteUtils; /** * Intended to retrieve {@link HKXType}-specific data. * {@link #getMember(String, HKXType, byte[])} converts a {@link byte} array to a {@link HKXMember}, * given the {@link HKXType} of the member is standard. */ public class MemberDataResolver { /** * Read a simple / defined member from a byte array. * @param name the name of the member to create. * @param type the {@link HKXType} of data to convert the array into. * @param byteArray the {@link byte} array to read the member from. * @return the {@link HKXMember} containing the data. * @throws IllegalArgumentException if the given {@link HKXType} isn't standard. */ public static HKXMember getMember(String name, HKXType type, byte[] byteArray) { switch(type) { // Base values case TYPE_BOOL: HKXDirectMember<Boolean> member1 = new HKXDirectMember<>(name, type); member1.set(ByteUtils.getInt(byteArray) > 0); return member1; case TYPE_CHAR: case TYPE_UINT8: case TYPE_INT8: HKXDirectMember<Character> member2 = new HKXDirectMember<>(name, type); member2.set((char) ByteUtils.getInt(byteArray)); return member2; case TYPE_UINT16: case TYPE_ULONG: case TYPE_UINT32: case TYPE_UINT64: HKXDirectMember<Integer> member3 = new HKXDirectMember<>(name, type); member3.set((int) ByteUtils.getInt(byteArray)); return member3; case TYPE_INT16: case TYPE_INT32: case TYPE_INT64: HKXDirectMember<Integer> member4 = new HKXDirectMember<>(name, type); member4.set((int) ByteUtils.getSInt(byteArray)); return member4; case TYPE_HALF: case TYPE_REAL: HKXDirectMember<Double> member5 = new HKXDirectMember<>(name, type); member5.set((double) ByteUtils.getFloat(byteArray)); return member5; // Complex values case TYPE_VECTOR4: case TYPE_QUATERNION: byte[] b21 = new byte[] {byteArray[0], byteArray[1], byteArray[2], byteArray[3]}; byte[] b22 = new byte[] {byteArray[4], byteArray[5], byteArray[6], byteArray[7]}; byte[] b23 = new byte[] {byteArray[8], byteArray[9], byteArray[10], byteArray[11]}; byte[] b24 = new byte[] {byteArray[12], byteArray[13], byteArray[14], byteArray[15]}; HKXDirectMember<Double[]> member8 = new HKXDirectMember<>(name, type); member8.set(new Double[] { (double) ByteUtils.getFloat(b21), (double) ByteUtils.getFloat(b22), (double) ByteUtils.getFloat(b23), (double) ByteUtils.getFloat(b24) }); return member8; case TYPE_MATRIX3: case TYPE_QSTRANSFORM: byte[] b31 = new byte[] {byteArray[0], byteArray[1], byteArray[2], byteArray[3]}; byte[] b32 = new byte[] {byteArray[4], byteArray[5], byteArray[6], byteArray[7]}; byte[] b33 = new byte[] {byteArray[8], byteArray[9], byteArray[10], byteArray[11]}; byte[] b34 = new byte[] {byteArray[12], byteArray[13], byteArray[14], byteArray[15]}; byte[] b35 = new byte[] {byteArray[16], byteArray[17], byteArray[18], byteArray[19]}; byte[] b36 = new byte[] {byteArray[20], byteArray[21], byteArray[22], byteArray[23]}; byte[] b37 = new byte[] {byteArray[24], byteArray[25], byteArray[26], byteArray[27]}; byte[] b38 = new byte[] {byteArray[28], byteArray[29], byteArray[30], byteArray[31]}; byte[] b39 = new byte[] {byteArray[32], byteArray[33], byteArray[34], byteArray[35]}; byte[] b3a = new byte[] {byteArray[36], byteArray[37], byteArray[38], byteArray[39]}; byte[] b3b = new byte[] {byteArray[40], byteArray[41], byteArray[42], byteArray[43]}; byte[] b3c = new byte[] {byteArray[44], byteArray[45], byteArray[46], byteArray[47]}; HKXDirectMember<Double[]> member9 = new HKXDirectMember<>(name, type); member9.set(new Double[] { (double) ByteUtils.getFloat(b31), (double) ByteUtils.getFloat(b32), (double) ByteUtils.getFloat(b33), (double) ByteUtils.getFloat(b34), (double) ByteUtils.getFloat(b35), (double) ByteUtils.getFloat(b36), (double) ByteUtils.getFloat(b37), (double) ByteUtils.getFloat(b38), (double) ByteUtils.getFloat(b39), (double) ByteUtils.getFloat(b3a), (double) ByteUtils.getFloat(b3b), (double) ByteUtils.getFloat(b3c) }); return member9; case TYPE_MATRIX4: case TYPE_TRANSFORM: byte[] b41 = new byte[] {byteArray[0], byteArray[1], byteArray[2], byteArray[3]}; byte[] b42 = new byte[] {byteArray[4], byteArray[5], byteArray[6], byteArray[7]}; byte[] b43 = new byte[] {byteArray[8], byteArray[9], byteArray[10], byteArray[11]}; byte[] b44 = new byte[] {byteArray[12], byteArray[13], byteArray[14], byteArray[15]}; byte[] b45 = new byte[] {byteArray[16], byteArray[17], byteArray[18], byteArray[19]}; byte[] b46 = new byte[] {byteArray[20], byteArray[21], byteArray[22], byteArray[23]}; byte[] b47 = new byte[] {byteArray[24], byteArray[25], byteArray[26], byteArray[27]}; byte[] b48 = new byte[] {byteArray[28], byteArray[29], byteArray[30], byteArray[31]}; byte[] b49 = new byte[] {byteArray[32], byteArray[33], byteArray[34], byteArray[35]}; byte[] b4a = new byte[] {byteArray[36], byteArray[37], byteArray[38], byteArray[39]}; byte[] b4b = new byte[] {byteArray[40], byteArray[41], byteArray[42], byteArray[43]}; byte[] b4c = new byte[] {byteArray[44], byteArray[45], byteArray[46], byteArray[47]}; byte[] b4d = new byte[] {byteArray[48], byteArray[49], byteArray[50], byteArray[51]}; byte[] b4e = new byte[] {byteArray[52], byteArray[53], byteArray[54], byteArray[55]}; byte[] b4f = new byte[] {byteArray[56], byteArray[57], byteArray[58], byteArray[59]}; byte[] b4g = new byte[] {byteArray[60], byteArray[61], byteArray[62], byteArray[63]}; HKXDirectMember<Double[]> member10 = new HKXDirectMember<>(name, type); member10.set(new Double[] { (double) ByteUtils.getFloat(b41), (double) ByteUtils.getFloat(b42), (double) ByteUtils.getFloat(b43), (double) ByteUtils.getFloat(b44), (double) ByteUtils.getFloat(b45), (double) ByteUtils.getFloat(b46), (double) ByteUtils.getFloat(b47), (double) ByteUtils.getFloat(b48), (double) ByteUtils.getFloat(b49), (double) ByteUtils.getFloat(b4a), (double) ByteUtils.getFloat(b4b), (double) ByteUtils.getFloat(b4c), (double) ByteUtils.getFloat(b4d), (double) ByteUtils.getFloat(b4e), (double) ByteUtils.getFloat(b4f), (double) ByteUtils.getFloat(b4g) }); return member10; // Default default: break; } throw new IllegalArgumentException(type + " can't be analyzed with MemberTypeResolver#getMember"); } /** * Write a simple / defined member to a byte array. * @param member the {@link HKXMember} of data to create the array from. * @return the byte aray containing the data. * @throws IllegalArgumentException if the given {@link HKXMember} isn't standard. */ @SuppressWarnings("unchecked") public static byte[] fromMember(HKXMember member) { switch(member.getType()) { // Base values case TYPE_BOOL: HKXDirectMember<Boolean> member1 = (HKXDirectMember<Boolean>) member; return new byte[]{(byte) (member1.get() ? 0x01 : 0x00)}; case TYPE_CHAR: case TYPE_UINT8: HKXDirectMember<Character> memberUInt8 = (HKXDirectMember<Character>) member; return ByteUtils.fromLong(memberUInt8.get(), 1); case TYPE_INT8: HKXDirectMember<Character> memberInt8 = (HKXDirectMember<Character>) member; return ByteUtils.fromSLong(memberInt8.get(), 1); case TYPE_UINT16: HKXDirectMember<Integer> memberUInt16 = (HKXDirectMember<Integer>) member; return ByteUtils.fromLong(memberUInt16.get(), 2); case TYPE_INT16: HKXDirectMember<Integer> memberInt16 = (HKXDirectMember<Integer>) member; return ByteUtils.fromSLong(memberInt16.get(), 2); case TYPE_UINT32: HKXDirectMember<Integer> memberUInt32 = (HKXDirectMember<Integer>) member; return ByteUtils.fromLong(memberUInt32.get(), 4); case TYPE_INT32: HKXDirectMember<Integer> memberInt32 = (HKXDirectMember<Integer>) member; return ByteUtils.fromSLong(memberInt32.get(), 4); case TYPE_ULONG: case TYPE_UINT64: HKXDirectMember<Integer> memberUInt64 = (HKXDirectMember<Integer>) member; return ByteUtils.fromLong(memberUInt64.get(), 8); case TYPE_INT64: HKXDirectMember<Integer> memberInt64 = (HKXDirectMember<Integer>) member; return ByteUtils.fromLong(memberInt64.get(), 8); case TYPE_HALF: HKXDirectMember<Double> memberHalf = (HKXDirectMember<Double>) member; return ByteUtils.fromFloat(memberHalf.get(), 2); case TYPE_REAL: HKXDirectMember<Double> memberReal = (HKXDirectMember<Double>) member; return ByteUtils.fromFloat(memberReal.get(), 4); // Complex values case TYPE_VECTOR4: case TYPE_QUATERNION: HKXDirectMember<Double[]> memberTransform = (HKXDirectMember<Double[]>) member; byte[] memberTr_1 = ByteUtils.fromFloat(memberTransform.get()[0], 4); byte[] memberTr_2 = ByteUtils.fromFloat(memberTransform.get()[1], 4); byte[] memberTr_3 = ByteUtils.fromFloat(memberTransform.get()[2], 4); byte[] memberTr_4 = ByteUtils.fromFloat(memberTransform.get()[3], 4); return new byte[]{ memberTr_1[0], memberTr_1[1], memberTr_1[2], memberTr_1[3], memberTr_2[0], memberTr_2[1], memberTr_2[2], memberTr_2[3], memberTr_3[0], memberTr_3[1], memberTr_3[2], memberTr_3[3], memberTr_4[0], memberTr_4[1], memberTr_4[2], memberTr_4[3] }; case TYPE_MATRIX3: case TYPE_QSTRANSFORM: HKXDirectMember<Double[]> memberQs = (HKXDirectMember<Double[]>) member; byte[][] memberQs_1 = new byte[][] { ByteUtils.fromFloat(memberQs.get()[0], 4), ByteUtils.fromFloat(memberQs.get()[1], 4), ByteUtils.fromFloat(memberQs.get()[2], 4), ByteUtils.fromFloat(memberQs.get()[3], 4), }; byte[][] memberQs_2 = new byte[][] { ByteUtils.fromFloat(memberQs.get()[4], 4), ByteUtils.fromFloat(memberQs.get()[5], 4), ByteUtils.fromFloat(memberQs.get()[6], 4), ByteUtils.fromFloat(memberQs.get()[7], 4), }; byte[][] memberQs_3 = new byte[][] { ByteUtils.fromFloat(memberQs.get()[8], 4), ByteUtils.fromFloat(memberQs.get()[9], 4), ByteUtils.fromFloat(memberQs.get()[10], 4), ByteUtils.fromFloat(memberQs.get()[11], 4), }; return new byte[]{ memberQs_1[0][0], memberQs_1[0][1], memberQs_1[0][2], memberQs_1[0][3], memberQs_1[1][0], memberQs_1[1][1], memberQs_1[1][2], memberQs_1[1][3], memberQs_1[2][0], memberQs_1[2][1], memberQs_1[2][2], memberQs_1[2][3], memberQs_1[3][0], memberQs_1[3][1], memberQs_1[3][2], memberQs_1[3][3], memberQs_2[0][0], memberQs_2[0][1], memberQs_2[0][2], memberQs_2[0][3], memberQs_2[1][0], memberQs_2[1][1], memberQs_2[1][2], memberQs_2[1][3], memberQs_2[2][0], memberQs_2[2][1], memberQs_2[2][2], memberQs_2[2][3], memberQs_2[3][0], memberQs_2[3][1], memberQs_2[3][2], memberQs_2[3][3], memberQs_3[0][0], memberQs_3[0][1], memberQs_3[0][2], memberQs_3[0][3], memberQs_3[1][0], memberQs_3[1][1], memberQs_3[1][2], memberQs_3[1][3], memberQs_3[2][0], memberQs_3[2][1], memberQs_3[2][2], memberQs_3[2][3], memberQs_3[3][0], memberQs_3[3][1], memberQs_3[3][2], memberQs_3[3][3] }; case TYPE_MATRIX4: case TYPE_TRANSFORM: HKXDirectMember<Double[]> memberM4 = (HKXDirectMember<Double[]>) member; byte[][] memberM4_1 = new byte[][] { ByteUtils.fromFloat(memberM4.get()[0], 4), ByteUtils.fromFloat(memberM4.get()[1], 4), ByteUtils.fromFloat(memberM4.get()[2], 4), ByteUtils.fromFloat(memberM4.get()[3], 4) }; byte[][] memberM4_2 = new byte[][] { ByteUtils.fromFloat(memberM4.get()[4], 4), ByteUtils.fromFloat(memberM4.get()[5], 4), ByteUtils.fromFloat(memberM4.get()[6], 4), ByteUtils.fromFloat(memberM4.get()[7], 4) }; byte[][] memberM4_3 = new byte[][] { ByteUtils.fromFloat(memberM4.get()[8], 4), ByteUtils.fromFloat(memberM4.get()[9], 4), ByteUtils.fromFloat(memberM4.get()[10], 4), ByteUtils.fromFloat(memberM4.get()[11], 4) }; byte[][] memberM4_4 = new byte[][] { ByteUtils.fromFloat(memberM4.get()[12], 4), ByteUtils.fromFloat(memberM4.get()[13], 4), ByteUtils.fromFloat(memberM4.get()[14], 4), ByteUtils.fromFloat(memberM4.get()[15], 4) }; return new byte[]{ memberM4_1[0][0], memberM4_1[0][1], memberM4_1[0][2], memberM4_1[0][3], memberM4_1[1][0], memberM4_1[1][1], memberM4_1[1][2], memberM4_1[1][3], memberM4_1[2][0], memberM4_1[2][1], memberM4_1[2][2], memberM4_1[2][3], memberM4_1[3][0], memberM4_1[3][1], memberM4_1[3][2], memberM4_1[3][3], memberM4_2[0][0], memberM4_2[0][1], memberM4_2[0][2], memberM4_2[0][3], memberM4_2[1][0], memberM4_2[1][1], memberM4_2[1][2], memberM4_2[1][3], memberM4_2[2][0], memberM4_2[2][1], memberM4_2[2][2], memberM4_2[2][3], memberM4_2[3][0], memberM4_2[3][1], memberM4_2[3][2], memberM4_2[3][3], memberM4_3[0][0], memberM4_3[0][1], memberM4_3[0][2], memberM4_3[0][3], memberM4_3[1][0], memberM4_3[1][1], memberM4_3[1][2], memberM4_3[1][3], memberM4_3[2][0], memberM4_3[2][1], memberM4_3[2][2], memberM4_3[2][3], memberM4_3[3][0], memberM4_3[3][1], memberM4_3[3][2], memberM4_3[3][3], memberM4_4[0][0], memberM4_4[0][1], memberM4_4[0][2], memberM4_4[0][3], memberM4_4[1][0], memberM4_4[1][1], memberM4_4[1][2], memberM4_4[1][3], memberM4_4[2][0], memberM4_4[2][1], memberM4_4[2][2], memberM4_4[2][3], memberM4_4[3][0], memberM4_4[3][1], memberM4_4[3][2], memberM4_4[3][3] }; // Default default: break; } throw new IllegalArgumentException(member.getType() + " can't be analyzed with MemberTypeResolver#fromMember"); } } <file_sep>package com.dexesttp.hkxpack.tagreader.serialized; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.descriptor.exceptions.ClassFileReadError; import com.dexesttp.hkxpack.descriptor.members.HKXMemberTemplate; import com.dexesttp.hkxpack.tagreader.exceptions.InvalidTagXMLException; /** * Handles a serialized member. */ public interface TagXMLSerializedHandler { /** * Creates a {@link HKXMember} based on a member's content description as a {@link HKXMemberTemplate} * @param memberTemplate the {@link HKXMemberTemplate} to build * @return an empty {@link HKXMember} * @throws InvalidTagXMLException * @throws ClassFileReadError */ public HKXMember handleMember(HKXMemberTemplate memberTemplate) throws ClassFileReadError, InvalidTagXMLException; } <file_sep>package com.dexesttp.hkxpack.hkxreader.member; import java.io.IOException; import java.io.RandomAccessFile; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.data.members.HKXStringMember; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.hkx.data.DataInternal; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkxreader.HKXReaderConnector; import com.dexesttp.hkxpack.resources.ByteUtils; class HKXStringMemberReader implements HKXMemberReader { private final HKXReaderConnector connector; private final String name; private final long memberOffset; private final HKXType vtype; HKXStringMemberReader(HKXReaderConnector connector, String name, HKXType vtype, long offset) { this.connector = connector; this.name = name; this.memberOffset = offset; this.vtype = vtype; } @Override public HKXMember read(long classOffset) throws IOException, InvalidPositionException { String contents = ""; try { DataInternal data = connector.data1.readNext(); if(data.from == memberOffset + classOffset) { RandomAccessFile file = connector.data.setup(data.to); contents = ByteUtils.readString(file); } else { connector.data1.backtrack(); } } catch(InvalidPositionException e) { // NO OP. } HKXStringMember result = new HKXStringMember(name, vtype); result.set(contents); return result; } } <file_sep>package com.dexesttp.hkxpack.hkxwriter.object; import java.io.File; import java.io.IOException; import java.util.List; import com.dexesttp.hkxpack.data.HKXObject; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.descriptor.members.HKXMemberTemplate; import com.dexesttp.hkxpack.hkx.types.ObjectSizeResolver; import com.dexesttp.hkxpack.hkxwriter.object.callbacks.HKXMemberCallback; /** * Handles writing a {@link HKXObject}'s contents into a {@link File}. */ public class HKXInternalObjectHandler { private final HKXMemberHandlerFactory memberHandlerFactory; private List<HKXMemberCallback> memberCallbacks; /** * Creates a handler to write an internal object to a {@link File}. * @param factory the {@link HKXMemberHandlerFactory} to use while solving the {@link HKXObject}'s members. * @param memberCallbacks the list of {@link HKXMemberCallback} to add callbacks into. */ public HKXInternalObjectHandler(HKXMemberHandlerFactory factory, List<HKXMemberCallback> memberCallbacks) { this.memberHandlerFactory = factory; this.memberCallbacks = memberCallbacks; } public long write(HKXMember objectAsMember, long currentPos) throws IOException { HKXObject object = (HKXObject) objectAsMember; // Prepare the member handlers, and fill the raw structure. List<HKXMember> members = object.members(); List<HKXMemberTemplate> memberTemplates = object.getDescriptor().getMemberTemplates(); for(int i = 0; i < memberTemplates.size(); i++) { HKXMember member = members.get(i); HKXMemberTemplate memberTemplate = memberTemplates.get(i); HKXMemberHandler memberHandler = memberHandlerFactory.create(memberTemplate.vtype, memberTemplate.offset); memberCallbacks.add(memberHandler.write(member, currentPos)); } return currentPos + ObjectSizeResolver.getSize(object); } } <file_sep>package com.dexesttp.hkxpack.hkxwriter.object.callbacks; import java.io.IOException; import java.util.List; import com.dexesttp.hkxpack.data.HKXData; import com.dexesttp.hkxpack.data.members.HKXArrayMember; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.hkx.HKXUtils; import com.dexesttp.hkxpack.hkx.types.MemberSizeResolver; import com.dexesttp.hkxpack.hkxwriter.object.HKXMemberHandler; import com.dexesttp.hkxpack.hkxwriter.object.HKXMemberHandlerFactory; public class HKXDefaultArrayMemberCallback implements HKXArrayMemberCallback { private final HKXArrayMember arrMember; private final HKXMemberHandlerFactory memberHandlerFactory; public HKXDefaultArrayMemberCallback(HKXArrayMember arrMember, HKXMemberHandlerFactory memberHandlerFactory) { this.arrMember = arrMember; this.memberHandlerFactory = memberHandlerFactory; } @Override public long process(List<HKXMemberCallback> memberCallbacks, long position) throws IOException { long newPos = position; long memberSize = MemberSizeResolver.getSize(arrMember.getSubType()); for(HKXData data : arrMember.contents()) { if(data instanceof HKXMember) { HKXMember internalMember = (HKXMember) data; HKXMemberHandler memberHandler = memberHandlerFactory.create(internalMember.getType(), 0); memberCallbacks.add(memberHandler.write(internalMember, newPos)); newPos += memberSize; } } return HKXUtils.snapLine(newPos) - position; } } <file_sep>package com.dexesttp.hkxpack.hkxwriter.object.callbacks; import java.io.IOException; import java.io.RandomAccessFile; import java.util.List; import com.dexesttp.hkxpack.resources.ByteUtils; public class HKXRelArrayMemberCallback implements HKXMemberCallback { private final HKXArrayMemberCallback callbackProcessor; private final RandomAccessFile outFile; private final long classPos; private final long argPos; public HKXRelArrayMemberCallback(HKXArrayMemberCallback callbackProcessor, RandomAccessFile outFile, long classPos, long argPos) { this.callbackProcessor = callbackProcessor; this.outFile = outFile; this.classPos = classPos; this.argPos = argPos; } @Override public long process(List<HKXMemberCallback> memberCallbacks, long position) throws IOException { byte[] offset = ByteUtils.fromLong(position - classPos, 2); outFile.seek(classPos + argPos + 2); outFile.write(offset); return callbackProcessor.process(memberCallbacks, position); } } <file_sep>package com.dexesttp.hkxpack.hkxwriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.dexesttp.hkxpack.data.HKXObject; import com.dexesttp.hkxpack.descriptor.HKXEnumResolver; import com.dexesttp.hkxpack.hkx.HKXUtils; import com.dexesttp.hkxpack.hkx.classnames.ClassnamesData; import com.dexesttp.hkxpack.hkx.data.DataExternal; import com.dexesttp.hkxpack.hkx.data.DataInternal; import com.dexesttp.hkxpack.hkx.header.SectionData; import com.dexesttp.hkxpack.hkx.types.ObjectSizeResolver; import com.dexesttp.hkxpack.hkxwriter.object.HKXInternalObjectHandler; import com.dexesttp.hkxpack.hkxwriter.object.HKXMemberHandlerFactory; import com.dexesttp.hkxpack.hkxwriter.object.callbacks.HKXMemberCallback; import com.dexesttp.hkxpack.hkxwriter.utils.PointerObject; import com.dexesttp.hkxpack.hkxwriter.utils.PointerResolver; public class HKXObjectHandler { private final ClassnamesData cnameData; private final SectionData section; private final PointerResolver resolver; private final File outFile; private final HKXEnumResolver enumResolver; private final List<DataInternal> data1List; private final List<PointerObject> data2List; private final List<DataExternal> data3List; public HKXObjectHandler(File outFile, ClassnamesData classnamesData, SectionData dataSection, HKXEnumResolver enumResolver, List<DataInternal> data1List, List<PointerObject> data2List, List<DataExternal> data3List, PointerResolver resolver) throws FileNotFoundException { this.outFile = outFile; this.enumResolver = enumResolver; this.cnameData = classnamesData; this.section = dataSection; this.data1List = data1List; this.data2List = data2List; this.data3List = data3List; this.resolver = resolver; } public long handle(HKXObject object, long currentPos) throws IOException { // Add the object into data3 and the resolver DataExternal classEntry = new DataExternal(); classEntry.from = currentPos - section.offset; classEntry.section = 0x00; classEntry.to = cnameData.getPosition(object.getDescriptor().getName()); data3List.add(classEntry); resolver.add(object.getName(), currentPos); List<HKXMemberCallback> memberCallbacks = new ArrayList<HKXMemberCallback>(); HKXMemberHandlerFactory memberHandlerFactory = new HKXMemberHandlerFactory(outFile, enumResolver, data1List, data2List, memberCallbacks); HKXInternalObjectHandler objectHandler = new HKXInternalObjectHandler(memberHandlerFactory, memberCallbacks); objectHandler.write(object, currentPos); // Resolve the member handlers. currentPos += HKXUtils.snapLine(ObjectSizeResolver.getSize(object)); while(!memberCallbacks.isEmpty()) { HKXMemberCallback callback = memberCallbacks.remove(0); currentPos += callback.process(memberCallbacks, currentPos); } memberHandlerFactory.close(); return currentPos; } } <file_sep>package com.dexesttp.hkxpack.cli.commands; import com.dexesttp.hkxpack.cli.utils.StaticProperties; /** * Displays the help of the Command Line Interface. */ public class Command_help implements Command { // TODO prettify help. @Override public int execute(String... parameters) { System.out.println("HKXPack version " + StaticProperties.version_number ); System.out.println("Use : java -jar hkxpack-cli.jar <args>"); System.out.println("Arguments :"); System.out.println("\t"+"unpack" +"\t" +"<filename>" + "\t\t" + "Extracts <filename>.hkx into <filename>.xml"); System.out.println("\t\t\t" +"-o <outputfile>" + "\t" + "Set the output file"); System.out.println("\t"+"pack" +"\t" +"<filename>" + "\t\t" + "Compress <filename>.xml into <filename>.hkx"); System.out.println("\t\t\t" +"-o <outputfile>" + "\t" + "Set the output file"); System.out.println("\t"+"help" +"\t\t\t\t"+ "Show this window"); System.out.println(); System.out.println("Report bugs or findings at github.com/dexesttp/hkxpack"); return 0; } } <file_sep>package com.dexesttp.hkxpack.hkxwriter.object.callbacks; import java.io.IOException; import java.util.List; import com.dexesttp.hkxpack.data.members.HKXArrayMember; import com.dexesttp.hkxpack.hkx.HKXUtils; import com.dexesttp.hkxpack.hkx.types.MemberSizeResolver; import com.dexesttp.hkxpack.hkxwriter.object.array.HKXArrayPointerMemberHandler; public class HKXPointerArrayMemberCallback implements HKXArrayMemberCallback { private final HKXArrayMember arrMember; private final List<HKXArrayPointerMemberHandler> apmhList; public HKXPointerArrayMemberCallback(HKXArrayMember arrMember, List<HKXArrayPointerMemberHandler> apmhList) { this.arrMember = arrMember; this.apmhList = apmhList; } @Override public long process(List<HKXMemberCallback> memberCallbacks, long position) throws IOException { long newPos = position; for(HKXArrayPointerMemberHandler apmh : apmhList) { long objectSize = MemberSizeResolver.getSize(arrMember.getSubType()); apmh.resolve(newPos); newPos += objectSize; } return HKXUtils.snapLine(newPos) - position; } } <file_sep>package com.dexesttp.hkxpack.data.members; import com.dexesttp.hkxpack.descriptor.enums.HKXType; public class HKXDirectMember<T> implements HKXMember { private final HKXType type; private final String name; private T value; public HKXDirectMember(String name, HKXType type) { this.name = name; this.type = type; } public void set(T value) { this.value = value; } public T get() { return value; } @Override public String getName() { return name; } @Override public HKXType getType() { return type; } } <file_sep>package com.dexesttp.hkxpack.data; import java.util.ArrayList; import java.util.List; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.descriptor.HKXDescriptor; import com.dexesttp.hkxpack.descriptor.enums.HKXType; public class HKXObject implements HKXMember { private final String name; private final HKXDescriptor descriptor; private final List<HKXMember> members; public HKXObject(String name, HKXDescriptor template) { this(name, template, new ArrayList<HKXMember>()); } public HKXObject(String name, HKXDescriptor descriptor, ArrayList<HKXMember> members) { this.name = name; this.descriptor = descriptor; this.members = members; } public String getName() { return name; } public HKXDescriptor getDescriptor() { return descriptor; } public List<HKXMember> members() { return members; } @Override public HKXType getType() { return HKXType.TYPE_STRUCT; } } <file_sep>package com.dexesttp.hkxpack.hkxreader.member; import java.io.IOException; import java.io.RandomAccessFile; import com.dexesttp.hkxpack.data.members.HKXEnumMember; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.descriptor.HKXEnumResolver; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkx.types.MemberSizeResolver; import com.dexesttp.hkxpack.hkxreader.HKXReaderConnector; import com.dexesttp.hkxpack.resources.ByteUtils; public class HKXEnumMemberReader implements HKXMemberReader { private final HKXReaderConnector connector; private final HKXEnumResolver enumResolver; private final String name; private final HKXType vtype; private final HKXType vsubtype; private final String etype; private final long memberOffset; HKXEnumMemberReader(HKXReaderConnector connector, HKXEnumResolver enumResolver, String name, HKXType vtype, HKXType vsubtype, String target, long offset) { this.connector = connector; this.enumResolver = enumResolver; this.name = name; this.vtype = vtype; this.vsubtype = vsubtype; this.etype = target; this.memberOffset = offset; } @Override public HKXMember read(long classOffset) throws IOException, InvalidPositionException { final int memberSize = (int) MemberSizeResolver.getSize(vsubtype); RandomAccessFile file = connector.data.setup(classOffset + memberOffset); byte[] b = new byte[memberSize]; file.read(b); int contents = ByteUtils.getInt(b); HKXEnumMember result = new HKXEnumMember(name, vtype, vsubtype, etype); result.set(enumResolver.resolve(etype, contents)); return result; } } <file_sep>package com.dexesttp.hkxpack.hkxreader.member.arrays; import java.io.IOException; import java.io.RandomAccessFile; import com.dexesttp.hkxpack.data.HKXData; import com.dexesttp.hkxpack.data.members.HKXStringMember; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.hkx.data.DataInternal; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkxreader.HKXReaderConnector; import com.dexesttp.hkxpack.resources.ByteUtils; class HKXStringArrayContentsReader implements HKXArrayContentsReader { private HKXReaderConnector connector; private HKXType contentsType; HKXStringArrayContentsReader(HKXReaderConnector connector, HKXType contentsType) { this.connector = connector; this.contentsType = contentsType; } @Override public HKXData getContents(long arrayStart, int position) throws IOException, InvalidPositionException { long descriptorPosition = arrayStart + position * 0x08; DataInternal data = connector.data1.readNext(); String contents = ""; if(data.from == descriptorPosition) { RandomAccessFile file = connector.data.setup(data.to); contents = ByteUtils.readString(file); } else { connector.data1.backtrack(); } HKXStringMember result = new HKXStringMember("", contentsType); result.set(contents); return result; } } <file_sep>package com.dexesttp.hkxpack.hkxwriter.utils; public class PointerObject { public long from; public String to; } <file_sep>package com.dexesttp.hkxpack.hkxreader.member.arrays; import java.io.IOException; import java.io.RandomAccessFile; import com.dexesttp.hkxpack.data.HKXData; import com.dexesttp.hkxpack.data.members.HKXMember; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkx.types.MemberDataResolver; import com.dexesttp.hkxpack.hkx.types.MemberSizeResolver; import com.dexesttp.hkxpack.hkxreader.HKXReaderConnector; class HKXDirectArrayContentsReader implements HKXArrayContentsReader { private final HKXReaderConnector connector; private final HKXType contentType; HKXDirectArrayContentsReader(HKXReaderConnector connector, HKXType contentType) { this.connector = connector; this.contentType = contentType; } @Override public HKXData getContents(long arrayStart, int position) throws IOException, InvalidPositionException { final int contentSize = (int) MemberSizeResolver.getSize(contentType); byte[] b = new byte[contentSize]; RandomAccessFile file = connector.data.setup(arrayStart + position * contentSize); file.read(b); HKXMember data = MemberDataResolver.getMember("", contentType, b); return data; } } <file_sep>package com.dexesttp.hkxpack.cli.commands; import java.io.File; /** * Routes an unknown command to either a help, pack or unpack command. */ public class Command_quick implements Command { @Override public int execute(String... parameters) { Command command = null; if(parameters.length > 1) { return (new Command_help()).execute(parameters); } String inName = parameters[0]; File inFile = new File(inName); String name = inFile.getName(); String command_arg = ""; try { if(!inFile.isFile()) throw new Exception("The given parameter isn't a HKX or XML file."); String ext = name.substring(name.lastIndexOf(".") + 1); if(ext.equals("hkx")) { command = new Command_unpack(); command_arg = "unpack"; } else if(ext.equals("xml")) { command = new Command_pack(); command_arg = "pack"; } else throw new Exception("Unsupported file type."); } catch (Exception e) { System.err.println(e.getMessage()); return 1; } return command.execute(command_arg, inName); } } <file_sep>package com.dexesttp.hkxpack.data.members; import com.dexesttp.hkxpack.descriptor.enums.HKXType; public class HKXPointerMember implements HKXMember { private final String name; private final HKXType type; private final HKXType subtype; private String value; public HKXPointerMember(String name, HKXType type, HKXType subtype, String target) { this.name = name; this.type = type; this.subtype = subtype; this.value = target; } public void set(String value) { this.value = value; } public String get() { return value; } public HKXType getSubtype() { return subtype; } @Override public String getName() { return name; } @Override public HKXType getType() { return type; } } <file_sep>package com.dexesttp.hkxpack.cli.utils; /** * Contains a list of static final properties. */ public class StaticProperties { /** * <pre> * Versioning convention: * 1st digit : main version identifier * * Supposed to be used in case of a huge fonctionnality change. * * A change shows a compatibility loss with previous versions. * * 2nd digit : version iteration * * Supposed to be used when a new functionnality set is added. * * 3rd digit : version state * * Even = stable, odd = unstable * * Changed each time a functionnality is added for release. * * Hyphen : state identifier * * Either alpha|beta|theta|gamma or any state identifier (unstable, snapshot, etc.. works) * * Linguistic representation of the 1st, second and 3rd digit. * * Doesn't exist with stable releases (no -HOTFIX or similar, this goes into the merge data or changelog !) * </pre> */ public static String version_number = "0.1.2-beta"; } <file_sep>package com.dexesttp.hkxpack.hkx.types; import java.util.List; import com.dexesttp.hkxpack.data.HKXObject; import com.dexesttp.hkxpack.descriptor.HKXDescriptor; import com.dexesttp.hkxpack.descriptor.HKXDescriptorFactory; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.descriptor.enums.HKXTypeFamily; import com.dexesttp.hkxpack.descriptor.exceptions.ClassFileReadError; import com.dexesttp.hkxpack.descriptor.members.HKXMemberTemplate; import com.dexesttp.hkxpack.hkx.HKXUtils; /** * Resolve the size of a {@link HKXObject} or a {@link HKXDescriptor}. */ public class ObjectSizeResolver { private static final long PTR_SIZE = 0x08; private static long primitiveSnap(HKXType type) { switch(type) { case TYPE_NONE: case TYPE_VOID: return 0X00; // Base values case TYPE_BOOL: return 0X01; case TYPE_CHAR: return 0X01; case TYPE_UINT8: case TYPE_INT8: return 0X01; case TYPE_HALF: case TYPE_UINT16: case TYPE_INT16: return 0X02; case TYPE_ULONG: case TYPE_UINT32: case TYPE_INT32: return 0X04; case TYPE_UINT64: case TYPE_INT64: return 0X08; case TYPE_REAL: return 0X04; // Complex values case TYPE_VECTOR4: case TYPE_QUATERNION: case TYPE_TRANSFORM: case TYPE_QSTRANSFORM: case TYPE_MATRIX3: case TYPE_MATRIX4: return 0x04; // Strings and ptrs case TYPE_CSTRING: case TYPE_STRINGPTR: return PTR_SIZE ; case TYPE_FUNCTIONPOINTER: case TYPE_POINTER: return PTR_SIZE; // Arrays case TYPE_RELARRAY: return 0x4; case TYPE_ARRAY: case TYPE_SIMPLEARRAY: return PTR_SIZE; default: return 0x00; } } /** * Retrieves the size of a {@link HKXDescriptor}, including end padding if needed. * @param descriptor the {@link HKXDescriptor} to retrieve the size from. * @return the {@link HKXDescriptor}'s size, in bytes. * @throws ClassFileReadError if there was an error resolving this {@link HKXDescriptor}'s subclass */ public static long getSize(HKXDescriptor descriptor, HKXDescriptorFactory descriptorFactory) throws ClassFileReadError { List<HKXMemberTemplate> templates = descriptor.getMemberTemplates(); if(templates.isEmpty()) return 0; long bestSnap = getSnap(descriptor, descriptorFactory); HKXMemberTemplate lastTemplate = templates.get(templates.size() - 1); if(lastTemplate.vtype.getFamily() == HKXTypeFamily.ENUM) return HKXUtils.snapSize(lastTemplate.offset + MemberSizeResolver.getSize(lastTemplate.vsubtype), bestSnap); if(lastTemplate.vtype != HKXType.TYPE_STRUCT) return HKXUtils.snapSize(lastTemplate.offset + MemberSizeResolver.getSize(lastTemplate.vtype), bestSnap); HKXDescriptor internalDescriptor = descriptorFactory.get(lastTemplate.target); return HKXUtils.snapSize(lastTemplate.offset + getSize(internalDescriptor, descriptorFactory), bestSnap); } private static long getSnap(HKXDescriptor descriptor, HKXDescriptorFactory descriptorFactory) throws ClassFileReadError { long bestSnap = 0; List<HKXMemberTemplate> list = descriptor.getMemberTemplates(); for(int i = 0; i < list.size(); i++) { HKXMemberTemplate template = list.get(i); long currSnap = 0; if(template.vtype.getFamily() == HKXTypeFamily.ENUM) currSnap = primitiveSnap(template.vsubtype); else if(template.vtype != HKXType.TYPE_STRUCT) currSnap = primitiveSnap(template.vtype); else { HKXDescriptor internalDescriptor = descriptorFactory.get(template.target); currSnap = getSnap(internalDescriptor, descriptorFactory); } bestSnap = currSnap > bestSnap ? currSnap : bestSnap; } return bestSnap; } /** * Retrieves the size of a {@link HKXObject}, including end padding if needed. * @param object the {@link HKXObject} to retrieve the size from. * @return the {@link HKXObject}'s size, in bytes. */ public static long getSize(HKXObject object) { List<HKXMemberTemplate> templates = object.getDescriptor().getMemberTemplates(); if(templates.isEmpty()) return 0; long bestSnap = getSnap(object); HKXMemberTemplate lastTemplate = templates.get(templates.size() - 1); if(lastTemplate.vtype.getFamily() == HKXTypeFamily.ENUM) return HKXUtils.snapSize(lastTemplate.offset + MemberSizeResolver.getSize(lastTemplate.vsubtype), bestSnap); if(lastTemplate.vtype != HKXType.TYPE_STRUCT) return HKXUtils.snapSize(lastTemplate.offset + MemberSizeResolver.getSize(lastTemplate.vtype), bestSnap); HKXObject internalObject = (HKXObject) object.members().get(templates.size() - 1); return HKXUtils.snapSize(lastTemplate.offset + getSize(internalObject), bestSnap); } private static long getSnap(HKXObject object) { long bestSnap = 0; List<HKXMemberTemplate> list = object.getDescriptor().getMemberTemplates(); for(int i = 0; i < list.size(); i++) { HKXMemberTemplate template = list.get(i); long currSnap = 0; if(template.vtype.getFamily() == HKXTypeFamily.ENUM) currSnap = primitiveSnap(template.vsubtype); else if(template.vtype != HKXType.TYPE_STRUCT) currSnap = primitiveSnap(template.vtype); else { HKXObject internalObject = (HKXObject) object.members().get(i); currSnap = getSnap(internalObject); } bestSnap = currSnap > bestSnap ? currSnap : bestSnap; } return bestSnap; } } <file_sep>package com.dexesttp.hkxpack.cli.commands; import java.io.File; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.dexesttp.hkxpack.cli.loggers.DirectoryWalkerLoggerFactory; import com.dexesttp.hkxpack.cli.loggers.DirectoryWalkerLoggerFactory.DirectoryWalkerLogger; import com.dexesttp.hkxpack.cli.utils.ArgsParser; import com.dexesttp.hkxpack.cli.utils.CLIProperties; import com.dexesttp.hkxpack.cli.utils.DirWalker; import com.dexesttp.hkxpack.cli.utils.WrongSizeException; import com.dexesttp.hkxpack.descriptor.HKXDescriptorFactory; import com.dexesttp.hkxpack.descriptor.HKXEnumResolver; import com.dexesttp.hkxpack.descriptor.exceptions.ClassListReadError; /** * Abstract command to handle routing between a single file and multiple files from a directory. <br /> * <p> * The new entry point is {@link #execution_core(String, String, HKXEnumResolver, HKXDescriptorFactory)}. This should contain the code to handle a single file. <br /> * The subclass should also implement {@link #extractFileName(String)}, a routine to convert the input file name to a suitable output one if needed. <br /> * Finally, the subclass should implement {@link #getFileExtensions()}, to return a list of accepted extensions for imput file detected when walking through directories. */ public abstract class Command_IO implements Command { private int nbConcurrentThreads = 32; @Override public int execute(String... args) { // Options handling ArgsParser parser = new ArgsParser(); parser.addOption("-o", 1); parser.addOption("-t", 1); parser.addOption("-d", 0); parser.addOption("-q", 0); parser.addOption("-v", 0); ArgsParser.Options result; try { result = parser.parse(args); } catch (WrongSizeException e1) { e1.printStackTrace(); return 1; } String fileName = result.get("", 1); String outName = result.get("-o", 0); if(result.exists("-t")) nbConcurrentThreads = Integer.parseInt(result.get("-t", 0)); CLIProperties.debug = result.exists("-d"); CLIProperties.quiet = result.exists("-q"); CLIProperties.verbose = result.exists("-v"); // Routing File fileIn = new File(fileName); if(fileIn.isDirectory()) return execute_multi(fileIn, outName); else return execute_single(fileName, outName); } /** * Executes the code for a single imput file to a single output file. * @param fileName the input file name. * @param outName the output file name. * @return the execution result value. */ private int execute_single(String fileName, String outName) { if(outName == "") outName = extractFileName(fileName); HKXEnumResolver enumResolver = new HKXEnumResolver(); HKXDescriptorFactory descriptorFactory; try { descriptorFactory = new HKXDescriptorFactory(enumResolver); execution_core(fileName, outName, enumResolver, descriptorFactory); } catch(Exception e) { e.printStackTrace(); return 1; } return 0; } /** * Executes the code for a directory * @param inDir the input directory {@link File}. * @param outDir the output directory name. * @return the execution result value. * @see DirWalker */ private int execute_multi(File inDir, String outDir) { // Create output directory. if(outDir.isEmpty()) outDir = "out"; // Walk through the directory DirWalker walker = new DirWalker(getFileExtensions()); List<DirWalker.Entry> toConvert = walker.walk(inDir); // Create logger DirectoryWalkerLogger logger = new DirectoryWalkerLoggerFactory().newLogger(toConvert.size()); // Create the thread pool. ThreadPoolExecutor pool = new ThreadPoolExecutor( nbConcurrentThreads, nbConcurrentThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); // Initailize the factorized tools. HKXEnumResolver enumResolver = new HKXEnumResolver(); HKXDescriptorFactory descriptorFactory; try { descriptorFactory = new HKXDescriptorFactory(enumResolver); } catch (ClassListReadError e) { e.printStackTrace(); return 1; } // Populate the thread pool using the directory entries. for(DirWalker.Entry fileInDirectory : toConvert) { new File(fileInDirectory.getPath("out")).mkdirs(); final String inputFileName = fileInDirectory.getFullName(); final String outputFileName = fileInDirectory.getPath("out") + "/" + extractFileName(fileInDirectory.getName()); pool.execute(() -> { execution_catcher(inputFileName, outputFileName, enumResolver, descriptorFactory); }); } // Handle pool termination, as well as logging of pool execution progress (every 30 seconds) pool.shutdown(); try { long numberOfHandledTasks = 0; while(!pool.awaitTermination(30, TimeUnit.SECONDS)) { if(pool.getCompletedTaskCount() > numberOfHandledTasks) numberOfHandledTasks = pool.getCompletedTaskCount(); logger.log(numberOfHandledTasks); } } catch (InterruptedException e) { // Force shutdown of all tasks. pool.shutdownNow(); } return 0; } protected void execution_catcher(String inputFileName, String outputFileName, HKXEnumResolver enumResolver, HKXDescriptorFactory descriptorFactory) { try { execution_core(inputFileName, outputFileName, enumResolver, descriptorFactory); } catch (Exception e) { System.out.println("Error reading file : " + inputFileName); if(CLIProperties.debug) e.printStackTrace(); else if(!CLIProperties.quiet) System.err.println(e.getMessage()); } finally { if(CLIProperties.verbose) { System.out.println(inputFileName); System.out.println("\t=> " + outputFileName); } } } /** * Handles a single file * @param inputFileName the input file name * @param outputFileName the output file name * @param enumResolver the {@link HKXEnumResolver} to use. * @param descriptorFactory the {@link HKXDescriptorFactory} to use. * @throws Exception if there was an issue while handling the file */ protected abstract void execution_core(String inputFileName, String outputFileName, HKXEnumResolver enumResolver, HKXDescriptorFactory descriptorFactory) throws Exception; /** * Extracts a suitable output name from an input file name. * @param ogName the original input file name * @return a suitable output name. */ protected abstract String extractFileName(String ogName); /** * Retrieves a list of file extensions to select while crawling through a directory. * @return the file extensions as a {@link String} list. */ protected abstract String[] getFileExtensions(); } <file_sep>package com.dexesttp.hkxpack.hkxreader.member; import com.dexesttp.hkxpack.descriptor.HKXDescriptor; import com.dexesttp.hkxpack.descriptor.HKXDescriptorFactory; import com.dexesttp.hkxpack.descriptor.HKXEnumResolver; import com.dexesttp.hkxpack.descriptor.enums.HKXType; import com.dexesttp.hkxpack.descriptor.exceptions.ClassFileReadError; import com.dexesttp.hkxpack.descriptor.members.HKXMemberTemplate; import com.dexesttp.hkxpack.hkxreader.HKXObjectReader; import com.dexesttp.hkxpack.hkxreader.HKXReaderConnector; import com.dexesttp.hkxpack.hkxreader.PointerNameGenerator; import com.dexesttp.hkxpack.hkxreader.member.arrays.HKXArrayContentsReader; import com.dexesttp.hkxpack.hkxreader.member.arrays.HKXArrayContentsReaderFactory; import com.dexesttp.hkxpack.l10n.SBundle; public class HKXMemberReaderFactory { private final HKXDescriptorFactory descriptorFactory; private final HKXReaderConnector connector; private final PointerNameGenerator generator; private final HKXEnumResolver enumResolver; private HKXObjectReader objectCreator; private HKXArrayContentsReaderFactory acrFactory; public HKXMemberReaderFactory(HKXDescriptorFactory descriptorFactory, HKXReaderConnector connector, PointerNameGenerator generator, HKXEnumResolver enumResolver) { this.descriptorFactory = descriptorFactory; this.connector = connector; this.generator = generator; this.enumResolver = enumResolver; } public void connectObjectCreator(HKXObjectReader objectCreator) { this.objectCreator = objectCreator; this.acrFactory = new HKXArrayContentsReaderFactory(connector, descriptorFactory, objectCreator, generator); } public HKXMemberReader getMemberReader(HKXMemberTemplate template) throws ClassFileReadError { switch(template.vtype.getFamily()) { case DIRECT: case COMPLEX: return new HKXDirectMemberReader(connector, template.name, template.vtype, template.offset); case ENUM: return new HKXEnumMemberReader(connector, enumResolver, template.name, template.vtype, template.vsubtype, template.target, template.offset); case ARRAY: HKXArrayContentsReader arrayContentsReader = acrFactory.get(template); if(template.vtype == HKXType.TYPE_RELARRAY) return new HKXRelArrayMemberReader(connector, template.name, template.vsubtype, arrayContentsReader, template.offset); else return new HKXArrayMemberReader(connector, template.name, template.vsubtype, arrayContentsReader, template.offset); case OBJECT: HKXDescriptor descriptor = descriptorFactory.get(template.target); return new HKXObjectMemberReader(objectCreator, template.name, template.offset, descriptor); case POINTER: return new HKXPointerMemberReader(connector, generator, template.name, template.vsubtype, template.offset); case STRING: return new HKXStringMemberReader(connector, template.name, template.vtype, template.offset); default: throw new IllegalArgumentException(SBundle.getString("error.hkx.read.type") + template.vtype); } } } <file_sep>package com.dexesttp.hkxpack.hkxreader.member.arrays; import java.io.IOException; import com.dexesttp.hkxpack.data.HKXData; import com.dexesttp.hkxpack.data.HKXObject; import com.dexesttp.hkxpack.descriptor.HKXDescriptor; import com.dexesttp.hkxpack.descriptor.HKXDescriptorFactory; import com.dexesttp.hkxpack.descriptor.exceptions.ClassFileReadError; import com.dexesttp.hkxpack.hkx.exceptions.InvalidPositionException; import com.dexesttp.hkxpack.hkx.types.ObjectSizeResolver; import com.dexesttp.hkxpack.hkxreader.HKXObjectReader; class HKXObjectArrayContentsReader implements HKXArrayContentsReader { private final HKXObjectReader reader; private final HKXDescriptor descriptor; private final int contentSize; HKXObjectArrayContentsReader(HKXObjectReader reader, HKXDescriptorFactory descriptorFactory, HKXDescriptor descriptor) throws ClassFileReadError { this.reader = reader; this.descriptor = descriptor; this.contentSize = (int) ObjectSizeResolver.getSize(descriptor, descriptorFactory); } @Override public HKXData getContents(long arrayStart, int position) throws IOException, InvalidPositionException { long contentsPos = arrayStart + position * contentSize; HKXObject data = reader.createHKXObject("", contentsPos, descriptor); return data; } } <file_sep>package com.dexesttp.hkxpack.cli.utils; /** * Contains general options about the Command Line Interface behavior */ public class CLIProperties { /** * Debug option */ public static boolean debug = false; /** * Verbose (lots of text) option */ public static boolean verbose = false; /** * Quiet (no text) option. */ public static boolean quiet = false; }
66461902783811569fce14a9519572c70ca9a011
[ "Java" ]
34
Java
philjord/hkxpack
77e66ed1015437340c9e77a720ff6cd5b91e470c
9c8b684ca8c225bac84f318f7c49e2544abd4ec2
refs/heads/master
<repo_name>TPLinux/foundation-solver<file_sep>/solver.py from sympy import Eq, Symbol, solve import math class Solver: def __init__(self, command_line=False, **info): self.need_to_calculate_q_all = False if command_line: self.column = input("column dimentions in meter , ex: [0.3x0.3]: ") self.bc = float(self.column.split('x')[0]) self.lc = float(self.column.split('x')[1]) self.load = float(input("Load in ton: ")) self.plain_concrete_thickness = float(input("Plain concrete thickness in cm: ")) # noqa is_q = input("Do you have [q all_net] as given ?[n\\y]: ") if(is_q == 'y'): self.q_all = float(input("(q) allowable in (ton per meter square): ")) # noqa else: self.need_to_calculate_q_all = True self.all_soil_pressure = float(input("allowable soil pressure in (kg per cm square): ")) # noqa self.soli_density = float(input("Soil Desnsity in (ton per meter cube) : ")) # noqa self.Df = float(input("Df (depth of footing below ground level) in meter: ")) # noqa self.qsh = float(input("qsh (q shear) in (kg per cm square): ")) self.qp = float(input("qp (q punch) in (kg per cm square): ")) self.K1 = float(input("K1: ")) self.K2 = float(input("K2: ")) else: self.column = info['column'] self.bc = float(self.column.split('x')[0]) self.lc = float(self.column.split('x')[1]) self.load = float(info['load']) self.plain_concrete_thickness = float(info['plain_concrete_thickness']) # noqa self.q_all = float(info['q_all']) # noqa self.qsh = float(info['qsh']) self.qp = float(info['qp']) self.K1 = float(info['K1']) self.K2 = float(info['K2']) self.bc_min_lc = self.bc - self.lc self.calculate_q_all() self.area_of_footing() self.dimentions() self.q_act() self.calc_C() self.calc_monments() self.calc_depth() self.area_of_steel() def calculate_q_all(self): if self.need_to_calculate_q_all: self.q_all = self.all_soil_pressure * 10 - self.soli_density * self.Df # noqa print("Q Allawable: ", self.q_all) return self.q_all def area_of_footing(self): self.area_of_footing = self.load / self.q_all self.area_of_footing = round(self.area_of_footing, 1) print("Area Of footing: ", self.area_of_footing) return self.area_of_footing def dimentions(self): self.B_pc = self.L_pc = 0 if self.plain_concrete_thickness < 30: if self.bc == self.lc: self.B_rc = self.L_rc = self.area_of_footing ** 0.5 else: self.area_of_footing_pc = self.area_of_footing Bpc = Symbol('Bpc') eq = Eq(Bpc - (self.area_of_footing_pc / Bpc) + (self.bc - self.lc), 0) # noqa self.B_rc = round(abs(solve(eq)[0]), 3) self.L_rc = round(self.area_of_footing_pc / self.B_rc, 3) self.B_rc = round(self.round_nearest(self.B_rc, 0.05), 3) self.L_rc = round(self.round_nearest(self.L_rc, 0.05), 3) else: if self.bc == self.lc: self.area_of_footing_pc = self.area_of_footing self.B_pc = self.L_pc = self.area_of_footing ** 0.5 else: self.area_of_footing_pc = self.area_of_footing Bpc = Symbol('Bpc') eq = Eq(Bpc - (self.area_of_footing_pc / Bpc) + (self.bc - self.lc), 0) # noqa self.B_pc = round(abs(solve(eq)[0]), 3) self.L_pc = round(self.area_of_footing_pc / self.B_pc, 3) self.B_pc = round(self.round_nearest(self.B_pc, 0.05), 3) self.L_pc = round(self.round_nearest(self.L_pc, 0.05), 3) self.L_rc = round(self.round_nearest(round(self.L_pc - (2 * (self.plain_concrete_thickness / 100)), 3), 0.05), 2) # noqa self.B_rc = round(self.round_nearest(round(self.B_pc - (2 * (self.plain_concrete_thickness / 100)), 3), 0.05), 2) # noqa print("PC Dimentions: ", self.B_pc, self.L_pc) print("RC Dimentions: ", self.B_rc, self.L_rc) def q_act(self): self.q_act = round(self.load / (self.B_rc * self.L_rc), 3) print("Q act: ", self.q_act) return self.q_act def calc_C(self): if self.bc == self.lc: self.Cx = self.Cy = round((self.B_rc - self.bc) / 2, 3) else: self.Cx = round((self.B_rc - self.bc) / 2, 3) self.Cy = round((self.L_rc - self.lc) / 2, 3) print("Cx, Cy: ", self.Cx, self.Cy) def calc_monments(self): if self.bc == self.lc: self.M1_1 = self.M2_2 = round(self.q_act * ((self.Cx ** 2) / 2) * self.B_rc, 3) # noqa else: self.M1_1 = round(self.q_act * ((self.Cx ** 2) / 2) * self.L_rc, 3) self.M2_2 = round(self.q_act * ((self.Cy ** 2) / 2) * self.B_rc, 3) print("Moments: ", self.M1_1, self.M2_2) def calc_depth(self): self.m_max = max([self.M1_1, self.M2_2]) if self.bc == self.lc: # depth of B.M self.depth_bm = round(self.K1 * ((self.m_max * (10 ** 5)) / ((self.bc * 100) + 10)) ** 0.5, 3) # noqa # depth for shear depth_sh = Symbol('dsh') Qsh = self.q_act * self.B_rc * (self.Cx - depth_sh) eqn = Eq(depth_sh, Qsh / (0.87 * self.L_rc * (self.qsh * 10))) self.depth_sh = round(solve(eqn)[0] * 100, 3) else: # depth of B.M self.depth_bm = round(self.K1 * ((self.m_max * (10 ** 5)) / ((self.lc * 100) + 10)) ** 0.5, 3) # noqa # depth for shear depth_sh = Symbol('dsh') Qsh = self.q_act * self.B_rc * (self.Cx - depth_sh) eqn = Eq(depth_sh, Qsh / (0.87 * self.B_rc * (self.qsh * 10))) self.depth_sh = round(solve(eqn)[0] * 100, 3) # depth for punch Qp = self.load - (self.q_act * (self.bc * self.lc)) self.Qp = Qp self.dp = round(Qp / ((self.qp * 10) * (2 * self.bc + 2 * self.lc)) * 100, 3) # noqa self.depthes = [self.depth_sh, self.depth_bm, self.dp] # get the maximum depth self.max_depth = max(self.depthes) self.T = self.max_depth + 7 self.old_T = self.T if self.T < 50: self.T = 50 self.fix_T() self.D = self.T - 7 print("Depthes: ", self.depth_sh, self.depth_bm, self.dp) print('T, D: ', (self.T, self.D)) def area_of_steel(self): self.m_short = max([self.M1_1, self.M2_2]) self.m_long = min([self.M1_1, self.M2_2]) self.b_short = max([self.B_rc, self.L_rc]) self.b_long = min([self.B_rc, self.L_rc]) self.As_short = round((self.m_short * (10 ** 5)) / (self.K2 * self.D), 3) self.As_short_min = round(0.0025 * max([self.B_rc, self.L_rc]) * 100 * self.D, 3) # noqa self.As_long = round((self.m_long * (10 ** 5)) / (self.K2 * self.D), 3) self.As_long_min = round(0.0025 * min([self.B_rc, self.L_rc]) * 100 * self.D, 3) # noqa print("As (long): ", self.As_long) print("As (long MIN): ", self.As_long_min) print("As (short): ", self.As_short) print("As (short) MIN: ", self.As_short_min) def round_nearest(self, x, a): return round(x / a) * a def fix_T(self): m = self.T % 10 if m == 0: pass elif m <= 5: self.T = math.floor(self.T - m) + 5 else: self.T = math.floor(self.T - m) + 10 # s = Solver(True)
22b35b2dc55617300f95439f346de359c03d1e4b
[ "Python" ]
1
Python
TPLinux/foundation-solver
98ffec3a18527453f9777b1e8b712d5c1db41878
34970fc5c6d3d08688c92233d0eef927fb5f83bc
refs/heads/master
<repo_name>werneriaa/Fullstackopen<file_sep>/osa2/kurssitiedotapp2/src/components/Course.js import React from "react"; const Course = ({ courses }) => { return courses.map(b => ( <div key={b.parts.map(part => part.id)}> <Header name={b.name} /> <Content parts={b.parts} /> </div> )); }; const Header = ({ name }) => { return ( <> <h1>{name}</h1> </> ); }; const Content = ({ parts }) => { return ( <> <Parts parts={parts} /> <Total parts={parts} /> </> ); }; const Parts = ({ parts }) => { return parts.map(part => ( <p key={part.id}> {part.name} {part.exercises} </p> )); }; const Total = ({ parts }) => { console.log(parts); return ( <b> total of {parts.reduce((acum, curval) => curval.exercises + acum, 0)}{" "} exercises </b> ); }; export default Course; <file_sep>/README.md # Fullstackopen FSO Course https://gentle-bastion-43538.herokuapp.com/ /info /persons Frontend made with React and backend with Node.js <file_sep>/osa2/puhelinluetteloapp/src/App.js import React, { useState, useEffect } from "react"; import Filter from "./components/Filter"; import Personform from "./components/Personform"; import Person from "./components/Person"; import personService from "./services/persons"; const App = () => { const [persons, setPersons] = useState([""]); const [newName, setNewName] = useState(""); const [newNumber, setNewNumber] = useState(""); const [filter, setFilter] = useState(""); useEffect(() => { console.log("effect"); personService.getAll().then(initialNumbers => { setPersons(initialNumbers); }); }, []); const personsToShow = filter === "" ? persons : persons.filter( p => p.name.toLowerCase().includes(filter.toLowerCase()) || p.number.includes(filter) ); const addName = event => { console.log("name added"); event.preventDefault(); const nameObject = { name: newName, number: newNumber }; const person = persons.find(person => person.name === newName); if (person !== undefined) { if ( window.confirm( `${newName} is already added to phonebook. Do you want to update it?` ) ) { const updatedPerson = { ...person, number: newNumber }; personService .update(person.id, updatedPerson) .then(res => setPersons(persons.map(p => (p.id === res.id ? res : p))) ); setNewName(""); setNewNumber(""); } } else { personService.create(nameObject).then(reponse => { console.log(nameObject); setPersons(persons.concat(nameObject)); setNewName(""); setNewNumber(""); }); } }; const rows = () => personsToShow.map(person => ( <Person key={person.name} person={person} personDelete={() => personDelete(person.id)} /> )); const handleNameChange = event => { setNewName(event.target.value); }; const handleNumberChange = event => { setNewNumber(event.target.value); }; const personDelete = id => { const delPerson = persons.find(p => p.id === id); if (window.confirm(`Do you really want to delete ${delPerson.name}?`)) { console.log(delPerson); const newPersons = persons.filter(p => p !== delPerson); personService.remove(id); setPersons(newPersons); } }; return ( <div> <h2>Phonebook</h2> <Filter value={filter} onChange={e => setFilter(e.target.value)} /> <Personform addName={addName} newName={newName} handleNameChange={handleNameChange} newNumber={newNumber} handleNumberChange={handleNumberChange} /> <h2>Numbers</h2> <ul>{rows()}</ul> </div> ); }; export default App;
d9e08ac7479912920cd51e31eacba604d9cc55b0
[ "JavaScript", "Markdown" ]
3
JavaScript
werneriaa/Fullstackopen
d7ecf95dfd41ce18466004281c6089bc0f1187d5
989974d1871a625d0d0e50b0f28e70923754ebf7
refs/heads/master
<repo_name>sunxu3074/android-about-page<file_sep>/library/src/main/java/mehdi/sakout/aboutpage/AboutPage.java package mehdi.sakout.aboutpage; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.support.graphics.drawable.VectorDrawableCompat; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.widget.TextViewCompat; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.net.URISyntaxException; import java.util.logging.Logger; /** * Created by medyo on 3/25/16. */ public class AboutPage { private final Context mContext; private final LayoutInflater mInflater; private final View mView; private String mDescription; private int mImage = 0; private boolean mIsRTL = false; private Typeface mCustomFont; public AboutPage(Context context) { this.mContext = context; this.mInflater = LayoutInflater.from(context); this.mView = mInflater.inflate(R.layout.about_page, null); } public AboutPage setCustomFont(String path) { mCustomFont = Typeface.createFromAsset(mContext.getAssets(), path); return this; } /* Add Email Element */ public AboutPage addEmail(String email) { Element emailElement = new Element(); emailElement.setTitle(mContext.getString(R.string.about_contact_us)); emailElement.setIcon(R.drawable.about_icon_email); emailElement.setColor(ContextCompat.getColor(mContext, R.color.about_item_icon_color)); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email }); emailElement.setIntent(intent); addItem(emailElement); return this; } /* Add Facebook Element */ public AboutPage addFacebook(String id) { Element facebookElement = new Element(); facebookElement.setTitle(mContext.getString(R.string.about_facebook)); facebookElement.setIcon(R.drawable.about_icon_facebook); facebookElement.setColor(ContextCompat.getColor(mContext, R.color.about_facebook_color)); facebookElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); if (AboutPageUtils.isAppInstalled(mContext, "com.facebook.katana")) { intent.setPackage("com.facebook.katana"); int versionCode = 0; try { versionCode = mContext.getPackageManager().getPackageInfo("com.facebook.katana", 0).versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (versionCode >= 3002850) { Uri uri = Uri.parse("fb://facewebmodal/f?href=" + "http://m.facebook.com/" + id); intent.setData(uri); } else { Uri uri = Uri.parse("fb://page/" + id); intent.setData(uri); } } else { intent.setData(Uri.parse("http://m.facebook.com/" + id)); } facebookElement.setIntent(intent); addItem(facebookElement); return this; } /* Add Twitter Element */ public AboutPage addTwitter(String id) { Element twitterElement = new Element(); twitterElement.setTitle(mContext.getString(R.string.about_twitter)); twitterElement.setIcon(R.drawable.about_icon_twitter); twitterElement.setColor(ContextCompat.getColor(mContext, R.color.about_twitter_color)); twitterElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); if (AboutPageUtils.isAppInstalled(mContext, "com.twitter.android")) { intent.setPackage("com.twitter.android"); intent.setData(Uri.parse(String.format("twitter://user?screen_name=%s", id))); } else { intent.setData(Uri.parse(String.format("http://twitter.com/intent/user?screen_name=%s", id))); } twitterElement.setIntent(intent); addItem(twitterElement); return this; } /* Add Play store Element */ public AboutPage addPlayStore(String id) { Element playStoreElement = new Element(); playStoreElement.setTitle(mContext.getString(R.string.about_play_store)); playStoreElement.setIcon(R.drawable.about_icon_google_play); playStoreElement.setColor(ContextCompat.getColor(mContext, R.color.about_play_store_color)); playStoreElement.setValue(id); Uri uri = Uri.parse("market://details?id=" + id); Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri); playStoreElement.setIntent(goToMarket); addItem(playStoreElement); return this; } /* Add Youtube Element */ public AboutPage addYoutube(String id) { Element youtubeElement = new Element(); youtubeElement.setTitle(mContext.getString(R.string.about_youtube)); youtubeElement.setIcon(R.drawable.about_icon_youtube); youtubeElement.setColor(ContextCompat.getColor(mContext, R.color.about_youtube_color)); youtubeElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse(String.format("http://youtube.com/channel/%s", id))); if (AboutPageUtils.isAppInstalled(mContext, "com.google.android.youtube")) { intent.setPackage("com.google.android.youtube"); } youtubeElement.setIntent(intent); addItem(youtubeElement); return this; } /* Add Instagram Element */ public AboutPage addInstagram(String id) { Element instagramElement = new Element(); instagramElement.setTitle(mContext.getString(R.string.about_instagram)); instagramElement.setIcon(R.drawable.about_icon_instagram); instagramElement.setColor(ContextCompat.getColor(mContext, R.color.about_instagram_color)); instagramElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://instagram.com/_u/" + id)); if (AboutPageUtils.isAppInstalled(mContext, "com.instagram.android")) { intent.setPackage("com.instagram.android"); } instagramElement.setIntent(intent); addItem(instagramElement); return this; } /* Add GitHub Element */ public AboutPage addGitHub(String id) { Element gitHubElement = new Element(); gitHubElement.setTitle(mContext.getString(R.string.about_github)); gitHubElement.setIcon(R.drawable.about_icon_github); gitHubElement.setColor(ContextCompat.getColor(mContext, R.color.about_github_color)); gitHubElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(String.format("https://github.com/%s", id))); gitHubElement.setIntent(intent); addItem(gitHubElement); return this; } /* Add Website Element */ public AboutPage addWebsite(String url) { if (!url.startsWith("http://") && !url.startsWith("https://")) { url = "http://" + url; } Element websiteElement = new Element(); websiteElement.setTitle(mContext.getString(R.string.about_website)); websiteElement.setIcon(R.drawable.about_icon_link); websiteElement.setColor(ContextCompat.getColor(mContext, R.color.about_item_icon_color)); websiteElement.setValue(url); Uri uri = Uri.parse(url); Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri); websiteElement.setIntent(browserIntent); addItem(websiteElement); return this; } public AboutPage addItem(Element element) { return this.addItem(element, true); } public AboutPage addItem(Element element, boolean isVertor) { LinearLayout wrapper = (LinearLayout) mView.findViewById(R.id.about_providers); wrapper.addView(createItem(element, isVertor)); wrapper.addView(getSeparator(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mContext.getResources().getDimensionPixelSize(R.dimen.about_separator_height))); return this; } public AboutPage setImage(int resource) { this.mImage = resource; return this; } public AboutPage addGroup(String name) { TextView textView = new TextView(mContext); textView.setText(name); TextViewCompat.setTextAppearance(textView, R.style.about_groupTextAppearance); LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); if (mCustomFont != null) { textView.setTypeface(mCustomFont); } int padding = mContext.getResources().getDimensionPixelSize(R.dimen.about_group_text_padding); textView.setPadding(padding, padding, padding, padding); if (mIsRTL) { textView.setGravity(Gravity.END | Gravity.CENTER_VERTICAL); textParams.gravity = Gravity.END | Gravity.CENTER_VERTICAL; } else { textView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); textParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL; } textView.setLayoutParams(textParams); ((LinearLayout) mView.findViewById(R.id.about_providers)).addView(textView); return this; } public AboutPage isRTL(boolean value) { this.mIsRTL = value; return this; } public AboutPage setDescription(String description) { this.mDescription = description; return this; } public View create() { TextView description = (TextView) mView.findViewById(R.id.description); ImageView image = (ImageView) mView.findViewById(R.id.image); if (mImage > 0) { image.setImageResource(mImage); } if (!TextUtils.isEmpty(mDescription)) { description.setText(mDescription); } description.setGravity(Gravity.CENTER); if (mCustomFont != null) { description.setTypeface(mCustomFont); } return mView; } private View createItem(final Element element) { return this.createItem(element, true); } private View createItem(final Element element, boolean isVector) { LinearLayout wrapper = new LinearLayout(mContext); wrapper.setOrientation(LinearLayout.HORIZONTAL); wrapper.setClickable(true); if (element.getOnClickListener() != null) { wrapper.setOnClickListener(element.getOnClickListener()); } else if (element.getIntent() != null) { wrapper.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { mContext.startActivity(element.getIntent()); } catch (Exception e) { } } }); } TypedValue outValue = new TypedValue(); mContext.getTheme().resolveAttribute(R.attr.selectableItemBackground, outValue, true); wrapper.setBackgroundResource(outValue.resourceId); int padding = mContext.getResources().getDimensionPixelSize(R.dimen.about_text_padding); wrapper.setPadding(padding, padding, padding, padding); LinearLayout.LayoutParams wrapperParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); wrapper.setLayoutParams(wrapperParams); TextView textView = new TextView(mContext); TextViewCompat.setTextAppearance(textView, R.style.about_elementTextAppearance); LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); textView.setLayoutParams(textParams); if (mCustomFont != null) { textView.setTypeface(mCustomFont); } ImageView iconView = null; if (element.getIcon() != null) { iconView = new ImageView(mContext); int size = mContext.getResources().getDimensionPixelSize(R.dimen.about_icon_size); LinearLayout.LayoutParams iconParams = new LinearLayout.LayoutParams(size, size); iconView.setLayoutParams(iconParams); int iconPadding = mContext.getResources().getDimensionPixelSize(R.dimen.about_icon_padding); iconView.setPadding(iconPadding, 0, iconPadding, 0); if (Build.VERSION.SDK_INT < 21) { if (isVector) { Drawable drawable = VectorDrawableCompat.create(iconView.getResources(), element.getIcon(), iconView.getContext().getTheme()); iconView.setImageDrawable(drawable); } else { iconView.setImageResource(element.getIcon()); } } else { iconView.setImageResource(element.getIcon()); } if (isVector) { Drawable wrappedDrawable = DrawableCompat.wrap(iconView.getDrawable()); wrappedDrawable = wrappedDrawable.mutate(); if (element.getAutoIconColor()) { if (element.getColor() != null) { DrawableCompat.setTint(wrappedDrawable, element.getColor()); } else { DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(mContext, R.color.about_item_icon_color)); } } } } else { int iconPadding = mContext.getResources().getDimensionPixelSize(R.dimen.about_icon_padding); textView.setPadding(iconPadding, iconPadding, iconPadding, iconPadding); } textView.setText(element.getTitle()); if (mIsRTL) { final int gravity = element.getGravity() != null ? element.getGravity() : Gravity.END; wrapper.setGravity(gravity | Gravity.CENTER_VERTICAL); //noinspection ResourceType textParams.gravity = gravity | Gravity.CENTER_VERTICAL; wrapper.addView(textView); if (element.getIcon() != null) { wrapper.addView(iconView); } } else { final int gravity = element.getGravity() != null ? element.getGravity() : Gravity.START; wrapper.setGravity(gravity | Gravity.CENTER_VERTICAL); //noinspection ResourceType textParams.gravity = gravity | Gravity.CENTER_VERTICAL; if (element.getIcon() != null) { wrapper.addView(iconView); } wrapper.addView(textView); } return wrapper; } private View getSeparator() { return mInflater.inflate(R.layout.about_page_separator, null); } /** * for China App */ /** * Des : 关注我的知乎 * * @param id 知乎的username */ public AboutPage addZhihu(String id) { Element zhihuElement = new Element(); zhihuElement.setTitle(mContext.getString(R.string.about_zhihu)); zhihuElement.setIcon(R.drawable.ic_zhihu); zhihuElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(String.format("https://www.zhihu.com/people/%s", id))); if (AboutPageUtils.isAppInstalled(mContext, "com.zhihu.android")) { intent.setPackage("com.zhihu.android"); } zhihuElement.setIntent(intent); addItem(zhihuElement, false); return this; } /** * 在qq上与我交谈 * * @param id qq号码 */ public AboutPage addQQ(String id) { Element qqElement = new Element(); qqElement.setTitle(mContext.getString(R.string.about_qq)); qqElement.setIcon(R.drawable.ic_qq); qqElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(String.format("mqqwpa://im/chat?chat_type=wpa&uin=%s", id))); if (AboutPageUtils.isAppInstalled(mContext, "com.tencent.mobileqq")) { intent.setPackage("com.tencent.mobileqq"); } qqElement.setIntent(intent); addItem(qqElement, false); return this; } /** * 关注我的sina微博 * * @param id sina号 */ public AboutPage addSinaWeibo(String id) { Element qqElement = new Element(); qqElement.setTitle(mContext.getString(R.string.about_sina)); qqElement.setIcon(R.drawable.ic_sina_weibo); qqElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(String.format("http://weibo.cn/qr/userinfo?uid=%s", id))); if (AboutPageUtils.isAppInstalled(mContext, "com.sina.weibo")) { intent.setComponent(new ComponentName("com.sina.weibo", "com.sina.weibo.page.ProfileInfoActivity")); intent.setPackage("com.sina.weibo"); } qqElement.setIntent(intent); addItem(qqElement, false); return this; } /** * 在稀土掘金上关注我 * * 由于UserHomePageActivity的"android:exported"属性为false,也没有对应的scheme,所以暂不支持跳转.. (当前版本3.7.5) * * @param id userId */ public AboutPage addGoldXitu(String id) { Element qqElement = new Element(); qqElement.setTitle(mContext.getString(R.string.about_gold_xitu)); qqElement.setIcon(R.drawable.ic_gold_xitu); qqElement.setValue(id); Intent intent = new Intent(); //intent.setAction(Intent.ACTION_VIEW); //intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.putExtra("user_id", "57c92a3c67f3560057b03348"); intent.setData(Uri.parse(String.format("http://gold.xitu.io/user/%s", id))); if (AboutPageUtils.isAppInstalled(mContext, "com.daimajia.gold")) { intent.setComponent(new ComponentName("com.daimajia.gold", "com.daimajia.gold.ui.user.UserHomePageActivity")); intent.setPackage("com.daimajia.gold"); } qqElement.setIntent(intent); addItem(qqElement, false); return this; } /** * Des : 关注我的简书 * * @param id 简书ID */ public AboutPage addJianshu(String id) { Element zhihuElement = new Element(); zhihuElement.setTitle(mContext.getString(R.string.about_jianshu)); zhihuElement.setIcon(R.drawable.ic_jianshu); zhihuElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.putExtra("_id", id); if (AboutPageUtils.isAppInstalled(mContext, "com.jianshu.haruki")) { intent.setComponent(new ComponentName("com.jianshu.haruki", "com.baiji.jianshu.activity.UserCenterActivity")); intent.setPackage("com.jianshu.haruki"); } zhihuElement.setIntent(intent); addItem(zhihuElement, false); return this; } /** * Des : 关注我的豆瓣 * * @param id douban people ID */ public AboutPage addDouban(String id) { Element doubanElement = new Element(); doubanElement.setTitle(mContext.getString(R.string.about_douban)); doubanElement.setIcon(R.drawable.ic_douban); doubanElement.setValue(id); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(String.format("https://www.douban.com/people/%s", id))); if (AboutPageUtils.isAppInstalled(mContext, "com.douban.frodo")) { intent.setPackage("com.douban.frodo"); } doubanElement.setIntent(intent); addItem(doubanElement, false); return this; } /** * Des : 关注我的饭否 * * @param id fanfou ID */ public AboutPage addFanfou(String id) { Element fanfouElement = new Element(); fanfouElement.setTitle(mContext.getString(R.string.about_fanfou)); fanfouElement.setIcon(R.drawable.ic_minicat); fanfouElement.setValue(id); Intent intent = new Intent(); intent.putExtra("id", id); if (AboutPageUtils.isAppInstalled(mContext, "com.mcxiaoke.minicat2")) { intent.setComponent(new ComponentName("com.mcxiaoke.minicat2", "com.mcxiaoke.minicat.app.UIProfile")); intent.setPackage("com.mcxiaoke.minicat2"); } fanfouElement.setIntent(intent); addItem(fanfouElement, false); return this; } /** * Des : 在支付宝上赞助我 * * @param id alipay qrcode */ public AboutPage addAlipay(final String id) { Element fanfouElement = new Element(); fanfouElement.setTitle(mContext.getString(R.string.about_alipay)); fanfouElement.setIcon(R.drawable.ic_alipay); fanfouElement.setValue(id); try { String alipayIntentUri = "intent://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=https%3A%2F%2Fqr.alipay.com%2F{urlCode}%3F_s%3Dweb-other&_t=1472443966571#Intent;scheme=alipayqr;" + "package=com.eg.android.AlipayGphone;end"; Intent intent = Intent.parseUri((alipayIntentUri.replace("{urlCode}", id)), Intent.URI_INTENT_SCHEME); intent.putExtra("id", id); if (AboutPageUtils.isAppInstalled(mContext, "com.eg.android.AlipayGphone")) { intent.setPackage("com.eg.android.AlipayGphone"); } fanfouElement.setIntent(intent); addItem(fanfouElement, false); } catch (URISyntaxException e) { e.printStackTrace(); } return this; } } <file_sep>/README.md # Android About Page Support for China APP 一键创建关于页面,支持了国内主流应用的应用内跳转。 ## 功能介绍 - 点击跳转支付宝捐赠页面 - 点击直接与我qq聊天 - 点击关注知乎、新浪微博、豆瓣、简书、饭否 ## 导入姿势 ```java compile 'xyz.isunxu:about-page:1.0.0' ``` ## 代码示例 ```java View aboutPage = new AboutPage(this) .isRTL(false) .setImage(R.drawable.ic_cn_preview) .setDescription("在原有aboutpage基础上支持了中国主流应用,包括:支付宝、知乎、新浪微博、qq、饭否、简书、豆瓣。由于应用内部限制暂时不支持:微信、Acfun、Bilibili、掘金。") .addGroup("Support for China APP") .addAlipay("aex06786lptrb4cy1g54w15") .addQQ("393353762") .addZhihu("taken2016") .addSinaWeibo("1291760303") .addDouban("39114237") .addJianshu("d86f33ff1f72") .addFanfou("wangxing") .addGoldXitu("56eac9bdb0146000293a233b"); setContentView(aboutPage); ``` ## apk demo - [查看apkdemo](https://github.com/sunxu3074/android-about-page/blob/master/resources/demo.apk) ## 效果图 <img src="/resources/m1l_preview.png" width="50%" height="50%" alt="m1l预览图"/> ## 效果图gif (由于时间很长,gif很大,建议观看视频) - <img src="/resources/preview_video.gif" width="50%" height="50%" alt="m1l预览gif"/> - [优酷观看](http://v.youku.com/v_show/id_XMTgzOTkyMDQ2MA) - [Youtube观看](https://www.youtube.com/watch?v=vab9m76BfYY) ## 说明 (饭否是用了蘑菇饭作为默认应用) | 应用名称 | 版本名称 | | :------------- |-----:| | 支付宝 | 9.9.5| | 知乎 | 4.10.1 (443)| | 新浪微博 | 6.3.1| | QQ | 6.5.8.2910| | 饭否 | 1.5.5| | 简书 | 1.11.5 | | 豆瓣 | 4.7.0 (85) | ## 感谢 - [在线反编译](http://www.javadecompilers.com/) - [AlipayZeroSdk](https://github.com/fython/AlipayZeroSdk) - [TopActivity](https://github.com/109021017/android-TopActivity) - 反编译不易,望大家支持,欢迎支付宝赞赏我... - - - - - - - - - - #### 原工程Readme - - - - - - - - - - ## Android About Page Create an awesome About Page for your Android App in 2 minutes <img src="/resources/cover.png" width="80%" alt="Android About Page Cover"/> This library allows to generate beautiful About Pages with less effort, it's fully customizable and supports opening specific intent ```java View aboutPage = new AboutPage(this) .isRTL(false) .setImage(R.drawable.dummy_image) .addItem(versionElement) .addItem(adsElement) .addGroup("Connect with us") .addEmail("<EMAIL>") .addWebsite("http://medyo.github.io/") .addFacebook("the.medy") .addTwitter("medyo80") .addYoutube("UCdPQtdWIsg7_pi4mrRu46vA") .addPlayStore("com.ideashower.readitlater.pro") .addGitHub("medyo") .addInstagram("medyo80") .create(); ``` ## Setup Available on Jcenter, Maven and JitPack ```groovy compile 'com.github.medyo:android-about-page:1.1.1' ``` ## Usage ### 1. Add Description ```java setDescription(String) ``` ### 2. Add Image ```java setImage(Int) ``` ### 3. Add predefined Social network The library has already some predefined social networks like : * Facebook * Twitter * Instagram * Youtube * PlayStore ```java addFacebook(String PageID) addTwitter(String AccountID) addYoutube(String AccountID) addPlayStore(String PackageName) addInstagram(String AccountID) addGitHub(String AccountID) ``` ### 4. Add Custom Element For example `app version` : ```java Element versionElement = new Element(); versionElement.setTitle("Version 6.2"); addItem(versionElement) ``` ### 5. Available attributes for Element Class | Function | Description | | ------------- |:-------------:| -----:| | setTitle(String) | Set title of the element| | setColor(Int) | Set color of the element| | setIcon(Int) | Set icon of the element| | setValue(String) | Set Element value like Facebook ID| | setTag(String) | Set a unique tag value to the element| | setIntent(Intent) | Set an intent to be called on `onClickListener` | | setGravity(Gravity) | Set a Gravity for the element | | setOnClickListener(View.OnClickListener) | If `intent` isn't suitable for you need, implement your custom behaviour by overriding the click listener| ## Sample Project [medyo/android-about-page/app/](https://github.com/medyo/android-about-page/tree/master/app) ## Translations The library does supports the following languages : * English (default) * German (by [vanniktech](https://github.com/vanniktech)) * Italian (by [greenaddress](https://github.com/greenaddress)) * Croatian (by [skmlcd](https://github.com/skmlcd)) * Arabic (by [zecharyah](https://github.com/zecharyah)) * Slovenian (by [skmlcd](https://github.com/skmlcd)) * Ukrainian (by [NumezmaT](https://github.com/NumezmaT)) * Russian (by [NumezmaT](https://github.com/NumezmaT)) * Romanian (by [Vally79](https://github.com/Vally79)) * Portuguese Brazil (by [rbaprado](https://github.com/rbaprado)) * French (by [medyo](https://github.com/medyo)) * Simplified Chinese (by [whiskeyfei](https://github.com/whiskeyfei)) * Spanish (by [danramirez](https://github.com/danramirez)) * Japanese (by [chibatching](https://github.com/chibatching)) * Turkish (by [tekseker](https://github.com/tekseker)) * Catalan (by [unxavi](https://github.com/unxavi)) * Czech (by [semanticer](https://github.com/semanticer)) * Hungarian (by [jbarat](https://github.com/jbarat)) * Korean (by [Alfex4936](https://github.com/Alfex4936)) Please make a Pull request to add a new language. ## ProGuard Nothing to include ## License ~~~ The MIT License (MIT) Copyright (c) 2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ~~~
a754a96645f9bf1a6b276a7af5ddae07138e42fe
[ "Markdown", "Java" ]
2
Java
sunxu3074/android-about-page
43b7b8063d5ada993d68df5000c6607f0a55c6f2
e134368caf49001d08d7dc794bc8703cee76c13d
refs/heads/master
<file_sep># Codeigniter 4 CRUD API Simple CRUD REST API using Codeigniter 4 ## Tech Stack PHP 7, Codeigniter 4 ## Documentation Link https://web.postman.co/collections/13564534-13316c0f-eed9-4b5b-a821-8342ac73199b?version=latest&workspace=c3e5a167-45ea-4d30-98ce-d99d4262dbb5 <file_sep>-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Nov 22, 2020 at 11:34 AM -- Server version: 10.4.14-MariaDB -- PHP Version: 7.4.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `perpustakaan` -- -- -------------------------------------------------------- -- -- Table structure for table `pengunjung` -- CREATE TABLE `pengunjung` ( `id` bigint(20) NOT NULL, `nama` varchar(255) NOT NULL, `instansi` varchar(255) DEFAULT NULL, `alasan` varchar(255) DEFAULT NULL, `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `pengunjung` -- INSERT INTO `pengunjung` (`id`, `nama`, `instansi`, `alasan`, `timestamp`) VALUES (14, 'Tono', 'Universitas Indonesia', 'Belajar', '2020-11-20 08:32:44'), (15, 'Andi', 'ITB', 'Membaca', '2020-11-20 08:33:01'), (16, '<NAME>', 'Unpad', 'Membaca', '2020-11-20 08:34:26'); -- -- Indexes for dumped tables -- -- -- Indexes for table `pengunjung` -- ALTER TABLE `pengunjung` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `pengunjung` -- ALTER TABLE `pengunjung` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php namespace App\Controllers; use App\Models\PengunjungModel; use CodeIgniter\API\ResponseTrait; use CodeIgniter\RESTful\ResourceController; class Pengunjung extends ResourceController { use ResponseTrait; protected $model; public function __construct() { $this->model = new PengunjungModel(); } protected function formatResponse(int $status, $data = null, $error = null, string $message) { return [ 'status' => $status, 'data' => $data, 'error' => $error, 'message' => $message ]; } public function index() { $data = $this->model->findAll(); return $this->respond($this->formatResponse(200, $data, null, 'Mendapatkan semua data berhasil'), 200); } public function show($id = null) { $data = $this->model->find($id); if ($data) return $this->respond($this->formatResponse(200, $data, null, 'Data ditemukan'), 200); return $this->failNotFound('Data tidak ditemukan'); } public function create() { $data = [ 'nama' => $this->request->getPost('nama'), 'instansi' => $this->request->getPost('instansi'), 'alasan' => $this->request->getPost('alasan'), ]; if ($this->model->insert($data)) { return $this->respondCreated($this->formatResponse(201, null, null, 'Data berhasil ditambahkan')); } return $this->failServerError(); } public function update($id = null) { $input = $this->request->getRawInput(); $data = [ 'nama' => $input['nama'], 'instansi' => $input['instansi'], 'alasan' => $input['alasan'], ]; if ($this->model->update($id, $data)) return $this->respondUpdated($this->formatResponse(200, null, null, 'Data berhasil diperbarui')); return $this->failNotFound('Data tidak ditemukan'); } public function delete($id = null) { if ($this->model->find($id)) { $this->model->delete($id); return $this->respondDeleted($this->formatResponse(200, null, null, 'Data berhasil dihapus')); } return $this->failNotFound('Data tidak ditemukan'); } } <file_sep><?php namespace App\Models; use CodeIgniter\Model; class PengunjungModel extends Model { protected $table = 'pengunjung'; protected $primaryKey = 'id'; protected $allowedFields = ['nama', 'instansi', 'alasan', 'timestamp']; }
8f2cc8b950bdbbf3916b56a8751c128aa752a120
[ "Markdown", "SQL", "PHP" ]
4
Markdown
bagasadif/Codeigniter4-CRUD-API
a3ae56b3d234f3f94a2b4baeb9117c975f8cf48f
b7ab4352588a957d2aaf532b7ef89f1bcb306510
refs/heads/master
<repo_name>MarquisDeLafayette/Vietnamese<file_sep>/viet script.py from string import punctuation import codecs # Sorts words by alphabetical order with the count as a secondary key def sort_words(x, y): return cmp(x[1], y[1]) or cmp(y[0], x[0]) # Words to be listed Number = 50 words = {} # Parses file line by line, removing all punctuation, and splits each word words_gen = (word.strip(punctuation).lower() for line in codecs.open("dialogue.txt", encoding = 'utf-8') for word in line.split()) # Parses through each word in for word in words_gen: words[word] = words.get(word, 0) + 1 # Sorts the words top_words = sorted(words.iteritems(), cmp=sort_words, reverse=True)[:Number] # Prints out the top N words for word, frequency in top_words: print "%s: %d" % (word, frequency)
185f1078433f24a03efa5899235210f99296f525
[ "Python" ]
1
Python
MarquisDeLafayette/Vietnamese
af0f8cfbf2083149cf0d32326cebae9ac60a70ec
971db97724ae155dbfc847ecb5dc44ae079cb609
refs/heads/master
<file_sep>// info thông tin(Dữ liệu đã qua sử lí hiện thị lên ui cho user) // data dữ liệu(Là những thông tin được chuyển thành jSon , là dữ liệu backend đưa cho json) function nhanvienservices() { // Láy danh sách sản phẩm this.layds = function () { return axios({ method: 'get', url: 'https://6131805d7287b70017e64148.mockapi.io/QLND', }); } this.them = function(sp){ return axios({ method: 'post', url: 'https://6131805d7287b70017e64148.mockapi.io/QLND', data:sp }); } this.laynv = function (id) { return axios({ method: 'get', url: `https://6131805d7287b70017e64148.mockapi.io/QLND/${id}`, }); } this.capnhat = function(sp,id){ return axios({ method: 'put', url: `https://6131805d7287b70017e64148.mockapi.io/QLND/${id}`, data:sp }); } this.xoaNV = function(id){ return axios({ method: 'delete', url: `https://6131805d7287b70017e64148.mockapi.io/QLND/${id}`, }); } } <file_sep>function nhanvien(tk,hoten,mk,email,hinhanh,nguoidung,ngonngu,mota){ this.tk = tk; this.hoten = hoten; this.mk = mk; this.email = email; this.hinhanh = hinhanh; this.nguoidung = nguoidung; this.ngonngu = ngonngu; this.mota = mota; }
a290b7907b0ffc2f553e2da177ee5213f898c2dc
[ "JavaScript" ]
2
JavaScript
HaTuanThuyet/QLND
7cb5e3eb7fec58206ed25ed7eed79ac86622e064
6600b2faa8ef8c43ee740d3183f5182429eac219
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace AcademList.Models.DAOModels { public class DAOAcadList { private Entities entities = new Entities(); DAOPattern daopat = new DAOPattern(); public IEnumerable<AcadList> GetAllAcadList() { return entities.AcadList.Select(n => n); } public IEnumerable<AcadList> GetGroupAcadList(int id) { return entities.AcadList.Select(n => n) .Where(n => n.Pattern_Id == id); } public AcadList GetAcadList(int id) { return entities.AcadList.Where(n => n.Id == id).First(); } public bool AddAcadList(AcadList aclist) { try { entities.AcadList.Add(aclist); entities.SaveChanges(); } catch { return false; } return true; } public bool UpdateAcadList(AcadList aclist) { try { var Entity = entities.AcadList.FirstOrDefault(x => x.Id == aclist.Id); Entity.Counter = aclist.Counter; entities.SaveChanges(); } catch { return false; } return true; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AcademList.Models.DAOModels { public class DAOGroups { private Entities entities = new Entities(); //получение списка всех групп public IEnumerable<Groups> GetAllGroups() { return entities.Groups.Select(n => n); } //добавление новой группы public bool AddGroups(Groups groups) { try { entities.Groups.Add(groups); entities.SaveChanges(); } catch { return false; } return true; } //переименование группы public void UpdateGroups(Groups groups) { var Entity = entities.Groups.FirstOrDefault(x => x.Id == groups.Id); Entity.GroupName = groups.GroupName; entities.SaveChanges(); } //получение названия группы по идентификатору public Groups GetGroups(int id) { return entities.Groups.Where(n => n.Id == id).First(); } //удаление группы по идентификатору public void DeleteGroups(int id) { Groups gr = GetGroups(id); entities.Groups.Remove(gr); entities.SaveChanges(); } } }<file_sep>using AcademList.Models.DAOModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AcademList.Controllers.DAOControllers { public class DAOGroupsController : Controller { Entities entities = new Entities(); DAOGroups daogroup = new DAOGroups(); public ActionResult Index(int? page) { return View(daogroup.GetAllGroups()); } public ActionResult Details(int id) { return View(daogroup.GetGroups(id)); } public ActionResult Create() { return View("Create"); } [HttpPost] public ActionResult Create([Bind(Exclude = "Id")] Groups groups) { if (daogroup.AddGroups(groups)) return RedirectToAction("Index"); else { return View("Create"); } } public ActionResult Edit(int id) { return View(daogroup.GetGroups(id)); } [HttpPost] public ActionResult Edit(int id, Groups groups) { if ((id > 0) && (groups != null) && (ModelState.IsValid)) { daogroup.UpdateGroups(groups); return RedirectToAction("Index"); } else { return View("Edit"); } } public ActionResult Delete(int id) { return View("Delete", daogroup.GetGroups(id)); } [HttpPost] public ActionResult Delete(int id, FormCollection collection) { if (id > 0 && ModelState.IsValid) { daogroup.DeleteGroups(id); return RedirectToAction("Index"); } else return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AcademList.Models.DAOModels { public class DAOExam { private Entities entities = new Entities(); //получение списка всех оценок за экзамен public IEnumerable<Exam> GetAllExam() { return entities.Exam.Select(n => n); } //добавление новой оценки за экзамен public bool AddExam(Exam exam) { try { entities.Exam.Add(exam); entities.SaveChanges(); } catch { return false; } return true; } //измнение оценки за экзамен public void UpdateExam(Exam exam) { var Entity = entities.Exam.FirstOrDefault(x => x.Id == exam.Id); Entity.ExamValue = exam.ExamValue; entities.SaveChanges(); } //получение оценки за экзамен по идентификатору public Exam GetExam(int id) { return entities.Exam.Where(n => n.Id == id).First(); } //удаление оценки за экзамен по идентификатору public void DeleteExam(int id) { Exam ex = GetExam(id); entities.Exam.Remove(ex); entities.SaveChanges(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AcademList.Models.DAOModels { public class DAOSubject { private Entities entities = new Entities(); //получение списка всех предметов public IEnumerable<Subject> GetAllSubject() { return entities.Subject.Select(n => n); } //добавление нового предмета public bool AddSubject(Subject subject) { try { entities.Subject.Add(subject); entities.SaveChanges(); } catch { return false; } return true; } //переименование предмета public void UpdateSubject(Subject subject) { var Entity = entities.Subject.FirstOrDefault(x => x.Id == subject.Id); Entity.SubjectName = subject.SubjectName; entities.SaveChanges(); } //получение названия предмета по идентификатору public Subject GetSubject(int id) { return entities.Subject.Where(n => n.Id == id).First(); } //удаление предмета по идентификатору public void DeleteSubject(int id) { Subject sub = GetSubject(id); entities.Subject.Remove(sub); entities.SaveChanges(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AcademList.Models.DAOModels; namespace AcademList.Controllers.DAOControllers { public class DAOAspNetUserController : Controller { DAOAspNetUser daouser = new DAOAspNetUser(); public ActionResult Index() { return View(daouser.GetAllUsers()); } public ActionResult Details(int id) { return View(); } public ActionResult Edit(string id) { return View(daouser.GetUser(id)); } [HttpPost] public ActionResult Edit(string id, AspNetUsers anu) { if ((id != null) && (anu != null) && (ModelState.IsValid)) { daouser.UpdateUser(anu); return RedirectToAction("Index"); } else { return View("Edit"); } } public ActionResult Delete(string id) { return View("Delete", daouser.GetUser(id)); } [HttpPost] public ActionResult Delete(string id, FormCollection collection) { if (id != null && ModelState.IsValid) { daouser.DeleteUser(id); return RedirectToAction("Index"); } else return View(); } } }<file_sep>using AcademList.Models.DAOModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AcademList.Controllers.DAOControllers { public class DAOExamController : Controller { DAOExam daoex = new DAOExam(); public ActionResult Edit(int id) { return View(daoex.GetExam(id)); } [HttpPost] public ActionResult Edit(Exam ex) { int id = Convert.ToInt32(Request["id"]); if ((id > 0) && (ex != null) && (ModelState.IsValid)) { daoex.UpdateExam(ex); return RedirectToAction("ProffIndex", "DAOPattern"); } else { return View("Edit"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AcademList.Models.DAOModels { public class DAOLabs { private Entities entities = new Entities(); //получение списка всех оценок за лабораторные public IEnumerable<Labs> GetAllLabs() { return entities.Labs.Select(n => n); } //изменение информации оценок за лабораторные public bool UpdateLabs(Labs labs) { try { var Entity = entities.Labs.FirstOrDefault(x => x.Id == labs.Id); Entity.FirstLab = labs.FirstLab; Entity.SecondLab = labs.SecondLab; Entity.ThirdLab = labs.ThirdLab; Entity.FourthLab = labs.FourthLab; Entity.FifthLab = labs.FifthLab; entities.SaveChanges(); } catch { return false; } return true; } //получение оценок за лабораторные по идентификатору public Labs GetLabs(int id) { return entities.Labs.Where(n => n.Id == id).First(); } //удаление оценок за лабораторные по идентификатору public bool DeleteLabs(int id) { try { Labs lb = GetLabs(id); entities.Labs.Remove(lb); entities.SaveChanges(); } catch { return false; } return true; } } }<file_sep>using AcademList.Models.DAOModels; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AcademList.Controllers.DAOControllers { public class DAOPatternController : Controller { DAOPattern daopattern = new DAOPattern(); DAOAspNetUser daouser = new DAOAspNetUser(); DAOSubject daosub = new DAOSubject(); DAOGroups daogr = new DAOGroups(); // GET: DAOPattern public ActionResult Index() { return View(daopattern.GetAllPattern()); } public ActionResult ProffIndex() { string id = User.Identity.GetUserId(); return View(daopattern.GetUserPattern(id)); } public ActionResult Edit(int id) { return View(daopattern.GetPattern(id)); } [HttpPost] public ActionResult Edit(int id, Pattern pat) { if ((id > 0) && (pat != null) && (ModelState.IsValid)) { daopattern.UpdatePattern(pat); return RedirectToAction("ProffIndex"); } else { return View("Edit"); } } public ActionResult Create() { var user = daouser.GetAllUsers(); ViewData["Professor_Id"] = new SelectList(user, "Id", "Surname"); var sub = daosub.GetAllSubject(); ViewData["Subject_Id"] = new SelectList(sub, "Id", "SubjectName"); var group = daogr.GetAllGroups(); ViewData["Group_Id"] = new SelectList(group, "Id", "GroupName"); return View("Create"); } [HttpPost] public ActionResult Create([Bind(Exclude = "Id")] Pattern pat) { if (daopattern.AddPattern(pat)) return RedirectToAction("Index"); else { return View("Create"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AcademList.Models.DAOModels { public class DAORating { private Entities entities = new Entities(); //получение списка всех рейтингов public IEnumerable<Rating> GetAllRating() { return entities.Rating.Select(n => n); } //изменение информации о рейтингах public bool UpdateRating(Rating rating) { try { var Entity = entities.Rating.FirstOrDefault(x => x.Id == rating.Id); Entity.FirstRating = rating.FirstRating; Entity.SecondRating = rating.SecondRating; Entity.ThirdRating = rating.ThirdRating; entities.SaveChanges(); } catch { return false; } return true; } //получение оценок за рейтинги по идентификатору public Rating GetRating(int id) { return entities.Rating.Where(n => n.Id == id).First(); } //удаление оценок за рейтинги по идентификатору public bool DeleteRating(int id) { try { Rating rat = GetRating(id); entities.Rating.Remove(rat); entities.SaveChanges(); } catch { return false; } return true; } } }<file_sep>using AcademList.Models.DAOModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AcademList.Controllers.DAOControllers { public class DAORatingController : Controller { DAORating daorat = new DAORating(); public ActionResult Edit(int id) { return View(daorat.GetRating(id)); } [HttpPost] public ActionResult Edit(Rating r) { int id = Convert.ToInt32(Request["id"]); if ((id > 0) && (r != null) && (ModelState.IsValid)) { daorat.UpdateRating(r); return RedirectToAction("ProffIndex", "DAOPattern"); } else { return View("Edit"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AcademList.Models.DAOModels { public class DAOPattern { private Entities entities = new Entities(); public IEnumerable<Pattern> GetAllPattern() { return entities.Pattern.Select(n => n); } public Pattern GetPattern(int id) { return entities.Pattern.Where(n => n.Id == id).First(); } public IEnumerable<Pattern> GetUserPattern(string id) { return entities.Pattern.Where(n => n.Professor_Id == id); } public bool AddPattern(Pattern pattern) { try { entities.Pattern.Add(pattern); entities.SaveChanges(); } catch { return false; } return true; } public bool UpdatePattern(Pattern pattern) { try { var Entity = entities.Pattern.FirstOrDefault(x => x.Id == pattern.Id); Entity.Status = pattern.Status; entities.SaveChanges(); } catch { return false; } return true; } } }<file_sep>using AcademList.Models.DAOModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AcademList.Controllers.DAOControllers { public class DAOSubjectController : Controller { Entities entities = new Entities(); DAOSubject daosub = new DAOSubject(); public ActionResult Index(int? page) { return View(daosub.GetAllSubject()); } public ActionResult Details(int id) { return View(daosub.GetSubject(id)); } public ActionResult Create() { return View("Create"); } [HttpPost] public ActionResult Create([Bind(Exclude = "Id")] Subject subject) { if (daosub.AddSubject(subject)) return RedirectToAction("Index"); else { return View("Create"); } } public ActionResult Edit(int id) { return View(daosub.GetSubject(id)); } [HttpPost] public ActionResult Edit(int id, Subject subject) { if ((id > 0) && (subject != null) && (ModelState.IsValid)) { daosub.UpdateSubject(subject); return RedirectToAction("Index"); } else { return View("Edit"); } } public ActionResult Delete(int id) { return View("Delete", daosub.GetSubject(id)); } [HttpPost] public ActionResult Delete(int id, FormCollection collection) { if (id > 0 && ModelState.IsValid) { daosub.DeleteSubject(id); return RedirectToAction("Index"); } else return View(); } } }<file_sep>using AcademList.Models.DAOModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AcademList.Controllers.DAOControllers { public class DAOAcadListController : Controller { Entities entities = new Entities(); DAOAcadList daoacadlist = new DAOAcadList(); DAOPattern daopat = new DAOPattern(); DAOAspNetUser daouser = new DAOAspNetUser(); // GET: DAOAcadList public ActionResult Index() { return View(daoacadlist.GetAllAcadList()); } [HttpGet] public ActionResult AcadListIndex(int id) { return View(daoacadlist.GetGroupAcadList(id)); } [HttpPost] public ActionResult AcadListIndex() { int id = Convert.ToInt32(Request["id"]); return View(daoacadlist.GetGroupAcadList(id)); } public ActionResult Create() { var user = daouser.GetAllUsers(); ViewData["Student_Id"] = new SelectList(user, "Id", "Surname"); var pat = daopat.GetAllPattern(); ViewData["Pattern_Id"] = new SelectList(pat, "Id", "Number"); return View("Create"); } [HttpPost] public ActionResult Create([Bind(Exclude = "Id")] AcadList alist) { if (daoacadlist.AddAcadList(alist)) return RedirectToAction("Index", "DAOPattern"); else { return View("Create"); } } public ActionResult Edit(int id) { return View(daoacadlist.GetAcadList(id)); } [HttpPost] public ActionResult Edit(int id, AcadList al) { if ((id > 0) && (al != null) && (ModelState.IsValid)) { daoacadlist.UpdateAcadList(al); return RedirectToAction("ProffIndex", "DAOPattern"); } else { return View("Edit"); } } } }<file_sep>using AcademList.Models.DAOModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AcademList.Controllers.DAOControllers { public class DAOLabsController : Controller { DAOLabs daolabs = new DAOLabs(); public ActionResult Edit(int id) { return View(daolabs.GetLabs(id)); } [HttpPost] public ActionResult Edit( Labs l) { int id = Convert.ToInt32(Request["id"]); if ((id > 0) && (l != null) && (ModelState.IsValid)) { daolabs.UpdateLabs(l); return RedirectToAction("ProffIndex", "DAOPattern"); } else { return View("Edit"); } } } }
56c719b63d1f012e013490224aa676981580df87
[ "C#" ]
15
C#
sixsixsam/Kursa4TP
92a7f2b0a0b7698cb995cb9170059a24ae4b02fc
7f0b9d0062d17942e0b4722682e6cc2217b73880
refs/heads/master
<file_sep>package at.rovo.stemmer; /** * Represents any character in the range from a to z in an English alphabet. * <p> * Note that this class is abstract and is implemented by {@link Consonant} and {@link Vowel} class which correspond to * consonants and vowels in the alphabet depicted * <p> * Sequences of the same type (e.g. consonants) can be added together using the {@link #add(char)} method. * * @author <NAME> */ public abstract class Letter { protected String letter; /** * Initializes a new instance of a letter with the provided character as starting letter. * * @param letter * Character this letter should start with */ protected Letter(char letter) { this.letter = "" + letter; } /** * Returns all characters of this sequence. * * @return All characters of this sequence */ public String getLetter() { return this.letter; } /** * Adds a character to the letter-sequence. * * @param c * The character to add */ public void add(char c) { this.letter += c; } }
040edba3ed67f91fac450b0f6268462af31cb943
[ "Java" ]
1
Java
RovoMe/PorterStemmer
970da9bdb0c803aab5fffec33468f9b2bb223670
e0fed39c7e3a7a3f2af6d666553f05a2ee5fa3ba
refs/heads/master
<file_sep>#!/usr/bin/env python3 import serial from proto import leds_pb2 ser = serial.Serial('/dev/ttyUSB0', 115200) print(ser.name) while True: print("[R,G,B,O][0,1]") value = input("Cmd: ") if value == "q": print("Stopping") break if len(value) < 2: continue request = leds_pb2.LedStatus() if value[1] == '1': status = leds_pb2.LedStatus.Led.ON elif value[1] == '0': status = leds_pb2.LedStatus.Led.OFF else: status = leds_pb2.LedStatus.Led.NO_CHANGE if value[0] == 'R': request.LedRed = status if value[0] == 'O': request.LedOrange = status if value[0] == 'B': request.LedBlue = status if value[0] == 'G': request.LedGreen = status data = request.SerializeToString() ser.write(len(data).to_bytes(1, 'big')) ser.write(data) # Read length then data length = ser.read() length = int.from_bytes(length, 'big') data = ser.read(length) led_status = leds_pb2.LedStatus() led_status.ParseFromString(data) print(led_status) <file_sep># Stm32F4 protobuf over UART example - Stm32f4 microcontoller - Libopencm3 - Google protobuf - nanopb - Bazel ## Stm32f4 server ``` bazel run //f4_proto:flash --config=arm_config ``` ## Python client ``` bazel run //python_client:client ``` ## C++ client ``` bazel run //client:client ``` <file_sep>#ifndef _SERIAL_H #define _SERIAL_H int configure_serial(int device); int open_serial(const char * device_name); int read_message(int serial_port, char * data, int buffer_size); int send_message(int serial_port, const char * data, int buffer_size); #endif // _SERIAL_H <file_sep>#include <iostream> #include <cstring> #include <cerrno> #include <fcntl.h> #include <termios.h> #include <unistd.h> static void print_errno(const char * message) { std::cerr << "Error " << errno << " "<< message << ": " << std::strerror(errno) << std::endl; } int open_serial(const char * device_name) { int serial_port = 0; if ((serial_port = open(device_name, O_RDWR)) < 0) { print_errno("From opening tty"); exit(1); } return serial_port; } int configure_serial(int device) { struct termios tty; if (tcgetattr(device, &tty) != 0) { print_errno("From tcgetattr"); exit(1); } tty.c_cflag &= ~PARENB; // Disable parity tty.c_cflag &= ~CSTOPB; // Disable stop bits tty.c_cflag |= CS8; // 8bits/byte tty.c_cflag &= ~CRTSCTS; // Disbale flow control tty.c_cflag |= CREAD | CLOCAL; // ignore ctrl lines tty.c_lflag &= ~ICANON; // Disable text mode (don't wait for backspaces) tty.c_lflag &= ~ECHO; // Disable echo tty.c_lflag &= ~ECHOE; // Disable echo ensurance tty.c_lflag &= ~ECHONL; // Disable new-line echo tty.c_lflag &= ~ISIG; // Disable Signal interpretion tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off sw flow control tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); // Disable special handling on receive tty.c_oflag &= ~OPOST; // Disable special interpretion of out bytes tty.c_oflag &= ~ONLCR; // Disbale conversion of \n to \n\r tty.c_cc[VTIME] = 10; tty.c_cc[VMIN] = 0; cfsetispeed(&tty, B115200); cfsetospeed(&tty, B115200); if (tcsetattr(device, TCSANOW, &tty) != 0) { print_errno("from tcsetattr"); exit(1); } return 0; } int send_message(int serial_port, const char * data, int buffer_size) { int len = strnlen(data, buffer_size); write(serial_port, &len, 1); // Send length first write(serial_port, data, len); // Send data return 0; } int read_message(int serial_port, char * data, int buffer_size) { int len = 0; len = read(serial_port, data, buffer_size); data[len] = '\0'; return len; } <file_sep>#include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/gpio.h> #include <libopencm3/stm32/usart.h> #include "pb_encode.h" #include "pb_decode.h" #include "proto/leds.pb.h" const int pins[4] = {GPIO15, GPIO14, GPIO13, GPIO12}; void _error(void); static void clock_setup(void) { // Enable GPIO clock for LED & UART rcc_periph_clock_enable(RCC_GPIOD); rcc_periph_clock_enable(RCC_GPIOA); // Enable clock for UART2 rcc_periph_clock_enable(RCC_USART2); } static void gpio_setup(void) { // Setup GPIOD for leds gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO12); gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO13); gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO14); gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO15); // Setup GPIO for USART transmit gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2); gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO3); gpio_set_af(GPIOA, GPIO_AF7, GPIO2); gpio_set_af(GPIOA, GPIO_AF7, GPIO3); } static void usart_setup(void) { // Setup USART2 usart_set_baudrate(USART2, 115200); usart_set_databits(USART2, 8); usart_set_stopbits(USART2, USART_STOPBITS_1); usart_set_mode(USART2, USART_MODE_TX_RX); usart_set_parity(USART2, USART_PARITY_NONE); usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE); usart_enable(USART2); } static void uart_transmit(const uint8_t * data, int16_t len) { for (int16_t i = 0; i < len; i++) { usart_send_blocking(USART2, data[i]); } } static uint16_t uart_read_message(uint8_t * const data) { uint16_t length; // Read the length of the message length = usart_recv_blocking(USART2); for (uint16_t i = 0; i < length; i++) { data[i] = usart_recv_blocking(USART2); } return length; } int main(void) { clock_setup(); gpio_setup(); usart_setup(); uint16_t length; uint8_t buffer[15]; LedStatus led_status = {LedStatus_Led_OFF, LedStatus_Led_OFF, LedStatus_Led_OFF, LedStatus_Led_OFF}; LedStatus led_request = {}; LedStatus_Led * const request_leds[4] = {&led_request.LedBlue, &led_request.LedRed, &led_request.LedOrange, &led_request.LedGreen}; LedStatus_Led* const status_leds[4] = {&led_status.LedBlue, &led_status.LedRed, &led_status.LedOrange, &led_status.LedGreen}; while (1) { // Read message and decode protobuf length = uart_read_message(buffer); pb_istream_t istream = pb_istream_from_buffer(buffer, length); if (!pb_decode(&istream, LedStatus_fields, &led_request)) { _error(); } // Enable/disable leds as requested for (uint8_t i = 0; i < 4; i++) { switch(*request_leds[i]) { case LedStatus_Led_ON: gpio_set(GPIOD, pins[i]); *status_leds[i] = LedStatus_Led_ON; break; case LedStatus_Led_OFF: gpio_clear(GPIOD, pins[i]); *status_leds[i] = LedStatus_Led_OFF; break; default: break; } } // Encode ledstatus protobuf and send response over uart pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); if (!pb_encode(&stream, LedStatus_fields, &led_status)) { _error(); } // Send length + data usart_send_blocking(USART2, stream.bytes_written); uart_transmit(buffer, stream.bytes_written); } } void _error(void) { while (1) { // Flash red led gpio_toggle(GPIOD, GPIO14); for (int i=0; i<1000000; i++) { __asm__("nop"); } } } <file_sep>#include <iostream> #include <cstring> #include <sstream> #include <string> #include <unistd.h> #include "serial.h" #include "proto/leds.pb.h" int main() { char led; int status; char buffer[265]; int serial_port = 0; LedStatus_Led value; LedStatus led_status; // Open serial port serial_port = open_serial("/dev/ttyUSB0"); configure_serial(serial_port); std::cout << "[R,G,B,O][0,1]" << std::endl; while(true) { std::cout << "Cmd: "; std::cin >> led; if (led == 'q') { break; } std::cin >> status; switch (status) { case 0: value = LedStatus_Led_OFF; break; case 1: value = LedStatus_Led_ON; break; default: break; } switch (led) { case 'R': led_status.set_ledred(value); break; case 'G': led_status.set_ledgreen(value); break; case 'B': led_status.set_ledblue(value); break; case 'O': led_status.set_ledorange(value); break; } // Serialize protobuf and send over serial std::stringstream stream_buffer; stream_buffer.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); led_status.SerializeToOstream(&stream_buffer); stream_buffer << '\0'; send_message(serial_port, buffer, sizeof(buffer)); // Read response over serial int length = read_message(serial_port, buffer, sizeof(buffer)); // Decode protobuf std::stringstream input_buffer; input_buffer.rdbuf()->pubsetbuf(&buffer[1], length); led_status.ParseFromIstream(&input_buffer); std::cout << "Response: " << std::endl; std::cout << led_status.DebugString() << std::endl; } std::cout << "Stopping" << std::endl; close(serial_port); return 0; }
5b11301162477011dae82fd00f7e6bb349f794b7
[ "Markdown", "C", "Python", "C++" ]
6
Python
koson/Stm32f4-UART-protobuf
528aa17c376173bb0d09b96d466fceae2e5d8403
cc2fae86701acab84ab74858f9a1f4d4648bd018
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Scelta : MonoBehaviour { public GameObject pannello_mano; public GameObject pannello_spalla; public GameObject pannello_gamba; public GameObject pannello_piede; public GameObject pannello_collo; public void Mano() { pannello_spalla.SetActive(false); pannello_gamba.SetActive(false); pannello_piede.SetActive(false); pannello_collo.SetActive(false); if (pannello_mano!=null) pannello_mano.SetActive(true); } public void Spalla() { pannello_mano.SetActive(false); pannello_gamba.SetActive(false); pannello_piede.SetActive(false); pannello_collo.SetActive(false); if (pannello_spalla != null) pannello_spalla.SetActive(true); } public void Gamba() { pannello_spalla.SetActive(false); pannello_mano.SetActive(false); pannello_piede.SetActive(false); pannello_collo.SetActive(false); if (pannello_gamba != null) pannello_gamba.SetActive(true); } public void Piede() { pannello_spalla.SetActive(false); pannello_gamba.SetActive(false); pannello_mano.SetActive(false); pannello_collo.SetActive(false); if (pannello_piede != null) pannello_piede.SetActive(true); } public void Collo() { pannello_spalla.SetActive(false); pannello_gamba.SetActive(false); pannello_piede.SetActive(false); pannello_mano.SetActive(false); if (pannello_collo != null) pannello_collo.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MetricheEsSbagliato : MonoBehaviour { public int range; const float cosa = 20; const float cosa1 = 4; public List<Frame> arancione, biancoSbagliato; string pathArancione; string pathBianco; public int frameRate; int dimBoa, appoggio, percentuale; public float manoSx, manoDx, gomitoSx, gomitoDx, spallaSx, spallaDx; int frame_correnteArancione, frame_correnteBianco; bool attiva = false; public bool sogliaManoSx, sogliaManoDx, sogliaGomitoSx, sogliaGomitoDx, sogliaSpallaSx, sogliaSpallaDx; public float threshold; public Button play; public Button pausa; public Button framemin; public Text spallaR; public Text gomitoR; public Text polsoR; public Text spallaL; public Text gomitoL; public Text polsoL; public Text percentualeSvolto; public Text boolGomitoDx; public Text boolGomitoSx; public Text boolSpallaDx; public Text boolSpallaSx; public Text boolPolsoDx; public Text boolPolsoSx; public Slider soglia; public Text valoreSoglia; public Slider finestra; public Text valoreFinestra; void Start() { pathArancione = Application.dataPath + "/" + "ominoArancioneModello.json"; pathBianco = Application.dataPath + "/" + "ominoBiancoSbagliato.json"; arancione = new List<Frame>(); biancoSbagliato = new List<Frame>(); appoggio = 1; string contentArancione = System.IO.File.ReadAllText(pathArancione); string contentBianco = System.IO.File.ReadAllText(pathBianco); acquisisci_frame(contentArancione, ref arancione); acquisisci_frame(contentBianco, ref biancoSbagliato); dimBoa = arancione.Count / 10; frameRate = 1; threshold = 0.2f; range = 100; valoreSoglia.text = ((soglia.value) * cosa).ToString("F2") + " cm"; valoreFinestra.text = ((finestra.value) / 80).ToString("F1") + " sec"; } public void SistemaSoglia(float newthreshold) { threshold = newthreshold; } public void SistemaFinestra(float newRange) { range = Mathf.RoundToInt(newRange); } void Update() { valoreSoglia.text = ((soglia.value) * cosa).ToString("F2") + " cm"; valoreFinestra.text = ((finestra.value) / 80).ToString("F1") + " sec"; if (attiva == true) { if (frame_correnteArancione % frameRate == 0) { //Debug.Log("arancio " + frame_correnteArancione + " bianco " + frame_correnteBianco); manoSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione / frameRate].person_0.joint_4.x, arancione[frame_correnteArancione / frameRate].person_0.joint_4.y, arancione[frame_correnteArancione / frameRate].person_0.joint_4.z), new Vector3(biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_4.x, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_4.y, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_4.z)); manoDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione / frameRate].person_0.joint_7.x, arancione[frame_correnteArancione / frameRate].person_0.joint_7.y, arancione[frame_correnteArancione / frameRate].person_0.joint_7.z), new Vector3(biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_7.x, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_7.y, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_7.z)); gomitoSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione / frameRate].person_0.joint_3.x, arancione[frame_correnteArancione / frameRate].person_0.joint_3.y, arancione[frame_correnteArancione / frameRate].person_0.joint_3.z), new Vector3(biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_3.x, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_3.y, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_3.z)); gomitoDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione / frameRate].person_0.joint_6.x, arancione[frame_correnteArancione / frameRate].person_0.joint_6.y, arancione[frame_correnteArancione / frameRate].person_0.joint_6.z), new Vector3(biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_6.x, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_6.y, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_6.z)); spallaSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione / frameRate].person_0.joint_2.x, arancione[frame_correnteArancione / frameRate].person_0.joint_2.y, arancione[frame_correnteArancione / frameRate].person_0.joint_2.z), new Vector3(biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_2.x, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_2.y, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_2.z)); spallaDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione / frameRate].person_0.joint_5.x, arancione[frame_correnteArancione / frameRate].person_0.joint_5.y, arancione[frame_correnteArancione / frameRate].person_0.joint_5.z), new Vector3(biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_5.x, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_5.y, biancoSbagliato[frame_correnteBianco / frameRate].person_0.joint_5.z)); polsoL.text = (manoSx * cosa * cosa1).ToString("F2"); polsoR.text = (manoDx * cosa * cosa1).ToString("F2"); gomitoL.text = (gomitoSx * cosa * cosa1).ToString("F2"); gomitoR.text = (gomitoDx * cosa * cosa1).ToString("F2"); spallaL.text = (spallaSx * cosa * cosa1).ToString("F2"); spallaR.text = (spallaDx * cosa * cosa1).ToString("F2"); } if (frame_correnteBianco < biancoSbagliato.Count - 1) frame_correnteBianco++; if (frame_correnteArancione < arancione.Count - 1) frame_correnteArancione++; if (frame_correnteBianco == biancoSbagliato.Count - 1 && frame_correnteArancione == arancione.Count - 1) { ferma(); frame_correnteArancione = 0; frame_correnteBianco = 0; appoggio = 1; percentuale = 0; } if (manoSx < threshold/ cosa1) sogliaManoSx = true; else sogliaManoSx = false; if (manoDx < threshold / cosa1) sogliaManoDx = true; else sogliaManoDx = false; if (gomitoSx < threshold / cosa1) sogliaGomitoSx = true; else sogliaGomitoSx = false; if (gomitoDx < threshold / cosa1) sogliaGomitoDx = true; else sogliaGomitoDx = false; if (spallaSx < threshold / cosa1) sogliaSpallaSx = true; else sogliaSpallaSx = false; if (spallaDx < threshold / cosa1) sogliaSpallaDx = true; else sogliaSpallaDx = false; boolGomitoDx.text = sogliaGomitoSx.ToString(); boolGomitoSx.text = sogliaGomitoDx.ToString(); boolSpallaDx.text = sogliaSpallaSx.ToString(); boolSpallaSx.text = sogliaSpallaDx.ToString(); boolPolsoDx.text = sogliaManoSx.ToString(); boolPolsoSx.text = sogliaManoDx.ToString(); //manca la percentuale if (frame_correnteArancione == dimBoa * appoggio) { if (appoggio <= 0 || appoggio > 10) appoggio = 1; //Debug.Log("percentuale: " + 10 * appoggio + "%"); if (boa(dimBoa * appoggio) == true) percentuale += 10; //else Debug.Log("al frame " + dimBoa * appoggio + " non è stata rispettata la boa"); //Debug.Log("numero Boa: " + appoggio + " percentuale: " + percentuale + "%"); ++appoggio; percentualeSvolto.text = percentuale.ToString() + "%"; } } } bool boa(int nFrame) { int i = 0; if (nFrame <= range / 2)//siamo a inizio esercizio { for (int j = 0; j < range * 2 / 3; ++j) { if (calcola_distanza(new Vector3(arancione[nFrame].person_0.joint_4.x, arancione[nFrame].person_0.joint_4.y, arancione[nFrame].person_0.joint_4.z), new Vector3(biancoSbagliato[j].person_0.joint_4.x, biancoSbagliato[j].person_0.joint_4.y, biancoSbagliato[j].person_0.joint_4.z)) < threshold/ cosa1) { i += 1; } } } else if (nFrame > arancione.Count - range / 2 - 1 && nFrame + range / 2 < biancoSbagliato.Count - 1)//siamo a fine esercizio { for (int j = nFrame - range / 2; j < arancione.Count - 1; ++j) { if (calcola_distanza(new Vector3(arancione[nFrame].person_0.joint_4.x, arancione[nFrame].person_0.joint_4.y, arancione[nFrame].person_0.joint_4.z), new Vector3(biancoSbagliato[j].person_0.joint_4.x, biancoSbagliato[j].person_0.joint_4.y, biancoSbagliato[j].person_0.joint_4.z)) < threshold/ cosa1) { i += 1; } } } else if (nFrame > biancoSbagliato.Count - range / 2)//il tipo sta facendo l'es troppo velocemente { for (int j = nFrame - range / 2; j < biancoSbagliato.Count - 1; ++j) { if (calcola_distanza(new Vector3(arancione[nFrame].person_0.joint_4.x, arancione[nFrame].person_0.joint_4.y, arancione[nFrame].person_0.joint_4.z), new Vector3(biancoSbagliato[j].person_0.joint_4.x, biancoSbagliato[j].person_0.joint_4.y, biancoSbagliato[j].person_0.joint_4.z)) < threshold/ cosa1) { i += 1; } } } else if (nFrame > range / 2 || nFrame < arancione.Count - range / 2)//siamo nel vivo dell'esercizio { for (int j = nFrame - range / 2 + 1; j < nFrame + range / 2; ++j) { if (calcola_distanza(new Vector3(arancione[nFrame].person_0.joint_4.x, arancione[nFrame].person_0.joint_4.y, arancione[nFrame].person_0.joint_4.z), new Vector3(biancoSbagliato[j].person_0.joint_4.x, biancoSbagliato[j].person_0.joint_4.y, biancoSbagliato[j].person_0.joint_4.z)) < threshold/ cosa1) { i += 1; } } } if (i > 0) { return true; } else { return false; } } public void parti() { attiva = true; play.GetComponent<Button>().interactable = false; pausa.GetComponent<Button>().interactable = true; framemin.GetComponent<Button>().interactable = true; } public void ferma() { attiva = false; play.GetComponent<Button>().interactable = true; pausa.GetComponent<Button>().interactable = false; } public void framePlus() { attiva = false; play.GetComponent<Button>().interactable = true; pausa.GetComponent<Button>().interactable = false; framemin.GetComponent<Button>().interactable = true; if (frame_correnteArancione >= arancione.Count - 1) frame_correnteArancione = 0; if (frame_correnteBianco >= biancoSbagliato.Count - 1) frame_correnteBianco = 0; manoSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_4.x, arancione[frame_correnteArancione].person_0.joint_4.y, arancione[frame_correnteArancione].person_0.joint_4.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_4.x, biancoSbagliato[frame_correnteBianco].person_0.joint_4.y, biancoSbagliato[frame_correnteBianco].person_0.joint_4.z)); manoDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_7.x, arancione[frame_correnteArancione].person_0.joint_7.y, arancione[frame_correnteArancione].person_0.joint_7.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_7.x, biancoSbagliato[frame_correnteBianco].person_0.joint_7.y, biancoSbagliato[frame_correnteBianco].person_0.joint_7.z)); gomitoSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_3.x, arancione[frame_correnteArancione].person_0.joint_3.y, arancione[frame_correnteArancione].person_0.joint_3.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_3.x, biancoSbagliato[frame_correnteBianco].person_0.joint_3.y, biancoSbagliato[frame_correnteBianco].person_0.joint_3.z)); gomitoDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_6.x, arancione[frame_correnteArancione].person_0.joint_6.y, arancione[frame_correnteArancione].person_0.joint_6.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_6.x, biancoSbagliato[frame_correnteBianco].person_0.joint_6.y, biancoSbagliato[frame_correnteBianco].person_0.joint_6.z)); spallaSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_2.x, arancione[frame_correnteArancione].person_0.joint_2.y, arancione[frame_correnteArancione].person_0.joint_2.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_2.x, biancoSbagliato[frame_correnteBianco].person_0.joint_2.y, biancoSbagliato[frame_correnteBianco].person_0.joint_2.z)); spallaDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_5.x, arancione[frame_correnteArancione].person_0.joint_5.y, arancione[frame_correnteArancione].person_0.joint_5.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_5.x, biancoSbagliato[frame_correnteBianco].person_0.joint_5.y, biancoSbagliato[frame_correnteBianco].person_0.joint_5.z)); polsoL.text = (manoSx * cosa * cosa1).ToString("F2"); polsoR.text = (manoDx * cosa * cosa1).ToString("F2"); gomitoL.text = (gomitoSx * cosa * cosa1).ToString("F2"); gomitoR.text = (gomitoDx * cosa * cosa1).ToString("F2"); spallaL.text = (spallaSx * cosa * cosa1).ToString("F2"); spallaR.text = (spallaDx * cosa * cosa1).ToString("F2"); if (manoSx < threshold / cosa1) sogliaManoSx = true; else sogliaManoSx = false; if (manoDx < threshold / cosa1) sogliaManoDx = true; else sogliaManoDx = false; if (gomitoSx < threshold / cosa1) sogliaGomitoSx = true; else sogliaGomitoSx = false; if (gomitoDx < threshold / cosa1) sogliaGomitoDx = true; else sogliaGomitoDx = false; if (spallaSx < threshold / cosa1) sogliaSpallaSx = true; else sogliaSpallaSx = false; if (spallaDx < threshold / cosa1) sogliaSpallaDx = true; else sogliaSpallaDx = false; boolGomitoDx.text = sogliaGomitoSx.ToString(); boolGomitoSx.text = sogliaGomitoDx.ToString(); boolSpallaDx.text = sogliaSpallaSx.ToString(); boolSpallaSx.text = sogliaSpallaDx.ToString(); boolPolsoDx.text = sogliaManoSx.ToString(); boolPolsoSx.text = sogliaManoDx.ToString(); if (frame_correnteArancione == dimBoa * appoggio) { if (appoggio <= 0 || appoggio > 10) appoggio = 1; //Debug.Log("percentuale: " + 10 * appoggio + "%"); if (boa(dimBoa * appoggio) == true) percentuale += 10; else Debug.Log("al frame " + dimBoa * appoggio + " non è stata rispettata la boa"); //Debug.Log("numero Boa: " + appoggio + " percentuale: " + percentuale + "%"); ++appoggio; percentualeSvolto.text = percentuale.ToString() + "%"; } if (frame_correnteBianco < (biancoSbagliato.Count - 1)) frame_correnteBianco++; if (frame_correnteArancione < (arancione.Count - 1)) frame_correnteArancione++; if (frame_correnteBianco == biancoSbagliato.Count - 1 & frame_correnteArancione == arancione.Count - 1) { frame_correnteArancione++; frame_correnteBianco++; } valoreSoglia.text = ((soglia.value) * cosa).ToString("F2") + " cm"; valoreFinestra.text = ((finestra.value) / 80).ToString("F1") + " sec"; } public void frameMinus() { if (frame_correnteBianco == 0 & frame_correnteArancione == 0) { return; } attiva = false; play.GetComponent<Button>().interactable = true; pausa.GetComponent<Button>().interactable = false; //if (frame_correnteBianco == 0 & frame_correnteArancione == 0) { frame_correnteBianco = biancoSbagliato.Count; frame_correnteArancione = arancione.Count; } frame_correnteBianco--; frame_correnteArancione--; manoSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_4.x, arancione[frame_correnteArancione].person_0.joint_4.y, arancione[frame_correnteArancione].person_0.joint_4.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_4.x, biancoSbagliato[frame_correnteBianco].person_0.joint_4.y, biancoSbagliato[frame_correnteBianco].person_0.joint_4.z)); manoDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_7.x, arancione[frame_correnteArancione].person_0.joint_7.y, arancione[frame_correnteArancione].person_0.joint_7.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_7.x, biancoSbagliato[frame_correnteBianco].person_0.joint_7.y, biancoSbagliato[frame_correnteBianco].person_0.joint_7.z)); gomitoSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_3.x, arancione[frame_correnteArancione].person_0.joint_3.y, arancione[frame_correnteArancione].person_0.joint_3.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_3.x, biancoSbagliato[frame_correnteBianco].person_0.joint_3.y, biancoSbagliato[frame_correnteBianco].person_0.joint_3.z)); gomitoDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_6.x, arancione[frame_correnteArancione].person_0.joint_6.y, arancione[frame_correnteArancione].person_0.joint_6.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_6.x, biancoSbagliato[frame_correnteBianco].person_0.joint_6.y, biancoSbagliato[frame_correnteBianco].person_0.joint_6.z)); spallaSx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_2.x, arancione[frame_correnteArancione].person_0.joint_2.y, arancione[frame_correnteArancione].person_0.joint_2.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_2.x, biancoSbagliato[frame_correnteBianco].person_0.joint_2.y, biancoSbagliato[frame_correnteBianco].person_0.joint_2.z)); spallaDx = calcola_distanza(new Vector3(arancione[frame_correnteArancione].person_0.joint_5.x, arancione[frame_correnteArancione].person_0.joint_5.y, arancione[frame_correnteArancione].person_0.joint_5.z), new Vector3(biancoSbagliato[frame_correnteBianco].person_0.joint_5.x, biancoSbagliato[frame_correnteBianco].person_0.joint_5.y, biancoSbagliato[frame_correnteBianco].person_0.joint_5.z)); polsoL.text = (manoSx * cosa * cosa1).ToString("F2"); polsoR.text = (manoDx * cosa * cosa1).ToString("F2"); gomitoL.text = (gomitoSx * cosa * cosa1).ToString("F2"); gomitoR.text = (gomitoDx * cosa * cosa1).ToString("F2"); spallaL.text = (spallaSx * cosa * cosa1).ToString("F2"); spallaR.text = (spallaDx * cosa * cosa1).ToString("F2"); if (manoSx < threshold / cosa1) sogliaManoSx = true; else sogliaManoSx = false; if (manoDx < threshold / cosa1) sogliaManoDx = true; else sogliaManoDx = false; if (gomitoSx < threshold / cosa1) sogliaGomitoSx = true; else sogliaGomitoSx = false; if (gomitoDx < threshold / cosa1) sogliaGomitoDx = true; else sogliaGomitoDx = false; if (spallaSx < threshold / cosa1) sogliaSpallaSx = true; else sogliaSpallaSx = false; if (spallaDx < threshold / cosa1) sogliaSpallaDx = true; else sogliaSpallaDx = false; boolGomitoDx.text = sogliaGomitoSx.ToString(); boolGomitoSx.text = sogliaGomitoDx.ToString(); boolSpallaDx.text = sogliaSpallaSx.ToString(); boolSpallaSx.text = sogliaSpallaDx.ToString(); boolPolsoDx.text = sogliaManoSx.ToString(); boolPolsoSx.text = sogliaManoDx.ToString(); if (frame_correnteBianco > 0) frame_correnteBianco--; if (frame_correnteArancione > 0) frame_correnteArancione--; valoreSoglia.text = ((soglia.value) * cosa).ToString("F2") + " cm"; valoreFinestra.text = ((finestra.value) / 80).ToString("F1") + " sec"; } float calcola_distanza(Vector3 posArancione, Vector3 posBianco) { float distanza = 0; Vector3 delta_pos = new Vector3(posArancione.x - posBianco.x, posArancione.y - posBianco.y, posArancione.z - posBianco.z); distanza = Mathf.Sqrt(delta_pos.x * delta_pos.x + delta_pos.y * delta_pos.y + delta_pos.z * delta_pos.z); return distanza; } void acquisisci_frame(string contents, ref List<Frame> lista) { int i = 0; int pos = 0; int el = 0; do { int ini = contents.IndexOf("frame", pos); int dif = contents.IndexOf('"', ini) - ini; contents = contents.Remove(ini, dif); contents = contents.Insert(ini, "frame_primo"); FrameWrap wrapper = JsonUtility.FromJson<FrameWrap>(contents); lista.Add(wrapper.frame_primo); i++; el = contents.IndexOf("frame", ini + 100); contents = contents.Remove(contents.IndexOf('{', 0) + 1, el - (contents.IndexOf('{', 0) + 2)); } while (contents.IndexOf("frame", 100) > 0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Drop : MonoBehaviour { public GameObject mano; public GameObject spalla; public Dropdown drop_es; // Update is called once per frame void Update() { switch (drop_es.value) { case 0: mano.SetActive(false); spalla.SetActive(false); break; case 1: spalla.SetActive(false); mano.SetActive(true); break; case 2: mano.SetActive(false); spalla.SetActive(true); break; default: break; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class pall2new : MonoBehaviour { public GameObject another; int i = 0; List<Vector3> Posi; Vector3 movimento; public void Pos() { // return altro.vet1(); } // Start is called before the first frame update public void Start() { //Debug.Log("ciao"); } // Update is called once per frame void Update() { JsonFile altro = another.GetComponent<JsonFile>(); framerate fra = another.GetComponent<framerate>(); int rate = fra.frame_rate; Posi = altro.vet1(); //Debug.Log(Posi[1].x); //Posi = Pos(); int n = Posi.Count; if (i % rate == 0) { movimento = Posi[i / 100]; //Debug.Log("ciao"); transform.position = movimento; } i++; if (i > n * rate) { i = 0; } //Debug.Log(i); // Debug.Log(n); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.IO; public class SetText : MonoBehaviour { public InputField testo; public void CreateText() { string path = Application.dataPath + "/" + "note.txt"; if (!File.Exists(path)) { File.WriteAllText(path, System.DateTime.Today.Day.ToString() + "/"+ System.DateTime.Today.Month.ToString() + "/" + System.DateTime.Today.Year.ToString()+" "+ testo.text+'\n'); Debug.Log("Testo nuovo"); }else { string current = File.ReadAllText(path); File.WriteAllText(path, System.DateTime.Today.Day.ToString() + "/" + System.DateTime.Today.Month.ToString() + "/" + System.DateTime.Today.Year.ToString() + " "+ testo.text + '\n' + current); Debug.Log("Testo aggiunto"); } testo.Select(); testo.text = ""; } } <file_sep># progetto 4 ETI _ Gruppo ISA Repository Git contenente il necessario per eseguire questo software su sistema operativo Windows e a ricreare l'ambiente di sviluppo sui 3 sistemi operativi principali (macOS, linux e Windows). 1. ESECUZIONE (solo Windows): - scaricare la release in formato zip sul proprio computer - dopo averla decompressa spostarsi all'interno della cartella 'Modello-Progetto', dove si trova la cartella 'Eseguibile', entrando in quest'ultima e cliccando su 'Modello-Progetto.exe' partirà la demo - selezionare qualità media, i tempi di caricamento degli esercizi possono essere lunghi a seconda della macchina su cui si sta eseguendo il software - dalla schermata 'Home Page' si può clickare su 'Esercizio Braccio', si aprirà un secondo box in cui solo i primi due esercizi sono abilitati - il primo è l'ultimo esercizio svolto dal paziente dove mostra segni di miglioramento rispetto alla sessione della settimana precedente - è inoltre presente una cartella chiamata 'SCRIPTSforEVERYONE' dove è possibile visionare comodamente i principali scripts utilizzati dal programma 2. SOURCE CODE (macOS, linux e Windows): - scaricare il file zip dell'intero progetto e installare Unity per aprirlo - aprire Unity e importare la cartella decompressa contenente il progetto, quindi aprirlo <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class NewScript : MonoBehaviour { public void EsercizioGiusto() { SceneManager.LoadScene("EsercizioGiusto"); } public void EsercizioSbagliato() { SceneManager.LoadScene("EsercizioSbagliato"); } public void HomePage() { SceneManager.LoadScene("HomePage"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Persona { //public Joint joint_0; public Joint joint_1; public Joint joint_2; public Joint joint_3; public Joint joint_4; public Joint joint_5; public Joint joint_6; public Joint joint_7; public Joint joint_8; public Joint joint_9; public Joint joint_10; public Joint joint_11; public Joint joint_12; public Joint joint_13; //public Joint joint_14; //public Joint joint_15; public Joint joint_16; public Joint joint_17; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class JsonFile : MonoBehaviour { //int j = 0; string filename = "pallineData.json"; string path; string paths; string pathss; List<Frame> frames = new List<Frame>(); //string contents = System.IO.File.ReadAllText(Application.persistentDataPath + "/" + "esecuzione es1 irene con schiena storta.json"); //GameData gameData = new GameData(); Persona person_0 = new Persona(); Joint joint = new Joint(); List<Vector3> vettori1 = new List<Vector3>(); List<Vector3> vettori2 = new List<Vector3>(); List<Vector3> vettori3 = new List<Vector3>(); List<Vector3> vettori4 = new List<Vector3>(); List<Vector3> vettori5 = new List<Vector3>(); List<Vector3> vettori6 = new List<Vector3>(); List<Vector3> vettori7 = new List<Vector3>(); List<Vector3> vettori8 = new List<Vector3>(); List<Vector3> vettori9 = new List<Vector3>(); List<Vector3> vettori10 = new List<Vector3>(); List<Vector3> vettori11 = new List<Vector3>(); List<Vector3> vettori12 = new List<Vector3>(); List<Vector3> vettori13 = new List<Vector3>(); // List<Vector3> vettori14 = new List<Vector3>(); //List<Vector3> vettori15 = new List<Vector3>(); List<Vector3> vettori16 = new List<Vector3>(); List<Vector3> vettori17 = new List<Vector3>(); //Frame frame_0 = new Frame(); /*Frame frame_1 = new Frame(); Frame frame_2 = new Frame(); Frame frame_3 = new Frame(); Frame frame_4 = new Frame(); Frame frame_5 = new Frame(); Frame frame_6 = new Frame(); Frame frame_7 = new Frame(); Frame frame_8 = new Frame(); Frame frame_9 = new Frame(); Frame frame_10 = new Frame(); Frame frame_11 = new Frame(); Frame frame_12 = new Frame(); Frame frame_13 = new Frame(); Frame frame_14 = new Frame(); Frame frame_15 = new Frame(); Frame frame_16 = new Frame(); Frame frame_17 = new Frame(); Frame frame_18 = new Frame(); Frame frame_19 = new Frame(); Frame frame_20 = new Frame(); Frame frame_21 = new Frame(); Frame frame_22 = new Frame(); Frame frame_23 = new Frame(); Frame frame_24 = new Frame(); Frame frame_25 = new Frame();*/ //public Frame frame_7 { get; private set; } public void tornavettori() { //List<Frame> frames = altro.get_data(); int n_ele = frames.Count; //Debug.Log(n_ele); //GameObject line12 = new GameObject(); for (int k = 0; k<n_ele; k++) { //Vector3 a0 = new Vector3(frames[k].person_0.joint_0.x, frames[k].person_0.joint_0.y, frames[k].person_0.joint_0.z); Vector3 a1 = new Vector3(frames[k].person_0.joint_1.x, frames[k].person_0.joint_1.y, frames[k].person_0.joint_1.z); Vector3 a2 = new Vector3(frames[k].person_0.joint_2.x, frames[k].person_0.joint_2.y, frames[k].person_0.joint_2.z); Vector3 a3 = new Vector3(frames[k].person_0.joint_3.x, frames[k].person_0.joint_3.y, frames[k].person_0.joint_3.z); Vector3 a4 = new Vector3(frames[k].person_0.joint_4.x, frames[k].person_0.joint_4.y, frames[k].person_0.joint_4.z); Vector3 a5 = new Vector3(frames[k].person_0.joint_5.x, frames[k].person_0.joint_5.y, frames[k].person_0.joint_5.z); Vector3 a6 = new Vector3(frames[k].person_0.joint_6.x, frames[k].person_0.joint_6.y, frames[k].person_0.joint_6.z); Vector3 a7 = new Vector3(frames[k].person_0.joint_7.x, frames[k].person_0.joint_7.y, frames[k].person_0.joint_7.z); Vector3 a8 = new Vector3(frames[k].person_0.joint_8.x, frames[k].person_0.joint_8.y, frames[k].person_0.joint_8.z); Vector3 a9 = new Vector3(frames[k].person_0.joint_9.x, frames[k].person_0.joint_9.y, frames[k].person_0.joint_9.z); Vector3 a10 = new Vector3(frames[k].person_0.joint_10.x, frames[k].person_0.joint_10.y, frames[k].person_0.joint_10.z); Vector3 a11 = new Vector3(frames[k].person_0.joint_11.x, frames[k].person_0.joint_11.y, frames[k].person_0.joint_11.z); Vector3 a12 = new Vector3(frames[k].person_0.joint_12.x, frames[k].person_0.joint_12.y, frames[k].person_0.joint_12.z); Vector3 a13 = new Vector3(frames[k].person_0.joint_13.x, frames[k].person_0.joint_13.y, frames[k].person_0.joint_13.z); // Vector3 a14 = new Vector3(frames[k].person_0.joint_14.x, frames[k].person_0.joint_14.y, frames[k].person_0.joint_14.z); // Vector3 a15 = new Vector3(frames[k].person_0.joint_15.x, frames[k].person_0.joint_15.y, frames[k].person_0.joint_15.z); Vector3 a16 = new Vector3(frames[k].person_0.joint_16.x, frames[k].person_0.joint_16.y, frames[k].person_0.joint_16.z); Vector3 a17 = new Vector3(frames[k].person_0.joint_17.x, frames[k].person_0.joint_17.y, frames[k].person_0.joint_17.z); //vettori0.Add(a0); vettori1.Add(a1); vettori2.Add(a2); vettori3.Add(a3); vettori4.Add(a4); vettori5.Add(a5); vettori6.Add(a6); vettori7.Add(a7); vettori8.Add(a8); vettori9.Add(a9); vettori10.Add(a10); vettori11.Add(a11); vettori12.Add(a12); vettori13.Add(a13); //vettori14.Add(a14); //vettori15.Add(a15); vettori16.Add(a16); vettori17.Add(a17); } } public List<Frame> get_data() { return frames; } public List<Vector3> vet1() { tornavettori(); return vettori1; } public List<Vector3> vet2() { tornavettori(); return vettori2; } public List<Vector3> vet3() { tornavettori(); return vettori3; } public List<Vector3> vet4() { tornavettori(); return vettori4; } public List<Vector3> vet5() { tornavettori(); return vettori5; } public List<Vector3> vet6() { tornavettori(); return vettori6; } public List<Vector3> vet7() { tornavettori(); return vettori7; } public List<Vector3> vet8() { tornavettori(); return vettori8; } public List<Vector3> vet9() { tornavettori(); return vettori9; } public List<Vector3> vet10() { tornavettori(); return vettori10; } public List<Vector3> vet11() { tornavettori(); return vettori11; } public List<Vector3> vet12() { tornavettori(); return vettori12; } public List<Vector3> vet13() { tornavettori(); return vettori13; } public List<Vector3> vet16() { tornavettori(); return vettori16; } public List<Vector3> vet17() { tornavettori(); return vettori17; } ////////////////// Start is called before the first frame update void Start() { path = Application.dataPath + "/" + filename; paths = Application.dataPath + "/" + "provaseba.json"; pathss = Application.dataPath + "/" + "ominoArancioneModello.json"; //Debug.Log(paths); //CreateFile(); string contents = System.IO.File.ReadAllText(pathss); // contents=sostituisci_frame(contents); //ReadData(contents); acquisisci_frame(contents); } ////////////////// Update is called once per frame void Update() { /*GameObject sphere0 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere0.transform.position = new Vector3(frames[j].person_0.joint_0.x, frames[j].person_0.joint_0.y, frames[j].person_0.joint_0.z); GameObject sphere1 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere1.transform.position = new Vector3(frames[j].person_0.joint_1.x, frames[j].person_0.joint_1.y, frames[j].person_0.joint_1.z); */ /* GameObject sphere2 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere2.transform.position = new Vector3(frames[j].person_0.joint_2.x, frames[j].person_0.joint_2.y, frames[j].person_0.joint_2.z); GameObject sphere3 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere3.transform.position = new Vector3(frames[j].person_0.joint_3.x, frames[j].person_0.joint_3.y, frames[j].person_0.joint_3.z); GameObject sphere4 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere4.transform.position = new Vector3(frames[j].person_0.joint_3.x, frames[j].person_0.joint_3.y, frames[j].person_0.joint_3.z); GameObject sphere5 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere5.transform.position = new Vector3(frames[j].person_0.joint_5.x, frames[j].person_0.joint_5.y, frames[j].person_0.joint_5.z); GameObject sphere6 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere6.transform.position = new Vector3(frames[j].person_0.joint_6.x, frames[j].person_0.joint_6.y, frames[j].person_0.joint_6.z); GameObject sphere7 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere7.transform.position = new Vector3(frames[j].person_0.joint_7.x, frames[j].person_0.joint_7.y, frames[j].person_0.joint_7.z); GameObject sphere8 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere8.transform.position = new Vector3(frames[j].person_0.joint_8.x, frames[j].person_0.joint_8.y, frames[j].person_0.joint_8.z); GameObject sphere9 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere9.transform.position = new Vector3(frames[j].person_0.joint_9.x, frames[j].person_0.joint_9.y, frames[j].person_0.joint_9.z); GameObject sphere10 = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere10.transform.position = new Vector3(frames[j].person_0.joint_10.x, frames[j].person_0.joint_10.y, frames[j].person_0.joint_10.z); j++; */ /* if (Input.GetKeyDown(KeyCode.R)) { ReadData(); } */ } void CreateFile() { try { if (System.IO.File.Exists(path)) { Debug.Log("STATO OK : il file esiste e sembra leggibile."); } else { FrameWrap wrapper = new FrameWrap(); // wrapper.frame_0 = frame_0; //Debug.Log("Creating File..."); /*string contents = JsonUtility.ToJson(wrapper, true); System.IO.File.WriteAllText(path, contents);*/ string contents = JsonUtility.ToJson(wrapper,true); System.IO.File.WriteAllText(path,contents); Debug.Log("File creato"); } } catch (System.Exception ex) { Debug.Log(ex.Message); } //Debug.Log("Fuori dal try : STATO OK"); } /* void SaveData() { DataWrapper wrapper = new DataWrapper(); wrapper.gameData = gameData; Debug.Log("SaveData:"); Debug.Log(gameData.date + " @ " + gameData.time); string contents = JsonUtility.ToJson(wrapper, true); System.IO.File.WriteAllText(path, contents); } void ReadData() { if (System.IO.File.Exists(path)) { string contents = System.IO.File.ReadAllText(path); DataWrapper wrapper = JsonUtility.FromJson<DataWrapper>(contents); gameData = wrapper.gameData; Debug.Log("ReadData:"); Debug.Log(gameData.date + " @ " + gameData.time); } else { Debug.Log("unable to read data, file does not exist"); gameData = new GameData(); } } */ string sostituisci_frame(string contents) { int i = 0; int pos = 0; Debug.Log(contents); do { // Debug.Log(contents); int ini = contents.IndexOf("frame", pos); // Debug.Log(ini); int dif = contents.IndexOf('"', ini) - ini; // Debug.Log(dif); contents = contents.Remove(ini, dif); //Debug.Log(contents); //restituisce una stringa parte dalla posizione e per tot elementi //Debug.Log(i); contents = contents.Insert(ini, "frame_" + i ); i++; //Debug.Log(i); pos = ini + pos; //Debug.Log(contents); //Debug.Log(contents.IndexOf("frame", pos)); } while (contents.IndexOf("frame", pos)>0); // while (contents.IndexOf("frame", pos)+1 < contents.LastIndexOf("frame")); Debug.Log(contents); return contents; } void acquisisci_frame(string contents) { //var map = new Dictionary<int, Frame>(); //Frame [] array; int i = 0; int pos = 0; int el = 0; do { int ini = contents.IndexOf("frame", pos); int dif = contents.IndexOf('"', ini) - ini; // Debug.Log(dif); contents = contents.Remove(ini, dif); //Debug.Log(contents); //restituisce una stringa parte dalla posizione e per tot elementi //Debug.Log(i); contents = contents.Insert(ini, "frame_primo"); //Debug.Log(contents); //Debug.Log(i); FrameWrap wrapper = JsonUtility.FromJson<FrameWrap>(contents); //Debug.Log(wrapper.frame_primo.person_0.joint_1.x); frames.Add( wrapper.frame_primo); i++; //Debug.Log(wrapper.frame_primo.person_0.joint_0.x); el = contents.IndexOf("frame", ini+100); contents = contents.Remove(contents.IndexOf('{', 0)+1, el-(contents.IndexOf('{', 0)+2) ); //if (contents.IndexOf("frame", 100) > 0) { contents = contents.Remove(contents.IndexOf('{', 0) + 1, el - (contents.IndexOf('{', 0) + 2)); }//tolgo un frame ogni due perchè ho troppi frame //Debug.Log(contents); } while (contents.IndexOf("frame", 100)>0); } /* void ReadData(string contents) { //Debug.Log("Reading File..."); try { if (System.IO.File.Exists(pathss)) { Debug.Log("Reading Existing File"); //string contents = System.IO.File.ReadAllText(path); FrameWrap wrapper = JsonUtility.FromJson<FrameWrap>(contents); // frame_0 = wrapper.frame_0; frame_1 = wrapper.frame_1; frame_2 = wrapper.frame_2; frame_3 = wrapper.frame_3; frame_4 = wrapper.frame_4; frame_5 = wrapper.frame_5; frame_6 = wrapper.frame_6; frame_7 = wrapper.frame_7; frame_8 = wrapper.frame_8; frame_9 = wrapper.frame_9; frame_10 = wrapper.frame_10; frame_11 = wrapper.frame_11; frame_12 = wrapper.frame_12; frame_13 = wrapper.frame_13; frame_14 = wrapper.frame_14; frame_15 = wrapper.frame_15; frame_16 = wrapper.frame_16; frame_17 = wrapper.frame_17; frame_18 = wrapper.frame_18; frame_19 = wrapper.frame_19; frame_20 = wrapper.frame_20; frame_21 = wrapper.frame_21; frame_22 = wrapper.frame_22; frame_23 = wrapper.frame_23; frame_24 = wrapper.frame_24; frame_25 = wrapper.frame_25; Debug.Log( "x: " + frame_2.person_0.joint_0.x + ", y: " + frame_2.person_0.joint_0.y + ", z: " + frame_2.person_0.joint_0.z ); } else { Debug.Log("unable to read file : STATO BAD"); //frame_0 = new Frame(); } } catch (System.Exception ex) { Debug.Log(ex.Message); } } */ } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Jsonfilenew : MonoBehaviour { int q = 0; int numframe; Vector3 movimento1; Vector3 movimento2; Vector3 movimento3; Vector3 movimento4; Vector3 movimento5; Vector3 movimento6; Vector3 movimento7; Vector3 movimento8; Vector3 movimento9; Vector3 movimento10; Vector3 movimento11; Vector3 movimento12; Vector3 movimento13; Vector3 movimentotesta; public int frame_rate; public GameObject pallina1; public GameObject pallina2; public GameObject pallina3; public GameObject pallina4; public GameObject pallina5; public GameObject pallina6; public GameObject pallina7; public GameObject pallina8; public GameObject pallina9; public GameObject pallina10; public GameObject pallina11; public GameObject pallina12; public GameObject pallina13; public GameObject testa; public GameObject cilindro12; public GameObject cilindro23; public GameObject cilindro34; public GameObject cilindro51; public GameObject cilindro65; public GameObject cilindro67; public GameObject cilindro8_11; public GameObject cilindro1_8; public GameObject cilindro1_11; public GameObject cilindro9_8; public GameObject cilindro9_10; public GameObject cilindro11_12; public GameObject cilindro12_13; public Text manodx_; public Text manosx_; public Text gomitodx_; public Text gomitosx_; public Text spalladx_; public Text spallasx_; public bool manodx; public bool manosx; public bool gomitodx; public bool gomitosx; public bool spalladx; public bool spallasx; string pathss; public List<Frame> frames = new List<Frame>(); Persona person_0 = new Persona(); Joint joint = new Joint(); List<Vector3> vettori1 = new List<Vector3>(); List<Vector3> vettori2 = new List<Vector3>(); List<Vector3> vettori3 = new List<Vector3>(); List<Vector3> vettori4 = new List<Vector3>(); List<Vector3> vettori5 = new List<Vector3>(); List<Vector3> vettori6 = new List<Vector3>(); List<Vector3> vettori7 = new List<Vector3>(); List<Vector3> vettori8 = new List<Vector3>(); List<Vector3> vettori9 = new List<Vector3>(); List<Vector3> vettori10 = new List<Vector3>(); List<Vector3> vettori11 = new List<Vector3>(); List<Vector3> vettori12 = new List<Vector3>(); List<Vector3> vettori13 = new List<Vector3>(); List<Vector3> vettori16 = new List<Vector3>(); List<Vector3> vettori17 = new List<Vector3>(); public void tornavettori() { int n_ele = frames.Count; //Debug.Log("dim list jsonnew "+n_ele); for (int k = 0; k < n_ele; k++) { Vector3 a1 = new Vector3(frames[k].person_0.joint_1.x, frames[k].person_0.joint_1.y, frames[k].person_0.joint_1.z); Vector3 a2 = new Vector3(frames[k].person_0.joint_2.x, frames[k].person_0.joint_2.y, frames[k].person_0.joint_2.z); Vector3 a3 = new Vector3(frames[k].person_0.joint_3.x, frames[k].person_0.joint_3.y, frames[k].person_0.joint_3.z); Vector3 a4 = new Vector3(frames[k].person_0.joint_4.x, frames[k].person_0.joint_4.y, frames[k].person_0.joint_4.z); Vector3 a5 = new Vector3(frames[k].person_0.joint_5.x, frames[k].person_0.joint_5.y, frames[k].person_0.joint_5.z); Vector3 a6 = new Vector3(frames[k].person_0.joint_6.x, frames[k].person_0.joint_6.y, frames[k].person_0.joint_6.z); Vector3 a7 = new Vector3(frames[k].person_0.joint_7.x, frames[k].person_0.joint_7.y, frames[k].person_0.joint_7.z); Vector3 a8 = new Vector3(frames[k].person_0.joint_8.x, frames[k].person_0.joint_8.y, frames[k].person_0.joint_8.z); Vector3 a9 = new Vector3(frames[k].person_0.joint_9.x, frames[k].person_0.joint_9.y, frames[k].person_0.joint_9.z); Vector3 a10 = new Vector3(frames[k].person_0.joint_10.x, frames[k].person_0.joint_10.y, frames[k].person_0.joint_10.z); Vector3 a11 = new Vector3(frames[k].person_0.joint_11.x, frames[k].person_0.joint_11.y, frames[k].person_0.joint_11.z); Vector3 a12 = new Vector3(frames[k].person_0.joint_12.x, frames[k].person_0.joint_12.y, frames[k].person_0.joint_12.z); Vector3 a13 = new Vector3(frames[k].person_0.joint_13.x, frames[k].person_0.joint_13.y, frames[k].person_0.joint_13.z); Vector3 a16 = new Vector3(frames[k].person_0.joint_16.x, frames[k].person_0.joint_16.y, frames[k].person_0.joint_16.z); Vector3 a17 = new Vector3(frames[k].person_0.joint_17.x, frames[k].person_0.joint_17.y, frames[k].person_0.joint_17.z); vettori1.Add(a1); vettori2.Add(a2); vettori3.Add(a3); vettori4.Add(a4); vettori5.Add(a5); vettori6.Add(a6); vettori7.Add(a7); vettori8.Add(a8); vettori9.Add(a9); vettori10.Add(a10); vettori11.Add(a11); vettori12.Add(a12); vettori13.Add(a13); vettori16.Add(a16); vettori17.Add(a17); } numframe = vettori1.Count; } void Start() { pathss = Application.dataPath + "/" + "ominoArancioneModello.json"; string contents = System.IO.File.ReadAllText(pathss); acquisisci_frame(contents); tornavettori(); movimento1 = vettori1[0]; movimento2 = vettori2[0]; movimento3 = vettori3[0]; movimento4 = vettori4[0]; movimento5 = vettori5[0]; movimento6 = vettori6[0]; movimento7 = vettori7[0]; movimento8 = vettori8[0]; movimento9 = vettori9[0]; movimento10 = vettori10[0]; movimento11 = vettori11[0]; movimento12 = vettori12[0]; movimento13 = vettori13[0]; movimentotesta = ((vettori16[0] + vettori17[0]) / 2); testa.transform.position = movimentotesta; pallina1.transform.position = movimento1; pallina2.transform.position = movimento2; pallina3.transform.position = movimento3; pallina4.transform.position = movimento4; pallina5.transform.position = movimento5; pallina6.transform.position = movimento6; pallina7.transform.position = movimento7; pallina8.transform.position = movimento8; pallina9.transform.position = movimento9; pallina10.transform.position = movimento10; pallina11.transform.position = movimento11; pallina12.transform.position = movimento12; pallina13.transform.position = movimento13; } bool attiva = false; public Button play; public Button pausa; public Button framemin; public void Parti() { attiva = true; play.GetComponent<Button>().interactable = false; pausa.GetComponent<Button>().interactable = true; framemin.GetComponent<Button>().interactable = true; } public void Ferma() { attiva = false; play.GetComponent<Button>().interactable = true; pausa.GetComponent<Button>().interactable = false; } public void FramePlus() { attiva = false; play.GetComponent<Button>().interactable = true; pausa.GetComponent<Button>().interactable = false; framemin.GetComponent<Button>().interactable = true; if (q % frame_rate == 0) { movimento1 = vettori1[q / frame_rate]; movimento2 = vettori2[q / frame_rate]; movimento3 = vettori3[q / frame_rate]; movimento4 = vettori4[q / frame_rate]; movimento5 = vettori5[q / frame_rate]; movimento6 = vettori6[q / frame_rate]; movimento7 = vettori7[q / frame_rate]; movimento8 = vettori8[q / frame_rate]; movimento9 = vettori9[q / frame_rate]; movimento10 = vettori10[q / frame_rate]; movimento11 = vettori11[q / frame_rate]; movimento12 = vettori12[q / frame_rate]; movimento13 = vettori13[q / frame_rate]; movimentotesta = ((vettori16[q / frame_rate] + vettori17[q / frame_rate]) / 2); testa.transform.position = movimentotesta; pallina1.transform.position = movimento1; pallina2.transform.position = movimento2; pallina3.transform.position = movimento3; pallina4.transform.position = movimento4; pallina5.transform.position = movimento5; pallina6.transform.position = movimento6; pallina7.transform.position = movimento7; pallina8.transform.position = movimento8; pallina9.transform.position = movimento9; pallina10.transform.position = movimento10; pallina11.transform.position = movimento11; pallina12.transform.position = movimento12; pallina13.transform.position = movimento13; } q++; if (q > numframe * frame_rate) { q = 0; } } public void FrameMinus() { if (q == 0) { return; } attiva = false; play.GetComponent<Button>().interactable = true; pausa.GetComponent<Button>().interactable = false; if (q % frame_rate == 0) { movimento1 = vettori1[q / frame_rate]; movimento2 = vettori2[q / frame_rate]; movimento3 = vettori3[q / frame_rate]; movimento4 = vettori4[q / frame_rate]; movimento5 = vettori5[q / frame_rate]; movimento6 = vettori6[q / frame_rate]; movimento7 = vettori7[q / frame_rate]; movimento8 = vettori8[q / frame_rate]; movimento9 = vettori9[q / frame_rate]; movimento10 = vettori10[q / frame_rate]; movimento11 = vettori11[q / frame_rate]; movimento12 = vettori12[q / frame_rate]; movimento13 = vettori13[q / frame_rate]; movimentotesta = ((vettori16[q / frame_rate] + vettori17[q / frame_rate]) / 2); testa.transform.position = movimentotesta; pallina1.transform.position = movimento1; pallina2.transform.position = movimento2; pallina3.transform.position = movimento3; pallina4.transform.position = movimento4; pallina5.transform.position = movimento5; pallina6.transform.position = movimento6; pallina7.transform.position = movimento7; pallina8.transform.position = movimento8; pallina9.transform.position = movimento9; pallina10.transform.position = movimento10; pallina11.transform.position = movimento11; pallina12.transform.position = movimento12; pallina13.transform.position = movimento13; } q--; if (q > numframe * frame_rate) { q = 0; } } ////////////////// Update is called once per frame void Update() { if (manodx_.text == "True") { manodx = true; } else { manodx = false; } if (manosx_.text == "True") { manosx = true; } else { manosx = false; } if (gomitodx_.text == "True") { gomitodx = true; } else { gomitodx = false; } if (gomitosx_.text == "True") { gomitosx = true; } else { gomitosx = false; } if (spalladx_.text == "True") { spalladx = true; } else { spalladx = false; } if (spallasx_.text == "True") { spallasx = true; } else { spallasx = false; } if (attiva == true) { if (q % frame_rate == 0) { movimento1 = vettori1[q / frame_rate]; movimento2 = vettori2[q / frame_rate]; movimento3 = vettori3[q / frame_rate]; movimento4 = vettori4[q / frame_rate]; movimento5 = vettori5[q / frame_rate]; movimento6 = vettori6[q / frame_rate]; movimento7 = vettori7[q / frame_rate]; movimento8 = vettori8[q / frame_rate]; movimento9 = vettori9[q / frame_rate]; movimento10 = vettori10[q / frame_rate]; movimento11 = vettori11[q / frame_rate]; movimento12 = vettori12[q / frame_rate]; movimento13 = vettori13[q / frame_rate]; movimentotesta = ((vettori16[q / frame_rate] + vettori17[q / frame_rate]) / 2); testa.transform.position = movimentotesta; pallina1.transform.position = movimento1; pallina2.transform.position = movimento2; pallina3.transform.position = movimento3; pallina4.transform.position = movimento4; pallina5.transform.position = movimento5; pallina6.transform.position = movimento6; pallina7.transform.position = movimento7; pallina8.transform.position = movimento8; pallina9.transform.position = movimento9; pallina10.transform.position = movimento10; pallina11.transform.position = movimento11; pallina12.transform.position = movimento12; pallina13.transform.position = movimento13; } q++; if (q >= numframe * frame_rate) { Ferma(); q = 0; } } } void cspalla12() { if(spalladx) { pallina1.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); pallina2.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); cilindro12.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); } else { pallina1.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); pallina2.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); cilindro12.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); } } void cspalla15() { if(spallasx) { pallina1.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); pallina5.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); cilindro51.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); } else { pallina1.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); pallina5.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); cilindro51.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); } } void cgom23() { if(gomitodx) { pallina3.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); pallina2.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); cilindro23.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); } else { pallina3.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); pallina2.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); cilindro23.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); } } void cgom56() { if(gomitosx) { pallina5.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); pallina6.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); cilindro65.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); } else { pallina5.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); pallina6.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); cilindro65.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); } } void cman67() { if(manosx) { pallina6.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); pallina7.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); cilindro67.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); } else { pallina6.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); pallina7.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); cilindro67.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); } } void cman34() { if(manodx) { pallina3.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); pallina4.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); cilindro34.GetComponent<Renderer>().material.color = new Color(0, 1, 0, 1); } else { pallina3.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); pallina4.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); cilindro34.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1); } } string sostituisci_frame(string contents) { int i = 0; int pos = 0; do { int ini = contents.IndexOf("frame", pos); int dif = contents.IndexOf('"', ini) - ini; contents = contents.Remove(ini, dif); contents = contents.Insert(ini, "frame_" + i); i++; pos = ini + pos; } while (contents.IndexOf("frame", pos) > 0); return contents; } void acquisisci_frame(string contents) { int i = 0; int pos = 0; int el = 0; do { int ini = contents.IndexOf("frame", pos); int dif = contents.IndexOf('"', ini) - ini; contents = contents.Remove(ini, dif); contents = contents.Insert(ini, "frame_primo"); FrameWrap wrapper = JsonUtility.FromJson<FrameWrap>(contents); frames.Add(wrapper.frame_primo); i++; el = contents.IndexOf("frame", ini + 100); contents = contents.Remove(contents.IndexOf('{', 0) + 1, el - (contents.IndexOf('{', 0) + 2)); } while (contents.IndexOf("frame", 100) > 0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class cil1 : MonoBehaviour { public GameObject a; public GameObject b; Vector3 start, end; Vector3 var; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { //posizionamento start = a.transform.position; end = b.transform.position; transform.position = (end - start) / 2 + start; //scala var = transform.localScale; var.x=0.1f; var.z = (float)0.1; var.y = (end - start).magnitude / 2; /*var.x *= ((float)0.1); var.y *= ((float)0.1); var.z *= ((float)0.1);*/ transform.localScale = var; //rotazione transform.rotation = Quaternion.FromToRotation(Vector3.up, end - start); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Joint { public float x; public float y; public float z; public Joint() { } public Joint(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Frame { public Persona person_0; } <file_sep>internal class textAss { }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Creazione : MonoBehaviour { public GameObject punto = null; //List<Vector3> vettori0 = new List<Vector3>(); List<Vector3> vettori1 = new List<Vector3>(); List<Vector3> vettori2 = new List<Vector3>(); List<Vector3> vettori3 = new List<Vector3>(); List<Vector3> vettori4 = new List<Vector3>(); List<Vector3> vettori5 = new List<Vector3>(); List<Vector3> vettori6 = new List<Vector3>(); List<Vector3> vettori7 = new List<Vector3>(); List<Vector3> vettori8 = new List<Vector3>(); List<Vector3> vettori9 = new List<Vector3>(); List<Vector3> vettori10 = new List<Vector3>(); List<Vector3> vettori11 = new List<Vector3>(); List<Vector3> vettori12= new List<Vector3>(); List<Vector3> vettori13 = new List<Vector3>(); // List<Vector3> vettori14 = new List<Vector3>(); //List<Vector3> vettori15 = new List<Vector3>(); List<Vector3> vettori16 = new List<Vector3>(); List<Vector3> vettori17 = new List<Vector3>(); int frame = 0; //GameObject punto0 = null; GameObject punto1 = null; GameObject punto2 = null; GameObject punto3 = null; GameObject punto4 = null; GameObject punto5 = null; GameObject punto6 = null; GameObject punto7 = null; GameObject punto8 = null; GameObject punto9 = null; GameObject punto10 = null; GameObject punto11 = null; GameObject punto12 = null; GameObject punto13 = null; //GameObject punto14 = null; //GameObject punto15 = null; GameObject punto16 = null; GameObject punto17 = null; // Start is called before the first frame update void Start() { /* Quaternion b = new Quaternion(0, 0, 0, 0); Vector3 d = new Vector3(0, 0, 0); punto1 = GameObject.Instantiate(punto, d, b);*/ } // Update is called once per frame void Update() { JsonFile altro = GetComponent<JsonFile>(); List<Frame> lista = altro.get_data(); int n_ele = lista.Count; //Debug.Log(n_ele); GameObject line12 = new GameObject(); for (int k = 0; k < n_ele; k++) { //Vector3 a0 = new Vector3(lista[k].person_0.joint_0.x, lista[k].person_0.joint_0.y, lista[k].person_0.joint_0.z); Vector3 a1 = new Vector3(lista[k].person_0.joint_1.x, lista[k].person_0.joint_1.y, lista[k].person_0.joint_1.z); Vector3 a2 = new Vector3(lista[k].person_0.joint_2.x, lista[k].person_0.joint_2.y, lista[k].person_0.joint_2.z); Vector3 a3 = new Vector3(lista[k].person_0.joint_3.x, lista[k].person_0.joint_3.y, lista[k].person_0.joint_3.z); Vector3 a4 = new Vector3(lista[k].person_0.joint_4.x, lista[k].person_0.joint_4.y, lista[k].person_0.joint_4.z); Vector3 a5 = new Vector3(lista[k].person_0.joint_5.x, lista[k].person_0.joint_5.y, lista[k].person_0.joint_5.z); Vector3 a6 = new Vector3(lista[k].person_0.joint_6.x, lista[k].person_0.joint_6.y, lista[k].person_0.joint_6.z); Vector3 a7 = new Vector3(lista[k].person_0.joint_7.x, lista[k].person_0.joint_7.y, lista[k].person_0.joint_7.z); Vector3 a8 = new Vector3(lista[k].person_0.joint_8.x, lista[k].person_0.joint_8.y, lista[k].person_0.joint_8.z); Vector3 a9 = new Vector3(lista[k].person_0.joint_9.x, lista[k].person_0.joint_9.y, lista[k].person_0.joint_9.z); Vector3 a10 = new Vector3(lista[k].person_0.joint_10.x, lista[k].person_0.joint_10.y, lista[k].person_0.joint_10.z); Vector3 a11= new Vector3(lista[k].person_0.joint_11.x, lista[k].person_0.joint_11.y, lista[k].person_0.joint_11.z); Vector3 a12 = new Vector3(lista[k].person_0.joint_12.x, lista[k].person_0.joint_12.y, lista[k].person_0.joint_12.z); Vector3 a13 = new Vector3(lista[k].person_0.joint_13.x, lista[k].person_0.joint_13.y, lista[k].person_0.joint_13.z); // Vector3 a14 = new Vector3(lista[k].person_0.joint_14.x, lista[k].person_0.joint_14.y, lista[k].person_0.joint_14.z); // Vector3 a15 = new Vector3(lista[k].person_0.joint_15.x, lista[k].person_0.joint_15.y, lista[k].person_0.joint_15.z); Vector3 a16 = new Vector3(lista[k].person_0.joint_16.x, lista[k].person_0.joint_16.y, lista[k].person_0.joint_16.z); Vector3 a17 = new Vector3(lista[k].person_0.joint_17.x, lista[k].person_0.joint_17.y, lista[k].person_0.joint_17.z); //vettori0.Add(a0); vettori1.Add(a1); vettori2.Add(a2); vettori3.Add(a3); vettori4.Add(a4); vettori5.Add(a5); vettori6.Add(a6); vettori7.Add(a7); vettori8.Add(a8); vettori9.Add(a9); vettori10.Add(a10); vettori11.Add(a11); vettori12.Add(a12); vettori13.Add(a13); //vettori14.Add(a14); //vettori15.Add(a15); vettori16.Add(a16); vettori17.Add(a17); } Quaternion b = new Quaternion(0, 0, 0, 0); if(frame == 0) {/* punto0 = GameObject.Instantiate(punto, vettori0[0], b); punto1 = GameObject.Instantiate(punto, vettori1[0], b); punto2 = GameObject.Instantiate(punto, vettori2[0], b); punto3 = GameObject.Instantiate(punto, vettori3[0], b); punto4 = GameObject.Instantiate(punto, vettori4[0], b); punto5 = GameObject.Instantiate(punto, vettori5[0], b); punto6 = GameObject.Instantiate(punto, vettori6[0], b); */ } if (frame % 99 == 0) { // Destroy(punto0); Destroy(punto1); Destroy(line12); Destroy(punto2); Destroy(punto3); Destroy(punto4); Destroy(punto5); Destroy(punto6); Destroy(punto7); Destroy(punto8); Destroy(punto9); Destroy(punto10); Destroy(punto11); Destroy(punto12); Destroy(punto13); //Destroy(punto14); //Destroy(punto15); Destroy(punto16); Destroy(punto17); } if (frame % 100 == 0) {/* punto0.transform.Translate(vettori0[frame / 100], Space.World); punto1.transform.Translate(vettori1[frame / 100], Space.World); punto2.transform.Translate(vettori2[frame / 100], Space.World); punto3.transform.Translate(vettori3[frame / 100], Space.World); punto4.transform.Translate(vettori4[frame / 100], Space.World); punto5.transform.Translate(vettori5[frame / 100], Space.World); punto6.transform.Translate(vettori6[frame / 100], Space.World); */ // punto0 = GameObject.Instantiate(punto, vettori0[frame / 100],b); punto1 = GameObject.Instantiate(punto, vettori1[frame / 100],b); line12.transform.position = vettori1[frame / 100]; line12.AddComponent<LineRenderer>(); LineRenderer lr = line12.GetComponent<LineRenderer>(); lr.SetPosition(0, vettori1[frame / 100]); lr.SetPosition(1, vettori2[frame / 100]); punto2 = GameObject.Instantiate(punto, vettori2[frame / 100], b); punto3 = GameObject.Instantiate(punto, vettori3[frame / 100], b); punto4 = GameObject.Instantiate(punto, vettori4[frame / 100], b); punto5 = GameObject.Instantiate(punto, vettori5[frame / 100], b); punto6 = GameObject.Instantiate(punto, vettori6[frame / 100], b); punto7 = GameObject.Instantiate(punto, vettori7[frame / 100], b); punto8 = GameObject.Instantiate(punto, vettori8[frame / 100], b); punto9 = GameObject.Instantiate(punto, vettori9[frame / 100], b); punto10 = GameObject.Instantiate(punto, vettori10[frame / 100], b); punto11 = GameObject.Instantiate(punto, vettori11[frame / 100], b); punto12 = GameObject.Instantiate(punto, vettori12[frame / 100], b); punto13 = GameObject.Instantiate(punto, vettori13[frame / 100], b); //punto14 = GameObject.Instantiate(punto, vettori14[frame / 100], b); // punto15 = GameObject.Instantiate(punto, vettori15[frame / 100], b); punto16 = GameObject.Instantiate(punto, vettori16[frame / 100], b); punto17 = GameObject.Instantiate(punto, vettori17[frame / 100], b); } // Debug.Log(frame); frame++; if(frame > n_ele * 100) { frame -= (n_ele * 100); } } }
2804f0c35ccdb32d1787b2d443e90e32a5074c04
[ "Markdown", "C#" ]
15
C#
irebuf/progettoETI_4
e292a95cfeb812b591cd05fd6a29f27c4728e5a1
a69c8a059d83500ee9b41ea46657e59c8aaa6fe4
refs/heads/master
<file_sep>function activate() { demo(); } function demo(data) { console.log('some demo here', data); }<file_sep># CloudStore Extensions CloudStore Extensions is a powerful instrument which enables you to synchronize external systems with CloudStore Enterprise environment. Your extension can receive external requests or you can send requests to external systems. ## Quick start ## Manifest launcher, scheduler, listener, installer #### externally_connectable The externally_connectable manifest property declares which external sources can request extension's listeners.<file_sep>function install(context) { }
ad237219d0a8e83b26667b65325b8f0e988f6a4f
[ "JavaScript", "Markdown" ]
3
JavaScript
cloudstore-enterprise/sample-extension
40137b48bf2086d7f819bacfd0583de14964ee28
38d86c82685fe1806859a096f7e50cf74ddfcaaa
refs/heads/master
<repo_name>nikeshvarma/WikipediaTextAnalysis<file_sep>/WTA/views.py from django.contrib import messages from django.shortcuts import render from django.views.generic import View from urllib.request import urlopen from bs4 import BeautifulSoup import re class IndexView(View): template_name = 'index.html' def count_frequency(self, data): words = {} frequent_words = {} for i in data: if words.get(i): words[i] += 1 else: words[i] = 1 ans = sorted(words, key=words.get, reverse=True)[:10] for i in ans: frequent_words.update({i: words[i]}) return frequent_words def is_valid_url(self, url): page = urlopen(url) # only one time opening url check_url = '/'.join(url.split('/')[:4]) if page.getcode() == 200 and check_url == 'https://en.wikipedia.org/wiki': # page exists and is wiki url or not html_page = page.read() soup = BeautifulSoup(html_page, 'html.parser') content = soup.find(attrs={'id': 'bodyContent'}).text.lower() content = ' '.join(re.sub(r'[0-9!@#$%^&*(){}\[\]\-;–,.?:\"\\]', ' ', content).split()).split() # search and replace spacial characters and numbers => '' # print(content) # cleaned data ready return self.count_frequency(content) return None def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): url = request.POST.get('wiki-url') data = self.is_valid_url(url) if data: return render(request, self.template_name, context={'words': data}) else: messages.error(request, 'Only Wikipedia URL Accepted.') return render(request, self.template_name) <file_sep>/README.md # Wikipedia Text Analysis ### **Description** A django framework based web application, which count the top 10 frequent words occurs only in **wikipedia** page. Ask users to give wikipedia page URL as input process the URL then show the top 10 frequent words used on that page. ### **Installation** - Extract zip file - Open extracted folder and open **CMD** where **manage.py** file exist - Copy paste the following commands listed below one by one > Install virtualenv module pip install virtualenv > Create virtual environment virtualenv venv > For a windows system. cd venv/Scripts activate > For linux or mac system source/bin/active > Install requirements pip install -r requirement.txt > Run django development server python manage.py runserver Enter URL on your browser ```http://localhost:8000```
cde54172351bbd296ed66cbab46467faf2964e3e
[ "Markdown", "Python" ]
2
Python
nikeshvarma/WikipediaTextAnalysis
ed4f0b687927652b63899e6b22a2dc4eee61a0d4
066b862286afd7ad66118746f58fb3b881110f77
refs/heads/master
<repo_name>Anderita-Games/Minesweeper<file_sep>/README.md # Minesweeper TODO: - Fix bugs - Change UI - Add sound design <file_sep>/Assets/Code/GameMaster.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameMaster : MonoBehaviour { public RectTransform Game_Area; float Game_Arena_Max; public GameObject Cell; public GameObject Line; //Top User Interface public UnityEngine.UI.Image Face; public Sprite Face_Cool; public Sprite Face_Dead; public Sprite Face_Smile; public Sprite Face_Surprised; public UnityEngine.UI.Image Flag_Toggle; public Sprite Flag_Version; public Sprite Bomb_Version; public UnityEngine.UI.Text Flag_Count_Remaining; public UnityEngine.UI.Text Time_Count; //Settings User Interface public GameObject Settings; public UnityEngine.UI.Text Arena_Size_New; public UnityEngine.UI.Text Bomb_Amount_New; public UnityEngine.UI.Text Warning_Text; //Bottom User Interface float Line_Thicc = 6; float Buffer = 40; float Cell_Size; float Arena_Width; float Arena_Height; //Game Variables public string[] Bomb_Cells; int Arena_Size; int Arena_Blocks_X; int Arena_Blocks_Y; public bool Game_Active = true; public bool Flag_Mode = false; public int Bombs_Flagged = 0; public int Cells_Activated = 0; void Start () { if (PlayerPrefs.GetInt("Bomb Quantity") == 0 || PlayerPrefs.GetInt("Arena Size") == 0 || PlayerPrefs.GetInt("Arena Size") > 1000) { PlayerPrefs.SetInt("Arena Size", 100); PlayerPrefs.SetInt("Bomb Quantity", 10); } Flag_Text_Changer(PlayerPrefs.GetInt("Bomb Quantity")); Game_Arena_Max = (float)(Game_Area.rect.height < Game_Area.rect.width ? Game_Area.rect.height : Game_Area.rect.width) - 20; float Game_Arena_Average = (Game_Area.rect.width + Game_Area.rect.height) / 2.0f; Arena_Blocks_X = (int) Mathf.Round((Game_Area.rect.width / Game_Arena_Average) * Mathf.Sqrt(PlayerPrefs.GetInt("Arena Size"))); Arena_Blocks_Y = (int) Mathf.Floor((Game_Area.rect.height / Game_Arena_Average) * Mathf.Sqrt(PlayerPrefs.GetInt("Arena Size"))); Arena_Size = Arena_Blocks_X * Arena_Blocks_Y; Line_Thicc = (8.0f / Mathf.Sqrt(Arena_Size)) * Line_Thicc; Arena_Width = (Game_Area.rect.width - (Buffer * 2)); Arena_Height = ((Arena_Width - Line_Thicc) / Arena_Blocks_X) * Arena_Blocks_Y; Debug.Log(Arena_Height); Cell_Creation(); Line_Creation(); } void Update () { if (Game_Active == true) { if (Input.GetMouseButton(0)) { Face.sprite = Face_Surprised; }else { Face.sprite = Face_Smile; } if (int.Parse(Flag_Count_Remaining.text) == 0 && Bombs_Flagged == PlayerPrefs.GetInt("Bomb Quantity") && Cells_Activated == Arena_Blocks_X * Arena_Blocks_Y - PlayerPrefs.GetInt("Bomb Quantity")) { Game_Over("WIN!"); } } if (Input.GetMouseButtonDown(1)) { Flag_Toggler(); } } void Line_Creation () { //START OF CREATION for (int Line_Current = 1; Line_Current <= Arena_Blocks_X + 1; Line_Current++) { GameObject Clone_Horizontal = Instantiate(Line, new Vector3(0, 0, 0), Quaternion.identity); Clone_Horizontal.name = "Vertical Line #" + Line_Current; Clone_Horizontal.transform.SetParent(Game_Area.transform); Clone_Horizontal.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1); Clone_Horizontal.GetComponent<RectTransform>().sizeDelta = new Vector3(Line_Thicc, (Arena_Height + Line_Thicc), 1); Clone_Horizontal.transform.localPosition = new Vector3(((Arena_Width - Line_Thicc) / Arena_Blocks_X) * ((Line_Current) - 1) - ((Game_Area.rect.width - (Buffer * 2)) / 2) + (Line_Thicc / 2.0f), ((Arena_Height - Game_Area.rect.height) / 2.0f) + Buffer + (Line_Thicc / 2), 0); } for (int Line_Current = Arena_Blocks_Y + 1; Line_Current >= 1; Line_Current--) { GameObject Clone_Vertical = Instantiate(Line, new Vector3(0, 0, 0), Quaternion.identity); Clone_Vertical.name = "Horizontal Line #" + ((Arena_Blocks_Y + 2) - Line_Current); Clone_Vertical.transform.SetParent(Game_Area.transform); Clone_Vertical.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1); Clone_Vertical.GetComponent<RectTransform>().sizeDelta = new Vector3(Game_Area.rect.width - (Buffer * 2), Line_Thicc, 1); Clone_Vertical.transform.localPosition = new Vector3(0, (Arena_Height / Arena_Blocks_Y) * ((Line_Current) - 1) - (Game_Area.rect.height / 2.0f) + Buffer + (Line_Thicc / 2), 0); } } void Cell_Creation () { Cell_Size = Mathf.Min(Arena_Width - Line_Thicc, Arena_Height - Line_Thicc) / Mathf.Min(Arena_Blocks_X, Arena_Blocks_Y) - (Line_Thicc); for (int Row_Current = 0; Row_Current < Arena_Blocks_X; Row_Current++) { for (int Column_Current = 0; Column_Current < Arena_Blocks_Y; Column_Current++) { GameObject Clone = Instantiate(Cell, new Vector3(0, 0, 0), Quaternion.identity); Clone.name = "Cell " + (Row_Current + 1) + "-" + (Column_Current + 1); Clone.transform.SetParent(Game_Area.transform); Clone.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1); Clone.GetComponent<RectTransform>().sizeDelta = new Vector3(Cell_Size, Cell_Size, 1); float Cell_Position_x = ((Arena_Width - Line_Thicc) / Arena_Blocks_X) * (Row_Current + .5f) - ((Game_Area.rect.width) / 2.0f) + Buffer + (Line_Thicc / 2.0f); float Cell_Position_y = ((Arena_Width - Line_Thicc) / Arena_Blocks_X) * (Column_Current + .5f) - (Game_Area.rect.height / 2.0f) + Buffer + (Line_Thicc / 2.0f); Clone.transform.localPosition = new Vector3(Cell_Position_x, Cell_Position_y, 0); } } } public void Bomb_Creation(string[] Clean_Cells, int Bomb_Quantity) { Bomb_Cells = new string[PlayerPrefs.GetInt("Bomb Quantity") + 1]; for (int Current_Bombs = PlayerPrefs.GetInt("Bomb Quantity"); Current_Bombs > 0; Current_Bombs--) { int Current_X = Random.Range(1, Arena_Blocks_X + 1); int Current_Y = Random.Range(1, Arena_Blocks_Y + 1); Bomb_Cells[Current_Bombs] = Repetition(Current_X, Current_Y); } Game_Active = true; StartCoroutine(Time_Counter()); } string Repetition (int Current_X, int Current_Y) { //LAST PART OF INTIAL CREATION string Result = "Cell " + Current_X + "-" + Current_Y; foreach (string Item in Bomb_Cells) { if (Item == Result) { Current_X = Random.Range(1, Arena_Blocks_X + 1); Current_Y = Random.Range(1, Arena_Blocks_Y + 1); Result = Repetition(Current_X, Current_Y); } } return Result; } IEnumerator Time_Counter () { while (Game_Active == true) { yield return new WaitForSecondsRealtime(1); if ((int.Parse(Time_Count.text) + 1) < 10) { Time_Count.text = "000" + (int.Parse(Time_Count.text) + 1).ToString(); }else if ((int.Parse(Time_Count.text) + 1) < 100) { Time_Count.text = "00" + (int.Parse(Time_Count.text) + 1).ToString(); }else if ((int.Parse(Time_Count.text) + 1) < 1000) { Time_Count.text = "0" + (int.Parse(Time_Count.text) + 1).ToString(); }else if ((int.Parse(Time_Count.text) + 1) > 9999) { Time_Count.text = "9999"; }else { Time_Count.text = (int.Parse(Time_Count.text) + 1).ToString(); } } } public void Flag_Toggler () { if (Flag_Mode) { Flag_Mode = false; Flag_Toggle.sprite = Bomb_Version; }else { Flag_Mode = true; Flag_Toggle.sprite = Flag_Version; } } public void Flag_Text_Changer (int Change) { if (int.Parse(Flag_Count_Remaining.text) + Change < 10) { Flag_Count_Remaining.text = "000" + (int.Parse(Flag_Count_Remaining.text) + Change).ToString(); }else if (int.Parse(Flag_Count_Remaining.text) + Change < 100) { Flag_Count_Remaining.text = "00" + (int.Parse(Flag_Count_Remaining.text) + Change).ToString(); }else if (int.Parse(Flag_Count_Remaining.text) + Change < 1000) { Flag_Count_Remaining.text = "0" + (int.Parse(Flag_Count_Remaining.text) + Change).ToString(); }else if (int.Parse(Flag_Count_Remaining.text) + Change > 9999) { Flag_Count_Remaining.text = "9999"; }else { Flag_Count_Remaining.text = (int.Parse(Flag_Count_Remaining.text) + Change).ToString(); } } public void Game_Over (string Cause) { Game_Active = false; if (Cause == "Death") { Face.sprite = Face_Dead; for (int Row_Current = 1; Row_Current <= Arena_Blocks_X; Row_Current++) { for (int Column_Current = 1; Column_Current <= Arena_Blocks_Y; Column_Current++) { if (GameObject.Find("Cell " + Row_Current + "-" + Column_Current).GetComponent<Cell>().Is_Bomb == true && GameObject.Find("Cell " + Row_Current + "-" + Column_Current).GetComponent<Cell>().Activated == false) { GameObject.Find("Cell " + Row_Current + "-" + Column_Current).GetComponent<Cell>().Activating(); } Destroy(GameObject.Find("Cell " + Row_Current + "-" + Column_Current).GetComponent<UnityEngine.UI.Button>()); } } for (int Row_Current = 1; Row_Current <= Arena_Blocks_X; Row_Current++) { for (int Column_Current = 1; Column_Current <= Arena_Blocks_Y; Column_Current++) { GameObject.Find("Cell " + Row_Current + "-" + Column_Current).GetComponent<Cell>().Activating(); } } }else { Face.sprite = Face_Cool; } } public void Restart () { Application.LoadLevel("MainMenu"); } public void Settings_Toggler () { if (Settings.active) { Settings.SetActive(false); }else { Settings.SetActive(true); } } public void Settings_Applyer () { if (int.Parse(Arena_Size_New.text) <= 10) { Warning_Text.text = "Minefield needs to be bigger!"; }else if (int.Parse(Bomb_Amount_New.text) <= 0) { Warning_Text.text = "You need more bombs!"; }else if (int.Parse(Bomb_Amount_New.text) >= int.Parse(Arena_Size_New.text)) { Warning_Text.text = "That is too many bombs!"; }else { PlayerPrefs.SetInt("Arena Size", int.Parse(Arena_Size_New.text)); PlayerPrefs.SetInt("Bomb Quantity", int.Parse(Bomb_Amount_New.text)); Restart(); } } }<file_sep>/Assets/Code/Cell.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cell : MonoBehaviour { //Cell UI public UnityEngine.UI.Text Bomb_Quantity; public GameObject Flag; public GameObject Bomb; public GameObject Red_X; //Bomb Values int Bombs_Nearby; public bool Is_Bomb = false; int Pos_X = 0; int Pos_Y = 0; string[] Neighbors = new string[9]; //Player Changable Values public bool Flagged = false; public bool Activated = false; //Motherland public GameMaster Creator; // Use this for initialization void Start () { Creator = GameObject.Find("Canvas").GetComponent<GameMaster>(); string[] X_Text = new string[this.name.Length]; string[] Y_Text = new string[this.name.Length]; for (int Character_Count = 0; Character_Count < this.name.Length; Character_Count++) { //Get coordinates of cell char Character = this.name[Character_Count]; if (char.IsNumber(Character)) { if (X_Text[0] == null) { for (int Char_Number = 0; char.IsNumber(this.name[Character_Count]); Char_Number++) { X_Text[Char_Number] = this.name[Character_Count].ToString(); Character_Count++; } }else if (Y_Text[0] == null) { for (int Char_Number = 0; char.IsNumber(this.name[Character_Count]); Char_Number++) { Y_Text[Char_Number] = this.name[Character_Count].ToString(); Character_Count++; if (Character_Count >= this.name.Length) { break; } } } } } Pos_X = int.Parse(string.Concat(X_Text)); Pos_Y = int.Parse(string.Concat(Y_Text)); //Finding neighbor cells Neighbors[0] = "Cell " + Pos_X + "-" + Pos_Y; Neighbors[1] = "Cell " + Pos_X + "-" + (Pos_Y + 1); Neighbors[2] = "Cell " + Pos_X + "-" + (Pos_Y - 1); Neighbors[3] = "Cell " + (Pos_X + 1) + "-" + Pos_Y; Neighbors[4] = "Cell " + (Pos_X - 1) + "-" + Pos_Y; Neighbors[5] = "Cell " + (Pos_X + 1) + "-" + (Pos_Y + 1); Neighbors[6] = "Cell " + (Pos_X + 1) + "-" + (Pos_Y - 1); Neighbors[7] = "Cell " + (Pos_X - 1) + "-" + (Pos_Y + 1); Neighbors[8] = "Cell " + (Pos_X - 1) + "-" + (Pos_Y - 1); } public void Pressed () { if (Creator.Flag_Mode == false && Flagged == false) { Activating(); }else if (Creator.Flag_Mode == true) { Flagging(); } } public void Self_Bomb_Check () { for (int Current_Bombs = PlayerPrefs.GetInt("Bomb Quantity"); Current_Bombs > 0; Current_Bombs--) { if (Creator.Bomb_Cells[Current_Bombs] == this.name) { Is_Bomb = true; } } } public void Activating () { if (Activated == false) { Activated = true; if (Creator.Bomb_Cells.Length == 0) { Creator.Bomb_Creation(Neighbors, PlayerPrefs.GetInt("Bomb Quantity")); } Self_Bomb_Check(); Bombs_Nearby = Neighbor_Bomb_Check(); if (Creator.Game_Active == true) { if (Is_Bomb == true) { this.GetComponent<UnityEngine.UI.RawImage>().color = Color.red; GameObject.Find("Canvas").GetComponent<GameMaster>().Game_Over("Death"); Bomb.SetActive(true); }else { this.GetComponent<UnityEngine.UI.RawImage>().color = Color.white; if (Bombs_Nearby == 0) { //Expose 0 value Neighbors Bomb_Quantity.text = ""; for (int i = 1; i <= 8; i++) { if (GameObject.Find(Neighbors[i]) == true && GameObject.Find(Neighbors[i]).GetComponent<Cell>().Activated == false) { GameObject.Find(Neighbors[i]).GetComponent<Cell>().Activating(); } } }else { Bomb_Quantity.text = Bombs_Nearby.ToString(); } } }else { if (Flagged && Is_Bomb == false) { this.GetComponent<UnityEngine.UI.RawImage>().color = Color.white; Flag.SetActive(false); Bomb.SetActive(true); Red_X.SetActive(true); }else if (Is_Bomb == true && Flagged == false) { this.GetComponent<UnityEngine.UI.RawImage>().color = Color.white; Bomb.SetActive(true); } } Creator.Cells_Activated++; Destroy(this.GetComponent<UnityEngine.UI.Button>()); } } void Flagging () { if (int.Parse(Creator.Flag_Count_Remaining.text) > 0) { Self_Bomb_Check(); if (Flagged == false) { Flagged = true; Flag.SetActive(true); if (Is_Bomb == true) { Creator.Bombs_Flagged++; } Creator.Flag_Text_Changer(-1); } }else { Flagged = false; Flag.SetActive(false); if (Is_Bomb == true) { Creator.Bombs_Flagged--; } Creator.Flag_Text_Changer(1); } } int Neighbor_Bomb_Check () { //Finding quantity of nearby bombs int Result = 0; foreach (string Neighbor in Neighbors) { foreach (string Bomb in Creator.Bomb_Cells) { if (Neighbor == Bomb) { Result++; } } } return Result; } }
88a904874340ba2b85c6b26e45445717211e9992
[ "Markdown", "C#" ]
3
Markdown
Anderita-Games/Minesweeper
241c2608b1701aa9785944ab26e28a41e47b0335
7f0f7dcc9cb1ef9f1a95e513d432adc373ad2709
refs/heads/master
<repo_name>ekeough6/Sudoku-Java<file_sep>/src/SudokuCreation.java public class SudokuCreation { public static } <file_sep>/src/Square.java import java.util.ArrayList; public class Square{ private String num; private ArrayList<String>exceptions; private boolean fixed; public Square(){ num = " "; exceptions = new ArrayList<String>(); fixed = false; } public Square(String n) { num = n; exceptions = new ArrayList<String>(); if(!n.trim().isEmpty()) fixed = true; else fixed = false; } public void change(String n){ num = n; } public String getValue(){ return num; } public void addException(String ex){ exceptions.add(ex); } public ArrayList<String> getExceptions(){ return exceptions; } public boolean meetsException(String n){ for(String e:exceptions){ if(e.equals(n)) return false; } return true; } public void clearExceptions(){ exceptions = new ArrayList<String>(); } public boolean isFixed(){ return fixed; } } <file_sep>/src/SudokuBoard.java import java.util.ArrayList; public class SudokuBoard { public Square[][] board; private String[] digits = {"a", "b", "c", "d", "e", "f", "g", "h", "i"}; public SudokuBoard() { board = new Square[9][9]; for(int row = 0; row<9; row++) for(int col = 0; col<9; col++) board[row][col] = new Square(); fillBoard(); } public SudokuBoard(String b){ board = new Square[9][9]; for(int row = 0; row<9; row++) for(int col = 0; col<9; col++) board[row][col] = new Square(b.substring(row*9 + col, row*9 + col+1)); } public ArrayList<String> availableNumbers(int row, int col) { ArrayList<String> nums = new ArrayList<String>(); for(String d:digits) if(board[row][col].meetsException(d) && isLegal(row, col, d)) nums.add(d); return nums; } private boolean isLegal(int row, int col, String num) { return legalCol(col, num) && legalRow(row, num) && legalSquare(row, col, num); } private boolean legalCol(int col, String num) { for(int row=0; row<9; row++) if(board[row][col].getValue().equals(num)) return false; return true; } private boolean legalRow(int row, String num) { for(int col=0; col<9; col++) if(board[row][col].getValue().equals(num)) return false; return true; } private boolean legalSquare(int row, int col, String num){ int rowStart = row / 3 * 3; int colStart = col / 3 * 3; for(int r=rowStart; r<rowStart+3; r++) for(int c=colStart; c<colStart+3; c++) if(board[r][c].getValue().equals(num)) return false; return true; } private boolean fillBox(int row, int col){ ArrayList<String> nums = availableNumbers(row, col); if(nums.size() == 0) return false; board[row][col].change(nums.get((int)(Math.random() * nums.size()))); return true; } private void fillBoard(){ int row = 0; int col = 0; while(row < 9){ while(col < 9){ if(!fillBox(row, col)){ board[row][col].clearExceptions(); board[row][col].change(" "); col = (col > 0) ? col - 1: 8; if(col == 8) row--; board[row][col].addException(board[row][col].getValue()); } else{ col++; } } row++; col = 0; } } public void printBoard(){ for(Square[] row:board){ for(Square num:row) System.out.print(num.getValue()); System.out.println(); } } public String toString(){ String su = ""; for(Square[] b: board) for(Square num: b) su+=num.getValue(); return su; } private boolean equal = true; private boolean solve(String input){ equal = true; SudokuBoard broken = new SudokuBoard(input); return fill(broken, 0, 0); } private boolean fill(SudokuBoard broken, int row, int col){ if(equal){ if(broken.isComplete() && !toString().equals(broken.toString())){ equal = false; } else if(row < 9 && !broken.board[row][col].isFixed()){ ArrayList<String> nums = broken.availableNumbers(row, col); for(int x=0; x<nums.size(); x++){ broken.board[row][col].change(nums.get(x)); if(col == 8) fill(broken, row+1, 0); else fill(broken, row, col+1); broken.board[row][col].change(" "); if(!equal) break; } } else if(row < 9){ if(col == 8) fill(broken, row+1, 0); else fill(broken, row, col+1); } } return equal; } public String destroy(int n){ char[] str = toString().toCharArray(); for(int x=0; x<81-n; x++){ boolean done = false; while(!done){ int place = (int)(Math.random() * 81); if(str[place] != ' '){ str[place] = ' '; done = true; } } } String puzzle = ""; for(char s: str) puzzle += s; return puzzle; } public boolean isComplete(){ return !toString().contains(" "); } public String genPuzzle(int n){ boolean con = true; int count = 0; double time; String input = ""; while(con){ count++; input = destroy(n); time = System.currentTimeMillis(); con = !solve(input); System.out.println(count+" took: "+(System.currentTimeMillis()-time)+" milliseconds"); } return input; } private boolean cont = true; public void solve(){ cont = true; solve_fill(0,0); } private void solve_fill(int row, int col){ if(cont){ if(isComplete()){ cont = false; } else if(row < 9 && !board[row][col].isFixed()){ ArrayList<String> nums = availableNumbers(row, col); for(int x=0; x<nums.size(); x++){ board[row][col].change(nums.get(x)); if(col == 8) solve_fill( row+1, 0); else solve_fill(row, col+1); if(!cont) break; board[row][col].change(" "); } } else if(row < 9){ if(col == 8) solve_fill(row+1, 0); else solve_fill(row, col+1); } } } public static void main(String[] args) { SudokuBoard board = new SudokuBoard(); board.printBoard(); System.out.println(); SudokuBoard board2 = new SudokuBoard(board.genPuzzle(27)); board2.printBoard(); board2.solve(); System.out.println(); board2.printBoard(); } }
0cd0a53b7a020c5e712c227da35e56ba1d917a9e
[ "Java" ]
3
Java
ekeough6/Sudoku-Java
69dc9d05d964e4ba292053f0c5caa286a793c3f5
9cabf6975c53ee22bb1fa8ffc93dee35607a352a
refs/heads/master
<file_sep># **Behavioral Cloning** ## Project writeup --- **Behavioral Cloning Project** The goals / steps of this project are the following: * Use the simulator to collect data of good driving behavior * Build, a convolution neural network in Keras that predicts steering angles from images * Train and validate the model with a training and validation set * Test that the model successfully drives around track one without leaving the road * Summarize the results with a written report [//]: # (Image References) [image1]: ./examples/example0.jpg "Example Image 1" [image2]: ./examples/example1.jpg "Example Image 2" [image3]: ./examples/example2.jpg "Example Image 3" [image4]: ./examples/example3.jpg "Example Image 4" [image5]: ./examples/self_steering_model0.jpg "Validation Performance over epochs" ## Rubric Points ### Here I will consider the [rubric points](https://review.udacity.com/#!/rubrics/432/view) individually and describe how I addressed each point in my implementation. --- ### Files Submitted & Code Quality #### 1. Submission includes all required files and can be used to run the simulator in autonomous mode My project includes the following files: * model.py containing the script to create and train the model * drive.py for driving the car in autonomous mode * self_steering_model0.h5 containing a trained convolution neural network * model0_vid.mp4 a video for the car in the autonomous mode. * README.md summarizing the results #### 2. Submission includes functional code Using the Udacity provided simulator and my drive.py file, the car can be driven autonomously around the track by executing ```sh python self_steering_model0.h5 ``` #### 3. Submission code is usable and readable The self_steering_model0.h5 file contains the code for training and saving the convolution neural network. The file shows the pipeline I used for training and validating the model, and it contains comments to explain how the code works. ### Model Architecture and Training Strategy #### 1. An appropriate model architecture has been employed My model is Based on Convolutional Neural Networks and uses 5x5 and 3x3 kernel sizses. The model uses normalization, croping and dropout layers. More architichural details are provided in the model architecture section. #### 2. Attempts to reduce overfitting in the model To reduce overfitting, I used Max-Pooling layers after my convolutioal layers and Dropout layers after some of the fully connected layers. The Data also was augmented with flipped images. The details are provided in the model architecture section. #### 3. Model parameter tuning The model used an adam optimizer, so the learning rate was not tuned manually (model.py line 123). ### Model Architecture and Training Strategy #### 1. Creation of the Training Set & Training Process For the data collection part, I followed all the helpful hints of the course instructors by: - Collecting as much data as I could by trying to drive properly in the middle of the road. - Then, collect more data to capture the fact that we want the car to be as close to the middle of the road as possible by trying to record as many frames as possible of the car while moving from the sides of the road to the center. - Doing the same in the first two steps but driving in the reverse direction to help the model to generalize. - Data augmentation by introducing new examples by flipping the original ones and reverse the steering angle sign. - Only center images were filtered and used for training and validation. - As a result of all the previous steps, I collected a number of 37622 training examples before data augmentation and the double after data augmentation (75244 examples). Here are some examples of training the car to drive in the middle ![alt text][image1] ![alt text][image2] And here some examples where the car is starting to recover when it's not in the middle of the road ![alt text][image3] ![alt text][image4] #### 2. Solution Design Approach and Final Model Architecture To validate the performance, I splitted the dataset into train/validation based on 80% to 20% split ratio. After watching the Video lectures of the project, I started with what worked best which was NVIDIA architecture. NVIDIA architecture includes normalization layer but not cropping one which proved to be useful in the video lectures, so I added it. When I started with the basic [NVIDIA Architecture](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) and tested it in the simulation mode, It seemed that the model is a bit overfitting. Then I modified the model by addining dropout and Max-Pooling layers and by choosing the best number of epochs to avoid overfitting. I trained the model and given the data provided in the following chart. I chose 5 epochs as a good number of epochs where the performace on the validation set was stable and was consistently decreasing until that point, after that it started to fluctuate from one epoch to another. ![alt text][image5] Using the output model, the car was very stable and successfully ran into the first track as shown in the provided video. The detailed model architecture was as follows (from line 86 to 123 in model.py file): - Cropping layer to make use of only useful information by cropping 70 pixels from the top of the image and 25 from the bottom. - Lambda layer for normalization of the pixel values - 5x5 convolutioal layer with 24 filters followed by RELU activation - Max-pooling layer with 2x2 pooling filter size - 5x5 convolutioal layer with 36 filters followed by RELU activation - Max-pooling layer with 2x2 pooling filter size - 5x5 convolutioal layer with 48 filters followed by RELU activation - Max-pooling layer with 2x2 pooling filter size - 5x5 convolutioal layer with 64 filters followed by RELU activation - Flatten all output filter maps - Fully connected layer with 1064 units - Dropout layer with 50% dropout rate - Fully connected layer with 100 units - Dropout layer with 30% dropout rate - Fully connected layer with 50 units - Fully connected layer with 10 units - Final regression unit The model aimed to minimize the Mean Square Error (MSE) using adam optimizer.<file_sep># keras model for behavioual cloning project # <NAME> # importing the needed libraries import numpy as np from scipy import misc import argparse from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout from keras.layers.pooling import MaxPooling2D from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt # read driving data functions # read the lines function def read_data_lines(data_path): log_path = data_path + '/driving_log.csv' samples = [] with open(log_path) as f: for line in f: samples.append(line) return samples # batch processing generator def process_driving_data(samples, batch_size): imgs_path = data_path + '/IMG/' num_samples = len(samples) while 1: samples = shuffle(samples) for offset in range(0, num_samples, batch_size): imgs = [] measurements = [] batch_samples = samples[offset:offset+batch_size] for batch_sample in batch_samples: center_img_path, left_img_path, right_img_path, steering, throttle, brake, speed = batch_sample.strip().split(',') center_img_name = center_img_path.split('/')[-1] center_img_updated_path = imgs_path + center_img_name img = misc.imread(center_img_updated_path) img_steering = float(steering.strip()) imgs.append(img) measurements.append(img_steering) img_flipped = np.fliplr(img) img_flipped_steering = -1 * img_steering imgs.append(img_flipped) measurements.append(img_flipped_steering) imgs_array = np.array(imgs) measurements_array = np.array(measurements) yield shuffle(imgs_array, measurements_array) # parsing the arguments parser = argparse.ArgumentParser(description='Train a network for udacity Behavioural Cloning Project') parser.add_argument('--data_path', dest='data_path') parser.add_argument('--model_name', dest='model_name') parser.add_argument('--nb_epoch', dest='nb_epoch', type=float) parser.add_argument('--batch_size', dest='batch_size', type=int, default=128) args = parser.parse_args() data_path = args.data_path nb_epoch = args.nb_epoch batch_size = args.batch_size model_name = args.model_name if data_path[-1] == '/': data_path = data_path[:-1] # reading the data samples = read_data_lines(data_path) # 80%-20% train validation split train_samples, validation_samples = train_test_split(samples, test_size=0.2) # train and validation generators train_generator = process_driving_data(train_samples, batch_size=batch_size) validation_generator = process_driving_data(validation_samples, batch_size=batch_size) # building the model model = Sequential() # cropping layer that crops 70 pixels from the top of the image and 25 from the bottom model.add(Cropping2D(cropping=((70,25), (0,0)), input_shape=(160,320,3))) # lambda layer for normalization of the pixel values model.add(Lambda(lambda x: x / 255.0 - 0.5)) # 5x5 convolutioal layer with 24 filters followed by RELU activation model.add(Convolution2D(24, 5, 5, activation='relu')) # Max-pooling layer with 2x2 pooling filter size model.add(MaxPooling2D(pool_size=(2, 2))) # 5x5 convolutioal layer with 36 filters followed by RELU activation model.add(Convolution2D(36, 5, 5, activation='relu')) # Max-pooling layer with 2x2 pooling filter size model.add(MaxPooling2D(pool_size=(2, 2))) # 5x5 convolutioal layer with 48 filters followed by RELU activation model.add(Convolution2D(48, 5, 5, activation='relu')) # Max-pooling layer with 2x2 pooling filter size model.add(MaxPooling2D(pool_size=(2, 2))) # 5x5 convolutioal layer with 64 filters followed by RELU activation model.add(Convolution2D(64, 3, 3, subsample=(2,2), activation='relu')) # Flatten all output filter maps model.add(Flatten()) # Fully connected layer with 1064 units model.add(Dense(1064)) # Dropout layer with 50% dropout rate model.add(Dropout(0.5)) # Fully connected layer with 100 units model.add(Dense(100)) # Dropout layer with 30% dropout rate model.add(Dropout(0.3)) # Fully connected layer with 50 units model.add(Dense(50)) # Fully connected layer with 10 units model.add(Dense(10)) # Final regression unit model.add(Dense(1)) # adam optimizer to minimize mean square error model.compile(loss='mse', optimizer='adam') # Training the model model_history = model.fit_generator(train_generator, samples_per_epoch=len(train_samples), validation_data=validation_generator, nb_val_samples=len(validation_samples), nb_epoch=nb_epoch, verbose=1) # saving the model model.save(model_name) # plot the training and validation loss for each epoch plt.plot(model_history.history['loss']) plt.plot(model_history.history['val_loss']) plt.title('model mean squared error loss') plt.ylabel('mean squared error loss') plt.xlabel('epoch') plt.legend(['training set', 'validation set'], loc='upper right') plt.savefig(model_name[:-3] + '_loss.jpg') # Exit the program exit()
5a0cbe324085a1697ef1ead50fc1d4f8e4a3a3d7
[ "Markdown", "Python" ]
2
Markdown
tmkhalil/CarND-Behavioral-Cloning-P3
2c2559411567c01dff7ec35df267aceaae033498
33b58a93ec271d51040cfeffbd6973f412e6ca29
refs/heads/main
<repo_name>ZimehrAbbasi/Search-Engine<file_sep>/indexer/IMPLEMENTATION.md # CS50 Lab 5 ## CS50 Spring 2021 ### indexer ```c index_t* index_new(const int num_slots); bool index_insert(index_t* index, const char* key, int DocID); void index_print(index_t* index, FILE *fp); void index_delete(index_t* index); void index_save(index_t* index, FILE* fp); ``` We implement the index as a wrapper for the hashtable. The *index* itself is represented as a `struct index` containing a pointer to the hashtable stored in memory. To insert a new item in the index we create a new counter to hold the `docID` and the `count`, and insert into an available slot. The `index_print` method prints a little syntax around the index, and between items, but mostly calls the `itemprint` function on each item by scanning the hashtable and counters. The `index_save` method calls the `itemfunc` function on each item by scanning the hashtable and counters for each key, and print them out to a list. The `index_delete` method deletes the hashtable and the counters<file_sep>/libcs50/hashtable.c /* * hashtable.c - CS50 'hashtable' module * * see hashtable.h for more information. * * @Author <NAME> * Module for creating a hashtable data structure */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hashtable.h" #include "set.h" #include "hash.h" #include "mem.h" // Struct for hashtable typedef struct hashtable{ set_t** set; int size; int num_items; } hashtable_t; // Creating a new hashtable hashtable_t* hashtable_new(const int num_slots){ hashtable_t* hashtable = (hashtable_t*)mem_malloc(sizeof(hashtable_t)); if (hashtable == NULL) { return NULL; // error allocating counter } else { hashtable->set = mem_calloc(num_slots, sizeof(set_t*)); set_t** sets; sets = hashtable->set; for(int i = 0; i < num_slots; i++){ sets[i] = set_new(); } hashtable->size = num_slots; hashtable->num_items = 0; return hashtable; } } // Inserting key:item value into the hashtable bool hashtable_insert(hashtable_t* ht, const char* key, void* item){ if(ht != NULL && key != NULL && item != NULL){ set_t** sets; sets = ht->set; if(hashtable_find(ht, key) != NULL){ return false; } unsigned long index = hash_jenkins(key, ht->size); bool success = set_insert(sets[index], key, item); if(success){ ht->num_items += 1; return true; } } return false; } // Finding the item associated with a a particular key void* hashtable_find(hashtable_t* ht, const char* key){ if(ht != NULL && key != NULL){ set_t** sets; sets = ht->set; for(int i = 0; i < ht->size;i++){ void *item = set_find(sets[i], key); if(item != NULL){ return item; } } } return NULL; } // Finding the set associated with a particular key void* hashtable_insertat(hashtable_t* ht, const char* key, void* item, int num){ if(ht != NULL){ set_t** sets; sets = ht->set; unsigned long index = num; bool success = set_insert(sets[index], key, item); if(success){ ht->num_items += 1; return true; } } return NULL; } // Printing the hashtable void hashtable_print(hashtable_t* ht, FILE* fp, void (*itemprint)(FILE* fp, const char* key, void* item)){ if(fp != NULL){ if(ht != NULL){ set_t** sets; sets = ht->set; for(int i = 0; i < ht->size;i++){ if(itemprint == NULL){ fputs("{}\n", fp); continue; } set_print(sets[i], fp, itemprint); } }else{ fputs("(null)", fp); } } } // Iterating through the hashtable void hashtable_iterate(hashtable_t* ht, void* arg, void (*itemfunc)(void* arg, const char* key, void* item)){ if(ht != NULL && itemfunc != NULL){ set_t** sets; sets = ht->set; for(int i = 0; i < ht->size;i++){ set_iterate(sets[i], arg, itemfunc); } } } // Deleting the hashtable void hashtable_delete(hashtable_t* ht, void (*itemdelete)(void* item) ){ if (ht != NULL) { set_t** sets; sets = ht->set; for(int i = 0; i < ht->size;i++){ set_delete(sets[i], itemdelete); } free(sets); free(ht); } }<file_sep>/common/pagedir.c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "../libcs50/file.h" #include "../libcs50/webpage.h" #include "../libcs50/mem.h" #include <dirent.h> #include <errno.h> typedef struct webpage { char* url; char* html; size_t html_len; int depth; } webpage_t; bool pagedir_init(const char* pageDirectory){ char path[260]; sprintf(path, "%s/.crawler", pageDirectory); FILE* fp = fopen(path, "w+"); if(fp == NULL){ return false; } fclose(fp); return true; } char* pagedir_add(const char* pageDirectory, int fileNumber){ char docid[10]; // Since the limit for the integer is 2147483647 sprintf(docid, "%d", fileNumber); char* name = malloc(strlen(pageDirectory)+strlen(docid)+2); strcpy(name, pageDirectory); strcat(name, "/"); strcat(name, docid); return name; } bool pagedir_val(const char* pageDirectory){ DIR* dir = opendir(pageDirectory); if (dir) { closedir(dir); char name[strlen(pageDirectory)+strlen(".crawler")+1]; strcpy(name, pageDirectory); strcat(name, "/"); strcat(name, ".crawler"); FILE* fp; if((fp = fopen(name, "r")) != NULL){ fclose(fp); return true; } } return false; } void pagedir_save(const webpage_t* page, const char* pageDirectory, const int docID){ char docid[10]; // Since the limit for the integer is 2147483647 sprintf(docid, "%d", docID); char name[strlen(pageDirectory)+strlen(docid)+1]; strcpy(name, pageDirectory); strcat(name, "/"); strcat(name, docid); FILE* fp; fp = fopen(name, "w"); fprintf(fp, "%s\n", page->url); fprintf(fp, "%d\n", page->depth); fprintf(fp, "%s\n", page->html); fclose(fp); } webpage_t* pagedir_load(FILE* fp){ char* url = file_readLine(fp); char* depths = file_readLine(fp); int depth = atoi(depths); mem_free(depths); char* html = file_readFile(fp); webpage_t* wp = webpage_new(url, depth, html); return wp; }<file_sep>/indexer/README.md # <NAME> ## CS50 Spring 2021, Lab 5 GitHub username: ZimehrAbbasi ## ASSUMPTIONS The primary assumption this indexer works on is that the directory used to store the pages has already been created and the files have also been created. ## LIMITATIONS This program is limited by the amount of storage space available in the device.<file_sep>/crawler/crawler.c #include <stdlib.h> #include <stdio.h> #include "../libcs50/bag.h" #include "../libcs50/hashtable.h" #include "../libcs50/webpage.h" #include "../common/pagedir.h" #include "../libcs50/mem.h" #include <string.h> // STRUCTS typedef struct page { char* url; int depth; } page_t; // FUNCTION PROTOTYPES static void parseArgs(const int argc, char* argv[], char** seedURL, char** pageDirectory, int* maxDepth); static void pageScan(webpage_t* page, bag_t* pagesToCrawl, hashtable_t* pagesSeen); static void crawl(char* seedURL, char* pageDirectory, const int maxDepth); static page_t* new_page_t(char* url, int depth); static void page_delete(page_t* page); static void logr(const char *word, const int depth, const char *url); // FUNCTION TO PARSE THE ARGUMENTS AND SET UP THE VARIABLES TO BEGIN THE CRAWLING static void parseArgs(const int argc, char* argv[], char** seedURL, char** pageDirectory, int* maxDepth){ // Checks argument count if(argc == 4){ *seedURL = argv[1]; *pageDirectory = argv[2]; *maxDepth = atoi(argv[3]); char* url = normalizeURL(*seedURL); // Get the normalized url printf("Checking if URL is internal...\n"); sleep(1); if(isInternalURL(url)){ // Check if normalized url is internal printf("Creating page directory...\n"); sleep(1); if(pagedir_init(*pageDirectory)){ // Create the page directory printf("Checking if depth is in bounds...\n"); sleep(1); if(*maxDepth <= 10 && *maxDepth >= 0){ // Check if the maximum depth is out of range printf("Success!\n"); mem_free(url); // free the url return; }else{ fprintf(stderr, "Max Depth out of range.\n"); } }else{ fprintf(stderr, "Directory creation failed.\n"); } }else{ fprintf(stderr, "Url not internal.\n"); } mem_free(url); }else{ fprintf(stderr, "Argument count error.\n"); } exit(1); } // METHOD TO SCAN THE PAGE FOR ADDITIONAL URLS static void pageScan(webpage_t* page, bag_t* pagesToCrawl, hashtable_t* pagesSeen){ int pos = 0; char* url; while ((url = webpage_getNextURL(page, &pos)) != NULL) { char* normurl = normalizeURL(url); // Get normalized url logr("Found", webpage_getDepth(page), normurl); if(isInternalURL(normurl)){ // Check if it is internal if(hashtable_insert(pagesSeen, normurl, normurl)){ page_t* p = new_page_t(normurl, webpage_getDepth(page)+1); // Create new page for webpage bag_insert(pagesToCrawl, p); // Insert the page into the bag logr("Added", webpage_getDepth(page), normurl); }else{ logr("IgnDupl", webpage_getDepth(page), normurl); } }else{ logr("IgnExtrn", webpage_getDepth(page), normurl); } mem_free(url); mem_free(normurl); } } // ITERATING OVER THE URLS, FETHCING THEIR HTML, AND THE SUBSEQUENT URLS FOUNF IN THIR HTML CODE static void crawl(char* seedURL, char* pageDirectory, const int maxDepth){ hashtable_t* ht = hashtable_new(200); // Create the hashtable bag_t* bag = bag_new(); // Create the bag to store the pages page_t* page = new_page_t(seedURL, 0); // Seed page hashtable_insert(ht, seedURL, seedURL); bag_insert(bag, page); page_t* temp; int DocId = 0; while((temp = bag_extract(bag)) != NULL){ webpage_t* wp; wp = webpage_new(temp->url, temp->depth, NULL); // Create a new webpage from the page if(webpage_fetch(wp)){ // Fetch the html for the webpage pagedir_save(wp, pageDirectory, DocId); // Save the html to files logr("Fetched", temp->depth, temp->url); if(webpage_getDepth(wp) < maxDepth){ // Check its depth logr("Scanning", temp->depth, temp->url); pageScan(wp, bag, ht); // Scan the page for additional urls } } page_delete(temp); webpage_delete(wp); DocId++; } hashtable_delete(ht, NULL); bag_delete(bag, NULL); } // Method to create new pages static page_t* new_page_t(char* url, int depth){ if(url != NULL){ char* urlcpy = (char*)mem_malloc(sizeof(char)*(strlen(url)+1)); strcpy(urlcpy, url); page_t* page = (page_t*)mem_malloc(sizeof(page_t)); page->url = urlcpy; page->depth = depth; return page; } return NULL; } static void page_delete(page_t* page){ if(page != NULL){ mem_free(page); } } static void logr(const char *word, const int depth, const char *url) { printf("%2d %*s%9s: %s\n", depth, depth, "", word, url); } int main(const int argc, char* argv[]){ char** seedURL = (char **)malloc(sizeof(char*)); char** pageDirectory = (char **)malloc(sizeof(char*)); int* maxDepth = (int *)malloc(sizeof(int)); printf("\n####################################################################\n\n"); printf("Precrawl checks:\n"); parseArgs(argc, argv, seedURL, pageDirectory, maxDepth); printf("\n--------------------------------------------------------------------\n"); printf("\nSeed URL: %3s\nPageDir: %3s\nMax Depth: %d\n", *seedURL, *pageDirectory, *maxDepth); printf("\n####################################################################\n\n"); crawl(*seedURL, *pageDirectory, *maxDepth); printf("\n"); mem_free(seedURL); mem_free(pageDirectory); mem_free(maxDepth); return 0; }<file_sep>/common/index.h #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../libcs50/mem.h" #include "../libcs50/counters.h" #include "../libcs50/hashtable.h" #include "../libcs50/set.h" #include "../libcs50/hash.h" #ifndef __INDEX_H #define __INDEX_H typedef struct index index_t; index_t* index_new(const int num_slots); bool index_insert(index_t* index, const char* key, int DocID); int index_get(index_t* index, const char* key, int DocID); void index_print(index_t* index, FILE *fp); void index_delete(index_t* index); void index_save(index_t* index, FILE* fp); void index_load(index_t* index, FILE* fp, void (*itemfunc)(index_t* index, char* line)); #endif<file_sep>/querier/DESIGN.md # Design spec ## Index * [User Interface](#User-interface) * [Inputs and outputs](#Inputs-an-outputs) * [Functional decomposition into functions/modules](#Functional-decomposition-int-functions/modules) * [High-level pseudo code](#High-level-pseudo-code) * [Testing plan](##Testing-plan,-including-unit-tests,-integration-tests,-system-tests) ## User interface As described in the Requirements Spec, the querier's only interface with the user is on the command-line; it must always have two arguments: * **pageDir:** A crawler created directory in which all the documents are stored. * **indexFile:** A file containing the text version of the index ```bash= $ ./querier [pageDir] [indexFile] ``` #### Example Run ```bash= ./querier ../data/letters ../data/letters.index ``` ## Inputs and outputs _Input:_ Command line parameters are described above. Other inputs include the query to be processed which will be read from stdin. _Output:_ As per the Requirements spec, the program will output the score, document Id, and the URL of the document if the query matches any permutations of words found in the files. ```bash= Score: 3 Document: 7 URL: https://example.com/ ``` ## Functional decomposition into functions/modules * main: Parses arguments and begins the querier with given parameters * parse: Reads a line in the index file and inserts it into the index * load index: converts the index file into an index object * tokenize: create an array of words from the query * _querier: Main function of the querier program which takes in a request and outputs the search results ## High-level pseudo code ```text parse the command line, validate parameters, initialize other modules read index file into index check number of files in pageDirectory read query from stdin normalize query tokanize query (split into words) assign weights to query (0 for normal words, 1 for 'and', 2 for 'or') create document array check for invalid inputs squish scores of 'and' and the rest of the words into 1 number and create an orArray create score array from the orArray sort index outout the top n search results ``` ## Testing plan, including unit tests, integration tests, system tests. ### Unit Tests * Testing the parse function * Test writes file's line into the parse function and reads the resulting index * Testing the load index function * Test inputs an entire idnex file and prints resulting index ### Integration Tests * Testing the querier * Test the querier function with the parse function as well as the load index function ### System Tests * Testing if there are any memory leaks using valgrind. * Test modules separately. Make sure each module's data constructors and processors do not leak memory. * Test modules together. Make sure collective functionality does not leak memory. * Testing for compiler warnings. * Run make clean and make all to test for compilation warnings / errors<file_sep>/querier/testing.sh # Invalid page directory ./querier invalidir ../data/letters.index echo " " # Invalid index file ./querier ../data/letters invalidindex echo " " # incorrect number of arguments ./querier arg1 arg2 arg3 echo " " # Invalid queries echo "and" | ./querier ../data/letters ../data/letters.index echo " " echo "or" | ./querier ../data/letters ../data/letters.index echo " " echo "and earth" | ./querier ../data/letters ../data/letters.index echo " " echo "planet earth or" | ./querier ../data/letters ../data/letters.index echo " " echo "planet earth and" | ./querier ../data/letters ../data/letters.index echo " " echo "planet earth and and science" | ./querier ../data/letters ../data/letters.index echo " " echo "planet earth or and science" | ./querier ../data/letters ../data/letters.index echo " " # Normal cases echo "first" | ./querier ../data/letters ../data/letters.index echo " " echo "first and depth or page" | ./querier ../data/letters ../data/letters.index echo " " echo "fourier transform" | ./querier ../data/letters ../data/letters.index echo " " echo "reviews" | ./querier ../data/toscrape ../data/toscrape.index echo " " echo "reviews and meaning" | ./querier ../data/toscrape ../data/toscrape.index echo " " echo "reviews and meaning or baker" | ./querier ../data/toscrape ../data/toscrape.index echo " " echo "doctrine" | ./querier ../data/toscrape ../data/toscrape.index echo " " # Valgrind echo "first and depth or page" | valgrind ./querier ../data/letters ../data/letters.index echo "doctrine" | valgrind ./querier ../data/toscrape ../data/toscrape.index<file_sep>/common/word.c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <ctype.h> char* normalize_word(char* s){ char *lower = calloc(strlen(s)+1, sizeof(char)); for (int i = 0; i < strlen(s); ++i) { lower[i] = tolower((unsigned char) s[i]); } return lower; } // int main(const int argc, const char* argv[]){ // char* word = "wAR"; // char* temp = normalize_word(word); // printf("%s\n", temp); // free(temp); // }<file_sep>/libcs50/counters.c /* * counters.c - CS50 'counters' module * * see counters.h for more information. * * @Author <NAME> * Module for creating a counter data structure */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "counters.h" #include "mem.h" // Counters node struct typedef struct counternode { int key; int count; struct counternode *next; } counternode_t; // Counters struct typedef struct counters { struct counternode *head; int size; } counters_t; // Function prototype to create new counternode static counternode_t *counternode_new(const int key); // Creating a new counter counters_t * counters_new(void) { counters_t *counter = (counters_t *)mem_malloc(sizeof(counters_t)); if (counter == NULL) { return NULL; // error allocating counter } else { // initialize contents of counter structure counter->head = NULL; counter->size = 0; return counter; } } // Adding a key to the counter or incrementing predefinned key int counters_add(counters_t *ctrs, const int key) { if (ctrs != NULL && key >= 0) { int val = counters_get(ctrs, key); if (val != 0) { for (counternode_t *node = ctrs->head; node != NULL; node = node->next) { if(node->key == key){ node->count += 1; val = node->count; } } return val; } counternode_t *new = counternode_new(key); if (new != NULL) { // add it to the head of the list new->next = ctrs->head; ctrs->head = new; ctrs->size += 1; return new->count; } } return 0; } // Getting count for specific key int counters_get(counters_t *ctrs, const int key) { if (ctrs != NULL && key >= 0) { counternode_t *temp; temp = ctrs->head; while (temp != NULL) { if (temp->key == key) { return temp->count; } temp = temp->next; } } return 0; } // Set count for specific counter bool counters_set(counters_t *ctrs, const int key, const int count) { if (ctrs != NULL && key >= 0 && count >= 0) { counternode_t *temp; temp = ctrs->head; while (temp != NULL) { if (temp->key == key) { temp->count = count; return temp->count; } temp = temp->next; } counters_add(ctrs, key); return counters_set(ctrs, key, count); } return 0; } // Print value of counter void counters_print(counters_t *ctrs, FILE *fp) { if (fp != NULL) { if (ctrs != NULL) { for (counternode_t *node = ctrs->head; node != NULL; node = node->next) { fputc('{', fp); fprintf(fp, "%d=%d", node->key, node->count); fputc('}', fp); if (node->next != NULL) { fputc(',', fp); } } } else { fputs("(null)\n", fp); } } } // Iterating through the counter void counters_iterate(counters_t *ctrs, void *arg, void (*itemfunc)(void *arg, const int key, const int count)) { if (ctrs != NULL && itemfunc != NULL) { // call itemfunc with arg, on each item for (counternode_t *node = ctrs->head; node != NULL; node = node->next) { (*itemfunc)(arg, node->key, node->count); } } } // Deleting counter void counters_delete(counters_t *ctrs) { if (ctrs != NULL) { for (counternode_t *node = ctrs->head; node != NULL;) { counternode_t *next = node->next; // remember what comes next mem_free(node); // free the node node = next; // and move on to next } mem_free(ctrs); } } static counternode_t * // not visible outside this file counternode_new(const int key) { counternode_t *node = mem_malloc(sizeof(counternode_t)); if (node == NULL) { // error allocating memory for node; return error return NULL; } else { node->key = key; node->count = 1; node->next = NULL; return node; } }<file_sep>/common/pagedir.h #ifndef __PAGEDIR_H #define __PAGEDIR_H #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> // INITIATING A PAGE DIRECTORY TO SAVE THE HTML CODE FOR THE FOUND URLS bool pagedir_init(const char* pageDirectory); char* pagedir_add(const char* pageDirectory, int fileNumber); webpage_t* pagedir_load(FILE* fp); bool pagedir_val(const char* pageDirectory); // SAVIING THE HTML TO THE INITIATED PAGE DIRECTORY void pagedir_save(const webpage_t* page, const char* pageDirectory, const int docID); #endif // __PAGEDIR_H<file_sep>/crawler/testing.sh // TEST CASES // MORE THAN 3 ARGUMENTS ./crawler http://cs50tse.cs.dartmouth.edu/tse/letters/index.html ../data/letters 12 3 // DEPTH OUT OF RANGE ./crawler http://cs50tse.cs.dartmouth.edu/tse/letters/index.html ../data/letters 12 // EXTERNAL URL ./crawler http://www.google.com/ ../data/letters 10 // INVALID DIRECTORY ./crawler http://cs50tse.cs.dartmouth.edu/tse/letters/index.html ../dataa/ 1 // VALGRIND TEST NO TOSCRAPE DEPTH 1 valgrind ./crawler http://cs50tse.cs.dartmouth.edu/tse/toscrape/index.html ../data/toscrape 1 // LETTERS AT DEPTH 0, 1, 2, 10 ./crawler http://cs50tse.cs.dartmouth.edu/tse/letters/index.html ../data/letters 0 ./crawler http://cs50tse.cs.dartmouth.edu/tse/letters/index.html ../data/letters 1 ./crawler http://cs50tse.cs.dartmouth.edu/tse/letters/index.html ../data/letters 2 ./crawler http://cs50tse.cs.dartmouth.edu/tse/letters/index.html ../data/letters 10 // TOSCRAPE AT DEPTH 0, 1, 2, 10 ./crawler http://cs50tse.cs.dartmouth.edu/tse/toscrape/index.html ../data/toscrape 0 ./crawler http://cs50tse.cs.dartmouth.edu/tse/toscrape/index.html ../data/toscrape 1 ./crawler http://cs50tse.cs.dartmouth.edu/tse/toscrape/index.html ../data/toscrape 2 ./crawler http://cs50tse.cs.dartmouth.edu/tse/toscrape/index.html ../data/toscrape 3 // WIKIPEDIA AT DEPTH 0, 1 ./crawler http://cs50tse.cs.dartmouth.edu/tse/wikipedia ../data/wikipedia 0 ./crawler http://cs50tse.cs.dartmouth.edu/tse/wikipedia ../data/wikipedia 1 ./crawler http://cs50tse.cs.dartmouth.edu/tse/wikipedia ../data/wikipedia 2<file_sep>/querier/IMPLEMENTATION.md # Implementation spec ## Index * [Data structures](#Data-structures) * [Control flow](#Control-flow) * [Function prototypes](#Function-prototypes) * [Major data structures](#Major-data-structures) * [High-level pseudo code](#High-level-pseudo-code) * [Testing plan](##Testing-plan,-including-unit-tests,-integration-tests,-system-tests) ## Data structures We use 2 primary data structures: the index, which is a wrapper data structure for the hashtable, and the array data structure to hold the scores for each document. ## Control flow The querier.c is broken into 6 functions described below: ### main The main parses the arguments, validates the files and directories, cpounts the number of files in the inputed directory, initializes the index, and ultimately calls `_querier`. ### parse Parse takes in the `index` and the `line` and inserts the line into the index. ### pageDir_files Takes in the `pageDir`, counts the number of files in it, and returns the integer. ### tokenize Tokenize takes in the `token` array and the `query`, and inputs the words from the `query` into `token`. ```text= for x in query length if query[x] == '\n': query[x] = '\0' break if query[x] == ' ': if the letter before this not a space increment the total number of words by 1 (wordnum++) set query[x] = '\0' else: if the letter before is a space: tokens[wordnum] = address of query[x] ``` ### _querier _querier takes in the `index`, the `pageDir` and the number of files in `pageDir`. ```text= read query from stdin normalize the query tokenize the query Print the normalized query Create the document array[numOfFiles][numOfWordsinQuery] that stores the scores as a 2D array, of [docId][wordCount] Check if the first or last element of the array are negative, i.e. 'and' 'or' Check if consecutive words are (and, and), (and, or), (or, or), or (or, and) Count the number of 'or's in the query Create max score array for each document Sort by score (in descending order), sort the index array using the same operations display results ``` ## Function prototypes ### _querier ```c= void parse(index_t* index, char* line); int pageDir_files(const char* pageDir); void load_index(index_t* index, FILE* fp); int tokenize(char* tokens[] , char* query); void _querier(index_t* index, const char* pageDir, int i); ``` ### index ```c= index_t* index_new(const int num_slots); bool index_insert(index_t* index, const char* key, int DocID); int index_get(index_t* index, const char* key, int DocID); void index_print(index_t* index, FILE *fp); void index_delete(index_t* index); void index_save(index_t* index, FILE* fp); void index_load(index_t* index, FILE* fp, void (*itemfunc)(index_t* index, char* line)); ``` ### words ```c= char* normalize_word(char* s); ``` ### pagedir ```c= bool pagedir_init(const char* pageDirectory); char* pagedir_add(const char* pageDirectory, int fileNumber); webpage_t* pagedir_load(FILE* fp); bool pagedir_val(const char* pageDirectory); void pagedir_save(const webpage_t* page, const char* pageDirectory, const int docID); ``` ## Testing plan Here is an implementation-specific testing plan. ### Unit testing Most of the units have been tested before and the only one left to test will be the querier. The querier represents the whole system and is covered below. ### Integration Tests To test the querier program we will test the program against an invalid page directory, invalid file, invalid numebr of arguments, unreadable files, unopenable files. Further, we will also test the program against invalid queries, such as: ```text= and or and earth or earth planet earth or planet earth and planet earth and or science planet earth and and science planet earth or and science ``` ### System Tests To test the system we will run the program with valgrind to check if there are any memory leaks in the program. Further, we will check for any compilation errors from the compiler.<file_sep>/indexer/indextest.c #include <stdlib.h> #include <stdio.h> #include "../libcs50/bag.h" #include "../libcs50/hashtable.h" #include "../libcs50/webpage.h" #include "../common/pagedir.h" #include "../common/index.h" #include "../libcs50/mem.h" #include "../libcs50/file.h" #include "../common/word.h" #include <string.h> typedef struct index{ hashtable_t* ht; } index_t; void parse(index_t* index, char* line){ char delim[] = " "; char cpy[strlen(line)]; strcpy(cpy, line); char *ptr = strtok(line, delim); char *word = strtok(cpy, delim); int docID = -1; int count = -1; int i = 0; while(ptr != NULL) { if(strcmp(ptr, "0") == 0){ if(i%2==1){ docID = atoi(ptr); }else{ count = atoi(ptr); for(int j = 0; j < count;j++){ index_insert(index, word, docID); } } ptr = strtok(NULL, delim); i++; continue; } if(atoi(ptr) != 0){ if(i%2==1){ docID = atoi(ptr); }else{ count = atoi(ptr); for(int j = 0; j < count;j++){ index_insert(index, word, docID); } } } ptr = strtok(NULL, delim); i++; } } int main(const int argc, const char* argv[]){ if(argc == 3){ index_t* index = index_new(300); const char* old = argv[1]; const char* new = argv[2]; FILE* fp = fopen(old, "r"); if(fp != NULL){ index_load(index, fp, parse); fclose(fp); FILE* fp1 = fopen(new, "w"); if(fp1 != NULL){ index_save(index, fp1); fclose(fp1); index_print(index, stdout); index_delete(index); }else{ fprintf(stderr, "Second file invalid...\n"); } }else{ fprintf(stderr, "First file invalid...\n"); } }else{ fprintf(stderr, "Invalid arguments...\n"); } }<file_sep>/common/Makefile # Makefile for 'set' module # # <NAME>, April 2016, 2017, 2019, 2021 # updated by <NAME>, July 2016, 2018, January 2019 OBJS = index.o pagedir.o word.o ../libcs50/bag.o ../libcs50/counters.o ../libcs50/file.o ../libcs50/hashtable.o ../libcs50/hash.o ../libcs50/mem.o ../libcs50/set.o ../libcs50/webpage.o LIB = common.a CFLAGS = -Wall -pedantic -std=c11 -ggdb $(FLAGS) CC = gcc MAKE = make # Build $(LIB) by archiving object files # (you will need to drop in copy of set.c, counters.c, hashtable.c) $(LIB): $(OBJS) ar cr $(LIB) $(OBJS) index.o: index.h pagedir.o: pagedir.h word.o: word.h bag.o: ../libcs50/bag.h counters.o: ../libcs50/counters.h file.o: ../libcs50/file.h hashtable.o: ../libcs50/hashtable.h ../libcs50/set.h ../libcs50/hash.h hash.o: ../libcs50/hash.h mem.o: ../libcs50/mem.h set.o: ../libcs50/set.h webpage.o: ../libcs50/webpage.h .PHONY: clean sourcelist # list all the sources and docs in this directory. # (this rule is used only by the Professor in preparing the starter kit) sourcelist: Makefile *.md *.c *.h @echo $^ clean: rm -f core rm -f $(LIB) *~ *.o <file_sep>/indexer/indexer.c #include <stdlib.h> #include <stdio.h> #include "../libcs50/bag.h" #include "../libcs50/hashtable.h" #include "../libcs50/webpage.h" #include "../common/pagedir.h" #include "../common/index.h" #include "../libcs50/mem.h" #include "../common/word.h" #include <string.h> #include <unistd.h> typedef struct webpage { char* url; // url of the page char* html; // html code of the page size_t html_len; // length of html code int depth; // depth of crawl } webpage_t; typedef struct index{ hashtable_t* ht; } index_t; static void indexPage(index_t* index, webpage_t* webpage, int DocId){ int* pos = mem_malloc(sizeof(int)); *pos = 0; while(true){ char* word = webpage_getNextWord(webpage, pos); if(word == NULL){ break; } if(strlen(word) <= 3){ mem_free(word); continue; } char* norm = normalize_word(word); index_insert(index, norm, DocId); mem_free(word); mem_free(norm); } mem_free(pos); } static void indexBuild(const char* pageDirectory, FILE* fp){ index_t* index = index_new(300); int i = 0; while(true){ char* path = pagedir_add(pageDirectory, i); FILE *fp = fopen(path, "r"); if(fp == NULL){ mem_free(path); break; } mem_free(path); webpage_t* wp = pagedir_load(fp); if(wp != NULL){ indexPage(index, wp, i); } i += 1; webpage_delete(wp); fclose(fp); } index_save(index, fp); fclose(fp); index_print(index, stdout); index_delete(index); } int main(const int argc, const char* argv[]){ if(argc == 3){ const char* pagedir = argv[1]; const char* filepath = argv[2]; int r; int e; r = access(filepath, R_OK); e = access(filepath, F_OK); if( e == -1 ){ fprintf(stderr,"File does not exist...\n"); exit(1); } if( r == -1 ){ fprintf(stderr,"File not readable...\n"); exit(1); } if(pagedir_val(pagedir)){ FILE* fp; if((fp = fopen(filepath, "w+")) != NULL){ indexBuild(pagedir, fp); }else{ fprintf(stderr, "Could not open file...\n"); } }else{ fprintf(stderr, "Page Directory Invalid...\n"); } }else{ fprintf(stderr, "Invalid arguments...\n"); } }<file_sep>/libcs50/set.c /* * set.c - CS50 'set' module * * see set.h for more information. * * @Author <NAME> * Module for creating a set data structure */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "set.h" #include "mem.h" // Set node struct typedef struct setnode { char *key; void *item; struct setnode *next; } setnode_t; // Set struct typedef struct set { struct setnode *head; int size; } set_t; // Function prototype for creating new setnode static setnode_t *setnode_new(char *key, void *item); // Creating a new set set_t * set_new(void) { set_t *set = (set_t *)mem_malloc(sizeof(set_t)); if (set == NULL) { return NULL; // error allocating set } else { // initialize contents of set structure set->head = NULL; set->size = 0; return set; } } // Inserting key:item pair into set bool set_insert(set_t *set, const char *key, void *item) { if (set != NULL && key != NULL && item != NULL) { char *keycpy = (char *)mem_malloc((strlen(key)+1) * sizeof(char)); strcpy(keycpy, key); setnode_t *temp; temp = set->head; while (temp != NULL) { if (strcmp(temp->key, keycpy) == 0) { free(keycpy); return false; } temp = temp->next; } // allocate a new node to be added to the list setnode_t *new = setnode_new(keycpy, item); if (new != NULL) { // add it to the head of the list new->next = set->head; set->head = new; set->size += 1; return true; } } return false; #ifdef MEMTEST mem_report(stdout, "After set_insert"); #endif } // Finding item with corresponding key void *set_find(set_t *set, const char *key) { if (set != NULL && key != NULL) { setnode_t *temp; temp = set->head; while (temp != NULL) { if (strcmp(temp->key, key) == 0) { return (temp->item); } temp = temp->next; } } return NULL; } // Printing the set void set_print(set_t *set, FILE *fp, void (*itemprint)(FILE *fp, const char *key, void *item)) { if (fp != NULL) { if (set != NULL) { fputc('{', fp); for (setnode_t *node = set->head; node != NULL; node = node->next) { // print this node if (itemprint != NULL) { // print the node's item (*itemprint)(fp, node->key, node->item); if (node->next != NULL) { fputc(',', fp); } } } fputc('}', fp); } else { fputs("(null)", fp); } printf("\n"); } } // Iterating through the set void set_iterate(set_t *set, void *arg, void (*itemfunc)(void *arg, const char *key, void *item)) { if (set != NULL && itemfunc != NULL) { // call itemfunc with arg, on each item for (setnode_t *node = set->head; node != NULL; node = node->next) { (*itemfunc)(arg, node->key, node->item); } } } // Deleting the set void set_delete(set_t *set, void (*itemdelete)(void *item)) { if (set != NULL) { for (setnode_t *node = set->head; node != NULL;) { if (itemdelete != NULL) { // if possible... (*itemdelete)(node->item); // delete node's item } setnode_t *next = node->next; // remember what comes next char* key = node->key; mem_free(key); mem_free(node); // free the node node = next; // and move on to next } mem_free(set); set = NULL; } #ifdef MEMTEST mem_report(stdout, "End of set_delete"); #endif } static setnode_t * // not visible outside this file setnode_new(char *key, void *item) { setnode_t *node = mem_malloc(sizeof(setnode_t)); if (node == NULL) { // error allocating memory for node; return error return NULL; } else { node->key = key; node->item = item; node->next = NULL; return node; } }<file_sep>/common/index.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../libcs50/mem.h" #include "../libcs50/counters.h" #include "../libcs50/hashtable.h" #include "../libcs50/set.h" #include "../libcs50/hash.h" typedef struct index{ hashtable_t* ht; } index_t; static void index_print_helper(FILE* fp, const char* key, void* item); static void index_delete_helper(void* item); static void index_iterate_helper(void* arg, const char* key, void* item); static void counters_iterate_helper(void *arg, const int key, const int count); index_t* index_new(const int num_slots){ if(num_slots < 1){ return NULL; } index_t* index = (index_t*)mem_malloc(sizeof(index_t)); if(index != NULL){ index->ht = hashtable_new(num_slots); } return index; } bool index_insert(index_t* index, const char* key, int DocID){ if(index != NULL && key != NULL){ if(hashtable_find(index->ht, key) == NULL){ counters_t* c = counters_new(); counters_add(c, DocID); return hashtable_insert(index->ht, key, c); } counters_t* c = hashtable_find(index->ht, key); counters_add(c, DocID); return true; } return false; } int index_get(index_t* index, const char* key, int DocID){ if(index != NULL && key != NULL){ if(hashtable_find(index->ht, key) != NULL){ counters_t* c = hashtable_find(index->ht, key); return counters_get(c, DocID); } } return 0; } void index_print(index_t* index, FILE *fp){ if(index != NULL && fp != NULL){ hashtable_print(index->ht, fp, index_print_helper); } } void index_delete(index_t* index){ if(index != NULL){ hashtable_delete(index->ht, index_delete_helper); mem_free(index); } } void index_save(index_t* index, FILE* fp){ if(index != NULL && fp != NULL){ hashtable_iterate(index->ht, fp, index_iterate_helper); } } void index_load(index_t* index, FILE* fp, void (*itemfunc)(index_t* index, char* line)){ char* line; while((line = file_readLine(fp)) != NULL){ if(itemfunc != NULL){ itemfunc(index, line); } mem_free(line); } mem_free(line); } static void index_iterate_helper(void* arg, const char* key, void* item){ fputs(key, arg); fputs(" ", arg); counters_iterate(item, arg, counters_iterate_helper); fputs("\n", arg); } static void counters_iterate_helper(void *arg, const int key, const int count){ char keyc[10]; char countc[10]; sprintf(keyc, "%d", key); sprintf(countc, "%d", count); fputs(keyc, arg); fputs(" ", arg); fputs(countc, arg); fputs(" ", arg); } static void index_print_helper(FILE* fp, const char* key, void* item){ const char *keyname = key; counters_t* ct = item; fprintf(fp, "%s", keyname); counters_print(ct, fp); } static void index_delete_helper(void* item){ counters_t* ct = item; counters_delete(ct); } // int main(const int argc, const char* argv[]){ // index_t* i = index_new(200); // if(i == NULL){ // printf("Failed\n"); // } // index_insert(i, "word", 1); // index_insert(i, "word", 2); // bool x = index_insert(i, "word", 1); // if(x){ // printf("Success\n"); // } // index_print(i, stdout); // return 0; // }<file_sep>/querier/README.md # <NAME> ## CS50 Spring 2021, Lab 6 GitHub username: ZimehrAbbasi Since this is the last lab of the class, I tried using my own intuition to solve this querier problem, not using any of the hints. ## ASSUMPTIONS The primary assumption this querier is that the total number of words in the query will be less than 50. ## LIMITATIONS This program is limited by the amount of storage space available in the device.<file_sep>/indexer/testing.sh ./indexer ./indexer ./indexer ./indexer ./indexer ../data/invaliddir ../data/out ../data/invaliddir ../data/out ./indexer ../data/invaliddir ../data/out ./indexer ../data/letters ../data/unreadable.txt ./indexer ../data/letters ../data/letters.index ./indexer ../data/toscrape ../data/toscrape.index ./indexer ../data/wikipedia ../data/wikipedia.index ./indextest ../data/letters.index ../data/lettersnew.index ./indextest ../data/toscrape.index ../data/toscrapenew.index ./indextest ../data/wikipedia.index ../data/wikipedianew.index<file_sep>/querier/querier.c #include <stdlib.h> #include <stdio.h> #include "../libcs50/bag.h" #include "../libcs50/hashtable.h" #include "../libcs50/webpage.h" #include "../common/pagedir.h" #include "../common/index.h" #include "../libcs50/mem.h" #include "../libcs50/file.h" #include "../libcs50/set.h" #include "../common/word.h" #include <string.h> #include <unistd.h> #define BUFFERSIZE 200 #define INT_MAX 2147483647 typedef struct index{ hashtable_t* ht; } index_t; void parse(index_t* index, char* line); int pageDir_files(const char* pageDir); void load_index(index_t* index, FILE* fp); int tokenize(char* tokens[] , char* query); void _querier(index_t* index, const char* pageDir, int i); int pageDir_files(const char* pageDir){ int i = 0; while(true){ char* path = pagedir_add(pageDir, i); FILE *fp = fopen(path, "r"); if(fp == NULL){ mem_free(path); break; } mem_free(path); i += 1; fclose(fp); } return i; } int tokenize(char* tokens[] , char* query){ int querylength = strlen(query); bool space = true; int words = 0; for(int i = 0; i< querylength;i++){ if(query[i] == '\n'){ query[i] = '\0'; break; } if(query[i] == ' '){ if(space == false){ query[i] = '\0'; words += 1; } space = true; }else{ if(space == true){ tokens[words] = &query[i]; } space = false; } } words += 1; return words; } void parse(index_t* index, char* query){ int querylength = strlen(query); bool space = true; int words = 0; char* firstword; char* count; char* Id; for(int i = 0; i< querylength;i++){ if(query[i] == ' '){ if(space == false){ query[i] = '\0'; if(words % 2 == 0 && words != 0){ for(int j = 0; j<atoi(count);j++){ index_insert(index, firstword, atoi(Id)); } } words += 1; } space = true; }else{ if(space == true){ if(i == 0){ firstword = &query[i]; space = false; continue; } if(words%2 == 1){ Id = &query[i]; }else{ count = &query[i]; } } space = false; } } words += 1; } void load_index(index_t* index, FILE* fp){ char* line; while((line = file_readLine(fp)) != NULL){ parse(index, line); mem_free(line); } mem_free(line); } void _querier(index_t* index, const char* pageDir, int i){ char *line = calloc(1,1), buffer[BUFFERSIZE]; while(fgets(buffer, BUFFERSIZE, stdin)) { line = realloc(line, strlen(line)+1+strlen(buffer)); if(!line){ printf("----------------------------------------------------------------------------------"); exit(1); } strcat(line, buffer); } char* query = normalize_word(line); mem_free(line); char *tokens[50]; int words = tokenize(tokens, query); // Print the normalized query int weights[words]; printf("Query: "); for(int j = 0; j < words; j++){ weights[j] = 0; printf("%s ", tokens[j]); } printf("\n"); // Assign 1 to 'and', 2 to 'or' for(int j = 0; j < words; j++){ if(strcmp(tokens[j], "and")==0){ weights[j] = 1; } if(strcmp(tokens[j], "or")==0){ weights[j] = 2; } } // Create the document array that stores the scores as a 2D array int docArray[i][words]; for(int j = 0; j < i; j++){ char in[10]; sprintf(in, "%d", i); for(int k = 0; k < words; k++){ if(weights[k] == 0){ int num = index_get(index, tokens[k], j); docArray[j][k] = num; }else{ if(weights[k] == 1){ docArray[j][k] = -1; } if(weights[k] == 2){ docArray[j][k] = -2; } } } } mem_free(query); // Check for invalid entries //Check if the first or last element of the array are negative, i.e. 'and' 'or' if(docArray[0][0] < 0 || docArray[0][words-1] < 0){ fprintf(stderr, "Invalid query...\n"); exit(1); } // Check if consecutive words are (and, and), (and, or), (or, or), or (or, and) for(int x = 0; x < words-1; x++){ if(docArray[0][x] < 0 && docArray[0][x+1] < 0){ fprintf(stderr, "Invalid query...\n"); exit(1); } } // For no precedence // for(int x = 0; x < i; x++){ // int cur = 0; // for(int y = 0; y< words;y++){ // if(docArray[x][y] == 0){ // if(cur > docArray[x][y]){ // cur = docArray[x][y] // } // } // if(docArray[x][y] == -1){ // if(y != words-1){ // if(docArray[x][y+1] < cur){ // cur = docArray[x][y+1] // } // } // } // if(docArray[x][y] == -2){ // if(y != words-1){ // cur += docArray[x][y+1] // } // } // } // } // Check the number of 'or's in the query int orCount = 0; for(int y = 0; y< words;y++){ if(docArray[0][y] == -2){ orCount += 1; } } int orArray[i][orCount+1]; for(int x = 0; x < i; x++){ int min = INT_MAX; int ticker = 0; for(int y = 0; y< words;y++){ if(docArray[x][y] == -2){ orArray[x][ticker] = min; ticker += 1; min = INT_MAX; continue; } if(docArray[x][y] == -1){ continue; } if(docArray[x][y] < min){ min = docArray[x][y]; orArray[x][ticker] = min; } } orArray[x][ticker] = min; } int scoreArray[i]; int sortedIndex[i]; // Create max score array for each document for(int x = 0; x < i; x++){ int sum = 0; for(int y = 0; y< orCount+1;y++){ sum += orArray[x][y]; } scoreArray[x] = sum; sortedIndex[x] = x; } // Sort by score, sort the index array in the same way for(int x = 0; x < i; x++){ for(int y = 0; y< i;y++){ if(scoreArray[y] < scoreArray[x]){ int temp1 = scoreArray[x]; scoreArray[x] = scoreArray[y]; scoreArray[y] = temp1; int temp2 = sortedIndex[x]; sortedIndex[x] = sortedIndex[y]; sortedIndex[y] = temp2; } } } printf("\nSearch Results: \n"); for(int x = 0; x < i; x++){ if(scoreArray[x] == 0){ continue; } char *path = pagedir_add(pageDir, x); FILE *fp = fopen(path, "r"); if(fp == NULL){ mem_free(path); break; } char *line = file_readLine(fp); printf("Score: %4d Document: %4d URL: %4s\n", scoreArray[x], sortedIndex[x], line); mem_free(line); mem_free(path); fclose(fp); } printf("----------------------------------------------------------------------------------\n"); } int main(const int argc, const char* argv[]){ if(argc == 3){ const char* pagedir = argv[1]; const char* filepath = argv[2]; int r; int e; r = access(filepath, R_OK); e = access(filepath, F_OK); if( e == -1 ){ fprintf(stderr,"File does not exist...\n"); exit(1); } if( r == -1 ){ fprintf(stderr,"File not readable...\n"); exit(1); } printf("Staring processes...\n"); if(pagedir_val(pagedir)){ FILE* fp; if((fp = fopen(filepath, "r")) != NULL){ printf("Creating index object...\n"); index_t* index = index_new(300); printf("Loading in index...\n"); load_index(index, fp); printf("----------------------------------------------------------------------------------"); int num_files = pageDir_files(pagedir); while(true){ printf("\nQuery? "); break; } _querier(index, pagedir, num_files); index_delete(index); fclose(fp); }else{ fprintf(stderr, "Could not open file...\n"); } }else{ fprintf(stderr, "Page Directory Invalid...\n"); } }else{ fprintf(stderr, "Invalid arguments...\n"); } } <file_sep>/common/word.h #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <ctype.h> char* normalize_word(char* s);<file_sep>/crawler/README.md # <NAME> ## CS50 Spring 2021, Lab 4 GitHub username: ZimehrAbbasi ## ASSUMPTIONS The primary assumption this crawler works on is that the directory used to store the pages has already been created. ## LIMITATIONS This program is limited by the amount of storage space available in the device.
11368e826967227d8e173b9afaeb6289435fb7b1
[ "Markdown", "C", "Makefile", "Shell" ]
23
Markdown
ZimehrAbbasi/Search-Engine
9fd3b6287de06c9020cbac3a21bb2af53167923d
21dd98f733d3e7ee8a9339ac452f90728e0dd0b8
refs/heads/master
<file_sep>package org.sevenstar.app.config.action; import java.util.List; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.config.domain.S_configureDomain; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import org.sevenstar.web.annotation.SSList; @SSAction(name = "s_configure") public class S_configureAction extends DefaultAction { private S_configureDomain s_configureDomain; @SSList(type = "org.sevenstar.app.config.action.S_configureAction") private List configureList; public String deleteList() { if (configureList == null) { throw new ApplicationException("请先选中一项"); } for (int i = 0; i < configureList.size(); i++) { S_configureDomain domain = (S_configureDomain) configureList.get(i); domain.delete(); } return "批量删除成功"; } public String insertOrUpdate() { if (s_configureDomain == null) { throw new ApplicationException("没有录入信息"); } s_configureDomain.insertOrUpdate(); return "编辑配置类型[" + s_configureDomain.getName() + "]成功"; } public S_configureDomain getS_configureDomain() { return s_configureDomain; } public void setS_configureDomain(S_configureDomain domain) { s_configureDomain = domain; } public List getConfigureList() { return configureList; } public void setConfigureList(List configureList) { this.configureList = configureList; } } <file_sep>package org.sevenstar.app.monitor.domain; import java.util.Date; import org.sevenstar.app.manager.domain.S_userDomain; import org.sevenstar.app.module.domain.S_moduleDomain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSOneToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; import org.sevenstar.persistent.db.find.annotation.model.SSProperty; @SSDomain(table = "s_monitor_exception") @SSId(generateType = "seq", seq = "seq_monitor") public class S_monitor_exceptionDomain extends PersistentObject { @SSPrimaryKey private Long id; private String url; private String message; @SSManyToOne(parameter = "userDomain.id", column = "user_id") private S_userDomain userDomain; @SSManyToOne(parameter = "moduleDomain.id", column = "module_id") private S_moduleDomain moduleDomain; @SSProperty(value = "sysdate") private Date create_date; private String key_param0; private String key_param1; private String key_param2; @SSOneToOne(column = "exception_id") private S_monitor_exception_detailDomain detailDomain; public S_monitor_exception_detailDomain getDetailDomain() { return detailDomain; } public void setDetailDomain(S_monitor_exception_detailDomain detailDomain) { this.detailDomain = detailDomain; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public S_userDomain getUserDomain() { return userDomain; } public void setUserDomain(S_userDomain userDomain) { this.userDomain = userDomain; } public S_moduleDomain getModuleDomain() { return moduleDomain; } public void setModuleDomain(S_moduleDomain moduleDomain) { this.moduleDomain = moduleDomain; } public Date getCreate_date() { return create_date; } public void setCreate_date(Date create_date) { this.create_date = create_date; } public String getKey_param0() { return key_param0; } public void setKey_param0(String key_param0) { this.key_param0 = key_param0; } public String getKey_param1() { return key_param1; } public void setKey_param1(String key_param1) { this.key_param1 = key_param1; } public String getKey_param2() { return key_param2; } public void setKey_param2(String key_param2) { this.key_param2 = key_param2; } } <file_sep>var jiang_totalSize; var jiang_currentPage=0; var jiang_pageSize = 5; var jiangList; var jiangTitleSize = 50; var jiangBaseUrl ; function jiang_init(_jiangList,baseUrl){ jiangList = eval('(' + _jiangList + ')'); jiangBaseUrl = baseUrl; jiang_totalSize = jiangList.length; jiang_generatePage(); jiang_go2Page(1); } function jiang_generatePage(){ var pagehtml="<a href=\"javascript:jiang_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<jiang_totalSize/jiang_pageSize;i++){ var id = i+1; pagehtml+="<a id=jiang_"+id+" href=\"javascript:jiang_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:jiang_goNext()\" class=\"next\">下一页</a>" $("#jiang_page").html(pagehtml) } function jiang_goPrev(){ if(jiang_currentPage>0){ jiang_go2Page(jiang_currentPage); } } function jiang_goNext(){ if(jiang_currentPage<(jiang_totalSize/jiang_pageSize-1)){ jiang_go2Page(jiang_currentPage+2); } } function jiang_go2Page(id){ jiang_currentPage = id-1; var html=""; for(var i = jiang_currentPage*jiang_pageSize;i<(jiang_currentPage+1)*jiang_pageSize&&i<jiang_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+jiangBaseUrl+"/student/content/detail.html?id="+jiangList[i].id+"\" title="+jiangList[i].title+" href=\"#\" title="+jiangList[i].title+"><span class=\"new\">"; var tempTitle; if(jiangList[i].title.length>jiangTitleSize){ tempTitle = jiangList[i].title.substring(0,jiangTitleSize)+"..."; }else{ tempTitle = jiangList[i].title; } html+=tempTitle+"</span>"; html+="</a>"; } $("#jiang").empty(); $("#jiang").append(html); //设置点中的样式 for(var i=1;i<=jiang_totalSize/jiang_pageSize;i++){ $("#jiang_"+i).attr("class",""); } $("#jiang_"+id).attr("class","cur"); } <file_sep>$(function(){ //banner区选项卡 var imgArray = (function() { var a = [], banLengh, imgLength, bans, imgs; bans = $('.banner .ban'); banLengh = bans.length; for (var i=0; i<banLengh; i++) { imgs = bans.eq(i).find('ul img'); imgLength = imgs.length; a[i] = []; for (var j=0; j<imgLength; j++) { a[i][j] = imgs.eq(j).attr('src'); } } return a; }()); var imgIndex = []; for (var k=0; k<imgArray.length; k++) { imgIndex[k] = 0; } $('.t_js').on('click',function(){ var $this = $(this); var index = $this.index(); $this.parent().get(0).className = 'nav color_' + (index + 1); if (imgIndex[index] >= imgArray[index].length) { imgIndex[index] = 0; } $this.addClass('cur') .siblings().removeClass('cur'); $('.banner .ban').eq(index).find(' > img').attr('src', imgArray[index][imgIndex[index]++]) .end().show(300).siblings('.c_js').hide(300); }); setInterval(function(){ var i = $('.t_js.cur').index(); i < ($('.t_js').length-1) ? i++ : i = 0; $('.t_js').eq(i).trigger('click'); },8000); //gallery $('.gallery_js .prev').on('click',function(){ var $this = $(this); var $hid = $this.siblings('.hid'); var li_n = $hid.find('li').length; var li_w = $hid.find('li').width(); var ul_w = li_w * li_n; var $ul = $hid.find('ul'); var mag = parseInt($ul.css('margin-left'),10); $ul.css('width',ul_w); if(!$ul.is(':animated')){ if (mag <= li_w - ul_w) { $ul.animate({'margin-left':'0'},400); } else { $ul.animate({'margin-left':(mag - li_w) + 'px'},400); } } }); $('.gallery_js .next').on('click',function(){ var $this = $(this); var $hid = $this.siblings('.hid'); var li_n = $hid.find('li').length; var li_w = $hid.find('li').width(); var ul_w = li_w * li_n; var $ul = $hid.find('ul'); var mag = parseInt($ul.css('margin-left'),10); $ul.css('width',ul_w); if(!$ul.is(':animated')){ if (mag >= 0) { $ul.animate({'margin-left':(li_w - ul_w) +'px'},400); } else { $ul.animate({'margin-left':(mag + li_w) + 'px'},400); } } }); setInterval(function(){ $('.gallery_js .prev').trigger('click'); },6000); //header部分sub_nav $('.header .sub_nav .last').hover(function(){ $(this).addClass('down'); },function(){ $(this).removeClass('down'); }); $(function(){ // -- Constants -- var PLACE_HOLDER_COLOR = "rgb(169,169,169)"; // "darkGrey" does not work in IE6 var PLACE_HOLDER_DATA_NAME = "original-font-color"; // -- Util Methods -- var getContent = function(element){ return $(element).val(); } var setContent = function(element, content){ $(element).val(content); } var getPlaceholder = function(element){ return $(element).attr("placeholder"); } var isContentEmpty = function(element){ var content = getContent(element); return (content.length === 0) || content == getPlaceholder(element); } var setPlaceholderStyle = function(element){ $(element).data(PLACE_HOLDER_DATA_NAME, $(element).css("color")); $(element).css("color", PLACE_HOLDER_COLOR); } var clearPlaceholderStyle = function(element){ $(element).css("color", $(element).data(PLACE_HOLDER_DATA_NAME)); $(element).removeData(PLACE_HOLDER_DATA_NAME); } var showPlaceholder = function(element){ setContent(element, getPlaceholder(element)); setPlaceholderStyle(element); } var hidePlaceholder = function(element){ if($(element).data(PLACE_HOLDER_DATA_NAME)){ setContent(element, ""); clearPlaceholderStyle(element); } } // -- Event Handlers -- var inputFocused = function(){ if(isContentEmpty(this)){ hidePlaceholder(this); } } var inputBlurred = function(){ if(isContentEmpty(this)){ showPlaceholder(this); } } var parentFormSubmitted = function(){ if(isContentEmpty(this)){ hidePlaceholder(this); } } // -- Bind event to components -- $("textarea, input[type='text']").each(function(index, element){ if($(element).attr("placeholder")){ $(element).focus(inputFocused); $(element).blur(inputBlurred); $(element).bind("parentformsubmitted", parentFormSubmitted); // triggers show place holder on page load $(element).trigger("blur"); // triggers form submitted event on parent form submit $(element).parents("form").submit(function(){ $(element).trigger("parentformsubmitted"); }); } }); }); $('.ban .pic li img').click(function(){ $(this).parents('.ban').find('>img').attr('src', $(this).attr('src')); }); });<file_sep>package cn.edu.zjut.web.page.gjxy; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_menu_contentDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_resourceDomain; import cn.edu.zjut.cfg.domain.Zjut_resource_typeDomain; import cn.edu.zjut.cfg.service.Zjut_menu_contentService; public class Menu extends DefaultAction { private Zjut_menu_contentDomain zjut_menu_contentDomain; private IbatisPage page = new IbatisPage(); private static Zjut_organizationDomain organizationDomain; private static Zjut_resource_typeDomain resource_typeDomain; static { organizationDomain = new Zjut_organizationDomain(); organizationDomain.setName("international-college"); organizationDomain.loadEqual(); resource_typeDomain = new Zjut_resource_typeDomain(); resource_typeDomain.setName("course"); resource_typeDomain.loadEqual(); } public String about_college() { getMenuDomain("about_college"); return super.SUCCESS; } public String major() { getMenuDomain("major"); return super.SUCCESS; } public String recruit_students() { Pattern ptn = Pattern.compile("recruit_stu_(\\d{4})", Pattern.CASE_INSENSITIVE); getMenuDomain("recruit_students"); Map yearMap = new HashMap(); List childs = this.zjut_menu_contentDomain.getChildList(); for (int i = 0; i < childs.size(); i++) { Zjut_menu_contentDomain domain = (Zjut_menu_contentDomain) childs.get(i); String menu_name = domain.getMenu_name(); Matcher match = ptn.matcher(menu_name); if( match.matches()){ String year = match.group(1); yearMap.put(year, domain); } } Object[] keys = yearMap.keySet().toArray(); Arrays.sort(keys); List finalChilds = new ArrayList(); for(int i = keys.length-1;i >=0;i--){ if(finalChilds.size()>=3){ break; } finalChilds.add(yearMap.get(keys[i])); } zjut_menu_contentDomain.setChildList(finalChilds); return super.SUCCESS; } public String teach() { Zjut_organization_resourceDomain organization_resourceDomain = new Zjut_organization_resourceDomain(); organization_resourceDomain.setOrganizationDomain(organizationDomain); organization_resourceDomain.setResourceTypeDomain(resource_typeDomain); page.setPagesize(10); page = organization_resourceDomain.getSelectPage(page); getMenuDomain("teach"); return super.SUCCESS; } public String research() { getMenuDomain("research"); return super.SUCCESS; } public String schoolfellow() { getMenuDomain("schoolfellow"); return super.SUCCESS; } private void getMenuDomain(String menuName) { zjut_menu_contentDomain = Zjut_menu_contentService.instance .getMenuDomain(menuName, organizationDomain.getName()); } public Zjut_menu_contentDomain getZjut_menu_contentDomain() { return zjut_menu_contentDomain; } public void setZjut_menu_contentDomain( Zjut_menu_contentDomain zjut_menu_contentDomain) { this.zjut_menu_contentDomain = zjut_menu_contentDomain; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } // public static void main(String[] ben){ // Pattern ptn = Pattern.compile("recruit_stu_(\\d{4})", Pattern.CASE_INSENSITIVE); // Zjut_menu_contentDomain zjut_menu_contentDomain = Zjut_menu_contentService.instance // .getMenuDomain("recruit_students", organizationDomain.getName()); // Map yearMap = new HashMap(); // List childs = zjut_menu_contentDomain.getChildList(); // System.out.println(childs.size()); // for (int i = 0; i < childs.size(); i++) { // Zjut_menu_contentDomain domain = (Zjut_menu_contentDomain) childs.get(i); // String menu_name = domain.getMenu_name(); // Matcher match = ptn.matcher(menu_name); // if( match.matches()){ // String year = match.group(1); // yearMap.put(year, domain); // } // } // // Object[] keys = yearMap.keySet().toArray(); // Arrays.sort(keys); // // List finalChilds = new ArrayList(); // for(int i = 0;i < keys.length;i++){ // finalChilds.add(yearMap.get(keys[i])); // } // System.out.println(finalChilds.size()); // } } <file_sep>package org.sevenstar.app.monitor.service; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.PreparedStatement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.app.config.service.S_configureService; import org.sevenstar.app.module.domain.S_moduleDomain; import org.sevenstar.app.monitor.domain.S_monitor_exceptionDomain; import org.sevenstar.app.monitor.domain.S_monitor_exception_detailDomain; import org.sevenstar.persistent.db.ibatis.MyAppSqlConfig; import org.sevenstar.web.context.WebContext; import org.stringtree.json.JSONWriter; public class S_monitor_exceptionService { private static Log LOG = LogFactory .getLog(S_monitor_exceptionService.class); public static S_monitor_exceptionService instance = new S_monitor_exceptionService(); public static void main(String[] args) { String num = null; try { num.indexOf("d"); } catch (Exception e) { S_monitor_exceptionService.instance.log(e); } } public void log(String message) { if ("true".equalsIgnoreCase(S_configureService.instance .get("monitor_login_expire")) || "Y".equalsIgnoreCase(S_configureService.instance .get("monitor_login_expire"))) { String sql = "insert into s_monitor_exception (id,message,url,create_date)" + "values(seq_monitor.nextval,sysdate,?,?,sysdate)"; Connection conn = null; PreparedStatement ps = null; try { conn = MyAppSqlConfig.getSqlMapInstance().getDataSource() .getConnection(); ps = conn.prepareStatement(sql); ps.setString(1, message); ps.setString(2, WebContext.getUrl()); ps.execute(); if (!conn.getAutoCommit()) { conn.commit(); } } catch (RuntimeException e) { LOG.error(e); } catch (Exception e) { LOG.error(e); } finally { try { if (ps != null) { ps.close(); ps = null; } } catch (Exception e1) { LOG.error(e1); } try { if (conn != null && !conn.isClosed()) { conn.close(); conn = null; } } catch (Exception e1) { LOG.error(e1); } } } } public void log(Throwable exception) { if (exception == null || exception.getCause() == null) { // pass return; } try { if ("true".equalsIgnoreCase(S_configureService.instance .get("monitor_error")) || "Y".equalsIgnoreCase(S_configureService.instance .get("monitor_error"))) { S_monitor_exceptionDomain domain = new S_monitor_exceptionDomain(); domain.setMessage(exception.getMessage()); domain.setUrl(WebContext.getUrl()); if (ApplicationContext.hasLogin()) { domain.setUserDomain(ApplicationContext.get()); } if (WebContext.getUrl() != null) { S_moduleDomain moduleDomain = (new S_moduleDomain()) .getS_moduleDomain(WebContext.getUrl()); domain.setModuleDomain(moduleDomain); } domain.insert(); S_monitor_exception_detailDomain detailDomain = new S_monitor_exception_detailDomain(); StringBuffer sb = new StringBuffer(); Throwable trowable = exception; while (trowable.getCause() != null) { if (trowable instanceof InvocationTargetException) { trowable = ((InvocationTargetException) trowable) .getTargetException(); } trowable = trowable.getCause(); } StackTraceElement stack[] = trowable.getStackTrace(); if (stack != null) { for (int i = 0; i < stack.length; i++) { StackTraceElement ste = (StackTraceElement) stack[i]; String str = ste.getClassName() + "," + ste.getMethodName() + "[" + ste.getFileName() + ":" + ste.getLineNumber() + "]<br>"; sb.append(str); } } detailDomain.setStacktrace(sb.toString()); detailDomain.setMainDomain(domain); /** * 取请求parameter */ if (WebContext.getRequestParameterMap() != null && WebContext.getRequestParameterMap().size() > 0) { JSONWriter jsonWriter = new JSONWriter(); detailDomain.setRequest(jsonWriter.write(WebContext .getRequestParameterMap())); } detailDomain.insert(); } } catch (Throwable e) { LOG.error(e); } } } <file_sep>package org.sevenstar.app.rbac.relation.domain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; @SSDomain(table="s_rbac_rolemodule") @SSId(generateType="seq",seq="seq_app") public class S_rbac_rolemoduleDomain extends PersistentObject { @SSPrimaryKey private java.lang.Long id; @SSManyToOne(parameter="roleDomain.id",column="role_id") private org.sevenstar.app.rbac.domain.S_rbac_roleDomain roleDomain; @SSManyToOne(parameter="moduleDomain.id",column="module_id") private org.sevenstar.app.module.domain.S_moduleDomain moduleDomain; public void setId(java.lang.Long id) { this.id = id; } public java.lang.Long getId() { return this.id; } public void setRoleDomain( org.sevenstar.app.rbac.domain.S_rbac_roleDomain roleDomain) { this.roleDomain = roleDomain; } public org.sevenstar.app.rbac.domain.S_rbac_roleDomain getRoleDomain() { return this.roleDomain; } public void setModuleDomain( org.sevenstar.app.module.domain.S_moduleDomain moduleDomain) { this.moduleDomain = moduleDomain; } public org.sevenstar.app.module.domain.S_moduleDomain getModuleDomain() { return this.moduleDomain; } } <file_sep>var qin_totalSize; var qin_currentPage=0; var qin_pageSize = 5; var qinList; var qinTitleSize = 50; var qinBaseUrl ; function qin_init(_qinList,baseUrl){ qinList = eval('(' + _qinList + ')'); qinBaseUrl = baseUrl; qin_totalSize = qinList.length; qin_generatePage(); qin_go2Page(1); } function qin_generatePage(){ var pagehtml="<a href=\"javascript:qin_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<qin_totalSize/qin_pageSize;i++){ var id = i+1; pagehtml+="<a id=qin_"+id+" href=\"javascript:qin_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:qin_goNext()\" class=\"next\">下一页</a>" $("#qin_page").html(pagehtml) } function qin_goPrev(){ if(qin_currentPage>0){ qin_go2Page(qin_currentPage); } } function qin_goNext(){ if(qin_currentPage<(qin_totalSize/qin_pageSize-1)){ qin_go2Page(qin_currentPage+2); } } function qin_go2Page(id){ qin_currentPage = id-1; var html=""; for(var i = qin_currentPage*qin_pageSize;i<(qin_currentPage+1)*qin_pageSize&&i<qin_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+qinBaseUrl+"/student/content/detail.html?id="+qinList[i].id+"\" title="+qinList[i].title+" href=\"#\" title="+qinList[i].title+"><span class=\"new\">"; var tempTitle; if(qinList[i].title.length>qinTitleSize){ tempTitle = qinList[i].title.substring(0,qinTitleSize)+"..."; }else{ tempTitle = qinList[i].title; } html+=tempTitle+"</span>"; html+="</a>"; } $("#qin").empty(); $("#qin").append(html); //设置点中的样式 for(var i=1;i<=qin_totalSize/qin_pageSize;i++){ $("#qin_"+i).attr("class",""); } $("#qin_"+id).attr("class","cur"); } <file_sep>/** * 表格分页工具 * ben.s * <EMAIL> * 2013.6.21 * 创建一个对象 * var obj = new pagging('每一页的显示行数,不包括标题','表格id编号'); * 显示第一页:obj.first() * 显示上一页:obj.prev() * 显示下一页:obj.next() * 显示最后一页:obj.last() * 显示指定页数:obj.show(页数) * 其他功能请联系作者补充. **/ var pagging = function(){ this.init.apply(this, arguments); } pagging.prototype={ init:function(s){ if(s.pageSize){ this.pageSize = s.pageSize; }else{ this.pageSize = 10; } if(s.divId){ this.divId = s.divId; } this.currentPage = 0; this.size = $('#'+this.divId).find('a').length; }, show:function(pageSeq){ this.currentPage = pageSeq; var beginSeq = this.pageSize*this.currentPage; var endSeq = this.pageSize*(this.currentPage) >=this.size ? (this.size):(this.pageSize*(this.currentPage+1)-1); $('#'+this.divId).find('a').hide(); for(var i=beginSeq;i<=endSeq;i++){ $('#'+this.divId).find('a').eq(i).show(); } }, prev:function(){ if(this.currentPage>0){ this.show(this.currentPage-1); } }, next:function(){ if(this.currentPage<((($('#'+this.divId).find('a').length)/this.pageSize)-1)){ this.show(this.currentPage+1); } }, first:function(){ this.show(0); }, last:function(){ this.show((($('#'+this.divId).find('a').length-1)/this.pageSize)-1); } }<file_sep>var bulletin_totalSize; var bulletin_currentPage=0; var bulletin_pageSize = 15; var bulletinList; var bulletinTitleSize = 50; var bulletinBaseUrl ; function bulletin_init(_bulletinList,baseUrl){ bulletinList = eval('(' + _bulletinList + ')'); bulletinBaseUrl = baseUrl; bulletin_totalSize = bulletinList.length; bulletin_generatePage(); bulletin_go2Page(1); } function bulletin_generatePage(){ var pagehtml="<a href=\"javascript:bulletin_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<bulletin_totalSize/bulletin_pageSize;i++){ var id = i+1; pagehtml+="<a id=bulletin_"+id+" href=\"javascript:bulletin_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:bulletin_goNext()\" class=\"next\">下一页</a>" $("#bulletin_page").html(pagehtml) } function bulletin_goPrev(){ if(bulletin_currentPage>0){ bulletin_go2Page(bulletin_currentPage); } } function bulletin_goNext(){ if(bulletin_currentPage<(bulletin_totalSize/bulletin_pageSize-1)){ bulletin_go2Page(bulletin_currentPage+2); } } function bulletin_go2Page(id){ bulletin_currentPage = id-1; var html=""; for(var i = bulletin_currentPage*bulletin_pageSize;i<(bulletin_currentPage+1)*bulletin_pageSize&&i<bulletin_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+bulletinBaseUrl+"/student/bulletin/detail.html?id="+bulletinList[i].id+"\" title="+bulletinList[i].title+" href=\"#\" title="+bulletinList[i].title+"><span class=\"new\">"; var tempTitle; if(bulletinList[i].title.length>bulletinTitleSize){ tempTitle = bulletinList[i].title.substring(0,bulletinTitleSize)+"..."; }else{ tempTitle = bulletinList[i].title; } html+=tempTitle+"</span><span class=\"date\">"+bulletinList[i].create_date+"</span>"; html+="</a>"; } $("#bulletin").empty(); $("#bulletin").append(html); //设置点中的样式 for(var i=1;i<=bulletin_totalSize/bulletin_pageSize;i++){ $("#bulletin_"+i).attr("class",""); } $("#bulletin_"+id).attr("class","cur"); } <file_sep>//焦点图片切换JS代码 && placeholder属性兼容代码 (function($) { $.fn.sySlider = function() { $(this).each(function(){ var $this = $(this); // var html = '<span class="prev"></span><span class="next"></span><ul>'; var html = '<ul>'; var width = $this.width(), height = $this.height(), n = $this.find('a').length,index,$next,autoSlider $pic = $this.find('a'); $pic.eq(0).css('display','inline-block'); for (var i=0; i<n; i=i+1) { if (i===0) { html += '<li class="active">1</li>'; } else { html += '<li>'+ (i+1) +'</li>'; } } html += '</ul>'; $this.append(html); var $span = $this.find('span'); $span.css('top',((height/2) - ($span.height()/2)) + 'px'); $this.hover(function(){ $span.css('display','inline-block'); },function(){ $span.css('display','none'); }); //点击翻页按钮时 $span.on('click',function(){ clearInterval(autoSlider); var cls = $(this).attr('class'), $cur = $this.find('a:visible'); if (!$cur.is(':animated')) { if (cls === 'prev') { if ($cur.index() === 0) { index = n-1; } else { index = $cur.index() - 1; } $next = $this.find('a:eq('+index+')'); $next.css({'left':-width +'px','display':'inline-block'}).animate({'left':0},400); $cur.animate({'left':width +'px'},400).hide(10); }; if (cls === 'next') { if ($cur.index() === n-1) { index = 0; } else { index = $cur.index() + 1; } $next = $this.find('a:eq('+index+')'); $next.css({'left':width +'px','display':'inline-block'}).animate({'left':0},400); $cur.animate({'left':-width +'px'},400).hide(10); }; $this.find('li:eq('+index+')').addClass('active') .siblings().removeClass('active'); }; autoSlider = setInterval(auto,3000); return false; }); //点击页标按钮时 $this.find('li').on('click',function(){ clearInterval(autoSlider); var $cur = $this.find('a:visible'), index = $(this).index(); if (!$cur.is(':animated') && $cur.index() !== index){ $cur.fadeOut(400); $this.find('a:eq('+index+')').css('left',0).fadeIn(400); $(this).addClass('active').siblings().removeClass('active'); } autoSlider = setInterval(auto,3000); return false; }); function auto(){ var i, $cur = $this.find('a:visible'), ind = $cur.index(); if (ind === n-1) { i = 0; } else { i = ind+1; } if (!$cur.is(':animated')){ $cur.fadeOut(400); $this.find('a:eq('+i+')').css('left',0).fadeIn(400); $this.find('li:eq('+i+')').addClass('active').siblings().removeClass('active'); } } //无点击时自动播放 autoSlider = setInterval(auto,3000); }); } })(jQuery); $(function(){ //去除点击连接后,链接周围的虚线框 $('.leftNav a').focus(function(){ $(this).blur(); }); //二级导航 $('.header .nav li div').hover(function(){ $(this).css('height',($(this).find('a').length * 25) +'px'); this.style.overflow = 'visible'; },function(){ $(this).css('height','25px'); this.style.overflow = 'hidden'; }); //导航 $('.leftNav li').on('click',function(){ var index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $(this).parents('.navWrap').next().find('.tabBody:eq('+index+')').addClass('active').siblings().removeClass('active'); return false; }); //选项卡 $('.tab_t li').on('click',function(){ var index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $(this).parent().siblings('.tab_c:eq('+index+')').addClass('active').siblings().removeClass('active'); }); //焦点图片切换 $('.theGallery').sySlider(); //以下是placeholder属性兼容代码 // -- Constants -- var PLACE_HOLDER_COLOR = "rgb(169,169,169)"; // "darkGrey" does not work in IE6 var PLACE_HOLDER_DATA_NAME = "original-font-color"; // -- Util Methods -- var getContent = function(element){ return $(element).val(); } var setContent = function(element, content){ $(element).val(content); } var getPlaceholder = function(element){ return $(element).attr("placeholder"); } var isContentEmpty = function(element){ var content = getContent(element); return (content.length === 0) || content == getPlaceholder(element); } var setPlaceholderStyle = function(element){ $(element).data(PLACE_HOLDER_DATA_NAME, $(element).css("color")); $(element).css("color", PLACE_HOLDER_COLOR); } var clearPlaceholderStyle = function(element){ $(element).css("color", $(element).data(PLACE_HOLDER_DATA_NAME)); $(element).removeData(PLACE_HOLDER_DATA_NAME); } var showPlaceholder = function(element){ setContent(element, getPlaceholder(element)); setPlaceholderStyle(element); } var hidePlaceholder = function(element){ if($(element).data(PLACE_HOLDER_DATA_NAME)){ setContent(element, ""); clearPlaceholderStyle(element); } } // -- Event Handlers -- var inputFocused = function(){ if(isContentEmpty(this)){ hidePlaceholder(this); } } var inputBlurred = function(){ if(isContentEmpty(this)){ showPlaceholder(this); } } var parentFormSubmitted = function(){ if(isContentEmpty(this)){ hidePlaceholder(this); } } // -- Bind event to components -- $("textarea, input[type='text']").each(function(index, element){ if($(element).attr("placeholder")){ $(element).focus(inputFocused); $(element).blur(inputBlurred); $(element).bind("parentformsubmitted", parentFormSubmitted); // triggers show place holder on page load $(element).trigger("blur"); // triggers form submitted event on parent form submit $(element).parents("form").submit(function(){ $(element).trigger("parentformsubmitted"); }); } }); }); <file_sep>var dai_totalSize; var dai_currentPage=0; var dai_pageSize = 5; var daiList; var daiTitleSize = 50; var daiBaseUrl ; function dai_init(_daiList,baseUrl){ daiList = eval('(' + _daiList + ')'); daiBaseUrl = baseUrl; dai_totalSize = daiList.length; dai_generatePage(); dai_go2Page(1); } function dai_generatePage(){ var pagehtml="<a href=\"javascript:dai_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<dai_totalSize/dai_pageSize;i++){ var id = i+1; pagehtml+="<a id=dai_"+id+" href=\"javascript:dai_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:dai_goNext()\" class=\"next\">下一页</a>" $("#dai_page").html(pagehtml) } function dai_goPrev(){ if(dai_currentPage>0){ dai_go2Page(dai_currentPage); } } function dai_goNext(){ if(dai_currentPage<(dai_totalSize/dai_pageSize-1)){ dai_go2Page(dai_currentPage+2); } } function dai_go2Page(id){ dai_currentPage = id-1; var html=""; for(var i = dai_currentPage*dai_pageSize;i<(dai_currentPage+1)*dai_pageSize&&i<dai_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+daiBaseUrl+"/student/content/detail.html?id="+daiList[i].id+"\" title="+daiList[i].title+" href=\"#\" title="+daiList[i].title+"><span class=\"new\">"; var tempTitle; if(daiList[i].title.length>daiTitleSize){ tempTitle = daiList[i].title.substring(0,daiTitleSize)+"..."; }else{ tempTitle = daiList[i].title; } html+=tempTitle+"</span>"; html+="</a>"; } $("#dai").empty(); $("#dai").append(html); //设置点中的样式 for(var i=1;i<=dai_totalSize/dai_pageSize;i++){ $("#dai_"+i).attr("class",""); } $("#dai_"+id).attr("class","cur"); } <file_sep>/*==============================================================*/ /* Table: zjut_organization */ /*==============================================================*/ create table zjut_organization ( id number(12) not null, name varchar2(50), display_name varchar2(100), create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_ZJUT_ORGANIZATION primary key (id) ); /*==============================================================*/ /* Table: zjut_organization_new */ /*==============================================================*/ create table zjut_organization_new ( id number(12) not null, organization_id number(12), new_id number(12), create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_ZJUT_ORGANIZATION_NEW primary key (id) ); /*==============================================================*/ /* Table: zjut_organization_bulletin */ /*==============================================================*/ create table zjut_organization_bulletin ( id number(12) not null, organization_id number(12), bulletin_id number(12), create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_ZJUT_ORGANIZATION_BULLETIN primary key (id) ); /*==============================================================*/ /* Table: zjut_new */ /*==============================================================*/ create table zjut_new ( id number(12) not null, title varchar2(100), author varchar2(50), context varchar2(4000), is_top varchar2(1), is_valid varchar2(1), expire_time date, create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_ZJUT_NEWS primary key (id) ); /*==============================================================*/ /* Table: zjut_bulletin */ /*==============================================================*/ create table zjut_bulletin ( id number(12) not null, title varchar2(100), author varchar2(50), context varchar2(4000), is_top varchar2(1), is_valid varchar2(1), expire_time date, create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_ZJUT_BULLETIN primary key (id) ); /******************************************************************************/ /* 2013.3.4ะยิ๖ */ /******************************************************************************/ /*==============================================================*/ /* Table: zjut_organization_resource */ /*==============================================================*/ create table zjut_organization_resource ( id number(12) not null, organization_id number(12), resource_id number(12), create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_ZJUT_ORGANIZATION_RESOURCE primary key (id) ); /*==============================================================*/ /* Table: zjut_resources */ /*==============================================================*/ create table zjut_resources ( id number(12) not null, type_id number(12), name varchar2(50), description varchar2(500), download_path varchar2(500), expire_date date, create_date date, modify_date date, create_user_id number(12), modify_user_id number(12), sts varchar2(1), constraint PK_RESOURCES primary key (id) ); /*==============================================================*/ /* Table: zjut_resource_type */ /*==============================================================*/ create table zjut_resource_type ( id number(12) not null, name varchar2(50), display_name varchar2(200), description varchar2(500), up_id number(12), create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_RESOURCE_TYPE primary key (id) ); /*==============================================================*/ /* Table: zjut_menu_content */ /*==============================================================*/ create table zjut_menu_content ( id number(12) not null, menu_name varchar2(100), menu_display_name varchar2(200), up_id number(12), content varchar2(4000), organization_id number(12), create_date date, create_user_id number(12), modify_date date, modify_user_id number(12), sts varchar2(1), constraint PK_ZJUT_MENU_CONTENT primary key (id) ); alter table zjut_new add source varchar2(50); alter table zjut_new add browse_count number(12); alter table zjut_bulletin add source varchar2(50); alter table zjut_bulletin add browse_count number(12); /*==============================================================*/ /* Table: zjut_school_life */ /*==============================================================*/ create table zjut_school_life ( id number(12) not null, title varchar2(100), author varchar2(100), summary varchar2(2000), content varchar2(400), image varchar2(100), is_top varchar2(1), is_validate varchar2(1), create_user_id number(12), create_date date, modify_user_id number(12), modify_date date, sts varchar2(1), constraint PK_ZJUT_SCHOOL_LIFE primary key (id) ); /*==============================================================*/ /* Table: zjut_organization_life */ /*==============================================================*/ create table zjut_organization_life ( id number(12) not null, organization_id number(12), school_life_id number(12), create_user_id number(12), create_date date, modify_user_id number(12), modify_date date, sts varchar2(1), constraint PK_ZJUT_ORGANIZATION_LIFE primary key (id) ); /*==============================================================*/ /* Sequence: ZJUT_APP */ /*==============================================================*/ create sequence ZJUT_APP minvalue 1 maxvalue 999999999999999999999999999 start with 1889 increment by 1 cache 20; <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/> <meta name="description" content="浙江工业大学国际学院学生家园" /> <meta name="keywords" content="江工业大学,工业大学,浙工大,国际学院,学生家园" /> <meta name="author" content="Simplifly,qq941721234" /> <title>留学工大——学习园地</title> <link rel="stylesheet" href="../resources/css/common.css"/> <link rel="stylesheet" href="../resources/css/page.css"/> </head> <body class="page1"> <div class="wrapper"> <!-- 实际工程中请把HTML注释去掉 --> <!-- header部分(可公用代码),将页面动态化时可以把这个div单独提取成一个文件,然后包含到这个位置 --> <#include "../head.html"/> <!-- /header --> <div class="main"> <div class="navWrap"> <h2>学习园地</h2> <ul class="leftNav"> <li class="active"><a href="#">教学日历</a></li> <li><a href="#">汉语教学计划</a></li> <li><a href="#">相关课件下载</a></li> <li><a href="#">新旧hsk级别对照</a></li> <li><a href="#">考试时间</a></li> <li class="last"><a href="#">报名缴费</a></li> </ul> </div> <div class="rightBody"> <div class="tabBody active"> <h2 class="h2 orangeH2"> 教学日历 <span></span> </h2> <div class="content teachCalendar"><!--这里面的内容一般为编辑器输出 --> ${(zjut_menu_contentDomain.getChildWithName('jyrl').content)!''} </div> </div> <div class="tabBody"> <h2 class="h2 orangeH2"> 汉语教学计划 <span style="left:110px"></span> </h2> <div class="content teachCalendar"> ${(zjut_menu_contentDomain.getChildWithName('hyjxjh').content)!''} </div> </div> <div class="tabBody"> <h2 class="h2 orangeH2"> 相关课件下载 <span style="left:110px"></span> </h2> <div class="content teachCalendar"> ${(zjut_menu_contentDomain.getChildWithName('xgkjxz').content)!''} </div> </div> <div class="tabBody"> <h2 class="h2 orangeH2"> 新旧hsk级别对照 <span style="left:130px"></span> </h2> <div class="content teachCalendar"> ${(zjut_menu_contentDomain.getChildWithName('xjhskjbdz').content)!''} </div> </div> <div class="tabBody"> <h2 class="h2 orangeH2"> 考试时间 <span></span> </h2> <div class="content teachCalendar"> ${(zjut_menu_contentDomain.getChildWithName('kssj').content)!''} </div> </div> <div class="tabBody"> <h2 class="h2 orangeH2"> 报名缴费 <span></span> </h2> <div class="content teachCalendar"> ${(zjut_menu_contentDomain.getChildWithName('bmjf').content)!''} </div> </div> </div> </div> <!-- footer部分(可公用代码),将页面动态化时可以把这个div单独提取成一个文件,然后包含到这个位置 --> <#include "../foot.html"/> <!-- /footer --> </div> <script src="../resources/js/jquery.js"></script> <script src="../resources/js/common.js"></script> <script src="../resources/js/tab.js"></script> </body> </html> <file_sep>package test.cn.edu.zjut.cfg; import cn.edu.zjut.util.JsonFormatUtil; public class JsonFormat { public static void main(String[] ben){ String testStr = "2012年11月7日和17日,国际学院学生工作部先后组织了98名在读语言进修留学生和80名学历留学生赴东阳横店影视城秋游活动。此次秋游活动是国际学院\u201c中国梦\u2022留学生探索中国传统文化\u201d 的系列活动之一,深受广大留学生欢迎。\r\n\r\n"; System.out.println(JsonFormatUtil.instance.format(testStr)); } } <file_sep>package cn.edu.zjut.web.page.manager; import java.util.List; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.util.BeanHelper; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_resourceDomain; import cn.edu.zjut.cfg.domain.Zjut_resource_typeDomain; import cn.edu.zjut.cfg.domain.Zjut_resourcesDomain; public abstract class DefaultResources extends DefaultAction { private IbatisPage page; private Zjut_organization_resourceDomain zjut_organization_resourceDomain; private Zjut_resourcesDomain zjut_resourceDomain; private Zjut_organizationDomain zjut_organizationDomain; private Zjut_resource_typeDomain zjut_resource_typeDomain; public abstract Zjut_organizationDomain getOrganizationDomain(); public List typeList; public String tree() { typeList = (new Zjut_resource_typeDomain()).selectAll(); return "manager/defaultResources/tree.html"; } public String main(){ return "manager/defaultResources/main.html"; } public String list() { if (zjut_resource_typeDomain == null || zjut_resource_typeDomain.getId() == null) { zjut_resource_typeDomain = new Zjut_resource_typeDomain(); zjut_resource_typeDomain.setName("default"); zjut_resource_typeDomain.loadEqual(); } zjut_organization_resourceDomain = new Zjut_organization_resourceDomain(); zjut_organization_resourceDomain .setOrganizationDomain(getOrganizationDomain()); zjut_organization_resourceDomain .setResourceTypeDomain(zjut_resource_typeDomain); page = zjut_organization_resourceDomain.getSelectPage(page); return "manager/defaultResources/list.html"; } public String edit() { if (zjut_resourceDomain == null || zjut_resourceDomain.getId() == null) { throw new RuntimeException("缺少资源编号,不能修改!"); } zjut_resourceDomain.loadEqual(); zjut_resource_typeDomain = new Zjut_resource_typeDomain(); zjut_resource_typeDomain.setId(zjut_resourceDomain.getTypeDomain().getId()); zjut_resourceDomain.loadEqual(); zjut_organizationDomain = new Zjut_organizationDomain(); BeanHelper.copy(getOrganizationDomain(), zjut_organizationDomain); return "manager/defaultResources/edit.html"; } public String left() { if (zjut_resourceDomain.getId() == null) { throw new RuntimeException("缺少资源的信息,不能查看详情!"); } zjut_resourceDomain.loadEqual(); return "manager/defaultResources/left.html"; } public String input() { if(zjut_resource_typeDomain == null || zjut_resource_typeDomain.getId() == null){ throw new RuntimeException("缺少资源类型,不能新增!"); } zjut_resource_typeDomain.loadEqual(); zjut_organizationDomain = new Zjut_organizationDomain(); BeanHelper.copy(getOrganizationDomain(), zjut_organizationDomain); zjut_resourceDomain = new Zjut_resourcesDomain(); zjut_resourceDomain.setTypeDomain(zjut_resource_typeDomain); return "manager/defaultResources/edit.html"; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public Zjut_organization_resourceDomain getZjut_organization_resourceDomain() { return zjut_organization_resourceDomain; } public void setZjut_organization_resourceDomain( Zjut_organization_resourceDomain zjut_organization_resourceDomain) { this.zjut_organization_resourceDomain = zjut_organization_resourceDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } public Zjut_resourcesDomain getZjut_resourceDomain() { return zjut_resourceDomain; } public void setZjut_resourceDomain(Zjut_resourcesDomain zjut_resourceDomain) { this.zjut_resourceDomain = zjut_resourceDomain; } public Zjut_resource_typeDomain getZjut_resource_typeDomain() { return zjut_resource_typeDomain; } public void setZjut_resource_typeDomain( Zjut_resource_typeDomain zjut_resource_typeDomain) { this.zjut_resource_typeDomain = zjut_resource_typeDomain; } public List getTypeList() { return typeList; } public void setTypeList(List typeList) { this.typeList = typeList; } // public static void main(String[] ben) { // Zjut_resourcesDomain zjut_resourceDomain = null; // // Zjut_organizationDomain zjut_organizationDomain = null; // // Zjut_resource_typeDomain zjut_resource_typeDomain = null; // // Zjut_organization_resourceDomain zjut_organization_resourceDomain = null; // // IbatisPage page = null; // zjut_resource_typeDomain = new Zjut_resource_typeDomain(); // zjut_resource_typeDomain.setName("course"); // zjut_resource_typeDomain.loadEqual(); // zjut_organizationDomain = new Zjut_organizationDomain(); // zjut_organizationDomain.setName("college"); // zjut_organizationDomain.loadEqual(); // if (zjut_resource_typeDomain == null // || zjut_resource_typeDomain.getId() == null) { // throw new RuntimeException("缺少资源类型!"); // } // zjut_organization_resourceDomain = new Zjut_organization_resourceDomain(); // zjut_organization_resourceDomain // .setOrganizationDomain(zjut_organizationDomain); // zjut_organization_resourceDomain // .setResourceTypeDomain(zjut_resource_typeDomain); // // page = zjut_organization_resourceDomain.getSelectPage(page); // System.out.println(page.getTotal()); // } } <file_sep>package cn.edu.zjut.web.page.gjxy; import java.util.List; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_bulletinDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.service.Zjut_bulletinService; public class Bulletin extends DefaultAction { private Long id; private Zjut_bulletinDomain zjut_bulletinDomain; private static Zjut_organizationDomain organizationDomain; static { organizationDomain = new Zjut_organizationDomain(); organizationDomain.setName("international-college"); organizationDomain.loadEqual(); } public String detail() { if (id == null) { throw new RuntimeException("缺少公告编号,不能查看"); } List<Zjut_bulletinDomain> bulletinList = Zjut_bulletinService.instance .getBulletinList(organizationDomain.getName()); for (Zjut_bulletinDomain bulletinDomain : bulletinList) { if (id.compareTo(bulletinDomain.getId()) == 0) { zjut_bulletinDomain = bulletinDomain; try { zjut_bulletinDomain.setBrowse_count(zjut_bulletinDomain .getBrowse_count() == null ? 1 : zjut_bulletinDomain.getBrowse_count() + 1); zjut_bulletinDomain.update(); } catch (RuntimeException e) { e.printStackTrace(); } } } return super.SUCCESS; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Zjut_bulletinDomain getZjut_bulletinDomain() { return zjut_bulletinDomain; } public void setZjut_bulletinDomain(Zjut_bulletinDomain zjut_bulletinDomain) { this.zjut_bulletinDomain = zjut_bulletinDomain; } } <file_sep>java.util.Date=org.sevenstar.web.convert.DateConverter <file_sep>var num=8 //该值记录标签的个数 function chgChannelBg(oChannel,curChannel,sStyle1,sStyle2) { if(curChannel.className=sStyle2); if(oChannel.className!=sStyle1) { oChannel.className=sStyle1; } } //获取对应ID或Name的元素对象 function GetObj(objName){ if(document.getElementById){ return eval('document.getElementById("' + objName + '")'); }else if(document.layers){ return eval("document.layers['" + objName +"']"); }else{ return eval('document.all.' + objName); } } //index:当前控制元素序号;ctrledPrefix:被控制ID前缀;ctrlPrefix:控制ID前缀;ctrlClass1:控制元素初始样式;ctrlClass2:控制元素第二样式 function tabSwift(index,ctrlPrefix,ctrledPrefix,ctrlClass1,ctrlClass2) { for(var i=1;i<=num;i++){/* 最多支持8个标签 */ if(GetObj(ctrlPrefix+i)&&GetObj(ctrledPrefix+i)){ GetObj(ctrledPrefix+i).style.display = 'none'; if (ctrlClass1!=null) { GetObj(ctrlPrefix+i).className =ctrlClass1; } } } if(GetObj(ctrlPrefix+index)&&GetObj(ctrledPrefix+index)){ GetObj(ctrledPrefix+index).style.display = 'block'; if (ctrlClass2!=null) { GetObj(ctrlPrefix+index).className=ctrlClass2; } } } function showDesc(obj,desc,show){ //var xPos=event.x; var id=obj.id; var index=id.substring(id.indexOf("nbpt")+"nbpt".length+1); var oDiv=document.getElementById("desc_"+index); if(desc!=""){ oDiv.innerHTML=desc;} oDiv.style.display=show; } function chgMainNr(src){ document.getElementById("mainnr").src=src; } function swiftSubMenu(index,ctrlPrefix,ctrlClass1,ctrlClass2){ for(var i=1;i<=num;i++){/* 最多支持8个标签 */ if(GetObj(ctrlPrefix+i)){ if (ctrlClass1!=null) { GetObj(ctrlPrefix+i).className =ctrlClass1; } } } if(GetObj(ctrlPrefix+index)){ if (ctrlClass2!=null) { GetObj(ctrlPrefix+index).className=ctrlClass2; } } } //框架左右收缩 function MouseDownToResize(obj){ obj.mouseDownX=event.clientX; obj.pareneTdW=obj.parentElement.offsetWidth; obj.pareneTableW=tab.offsetWidth; obj.setCapture(); } function MouseMoveToResize(obj){ if(!obj.mouseDownX) return false; var newWidth=obj.pareneTdW*1+event.clientX*1-obj.mouseDownX; if(newWidth>0) { obj.parentElement.style.width = newWidth; //tab.style.width=obj.pareneTableW*1+event.clientX*1-obj.mouseDownX; tab.style.width="100%"; var obj = eval("mydiv0"); obj.style.left = obj.parentElement.offsetLeft*1+obj.parentElement.offsetWidth*1+tab.offsetLeft;//obj.parentElement.style.pos; } } function MouseUpToResize(obj){ obj.releaseCapture(); obj.mouseDownX=0; } function init(){ var tempStr = ""; tempStr = '<div id="mydiv0" class="resizeDivClass" onmousedown="MouseDownToResize(this);" onmousemove="MouseMoveToResize(this);" onmouseup="MouseUpToResize(this);"></div>'; tab.rows(0).cells(0).innerHTML = tab.rows(0).cells(0).innerHTML+tempStr; var obj = eval("mydiv0"); obj.style.left = obj.parentElement.style.pos; } //弹出窗口 function pupopen(){ document.getElementById("bg2").style.display="block"; document.getElementById("popbox2").style.display="block" ; } function pupclose(){ document.getElementById("bg2").style.display="none"; document.getElementById("popbox2").style.display="none" ; } //弹出窗口的取消 function closeWin(divId,divId2){ var oDiv=document.getElementById(divId); if(oDiv!=null){ oDiv.style.display='none'; } oDiv=document.getElementById(divId2); if(oDiv!=null){ oDiv.style.display='none'; } } //弹出层 var flag=0; var div; function Point(iX, iY){ this.x = iX; this.y = iY; } function getPosition(aTag,obj){ var oTmp = aTag; var pt = new Point(0,0); do { pt.x += oTmp.offsetLeft; pt.y += oTmp.offsetTop; oTmp = oTmp.offsetParent; } while(oTmp.tagName!="BODY"); pt.y += aTag.offsetHeight + 1; if((pt.x - document.body.scrollLeft) + obj.style.pixelWidth >= document.body.clientWidth){ //超出宽度了 pt.x -= ((pt.x - document.body.scrollLeft) + obj.style.pixelWidth - document.body.clientWidth); //减去超出部分 } return pt; } function setPosition(btn,div) { var p=getPosition(btn,div); div.style.left=p.x; div.style.top=p.y; } function showhide(which){ div=which; if( which.style.display=="none"){ which.style.display="" }else{ setTimeout("hideDiv()",1000); //which.style.display="none"; } } function hideDiv(){ if(div!=null && flag==0){ div.style.display="none"; } } <file_sep>package org.sevenstar.app.system.action; import java.util.List; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.system.domain.S_systemDomain; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import org.sevenstar.web.annotation.SSList; @SSAction(name = "s_system") public class S_systemAction extends DefaultAction { private S_systemDomain s_systemDomain; @SSList(type = "org.sevenstar.app.system.domain.S_systemDomain") private List systemList; public String deleteList() throws Exception { if (systemList != null && systemList.size() > 0) { for (int i = 0; i < systemList.size(); i++) { S_systemDomain s_systemDomain = (S_systemDomain) systemList .get(i); s_systemDomain.delete(); } } else { throw new ApplicationException("请先选择系统"); } return "批量删除系统成功"; } public String delete() throws Exception { super.setMsg("删除系统[" + s_systemDomain.getName() + "]成功"); s_systemDomain.delete(); super.setNextUrl("app/system/list.html"); return super.REDIRECT; } public String insert() throws Exception { s_systemDomain.insert(); super.setMsg("添加系统[" + s_systemDomain.getName() + "]成功"); super.setNextUrl("app/system/list.html"); return super.REDIRECT; } public String update() throws Exception { s_systemDomain.update(); super.setMsg("修改系统[" + s_systemDomain.getName() + "]成功"); super.setNextUrl("app/system/list.html"); return super.REDIRECT; } public String insertOrUpdate() throws Exception { s_systemDomain.insertOrUpdate(); return "编辑系统[" + s_systemDomain.getName() + "]成功"; } public S_systemDomain getS_systemDomain() { return s_systemDomain; } public void setS_systemDomain(S_systemDomain s_systemDomain) { this.s_systemDomain = s_systemDomain; } public List getSystemList() { return systemList; } public void setSystemList(List systemList) { this.systemList = systemList; } } <file_sep>package cn.edu.zjut.web.page; import java.util.List; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_bulletinDomain; import cn.edu.zjut.cfg.domain.Zjut_contentDomain; import cn.edu.zjut.cfg.domain.Zjut_menu_contentDomain; import cn.edu.zjut.cfg.domain.Zjut_newDomain; import cn.edu.zjut.cfg.domain.Zjut_partner_universitiesDomain; import cn.edu.zjut.cfg.domain.Zjut_resourcesDomain; import cn.edu.zjut.cfg.domain.Zjut_school_lifeDomain; import cn.edu.zjut.cfg.domain.Zjut_studentDomain; import cn.edu.zjut.util.ImagePathAnalyse; public class Filepathchange extends DefaultAction { private final String sourceBaseUrl = "/zjut"; private final String targetBaseUrl = ""; public void bulletin() { List<Zjut_bulletinDomain> bulletinList = (new Zjut_bulletinDomain()) .selectAll(); for (Zjut_bulletinDomain domain : bulletinList) { String context = domain.getContext(); List imgList = ImagePathAnalyse.instance.analyseImagePaths(context); if (imgList == null || imgList.isEmpty()) continue; for (int i = 0; i < imgList.size(); i++) { String imgPath = (String) imgList.get(i); String replaceImgPath = imgPath.replaceAll(sourceBaseUrl, targetBaseUrl); context = context.replaceAll(imgPath, replaceImgPath); } domain.setContext(context); domain.update(); } } public void content() { List<Zjut_contentDomain> contentList = (new Zjut_contentDomain()) .selectAll(); for (Zjut_contentDomain domain : contentList) { String content = domain.getContent(); List imgList = ImagePathAnalyse.instance.analyseImagePaths(content); if (imgList == null || imgList.isEmpty()) continue; for (int i = 0; i < imgList.size(); i++) { String imgPath = (String) imgList.get(i); String replaceImgPath = imgPath.replaceAll(sourceBaseUrl, targetBaseUrl); content = content.replaceAll(imgPath, replaceImgPath); } domain.setContent(content); domain.update(); } } public void news() { List<Zjut_newDomain> newsList = (new Zjut_newDomain()).selectAll(); for (Zjut_newDomain domain : newsList) { String context = domain.getContext(); List imgList = ImagePathAnalyse.instance.analyseImagePaths(context); if (imgList != null && !imgList.isEmpty()) { for (int i = 0; i < imgList.size(); i++) { String imgPath = (String) imgList.get(i); String replaceImgPath = imgPath.replaceAll(sourceBaseUrl, targetBaseUrl); context = context.replaceAll(imgPath, replaceImgPath); } } String image2index = domain.getImage2index(); if (image2index != null) { image2index = image2index.replaceAll(sourceBaseUrl, targetBaseUrl); domain.setImage2index(image2index); } domain.setContext(context); domain.update(); } } public void menucontent() { List<Zjut_menu_contentDomain> menuContentList = (new Zjut_menu_contentDomain()) .selectAll(); for (Zjut_menu_contentDomain domain : menuContentList) { String content = domain.getContent(); List imgList = ImagePathAnalyse.instance.analyseImagePaths(content); if (imgList == null || imgList.isEmpty()) continue; for (int i = 0; i < imgList.size(); i++) { String imgPath = (String) imgList.get(i); String replaceImgPath = imgPath.replaceAll(sourceBaseUrl, targetBaseUrl); content = content.replaceAll(imgPath, replaceImgPath); } domain.setContent(content); domain.update(); } } public void universities() { List<Zjut_partner_universitiesDomain> universitiesList = (new Zjut_partner_universitiesDomain()) .selectAll(); for (Zjut_partner_universitiesDomain domain : universitiesList) { String imgPath = domain.getImg_path(); if(imgPath == null)continue; String replaceImgPath = imgPath.replaceAll(sourceBaseUrl, targetBaseUrl); domain.setImg_path(replaceImgPath); domain.update(); } } public void life() { List<Zjut_school_lifeDomain> lifeList = (new Zjut_school_lifeDomain()) .selectAll(); for (Zjut_school_lifeDomain domain : lifeList) { String imgPath = domain.getImage(); if(imgPath == null)continue; String replaceImgPath = imgPath.replaceAll(sourceBaseUrl, targetBaseUrl); domain.setImage(replaceImgPath); domain.update(); } } public void student() { List<Zjut_studentDomain> studentList = (new Zjut_studentDomain()) .selectAll(); for (Zjut_studentDomain domain : studentList) { String imgPath = domain.getImg_path(); if(imgPath == null)continue; String replaceImgPath = imgPath.replaceAll(sourceBaseUrl, targetBaseUrl); domain.setImg_path(replaceImgPath); domain.update(); } } public void resources() { List<Zjut_resourcesDomain> resourcesList = (new Zjut_resourcesDomain()) .selectAll(); for (Zjut_resourcesDomain domain : resourcesList) { String filePath = domain.getDownload_path(); if(filePath == null)continue; String replaceFilePath = filePath.replaceAll(sourceBaseUrl, targetBaseUrl); domain.setDownload_path(replaceFilePath); domain.update(); } } public void replace() { bulletin(); content(); news(); menucontent(); universities(); life(); student(); resources(); } // // public static void main(String[] ben) { // Filepathchange fc = new Filepathchange(); // fc.replace(); // } } <file_sep>package cn.edu.zjut.util; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.edu.zjut.cfg.domain.Zjut_newDomain; public enum ImagePathAnalyse { instance; public List analyseImagePaths(String content) { if (content == null || "".equals(content)) { return null; } List imageList = new ArrayList(); String img = ""; String regEx_img = "<img.*src=(.*?)[^>]*?>"; // 图片链接地址 // String regEx_img = "src=\"?(.*?)(\"|>|\\s+)"; Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE); Matcher m_image = p_image.matcher(content); while (m_image.find()) { img = m_image.group(); Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); while (m.find()) { imageList.add(m.group(1)); } } return imageList; } public static void main(String[] ben) { Zjut_newDomain zjut_newDomain = new Zjut_newDomain(); zjut_newDomain.setTitle("测试下图片"); zjut_newDomain.loadEqual(); System.out.println(ImagePathAnalyse.instance .analyseImagePaths(zjut_newDomain.getContext())); } } <file_sep>package cn.edu.zjut.cfg.bean; public class ApplicationProgramBean { public String familyname; public String firstname; public String middlename; public String chinesename; public String gender; public String dateofbirth; public String nationally; public String countryofbirth; public String passportno; public String marital; public String religion; public String occupationorstatus; public String emailaddress; public String employer; public String perstreet; public String percity; public String percountry; public String perzipcode; public String perphonenumber; public String permanentemail; public String faxbumber; public String degreeobtained; public String learnedchinese; public String levelofchinese; public String inzjutstart; public String inzustend; public String sourceoffunding; public String getFamilyname() { return familyname; } public void setFamilyname(String familyname) { this.familyname = familyname; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getMiddlename() { return middlename; } public void setMiddlename(String middlename) { this.middlename = middlename; } public String getChinesename() { return chinesename; } public void setChinesename(String chinesename) { this.chinesename = chinesename; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getDateofbirth() { return dateofbirth; } public void setDateofbirth(String dateofbirth) { this.dateofbirth = dateofbirth; } public String getNationally() { return nationally; } public void setNationally(String nationally) { this.nationally = nationally; } public String getCountryofbirth() { return countryofbirth; } public void setCountryofbirth(String countryofbirth) { this.countryofbirth = countryofbirth; } public String getPassportno() { return passportno; } public void setPassportno(String passportno) { this.passportno = passportno; } public String getMarital() { return marital; } public void setMarital(String marital) { this.marital = marital; } public String getReligion() { return religion; } public void setReligion(String religion) { this.religion = religion; } public String getOccupationorstatus() { return occupationorstatus; } public void setOccupationorstatus(String occupationorstatus) { this.occupationorstatus = occupationorstatus; } public String getEmailaddress() { return emailaddress; } public void setEmailaddress(String emailaddress) { this.emailaddress = emailaddress; } public String getEmployer() { return employer; } public void setEmployer(String employer) { this.employer = employer; } public String getPerstreet() { return perstreet; } public void setPerstreet(String perstreet) { this.perstreet = perstreet; } public String getPercity() { return percity; } public void setPercity(String percity) { this.percity = percity; } public String getPercountry() { return percountry; } public void setPercountry(String percountry) { this.percountry = percountry; } public String getPerzipcode() { return perzipcode; } public void setPerzipcode(String perzipcode) { this.perzipcode = perzipcode; } public String getPerphonenumber() { return perphonenumber; } public void setPerphonenumber(String perphonenumber) { this.perphonenumber = perphonenumber; } public String getPermanentemail() { return permanentemail; } public void setPermanentemail(String permanentemail) { this.permanentemail = permanentemail; } public String getFaxbumber() { return faxbumber; } public void setFaxbumber(String faxbumber) { this.faxbumber = faxbumber; } public String getDegreeobtained() { return degreeobtained; } public void setDegreeobtained(String degreeobtained) { this.degreeobtained = degreeobtained; } public String getLearnedchinese() { return learnedchinese; } public void setLearnedchinese(String learnedchinese) { this.learnedchinese = learnedchinese; } public String getLevelofchinese() { return levelofchinese; } public void setLevelofchinese(String levelofchinese) { this.levelofchinese = levelofchinese; } public String getInzjutstart() { return inzjutstart; } public void setInzjutstart(String inzjutstart) { this.inzjutstart = inzjutstart; } public String getInzustend() { return inzustend; } public void setInzustend(String inzustend) { this.inzustend = inzustend; } public String getSourceoffunding() { return sourceoffunding; } public void setSourceoffunding(String sourceoffunding) { this.sourceoffunding = sourceoffunding; } } <file_sep>package cn.edu.zjut.cfg.service; import java.util.ArrayList; import java.util.List; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_resourceDomain; import cn.edu.zjut.cfg.domain.Zjut_resourcesDomain; public enum Zjut_resourcesService { instance; public List<Zjut_resourcesDomain> getResourceList(String organizationName){ Zjut_organization_resourceDomain resources_organizationDomain = new Zjut_organization_resourceDomain(); Zjut_organizationDomain organizationDomain = new Zjut_organizationDomain(); organizationDomain.setName(organizationName); organizationDomain.loadEqual(); resources_organizationDomain.setOrganizationDomain(organizationDomain); List<Zjut_organization_resourceDomain> tempList = resources_organizationDomain.selectEqual(); List<Zjut_resourcesDomain> resourcesList = new ArrayList<Zjut_resourcesDomain>(); for(Zjut_organization_resourceDomain domain : tempList){ resourcesList.add(domain.getResourceDomain()); } return resourcesList; } } <file_sep>$(function(){ $('.map .op').on('click', '.prev', function() { var me = $(this), ms = $('.ms'), cur = ms.find('.active').index(), li = $('.map li'); if (cur <= 0) { cur = 2; } else { cur -= 1; } if (!ms.find('.m').is(':animated')) { ms.find('.active').fadeOut(300).removeClass('active'); ms.find('.m').eq(cur).fadeIn(300).addClass('active'); li.filter('.active').removeClass('active'); li.eq(cur).addClass('active'); } return false; }); $('.map .op').on('click', '.next', function() { var me = $(this), ms = $('.ms'), cur = ms.find('.active').index(), li = $('.map li'); if (cur >= 2) { cur = 0; } else { cur += 1; } if (!ms.find('.m').is(':animated')) { ms.find('.active').fadeOut(300).removeClass('active'); ms.find('.m').eq(cur).fadeIn(300).addClass('active'); li.filter('.active').removeClass('active'); li.eq(cur).addClass('active'); } return false; }); $('.map .op').on('click', 'li', function(){ if ($(this).is('.active')) return false; var cur = $(this).index(), m = $('.ms .m'); m.filter('.active').fadeOut(300); m.eq(cur).fadeIn(300); m.eq(cur).addClass('active') .siblings().removeClass('active'); $(this).addClass('active'); $(this).siblings().removeClass('active'); return false; }) });<file_sep>package org.sevenstar.app.rbac.domain; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.system.domain.S_systemDomain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSCacheModel; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; @SSDomain(table = "s_rbac_permission", condition = "sts<>'N'") @SSId(generateType = "seq", seq = "seq_app") @SSCacheModel(selectAll = true, flushonexecute = "S_rbac_permissionDomain_base_insert,S_rbac_permissionDomain_base_update,S_rbac_permissionDomain_base_delete,S_rbac_operationDomain_base_insert,S_rbac_operationDomain_base_update,S_rbac_operationDomain_base_delete,S_rbac_resourceDomain_base_insert,S_rbac_resourceDomain_base_update,S_rbac_resourceDomain_base_delete") public class S_rbac_permissionDomain extends PersistentObject { @SSPrimaryKey private java.lang.Long id; private java.lang.String name; @SSManyToOne(parameter = "resourceDomain.id", column = "resource_id") private org.sevenstar.app.rbac.domain.S_rbac_resourceDomain resourceDomain; @SSManyToOne(parameter = "operationDomain.id", column = "operation_id") private org.sevenstar.app.rbac.domain.S_rbac_operationDomain operationDomain; private java.lang.String description; @SSManyToOne(parameter = "systemDomain.id", column = "system_id") private S_systemDomain systemDomain; private java.lang.String sts; public S_systemDomain getSystemDomain() { return systemDomain; } public void setSystemDomain(S_systemDomain systemDomain) { this.systemDomain = systemDomain; } public void update() { this.setSts("Y"); S_rbac_permissionDomain paramDomain = new S_rbac_permissionDomain(); paramDomain.setName(this.getName()); if (paramDomain.updateExist(this.getId())) { throw new ApplicationException("权限名[" + this.getName() + "]已存在"); } super.update(); } public void insert() { this.setSts("Y"); if (hasPermission(this.getName())) { throw new ApplicationException("权限名[" + this.getName() + "]已存在"); } super.insert(); } public void insertOrUpdate() { if (this.getId() != null) { this.update(); } else { this.insert(); } } public void delete() { this.setSts("N"); super.update(); } public boolean hasPermission(String name) { S_rbac_permissionDomain param = new S_rbac_permissionDomain(); param.setName(name); return param.exist(); } public void setId(java.lang.Long id) { this.id = id; } public java.lang.Long getId() { return this.id; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getName() { return this.name; } public void setResourceDomain( org.sevenstar.app.rbac.domain.S_rbac_resourceDomain resourceDomain) { this.resourceDomain = resourceDomain; } public org.sevenstar.app.rbac.domain.S_rbac_resourceDomain getResourceDomain() { return this.resourceDomain; } public void setOperationDomain( org.sevenstar.app.rbac.domain.S_rbac_operationDomain operationDomain) { this.operationDomain = operationDomain; } public org.sevenstar.app.rbac.domain.S_rbac_operationDomain getOperationDomain() { return this.operationDomain; } public void setDescription(java.lang.String description) { this.description = description; } public java.lang.String getDescription() { return this.description; } public void setSts(java.lang.String sts) { this.sts = sts; } public java.lang.String getSts() { return this.sts; } } <file_sep>package cn.edu.zjut.web.page.manager; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_lifeDomain; import cn.edu.zjut.cfg.domain.Zjut_school_lifeDomain; public abstract class Defaultlifes extends DefaultAction { private IbatisPage page; private Zjut_school_lifeDomain zjut_school_lifeDomain; private Zjut_organizationDomain zjut_organizationDomain; private Zjut_organization_lifeDomain zjut_organization_lifeDomain; public abstract Zjut_organizationDomain getOrganizationDomain(); public String list() { zjut_organization_lifeDomain = new Zjut_organization_lifeDomain(); zjut_organization_lifeDomain .setOrganizationDomain(getOrganizationDomain()); page = zjut_organization_lifeDomain.getSelectPage(page); return "manager/defaultlifes/list.html"; } public String left(){ if (zjut_school_lifeDomain == null || zjut_school_lifeDomain.getId() == null) { throw new RuntimeException("缺少参数,不能进入查看页面!"); } zjut_school_lifeDomain.loadEqual(); return "manager/defaultlifes/left.html"; } public String edit() { if (zjut_school_lifeDomain == null || zjut_school_lifeDomain.getId() == null) { throw new RuntimeException("缺少参数,不能进入编辑页面!"); } zjut_organizationDomain = getOrganizationDomain(); zjut_school_lifeDomain.loadEqual(); return "manager/defaultlifes/edit.html"; } public String input(){ zjut_organizationDomain = getOrganizationDomain(); return "manager/defaultlifes/edit.html"; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public Zjut_school_lifeDomain getZjut_school_lifeDomain() { return zjut_school_lifeDomain; } public void setZjut_school_lifeDomain( Zjut_school_lifeDomain zjut_school_lifeDomain) { this.zjut_school_lifeDomain = zjut_school_lifeDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } public Zjut_organization_lifeDomain getZjut_organization_lifeDomain() { return zjut_organization_lifeDomain; } public void setZjut_organization_lifeDomain( Zjut_organization_lifeDomain zjut_organization_lifeDomain) { this.zjut_organization_lifeDomain = zjut_organization_lifeDomain; } } <file_sep>package cn.edu.zjut.web.page.manager; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_partner_universitiesDomain; public class Partnerunis extends DefaultAction { private Zjut_partner_universitiesDomain partner_universitiesDomain; private IbatisPage page; public String list() { page = (new Zjut_partner_universitiesDomain()).getSelectPage(page); return super.SUCCESS; } public String detail() { if (partner_universitiesDomain == null || partner_universitiesDomain.getId() == null) { throw new RuntimeException("缺少参数,不能查看详情!"); } partner_universitiesDomain.loadEqual(); return super.SUCCESS; } public String edit() { if (partner_universitiesDomain == null || partner_universitiesDomain.getId() == null) { throw new RuntimeException("缺少参数,不能编辑!"); } partner_universitiesDomain.loadEqual(); return super.SUCCESS; } public String input() { partner_universitiesDomain = new Zjut_partner_universitiesDomain(); return "manager/partnerunis/edit.html"; } public Zjut_partner_universitiesDomain getPartner_universitiesDomain() { return partner_universitiesDomain; } public void setPartner_universitiesDomain( Zjut_partner_universitiesDomain partner_universitiesDomain) { this.partner_universitiesDomain = partner_universitiesDomain; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } } <file_sep>package org.sevenstar.app.rbac.relation.domain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; @SSDomain(table="s_rbac_userrole") @SSId(generateType="seq",seq="seq_app") public class S_rbac_userroleDomain extends PersistentObject { @SSPrimaryKey private java.lang.Long id; @SSManyToOne(parameter="userDomain.id",column="user_id") private org.sevenstar.app.manager.domain.S_userDomain userDomain; @SSManyToOne(parameter="roleDomain.id",column="role_id") private org.sevenstar.app.rbac.domain.S_rbac_roleDomain roleDomain; public void setId(java.lang.Long id) { this.id = id; } public java.lang.Long getId() { return this.id; } public void setUserDomain( org.sevenstar.app.manager.domain.S_userDomain userDomain) { this.userDomain = userDomain; } public org.sevenstar.app.manager.domain.S_userDomain getUserDomain() { return this.userDomain; } public void setRoleDomain( org.sevenstar.app.rbac.domain.S_rbac_roleDomain roleDomain) { this.roleDomain = roleDomain; } public org.sevenstar.app.rbac.domain.S_rbac_roleDomain getRoleDomain() { return this.roleDomain; } } <file_sep>package org.sevenstar.app.monitor.domain; import java.util.Date; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; import org.sevenstar.persistent.db.find.annotation.model.SSProperty; @SSDomain(table="s_monitor_sql") @SSId(generateType="seq",seq="seq_monitor") public class S_monitor_sqlDomain extends PersistentObject{ @SSPrimaryKey private Long id; private String sqlmapid; private Long resultset_size; private String stacktrace; private Long execute_time; @SSProperty(value="sysdate") private Date create_date; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSqlmapid() { return sqlmapid; } public void setSqlmapid(String sqlmapid) { this.sqlmapid = sqlmapid; } public Long getResultset_size() { return resultset_size; } public void setResultset_size(Long resultset_size) { this.resultset_size = resultset_size; } public String getStacktrace() { return stacktrace; } public void setStacktrace(String stacktrace) { this.stacktrace = stacktrace; } public Long getExecute_time() { return execute_time; } public void setExecute_time(Long execute_time) { this.execute_time = execute_time; } public Date getCreate_date() { return create_date; } public void setCreate_date(Date create_date) { this.create_date = create_date; } } <file_sep>var win_prize_history_totalSize; var win_prize_history_currentPage=0; var win_prize_history_pageSize = 15; var win_prize_historyList; var win_prize_historyTitleSize = 50; var win_prize_historyBaseUrl ; function win_prize_history_init(_win_prize_historyList,baseUrl){ win_prize_historyList = eval('(' + _win_prize_historyList + ')'); win_prize_historyBaseUrl = baseUrl; win_prize_history_totalSize = win_prize_historyList.length; win_prize_history_generatePage(); win_prize_history_go2Page(1); } function win_prize_history_generatePage(){ var pagehtml="<a href=\"javascript:win_prize_history_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<win_prize_history_totalSize/win_prize_history_pageSize;i++){ var id = i+1; pagehtml+="<a id=win_prize_history_"+id+" href=\"javascript:win_prize_history_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:win_prize_history_goNext()\" class=\"next\">下一页</a>" $("#win_prize_history_page").html(pagehtml) } function win_prize_history_goPrev(){ if(win_prize_history_currentPage>0){ win_prize_history_go2Page(win_prize_history_currentPage); } } function win_prize_history_goNext(){ if(win_prize_history_currentPage<(win_prize_history_totalSize/win_prize_history_pageSize-1)){ win_prize_history_go2Page(win_prize_history_currentPage+2); } } function win_prize_history_go2Page(id){ win_prize_history_currentPage = id-1; var html=""; for(var i = win_prize_history_currentPage*win_prize_history_pageSize;i<(win_prize_history_currentPage+1)*win_prize_history_pageSize&&i<win_prize_history_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+win_prize_historyBaseUrl+"/student/content/detail.html?id="+win_prize_historyList[i].id+"\" title="+win_prize_historyList[i].title+" href=\"#\" title="+win_prize_historyList[i].title+"><span class=\"new\">"; var tempTitle; if(win_prize_historyList[i].title.length>win_prize_historyTitleSize){ tempTitle = win_prize_historyList[i].title.substring(0,win_prize_historyTitleSize)+"..."; }else{ tempTitle = win_prize_historyList[i].title; } html+=tempTitle+"</span><span class=\"date\">"+win_prize_historyList[i].create_date+"</span>"; html+="</a>"; } $("#win_prize_history").empty(); $("#win_prize_history").append(html); //设置点中的样式 for(var i=1;i<=win_prize_history_totalSize/win_prize_history_pageSize;i++){ $("#win_prize_history_"+i).attr("class",""); } $("#win_prize_history_"+id).attr("class","cur"); } <file_sep>package org.sevenstar.app.common.context; import org.sevenstar.app.common.exception.UnLoginException; import org.sevenstar.app.manager.domain.S_userDomain; import org.sevenstar.web.context.WebContext; import org.sevenstar.component.cache.ehcache.EHCacheHelper; import org.sevenstar.persistent.db.ibatis.IbatisDao; import org.sevenstar.util.CookieHelper; import org.sevenstar.component.security.AES; /** * @author rtm 2008-5-8 封装对session操作 */ public class ApplicationContext { public static void put(S_userDomain userDomain) { if (!EHCacheHelper.exists("login")) { EHCacheHelper.addCache("login"); EHCacheHelper.getCache("login").getCacheConfiguration() .setTimeToIdleSeconds(1800); EHCacheHelper.getCache("login").getCacheConfiguration() .setTimeToLiveSeconds(1800); EHCacheHelper.getCache("login").getCacheConfiguration() .setMaxElementsInMemory(500000); EHCacheHelper.getCache("login").getCacheConfiguration() .setDiskPersistent(false); } EHCacheHelper.put("login", userDomain.getId(), userDomain); /** * 第一次以数据库为准 */ long currentTime = IbatisDao.getCurrentDBTimeInMillis(); String value = userDomain.getId() + "___" + currentTime; value = AES.Encrypt(value); String path = WebContext.getContextPath(); if("".equals(path) || !path.endsWith("/")){ path = path + "/"; } // CookieHelper.setPath(path); CookieHelper.setAttribute("login", value, WebContext.getResponse()); } /* * 登出操作 */ public static void remove() { String path = WebContext.getContextPath(); if("".equals(path) || !path.endsWith("/")){ path = path + "/"; } // CookieHelper.setPath(path); CookieHelper.setAttribute("login", "", WebContext.getResponse()); } public static S_userDomain get() { if (hasLogin()) { String value = CookieHelper.getAttribute("login", WebContext .getRequest()); value = AES.Decrypt(value); String loginid = value.substring(0, value.indexOf("___")); if (EHCacheHelper.get("login", loginid) != null) { return (S_userDomain) EHCacheHelper.get("login", loginid); } else { /** * 根据id到数据库load */ S_userDomain param = new S_userDomain(); param.setId(Long.valueOf(loginid)); try { param.loadEqual(); } catch (Exception e) { throw new UnLoginException(); } EHCacheHelper.put("login", param.getId(), param); return param; } } throw new UnLoginException(); } public static boolean hasLogin() { if (WebContext.getRequest() == null) { return false; } String value = CookieHelper.getAttribute("login", WebContext .getRequest()); if (value == null || "".equals(value) || value.toLowerCase().startsWith("null")) { return false; } try { value = AES.Decrypt(value); } catch (Exception e) { return false; } if (value == null || "".equals(value) || value.indexOf("___") == -1) { return false; } String loginid = value.substring(0, value.indexOf("___")); String logintime = value.substring(value.indexOf("___") + "___".length()); if (loginid == null || "".equals(loginid) || logintime == null || "".equals(logintime) || loginid.toLowerCase().startsWith("null")) { return false; } try { long logintimel = Long.parseLong(logintime); long currenttime = System.currentTimeMillis(); /** * 判断登录时间,第一次判断本机时间,误差2分钟之内,算通过 */ if ((currenttime < logintimel && (logintimel - currenttime) > 2 * 60 * 1000) || currenttime - logintimel > 1800 * 1000) { currenttime = IbatisDao.getCurrentDBTimeInMillis(); if (currenttime < logintimel || currenttime - logintimel > 1800 * 1000) { return false; } } String newValue = loginid + "___" + currenttime; /** * 刷新登录时间 */ if (WebContext.getRequest() .getAttribute("HASSETCOOKIE_APPLICATION") == null) { String path = WebContext.getContextPath(); if("".equals(path) || !path.endsWith("/")){ path = path + "/"; } // CookieHelper.setPath(path); CookieHelper.setAttribute("login", AES.Encrypt(newValue), WebContext.getResponse()); WebContext.getRequest().setAttribute( "HASSETCOOKIE_APPLICATION", "yes"); } return true; } catch (Exception e) { return false; } } } <file_sep>package cn.edu.zjut.servlet; import java.io.BufferedOutputStream; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadFileServlet extends HttpServlet { @SuppressWarnings({ "unchecked" }) public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); java.io.BufferedInputStream bis = null; java.io.BufferedOutputStream bos = null; String agent = request.getHeader("User-Agent"); boolean isMSIE = (agent!=null && agent.indexOf("MSIE")!=-1); String filePath = request.getParameter("filePath"); filePath = filePath.replace(filePath.substring(0, filePath.indexOf("resourcefile")), ""); if(!filePath.substring(0,1).equals("/")){ filePath = "/"+filePath; } String fileName = request.getParameter("fileName"); try { long fileLength = new File(this.getServletConfig().getServletContext().getRealPath("")+filePath).length(); response.setContentType("application/x-msdownload;"); if(isMSIE){ response.setHeader("Content-disposition", "attachment; filename=" +URLEncoder.encode(fileName+suffix(filePath),"UTF-8")); }else{ response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName+suffix(filePath)).getBytes("utf-8"), "ISO8859-1")); } response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(this.getServletConfig().getServletContext().getRealPath("")+filePath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { // e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } private String suffix(String path){ return path.substring(path.lastIndexOf("."), path.length()); } } <file_sep>$(function(){ //二级导航 $('.header .nav li div').hover(function(){ $(this).css('height',($(this).find('a').length * 25) +'px'); },function(){ $(this).css('height','25px'); }); //导航 $('.leftNav li').on('click',function(){ var index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $(this).parent().next().find('.tabBody:eq('+index+')').addClass('active').siblings().removeClass('active'); return false; }); //选项卡 $('.tab_t li').on('click',function(){ var index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $(this).parent().siblings('.tab_c:eq('+index+')').addClass('active').siblings().removeClass('active'); }); $('.gallery_js .prev').on('click',function(){ var $this = $(this); var $hid = $this.siblings('.hid'); var li_n = $hid.find('li').length; var li_w = 79; var ul_w = li_w * li_n; var $ul = $hid.find('ul'); var mag = parseInt($ul.css('margin-left'),10); $ul.css('width',ul_w); if(!$ul.is(':animated')){ if (mag <= li_w*3 - ul_w) { $ul.animate({'margin-left':'0'},400); } else { $ul.animate({'margin-left':(mag - li_w) + 'px'},400); } } }); $('.gallery_js .next').on('click',function(){ var $this = $(this); var $hid = $this.siblings('.hid'); var li_n = $hid.find('li').length; var li_w = 79; var ul_w = li_w * li_n; var $ul = $hid.find('ul'); var mag = parseInt($ul.css('margin-left'),10); $ul.css('width',ul_w); if(!$ul.is(':animated')){ if (mag >= 0) { $ul.animate({'margin-left':(li_w*3 - ul_w) +'px'},400); } else { $ul.animate({'margin-left':(mag + li_w) + 'px'},400); } } }); setInterval(function(){ $('.gallery_js .prev').trigger('click'); },3000); $('.col_2 .down .list li').click(function(){ var $me = $(this).find('img'), src = $me.attr('src'), info = $me.attr('data-info'); var link = $me.attr('link'); $(this).addClass('active').siblings().removeClass('active'); var $show = $me.closest('.down').find('.show'); $show.find('img').attr('src',src); $show.find('img').click(function(){ location.href=link; }); $show.find('p').html(info); $show.find('p').click(function(){ location.href=link; }); }); });<file_sep>package org.sevenstar.app.resource.action; import java.util.List; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.resource.domain.S_resourceDomain; import org.sevenstar.persistent.db.transaction.SSTransaction; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import org.sevenstar.web.annotation.SSList; @SSAction(name = "s_resource") public class S_resourceAction extends DefaultAction { private S_resourceDomain s_resourceDomain; @SSList(type="org.sevenstar.app.resource.domain.S_resourceDomain") private List resourceList; @SSTransaction public String insertOrUpdate() { if(s_resourceDomain == null ){ throw new ApplicationException("请录入资源信息"); } s_resourceDomain.insertOrUpdate(); return "编辑资源["+s_resourceDomain.getName()+"]成功"; } @SSTransaction public String deleteList(){ if(resourceList == null || resourceList.size() == 0){ throw new ApplicationException("请选择一项资源"); } for(int i=0;i<resourceList.size();i++){ S_resourceDomain domain = (S_resourceDomain)resourceList.get(i); domain.delete(); } return "批量删除成功"; } public S_resourceDomain getS_resourceDomain() { return s_resourceDomain; } public void setS_resourceDomain(S_resourceDomain domain) { s_resourceDomain = domain; } public List getResourceList() { return resourceList; } public void setResourceList(List resourceList) { this.resourceList = resourceList; } } <file_sep>ע��:�˰汾Ϊ 4.0 ��ʽ�� build 20080807 ������ʾ��ʹ��˵��,�󲿷����ⶼ����ͨ��������,��ϸ�� http://www.my97.net/dp/demo/ ��������������(������ʱ,һ��Ҫ������ص�HTML�������ϸ�Ĵ�����Ϣ): www.my97.net/dp/support.asp ���� http://my97.cnblogs.com http://blog.csdn.net/my97/ onFocus="WdatePicker({maxDate:'#F\{$dp.$D('_end_date_')\}'})" <file_sep>package cn.edu.zjut.web.action; import java.util.Date; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import cn.edu.zjut.cfg.domain.Zjut_contentDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.service.Zjut_contentService; @SSAction(name = "zjut_content") public class Zjut_contentDomainAction extends DefaultAction { private Zjut_contentDomain zjut_contentDomain; private Zjut_organizationDomain organizationDomain; public String delete() { if (zjut_contentDomain == null || zjut_contentDomain.getId() == null) { throw new RuntimeException("缺少参数,不能删除"); } zjut_contentDomain.loadEqual(); zjut_contentDomain.delete(); Zjut_contentService.instance.load(); return "删除[" + zjut_contentDomain.getTitle() + "]成功!"; } public String insertOrUpdate() { if (zjut_contentDomain == null || zjut_contentDomain.getTypeDomain().getId() == null || zjut_contentDomain.getOrganizationDomain().getId() == null) { throw new RuntimeException("缺少参数,不能编辑"); } zjut_contentDomain.getTypeDomain().loadEqual(); zjut_contentDomain.getOrganizationDomain().loadEqual(); zjut_contentDomain.setModify_date(new Date()); zjut_contentDomain.setModifyUserDomain(ApplicationContext.get()); zjut_contentDomain.insertOrUpdate(); Zjut_contentService.instance.load(); return "编辑[" + zjut_contentDomain.getTitle() + "]成功!"; } public Zjut_contentDomain getZjut_contentDomain() { return zjut_contentDomain; } public void setZjut_contentDomain(Zjut_contentDomain zjut_contentDomain) { this.zjut_contentDomain = zjut_contentDomain; } public Zjut_organizationDomain getOrganizationDomain() { return organizationDomain; } public void setOrganizationDomain(Zjut_organizationDomain organizationDomain) { this.organizationDomain = organizationDomain; } } <file_sep>package cn.edu.zjut.web.page.student; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_contentDomain; public class Content extends DefaultAction { private Long id; private Zjut_contentDomain zjut_contentDomain; public String detail() { if (id == null) { throw new RuntimeException("缺少参数,不能查看!"); } zjut_contentDomain = new Zjut_contentDomain(); zjut_contentDomain.setId(id); try { zjut_contentDomain.loadEqual(); } catch (RuntimeException e) { throw new RuntimeException("没有指定的内容可以查看!"); } return super.SUCCESS; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Zjut_contentDomain getZjut_contentDomain() { return zjut_contentDomain; } public void setZjut_contentDomain(Zjut_contentDomain zjut_contentDomain) { this.zjut_contentDomain = zjut_contentDomain; } } <file_sep>package cn.edu.zjut.web.action; import java.io.IOException; import java.io.StringWriter; import java.util.Map; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import cn.edu.zjut.cfg.bean.ApplicationDegreeBean; import cn.edu.zjut.cfg.bean.ApplicationProgramBean; import cn.edu.zjut.util.MailUtil; import cn.edu.zjut.util.ObjectFormat; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; @SSAction(name = "zjut_application") public class Zjut_applicationAction extends DefaultAction { private ApplicationProgramBean appProgramBean; private ApplicationDegreeBean appDegreeBean; public String send2Email() { if (appProgramBean == null) { throw new RuntimeException("缺少参数!"); } Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(MailUtil.class, ""); try { Template temp = cfg.getTemplate("application_program.ftl", "utf-8"); StringWriter sw = new StringWriter(); Map map = ObjectFormat.object2Map(appProgramBean); temp.process(map, sw); MailUtil mailUtil = new MailUtil("smtp.zjut.edu.cn", "<EMAIL>", "zjut", "iec", "gjxy1514", "<EMAIL>", "工大教育文件", sw.toString()); mailUtil.send(); return "send success!"; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "send fail!"; } public String sendDegree2Email() { if (appDegreeBean == null) { throw new RuntimeException("缺少参数!"); } Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(MailUtil.class, ""); try { Template temp = cfg.getTemplate("application_degree.ftl", "utf-8"); StringWriter sw = new StringWriter(); Map map = ObjectFormat.object2Map(appDegreeBean); temp.process(map, sw); MailUtil mailUtil = new MailUtil("smtp.zjut.edu.cn", "<EMAIL>", "zjut", "iec", "gjxy1514", "<EMAIL>", "工大教育文件", sw.toString()); mailUtil.send(); return "send success!"; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "send fail!"; } public ApplicationProgramBean getAppProgramBean() { return appProgramBean; } public void setAppProgramBean(ApplicationProgramBean appProgramBean) { this.appProgramBean = appProgramBean; } public ApplicationDegreeBean getAppDegreeBean() { return appDegreeBean; } public void setAppDegreeBean(ApplicationDegreeBean appDegreeBean) { this.appDegreeBean = appDegreeBean; } } <file_sep>package cn.edu.zjut.cfg.service; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; import cn.edu.zjut.cfg.domain.Zjut_faqsDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_faqDomain; public enum Zjut_faqsService { instance; public Map<String,List<Zjut_faqsDomain>> faqsMap = null; public void reload(){ faqsMap = new HashMap<String,List<Zjut_faqsDomain>>(); List<Zjut_organizationDomain> organizationList = (new Zjut_organizationDomain()).selectAll(); for(Zjut_organizationDomain organizationDomain : organizationList){ List<Zjut_faqsDomain> temps = new ArrayList<Zjut_faqsDomain>(); Zjut_organization_faqDomain zjut_organization_faqDomain = new Zjut_organization_faqDomain(); zjut_organization_faqDomain.setOrganizationDomain(organizationDomain); List<Zjut_organization_faqDomain> organization_faqList = zjut_organization_faqDomain.selectEqual(); for(Zjut_organization_faqDomain organizationFaqDomain : organization_faqList){ temps.add(organizationFaqDomain.getFaqsDomain()); } faqsMap.put(organizationDomain.getName(), temps); } } public List<Zjut_faqsDomain> getFaqsList(String organizatioName){ if(faqsMap == null){ reload(); } return faqsMap.get(organizatioName); } public List<Zjut_faqsDomain> getFaqsListUseTop(String organizatioName){ List<Zjut_faqsDomain> list = getFaqsList(organizatioName); List<Zjut_faqsDomain> topList = new ArrayList<Zjut_faqsDomain>(); List<Zjut_faqsDomain> unTopList = new ArrayList<Zjut_faqsDomain>(); for(Zjut_faqsDomain faqDomain : list){ if("Y".equalsIgnoreCase(faqDomain.getIs_top())){ topList.add(faqDomain); }else{ unTopList.add(faqDomain); } } topList.addAll(unTopList); return topList; } } <file_sep>/** * 数据分页 */ //取数据的开始索引 var start=0; //分页数据的每页展示数量 var step=10; //每行展示的数据量 var cellStep=2; //列表 var objectlist; //外围容器 var divname; var tablename; //初始化设置 function init_ben_assort(_start,_step,_cellStep){ start = _start; step = _step; cellStep = _cellStep; } /** * 开始分页 * */ function startpage_ben_assrot(_objectlist,_tableObj){ //alert(_objectlist); tablename = _tableObj; objectlist = eval('(' + _objectlist + ')'); //deleteDivContent(_tableObj); var end; if(start+step>=objectlist.length)end = objectlist.length; else end = start+step; //var tableObj = createTableObject_assort(); var tableObj = document.getElementById(_tableObj); //createTableHead(tableObj); clearSearchTable(tableObj); createTableBodytTd(tableObj,start,end); //document.getElementById(divname).appendChild(tableObj); createPageTr(tableObj,start,end); } function insertAssortTable(startIndex,endIndex){ //deleteDivContent(divname); //var tableObj = createTableObject_assort(); var tableObj = document.getElementById(tablename); //createTableHead(tableObj); clearSearchTable(tableObj); createTableBodytTd(tableObj,startIndex,endIndex); //document.getElementById(divname).appendChild(tableObj); createPageTr(tableObj,startIndex,endIndex); } /** * 根据分类彩铃的展示要求创建一个table对象返回 */ function createTableObject_assort(){ var tableObject = document.createElement("table"); tableObject.width = "100%"; tableObject.border = "0"; tableObject.cellspacing = "0"; tableObject.cellpadding = "0"; return tableObject; } /** * 删除指定div的内容 */ function deleteDivContent(divname){ document.getElementById(divname).innerHTML = ""; } /** * 删除指定table的obj */ function clearSearchTable(obj){ //alert(obj.rows.length); for(var i =obj.rows.length;i>1;i--){ obj.deleteRow(i-1); } } /** * 创建表的头部格式 */ function createTableHead(tableObj){ var tr = tableObj.insertRow(tableObj.rows.length); for(var i=0;i<cellStep;i++){ var td1 = tr.insertCell(4*i); var td2 = tr.insertCell(4*i+1); var td3 = tr.insertCell(4*i+2); var td4 = tr.insertCell(4*i+3) tdHeadStyle_assrot(td1,td2,td3,td4); } } /** * 根据分类彩铃的要求设置头部的样式 */ function tdHeadStyle_assrot(td1,td2,td3,td4){ td1.innerHTML = "歌曲名称"; td1.width = "36%"; td1.scope="col"; td2.innerHTML = "歌手"; td2.width = "26%"; td2.scope="col"; td3.innerHTML = "试听"; td3.width = "16%"; td3.scope="col"; td4.innerHTML = "定制"; td4.width = "28%"; td4.scope="col"; } /** * 创建分页主体 */ function createTableBodytTd(tableObj,_start,_end){ //var img1 = baseUrl+"/images/pic/chailing_yiny.gif"; //var img2 = baseUrl+"/images/pic/chailing_save.gif"; var img1 = baseUrl+"/images/pic/chialing_ting.gif"; var img2 = baseUrl+"/images/pic/chailing_phoe.gif"; if(_start>=objectlist.length)return; if(_end>objectlist.length)return; if(_start>=_end)return; var trindex = 1; for(var i=_start;i<_end;i++){ var tr=tableObj.insertRow(tableObj.rows.length); if(trindex%2 == 1){ tr.className="alt"; } for(var j = 0;j < cellStep;j++){ var td0 = tr.insertCell(4*j); td0.innerHTML = "&nbsp;"; var td1 = tr.insertCell(4*j+1); td1.title = objectlist[i].tonename; if(objectlist[i].tonename.length>8){ td1.innerHTML = (i+1)+"."+objectlist[i].tonename.substring(0,7)+".."; }else{ td1.innerHTML = (i+1)+"."+objectlist[i].tonename; } var td2 = tr.insertCell(4*j+2); td2.title=objectlist[i].singer; if(objectlist[i].singer.length>7){ td2.innerHTML = objectlist[i].singer.substring(0,6)+".."; }else{ td2.innerHTML = objectlist[i].singer; } var td3 = tr.insertCell(4*j+3); td3.innerHTML = objectlist[i].tonevalidday; var td4 = tr.insertCell(4*j+4); td4.innerHTML = objectlist[i].price; var td5 = tr.insertCell(4*j+5); td5.innerHTML = "<a href='javascript:getToneDetailSub(\""+objectlist[i].tonecode+"\",\""+objectlist[i].singer+"\",\""+objectlist[i].tonename+"\",\""+objectlist[i].toneinfo+"\",\""+objectlist[i].price+"\",\""+objectlist[i].tonevalidday+"\",\""+objectlist[i].updatetime+"\",\""+objectlist[i].downloadtimes+"\",\""+objectlist[i].prelistenurl+"\",\"\",\"false\")'><img src='"+img1+"' alt=\"试听\" /></a>"; var td6 = tr.insertCell(4*j+6); td6.innerHTML = "&nbsp"; var td7 = tr.insertCell(4*j+7); td7.colSpan="2"; td7.innerHTML = "<a href='javascript:getToneDetailSub(\""+objectlist[i].tonecode+"\",\""+objectlist[i].singer+"\",\""+objectlist[i].tonename+"\",\""+objectlist[i].toneinfo+"\",\""+objectlist[i].price+"\",\""+objectlist[i].tonevalidday+"\",\""+objectlist[i].updatetime+"\",\""+objectlist[i].downloadtimes+"\",\""+objectlist[i].prelistenurl+"\",\"\",\"true\")'><img src='"+img2+"' alt=\"定制\" /></a>"; i = i+j; if(i>=_start+step)break; } if(i>=_start+step)break; trindex++; } } function createPageTr(tableObj,starIndex,endIndex){ var tr = tableObj.insertRow(tableObj.rows.length); td = tr.insertCell(0); //td.colSpan = 8*cellStep+''; td.colSpan = '8'; var totalPage = Math.ceil(objectlist.length/step); var currentPage = Math.ceil(starIndex/step); td.innerHTML = "<table id='assrotCurrentIndexTable' width='100%'></table>"; var tableObj = document.getElementById("assrotCurrentIndexTable"); var tr = tableObj.insertRow(0); var td1 = tr.insertCell(0); td1.width="10%"; td1.align="center"; if(starIndex>=step){ td1.innerHTML = "<a href='javascript:insertAssortTable(0,"+step+")'>返回最前</a>"; }else{ td1.innerHTML = "<a>返回最前</a>"; } var td2 = tr.insertCell(1); td2.width="10%"; td2.align="center"; if(starIndex>=step){ td2.innerHTML = "<a href='javascript:insertAssortTable("+(starIndex-step)+","+starIndex+")'>上一页</a>"; }else{ td2.innerHTML = "<a>上一页</a>"; } var td3 = tr.insertCell(2); td3.width="15%"; td3.align="center"; td3.innerHTML = "Page <input type='text' size='1' id='currentIndex' value='"+(currentPage+1)+"' >of&nbsp;"+totalPage; var td4 = tr.insertCell(3); td4.width="10%"; td4.align="center"; if(endIndex>=objectlist.length){ td4.innerHTML = "<a>下一页<a>"; }else{ if((endIndex+step)>objectlist.length){ td4.innerHTML = "<a href='javascript:insertAssortTable("+endIndex+","+objectlist.length+")'>下一页<a>"; }else{ td4.innerHTML = "<a href='javascript:insertAssortTable("+endIndex+","+(endIndex+step)+")'>下一页<a>"; } } var td5 = tr.insertCell(4); td5.width="10%"; td5.align="center"; if(endIndex>=objectlist.length){ td5.innerHTML = "<a>最后一页</a>"; }else{ td5.innerHTML = "<a href='javascript:insertAssortTable("+step*(totalPage-1)+","+objectlist.length+")'>最后一页</a>"; } var td6 = tr.insertCell(5); td6.align='right'; td6.width="45%"; td6.innerHTML = "显示第"+starIndex+"到第"+endIndex+"记录,共"+objectlist.length+"条记录"; } <file_sep>package org.sevenstar.web.view.freemarker; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sevenstar.util.BeanHelper; import org.sevenstar.util.RegexpHelper; import org.sevenstar.web.Constants; import org.sevenstar.web.action.Action; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.cfg.SwebConfigure; import org.sevenstar.web.cfg.model.RuleModel; import org.sevenstar.web.context.WebContext; import org.sevenstar.web.exception.ActionException; import org.sevenstar.web.resource.IResource; import org.sevenstar.web.view.Result; import com.opensymphony.xwork.ActionContext; import freemarker.template.Template; import freemarker.template.TemplateException; public class FreemarkerResult implements Result { private Log LOG = LogFactory.getLog(FreemarkerResult.class); private Map paramMap; private static boolean hasSetTemplateCacheTime = false; private static Object LockedObject = new Object(); private final static String TemplateCache = "TemplateCache"; private final static String cahceExclude = "cahceExclude"; public Map getParamMap() { if (paramMap == null) { paramMap = new HashMap(); } return paramMap; } public void setParamMap(Map map) { this.paramMap = map; if (map.get("errorLocation") != null) { errorLocation = String.valueOf(map.get("errorLocation")); } } private static boolean hasSetSharedVariable = false; private static String errorLocation = null; public void flow(Action action, Object location) { LOG.debug("result[FreemarkerResult]:called location[" + location + "]"); RuleModel ruleModel = SwebConfigure.getUrlModel(WebContext.getUrl()); freemarker.template.Configuration freemarkConfig = null; if (ruleModel.getEncode() != null && !"".equals(ruleModel.getEncode())) { freemarkConfig = FreemarkerManager.getConfiguration(ruleModel .getEncode()); } else { freemarkConfig = FreemarkerManager.getConfiguration(SwebConfigure .getSwebModel().getEncode()); } ScopesHashModel model = (ScopesHashModel) FreemarkerManager .createModel(WebContext.getServletContext(), WebContext .getRequest(), WebContext.getResponse(), ActionContext .getContext()); IResource ir = SwebConfigure.getResourceByUrl(WebContext.getUrl()); ActionContext.getContext().put("i18n", ir); ActionContext.getContext().getValueStack().push(action); if (location instanceof String) { if (((String) location).indexOf("?") != -1) { location = ((String) location).substring(0, ((String) location) .indexOf("?")); } } try { // freemarkConfig.setSharedVariable("DateHelper", new DateHelper()); if (!hasSetSharedVariable) { try { synchronized (LockedObject) { Iterator paramIterator = getParamMap().keySet() .iterator(); while (paramIterator.hasNext()) { String key = String.valueOf(paramIterator.next()); String classPath = String.valueOf(getParamMap() .get(key)); if (hasClass(classPath)) { freemarkConfig.setSharedVariable(key, BeanHelper.newInstance(classPath)); } } /** * 整合spring,设置spring中定义bean为freemarker的shared variable */ SpringFreemarkerIntergrade.inject(WebContext .getServletContext(), freemarkConfig); } } finally { hasSetSharedVariable = true; } } Template template = getTemplate(freemarkConfig, (String) location); if (ruleModel.getEncode() != null && !"".equals(ruleModel.getEncode())) { template.setEncoding(ruleModel.getEncode()); WebContext.getResponse().setCharacterEncoding( ruleModel.getEncode()); } else { template.setEncoding(SwebConfigure.getSwebModel().getEncode()); WebContext.getResponse().setCharacterEncoding( SwebConfigure.getSwebModel().getEncode()); } /** * 登陆页面需要缓存用户名密码 */ if (!cahceExclude(String.valueOf(location))) { WebContext.getResponse().setHeader("Pragma", "no-cache"); WebContext.getResponse().setHeader("Cache-Control", "no-cache"); WebContext.getResponse().setDateHeader("Expires", 0); } if (WebContext.getUrl().endsWith(".js")) { WebContext.getResponse().setContentType("text/javascript"); } else if (WebContext.getUrl().endsWith(".css")) { WebContext.getResponse().setContentType("text/css"); } else if (WebContext.getUrl().endsWith("html") || WebContext.getUrl().endsWith("htm")) { WebContext.getResponse().setContentType("text/html"); } StringWriter writer = new StringWriter(); long startTime = System.currentTimeMillis(); try { template.process(model, writer); writer.flush(); } catch (Throwable e) { e.printStackTrace(); if (errorLocation != null) { Throwable trowable = e; while (trowable.getCause() != null) { if (trowable instanceof InvocationTargetException) { trowable = ((InvocationTargetException) trowable) .getTargetException(); } if (trowable.getCause() != null) { trowable = trowable.getCause(); } } if (action instanceof DefaultAction) { ((DefaultAction) action).setMsg("render error:" + trowable.getMessage()); } else { ActionContext.getContext().put("msg", "render error:" + trowable.getMessage()); } writer.flush(); writer.close(); writer = new StringWriter(); template = this.getTemplate(freemarkConfig, errorLocation); template.process(model, writer); writer.flush(); } } finally { LOG.debug("render template[" + location + "] couttime[" + (System.currentTimeMillis() - startTime) + "]"); try { writer.close(); } catch (Exception e) { LOG.error(e); } } ServletOutputStream sos = WebContext.getResponse() .getOutputStream(); try { if (ruleModel.getEncode() != null && !"".equals(ruleModel.getEncode())) { sos .write(writer.toString().getBytes( ruleModel.getEncode())); } else { String result = writer.toString(); sos.write(result.getBytes(SwebConfigure.getSwebModel() .getEncode())); } } finally { if (shouldClose()) { sos.close(); } } } catch (IOException e) { e.printStackTrace(); throw new ActionException(e); } catch (TemplateException e) { e.printStackTrace(); throw new ActionException(e); } } private boolean cahceExclude(String url) { if (getParamMap().get(cahceExclude) != null && !"".equals(getParamMap().get(cahceExclude))) { String excludeUrls = (String) getParamMap().get(cahceExclude); if (excludeUrls.indexOf(Constants.separator) == -1) { return RegexpHelper.isGlobmatches(url, excludeUrls); } else { String[] excludeUrlss = excludeUrls.split(Constants.separator); boolean flag = false; for (int i = 0; i < excludeUrlss.length; i++) { if (RegexpHelper.isGlobmatches(url, excludeUrlss[i])) { flag = true; } } return flag; } } return false; } private boolean shouldClose() { if ("true".equalsIgnoreCase((String) getParamMap().get("close")) || "Y".equalsIgnoreCase((String) getParamMap().get("close"))) { return true; } return false; } private boolean hasClass(String classPath) { try { Class.forName(classPath); return true; } catch (Exception e) { return false; } } private Template getTemplate( freemarker.template.Configuration freemarkConfig, String location) throws IOException { if (getParamMap().get(TemplateCache) != null) { try { if (!hasSetTemplateCacheTime) { int cacheTimes = Integer.parseInt((String) getParamMap() .get(TemplateCache)); freemarkConfig.setTemplateUpdateDelay(cacheTimes); synchronized (LockedObject) { hasSetTemplateCacheTime = true; } } } catch (Exception e) { synchronized (LockedObject) { hasSetTemplateCacheTime = true; } return freemarkConfig.getTemplate(location); } } return freemarkConfig.getTemplate(location); } } <file_sep>package org.sevenstar.app.manager.action; import java.util.List; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.util.BeanHelper; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import org.sevenstar.web.annotation.SSList; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.manager.domain.S_org_positionDomain; import org.sevenstar.app.manager.relation.domain.S_org_positionroleDomain; import org.sevenstar.app.rbac.domain.S_rbac_roleDomain; @SSAction(name = "s_org_position") public class S_org_positionAction extends DefaultAction { private S_org_positionDomain s_org_positionDomain; @SSList(type = "org.sevenstar.app.manager.domain.S_org_positionDomain") private List positionList; @SSList(type = "org.sevenstar.app.rbac.domain.S_rbac_roleDomain") private List roleList; private IbatisPage page; public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public IbatisPage query() { if (s_org_positionDomain == null) { s_org_positionDomain = new S_org_positionDomain(); } page = s_org_positionDomain.getSelectPage(page); List dataList = page.getDataList(); if (dataList != null && dataList.size() > 0) { for (int i = 0; i < dataList.size(); i++) { S_org_positionDomain positionDomain = (S_org_positionDomain) dataList .get(i); S_org_positionDomain newPositionDomain = new S_org_positionDomain(); BeanHelper.copyNotNullPrimitiveProperties(positionDomain, newPositionDomain); dataList.set(i, newPositionDomain); } } return page; } public String deleteList() throws Exception { if (positionList == null || positionList.size() == 0) { throw new ApplicationException("请先选择职位"); } super.setMsg("批量删除职位成功"); for (int i = 0; i < positionList.size(); i++) { S_org_positionDomain positionDomain = (S_org_positionDomain) positionList .get(i); positionDomain.load(); super .setNextUrl("app/manager/org/position/list.htm?s_orgDomain.id=" + positionDomain.getOrgDomain().getId()); positionDomain.delete(); } return super.REDIRECT; } public String delete() throws Exception { super.setMsg("删除职位[" + s_org_positionDomain.getName() + "]成功"); s_org_positionDomain.load(); super.setNextUrl("app/manager/org/position/list.htm?s_orgDomain.id=" + s_org_positionDomain.getOrgDomain().getId()); s_org_positionDomain.delete(); return super.REDIRECT; } public String insert() throws Exception { s_org_positionDomain.insert(); if (roleList != null && roleList.size() > 0) { for (int i = 0; i < roleList.size(); i++) { S_org_positionroleDomain s_org_positionroleDomain = new S_org_positionroleDomain(); s_org_positionroleDomain .setPositionDomain(s_org_positionDomain); s_org_positionroleDomain .setRoleDomain((S_rbac_roleDomain) roleList.get(i)); s_org_positionroleDomain.insert(); } } super.setMsg("增加职位[" + s_org_positionDomain.getName() + "]成功"); super.setNextUrl("app/manager/org/position/list.htm?s_orgDomain.id=" + s_org_positionDomain.getOrgDomain().getId()); return super.REDIRECT; } public String update() throws Exception { s_org_positionDomain.update(); doUpdateRole(); super.setMsg("修改职位[" + s_org_positionDomain.getName() + "]成功"); super.setNextUrl("app/manager/org/position/list.htm?s_orgDomain.id=" + s_org_positionDomain.getOrgDomain().getId()); return super.REDIRECT; } private void doUpdateRole() { S_org_positionroleDomain paramDomain = new S_org_positionroleDomain(); paramDomain.setPositionDomain(s_org_positionDomain); List groupRoleList = paramDomain.selectEqual(); for (int i = 0; i < groupRoleList.size(); i++) { S_org_positionroleDomain positionroleDomain = (S_org_positionroleDomain) groupRoleList .get(i); positionroleDomain.delete(); } if (roleList != null && roleList.size() > 0) { for (int i = 0; i < roleList.size(); i++) { S_org_positionroleDomain s_org_positionroleDomain = new S_org_positionroleDomain(); s_org_positionroleDomain .setPositionDomain(s_org_positionDomain); s_org_positionroleDomain .setRoleDomain((S_rbac_roleDomain) roleList.get(i)); s_org_positionroleDomain.insert(); } } } public String insertOrUpdate() throws Exception { s_org_positionDomain.insertOrUpdate(); doUpdateRole(); return "编辑职位[" + s_org_positionDomain.getName() + "]成功"; } public S_org_positionDomain getS_org_positionDomain() { return s_org_positionDomain; } public void setS_org_positionDomain( S_org_positionDomain s_org_positionDomain) { this.s_org_positionDomain = s_org_positionDomain; } public List getPositionList() { return positionList; } public void setPositionList(List positionList) { this.positionList = positionList; } public List getRoleList() { return roleList; } public void setRoleList(List roleList) { this.roleList = roleList; } } <file_sep>package org.sevenstar.app.manager.tree; import java.util.List; import org.sevenstar.app.manager.domain.S_orgDomain; import org.sevenstar.app.manager.service.S_orgService; import org.sevenstar.component.tag.tree.Tree; /** * @author rtm 2008-5-8 */ public class OrgTree extends Tree{ public void getChildren(String id) { S_orgService s_orgService = new S_orgService(); if("null".equals(id) || id == null || "".equals(id) || "-1".equals(id) || "0".equals(id)){ List firstLevelList = s_orgService.selectFirstLevelList(); for(int i=0;i<firstLevelList.size();i++){ S_orgDomain domain = (S_orgDomain)firstLevelList.get(i); if(domain.getChildList().size() > 0){ entity.addBranh(String.valueOf(domain.getId()),domain.getName(),null); }else{ entity.addLeaf(String.valueOf(domain.getId()),domain.getName(),null); } } }else{ S_orgDomain orgDomain = new S_orgDomain(); orgDomain.setId(Long.valueOf(id)); orgDomain.load(); List childList = orgDomain.getChildList(); for(int i=0;i<childList.size();i++){ S_orgDomain domain = (S_orgDomain)childList.get(i); if(domain.getChildList().size() > 0){ entity.addBranh(String.valueOf(domain.getId()),domain.getName(),null); }else{ entity.addLeaf(String.valueOf(domain.getId()),domain.getName(),null); } } } } } <file_sep>var zhu_totalSize; var zhu_currentPage=0; var zhu_pageSize = 5; var zhuList; var zhuTitleSize = 50; var zhuBaseUrl ; function zhu_init(_zhuList,baseUrl){ zhuList = eval('(' + _zhuList + ')'); zhuBaseUrl = baseUrl; zhu_totalSize = zhuList.length; zhu_generatePage(); zhu_go2Page(1); } function zhu_generatePage(){ var pagehtml="<a href=\"javascript:zhu_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<zhu_totalSize/zhu_pageSize;i++){ var id = i+1; pagehtml+="<a id=zhu_"+id+" href=\"javascript:zhu_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:zhu_goNext()\" class=\"next\">下一页</a>" $("#zhu_page").html(pagehtml) } function zhu_goPrev(){ if(zhu_currentPage>0){ zhu_go2Page(zhu_currentPage); } } function zhu_goNext(){ if(zhu_currentPage<(zhu_totalSize/zhu_pageSize-1)){ zhu_go2Page(zhu_currentPage+2); } } function zhu_go2Page(id){ zhu_currentPage = id-1; var html=""; for(var i = zhu_currentPage*zhu_pageSize;i<(zhu_currentPage+1)*zhu_pageSize&&i<zhu_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+zhuBaseUrl+"/student/content/detail.html?id="+zhuList[i].id+"\" title="+zhuList[i].title+" href=\"#\" title="+zhuList[i].title+"><span class=\"new\">"; var tempTitle; if(zhuList[i].title.length>zhuTitleSize){ tempTitle = zhuList[i].title.substring(0,zhuTitleSize)+"..."; }else{ tempTitle = zhuList[i].title; } html+=tempTitle+"</span>"; html+="</a>"; } $("#zhu").empty(); $("#zhu").append(html); //设置点中的样式 for(var i=1;i<=zhu_totalSize/zhu_pageSize;i++){ $("#zhu_"+i).attr("class",""); } $("#zhu_"+id).attr("class","cur"); } <file_sep>package org.sevenstar.component.tree; import net.jcreate.e3.tree.UncodeException; import net.jcreate.e3.tree.UserDataUncoder; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.component.tree.domain.TreeDomain; public class TreeDataUncoder implements UserDataUncoder{ public Object getID(Object menuData) throws UncodeException{ if(menuData instanceof TreeDomain){ return ((TreeDomain)menuData).getId(); } throw new ApplicationException("业务编码id错误,树中节点的数据类型错误!"); } public Object getParentID(Object menuData) throws UncodeException{ if(menuData instanceof TreeDomain){ return ((TreeDomain)menuData).getParentId(); } throw new ApplicationException("业务编码ParentId错误,树中节点的数据类型错误!"); } } <file_sep>package org.sevenstar.app.page.app.manager; import java.util.ArrayList; import java.util.List; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.manager.domain.S_orgDomain; import org.sevenstar.app.manager.domain.S_org_positionDomain; import org.sevenstar.app.manager.domain.S_userDomain; import org.sevenstar.app.manager.domain.S_user_typeDomain; import org.sevenstar.app.manager.service.S_orgService; import org.sevenstar.app.rbac.domain.S_rbac_groupDomain; import org.sevenstar.app.rbac.domain.S_rbac_roleDomain; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.util.BeanHelper; import org.sevenstar.web.action.java.DefaultAction; /** * @author rtm 2008-5-8 */ public class User extends DefaultAction { private S_userDomain s_userDomain; private IbatisPage page; private List groupList; private List roleList; private List positionList; private S_orgService s_orgService = new S_orgService(); private String inputID ; private String inputName ; private List userTypeList; public String list() { if(s_userDomain == null){ s_userDomain = new S_userDomain(); } page = s_userDomain.getSelectPage(page); return super.SUCCESS; } public String edit(){ if(s_userDomain == null || s_userDomain.getId() == null){ throw new ApplicationException("没有选中用户"); } s_userDomain.load(); userTypeList = (new S_user_typeDomain()).selectAll(); groupList = BeanHelper.copyNewList((new S_rbac_groupDomain()).selectAll()); roleList = BeanHelper.copyNewList((new S_rbac_roleDomain()).selectAll()); positionList = new ArrayList(); List firstLevelOrgList =s_orgService.selectFirstLevelList(); List hasSelectedGroupList = s_userDomain.getGroupList(); List hasSelectedRoleList = s_userDomain.getRoleList(); for(int i=0;i<groupList.size();i++){ S_rbac_groupDomain s_rbac_groupDomain = (S_rbac_groupDomain)groupList.get(i); for(int j=0;j<hasSelectedGroupList.size();j++){ S_rbac_groupDomain domain = (S_rbac_groupDomain)hasSelectedGroupList.get(j); if(domain.getId().equals(s_rbac_groupDomain.getId())){ groupList.remove(i); i--; continue; } } } for(int i=0;i<roleList.size();i++){ S_rbac_roleDomain s_rbac_roleDomain = (S_rbac_roleDomain)roleList.get(i); for(int j=0;j<hasSelectedRoleList.size();j++){ S_rbac_roleDomain domain = (S_rbac_roleDomain)hasSelectedRoleList.get(j); if(domain.getId().equals(s_rbac_roleDomain.getId())){ roleList.remove(i); i--; continue; } } } for(int i=0;i<firstLevelOrgList.size();i++){ S_orgDomain s_orgDomain = (S_orgDomain)firstLevelOrgList.get(i); addPosition(s_orgDomain); } return super.SUCCESS; } public String view(){ if(s_userDomain == null){ throw new ApplicationException("没有选中用户"); } s_userDomain.load(); userTypeList = (new S_user_typeDomain()).selectAll(); return super.SUCCESS; } private void addPosition(S_orgDomain s_orgDomain){ List orgPositionList = s_orgDomain.getPositionList(); List hasSelectPositionList = new ArrayList(); if(s_userDomain != null && s_userDomain.getPositionList() != null ){ hasSelectPositionList = s_userDomain.getPositionList(); } for(int i=0;i<orgPositionList.size();i++){ S_org_positionDomain positionDomain = (S_org_positionDomain)orgPositionList.get(i); boolean hasSelected = false; for(int j=0;j<hasSelectPositionList.size();j++){ S_org_positionDomain selectedPositionDomain = (S_org_positionDomain)hasSelectPositionList.get(j); if(positionDomain.getId().equals(selectedPositionDomain.getId())){ hasSelected = true; } } if(!hasSelected){ positionList.add(positionDomain); } } List childList = s_orgDomain.getChildList(); for(int i=0;i<childList.size();i++){ addPosition((S_orgDomain)childList.get(i)); } } public String input(){ groupList = (new S_rbac_groupDomain()).selectAll(); roleList = (new S_rbac_roleDomain()).selectAll(); positionList = new ArrayList(); userTypeList = (new S_user_typeDomain()).selectAll(); List firstLevelOrgList =s_orgService.selectFirstLevelList(); for(int i=0;i<firstLevelOrgList.size();i++){ S_orgDomain s_orgDomain = (S_orgDomain)firstLevelOrgList.get(i); addPosition(s_orgDomain); } return "app/manager/user/edit.html"; } public String userinfo() throws Exception{ return list(); } public List getGroupList() { return groupList; } public void setGroupList(List groupList) { this.groupList = groupList; } public List getRoleList() { return roleList; } public void setRoleList(List roleList) { this.roleList = roleList; } public S_userDomain getS_userDomain() { return s_userDomain; } public void setS_userDomain(S_userDomain domain) { s_userDomain = domain; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public List getPositionList() { return positionList; } public void setPositionList(List positionList) { this.positionList = positionList; } public List getUserTypeList() { return userTypeList; } public void setUserTypeList(List userTypeList) { this.userTypeList = userTypeList; } } <file_sep>package org.sevenstar.app.rbac.action; import java.util.List; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import org.sevenstar.web.annotation.SSList; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.rbac.domain.S_rbac_permissionDomain; @SSAction(name = "s_rbac_permission") public class S_rbac_permissionAction extends DefaultAction { private S_rbac_permissionDomain s_rbac_permissionDomain; @SSList(type="org.sevenstar.app.rbac.domain.S_rbac_permissionDomain") private List permissionList; public String deleteList() throws Exception { if (permissionList != null && permissionList.size() > 0) { for (int i = 0; i < permissionList.size(); i++) { S_rbac_permissionDomain s_rbac_permissionDomain = (S_rbac_permissionDomain) permissionList .get(i); s_rbac_permissionDomain.delete(); } } else { throw new ApplicationException("请先选择权限"); } return "批量删除权限成功"; } public String delete() throws Exception { super.setMsg("删除权限[" + s_rbac_permissionDomain.getName() + "]成功"); s_rbac_permissionDomain.delete(); super.setNextUrl("app/rbac/permission/list.html"); return super.REDIRECT; } public String insert() throws Exception { s_rbac_permissionDomain.insert(); super.setMsg("添加权限[" + s_rbac_permissionDomain.getName() + "]成功"); super.setNextUrl("app/rbac/permission/list.html"); return super.REDIRECT; } public String update() throws Exception { s_rbac_permissionDomain.update(); super.setMsg("修改权限[" + s_rbac_permissionDomain.getName() + "]成功"); super.setNextUrl("app/rbac/permission/list.html"); return super.REDIRECT; } public String insertOrUpdate() throws Exception { s_rbac_permissionDomain.insertOrUpdate(); return "编辑权限[" + s_rbac_permissionDomain.getName() + "]成功"; } public S_rbac_permissionDomain getS_rbac_permissionDomain() { return s_rbac_permissionDomain; } public void setS_rbac_permissionDomain( S_rbac_permissionDomain s_rbac_permissionDomain) { this.s_rbac_permissionDomain = s_rbac_permissionDomain; } public List getPermissionList() { return permissionList; } public void setPermissionList(List permissionList) { this.permissionList = permissionList; } } <file_sep>var locationUrl = location.href.trim(); if(locationUrl.indexOf('tab')>=0){ var id = locationUrl.substring(locationUrl.indexOf('tab')+4,locationUrl.indexOf('tab')+5); $('.tabBody').eq(parseInt(id)).addClass('active').siblings().removeClass('active'); $('.leftNav').find('li').eq(parseInt(id)).addClass('active').siblings().removeClass('active'); }<file_sep>package cn.edu.zjut.web.action; import java.util.Date; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.persistent.db.transaction.TransactionFactory; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import cn.edu.zjut.cfg.domain.Zjut_bulletinDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_bulletinDomain; import cn.edu.zjut.cfg.service.Zjut_bulletinService; @SSAction(name = "zjut_bulletins") public class Zjut_bulletinsDomainAction extends DefaultAction { private Zjut_bulletinDomain zjut_bulletinDomain; private Zjut_organizationDomain zjut_organizationDomain; public Zjut_bulletinDomain getZjut_bulletinDomain() { return zjut_bulletinDomain; } public void setZjut_bulletinDomain(Zjut_bulletinDomain zjut_bulletinDomain) { this.zjut_bulletinDomain = zjut_bulletinDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } public String delete() { if (zjut_bulletinDomain == null || zjut_bulletinDomain.getId() == null) { throw new RuntimeException("缺少公告主键,不能进行删除操作!"); } zjut_bulletinDomain.loadEqual(); Zjut_organization_bulletinDomain zjut_organization_bulletinDomain = new Zjut_organization_bulletinDomain(); zjut_organization_bulletinDomain.setBulletinDomain(zjut_bulletinDomain); zjut_organization_bulletinDomain.loadEqual(); try { TransactionFactory.startTransaction(); zjut_organization_bulletinDomain.delete(); zjut_bulletinDomain.delete(); TransactionFactory.commitTransaction(); } finally { TransactionFactory.endTransaction(); } Zjut_bulletinService.instance.reload(); return "删除成功!"; } public String insertOrUpdate() { Zjut_organization_bulletinDomain zjut_organization_bulletinsDomain = null; String context = zjut_bulletinDomain.getContext(); if (context.indexOf("'") >= 0) { zjut_bulletinDomain.setContext(context.replaceAll("'", "‘")); } if (zjut_bulletinDomain.getId() == null) { if (zjut_organizationDomain == null || zjut_organizationDomain.getId() == null) { throw new RuntimeException("缺少组织信息,不能新增新闻!"); } zjut_organizationDomain.loadEqual(); zjut_organization_bulletinsDomain = new Zjut_organization_bulletinDomain(); zjut_organization_bulletinsDomain .setOrganizationDomain(zjut_organizationDomain); zjut_bulletinDomain.setCreate_date(new Date()); zjut_bulletinDomain.setCreateUserDomain(ApplicationContext.get()); } zjut_bulletinDomain.setModify_date(new Date()); zjut_bulletinDomain.setModifyUserDomain(ApplicationContext.get()); if(!"Y".equalsIgnoreCase(zjut_bulletinDomain.getIs_en())){ zjut_bulletinDomain.setIs_en("N"); } zjut_bulletinDomain.insertOrUpdate(); if (zjut_organization_bulletinsDomain != null) { zjut_organization_bulletinsDomain.setBulletinDomain(zjut_bulletinDomain); zjut_organization_bulletinsDomain.setCreate_date(new Date()); zjut_organization_bulletinsDomain.setModify_date(new Date()); zjut_organization_bulletinsDomain.setIs_en(zjut_bulletinDomain.getIs_en()); zjut_organization_bulletinsDomain .setCreateUserDomain(ApplicationContext.get()); zjut_organization_bulletinsDomain .setModifyUserDomain(ApplicationContext.get()); zjut_organization_bulletinsDomain.insert(); } Zjut_bulletinService.instance.reload(); return "编辑成功!"; } } <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/> <meta name="description" content="浙江工业大学国际学院学生家园" /> <meta name="keywords" content="江工业大学,工业大学,浙工大,国际学院,学生家园" /> <meta name="author" content="Simplifly,qq941721234" /> <title>国际学院——学生家园</title> <link rel="stylesheet" href="${base}/student/resources/css/common.css"/> <link rel="stylesheet" href="${base}/student/resources/css/index.css"/> <style> .fish11 { background: url("../img/square.png") no-repeat scroll 5px center transparent; color: #FFFFFF; display: inline-block; font-family: '宋体'; font-size: 12px; height: 25px; line-height: 25px; padding-left: 20px; position: relative; text-decoration: none; width: 325px; } </style> </head> <body class="page1"> <div class="wrapper"> <!-- 实际工程中请把HTML注释去掉 --> <!-- header部分(可公用代码),将页面动态化时可以把这个div单独提取成一个文件,然后包含到这个位置 --> <#include "common/header.html" /> <!-- /header --> <div class="banner"> <div class="theGallery"><!-- 此处可更改图片数目 --> <a href="#1" ><img src="${base}/student/resources/img/pic/ban_1.jpg" alt="#" /></a> <a href="#2" ><img src="${base}/student/resources/img/pic/index_img_1.jpg" alt="#"/></a> <a href="#3" ><img src="${base}/student/resources/img/pic/index_img_2.jpg" alt="#"/></a> <a href="#4" ><img src="${base}/student/resources/img/pic/index_img_3.jpg" alt="#"/></a> <a href="#5" ><img src="${base}/student/resources/img/pic/index_img_4.jpg" alt="#"/></a> </div><!-- 焦点图切换部分结束 --> </div><!-- /banner --> <div class="main"> <div class="col_1"> <div class="up"> <h2 class="mainHead orangehead"> <span class="title">图片新闻</span> <span class="more" onclick="javascript:location.href='${base}/student/new/imglist.html'"></span> </h2> <#if imgNewList??> <#list imgNewList as imgNew> <div class="imgNew"> <img src="${(imgNew.image2index)!''}" style="cursor:pointer" onclick="javascript:location.href='${base}/student/new/detail.html?id=${(imgNew.id)!''}'"/> <p target="_blank" style="cursor:pointer" onclick="javascript:location.href='${base}/student/new/detail.html?id=${(imgNew.id)!''}'"> <#if (imgNew.context??) && (imgNew.context?length>60)> ${(imgNew.context[0..60])!''}.. <#else> ${(imgNew.context)!''} </#if> </p> </div> </#list> </#if> </div> <div class="down"> <h2 class="mainHead orangehead"> <span class="title">新闻速递</span> <span class="more" onclick="javascript:location.href='${base}/student/new/list.html'"></span> </h2> <#if newList ??> <#list newList as new> <a alert="_blank" class="fish" href="${base}/student/new/detail.html?id=${(new.id)!''}"> <span class="new"> <#if (new.title??) && (new.title?length>17)> ${(new.title[0..17])!''}.. <#else> ${(new.title)!''} </#if> </span> <span class="date">${DateHelper.dateToString(new.create_date,'yyyy-MM-dd')}</span> </a> </#list> </#if> </div> </div> <div class="col_2"> <div class="up"> <h2 class="mainHead greenhead"> <span class="title">公 告</span> <span class="more" onclick="javascript:location.href='${base}/student/bulletin/list.html'"></span> </h2> <#if bulletinList??> <#list bulletinList as bulletin> <a class="fish" href="${base}/student/bulletin/detail.html?id=${(bulletin.id)!''}"> <span class="new">${(bulletin.title)!''}</span> <span class="date">${DateHelper.dateToString(bulletin.create_date,'yyyy-MM-dd')}</span> </a> </#list> </#if> </div> <div class="down"> <h2 class="mainHead greenhead"> <span class="title">学子风采</span> <span onclick="javascript:location.href='${base}/student/xzfc.html'" class="more"></span> </h2> <div class="show" > <#if stdStyleList ??> <#list stdStyleList as style> <img style="cursor:pointer" src="${(style.img_path)!''}" onclick="javascript:location.href='${base}/student/stdstyle/detail.html?id=${(style.id)!''}'"/> <p style="cursor:pointer" onclick="javascript:location.href='${base}/student/stdstyle/detail.html?id=${(style.id)!''}'"> <#if (style.summary??) && (style.summary?length>52)> ${(style.summary[0..52])!''}.. <#else> ${(style.summary)!''}.. </#if> </p> <#break> </#list> </#if> </div> <div class="list gallery_js"> <span class="prev"></span> <div class="hid"> <ul><!-- 可以根据需要按结构增减 --> <#if stdStyleList ??> <#list stdStyleList as style> <li <#if (style_index==0)>class="active"</#if>> <img src="${(style.img_path)!''}" link="${base}/student/stdstyle/detail.html?id=${(style.id)!''}" data-info="<#if (style.summary ??) && (style.summary?length>45)>${(style.summary[0..44])!''}..<#else>${(style.summary)!''}</#if>" /> <div class="shade"></div> </li> </#list> </#if> </ul> </div> <span class="next"></span> </div> </div> </div> <div class="col_3"> <div class="up"> <h2 class="mainHead bluehead"> <span class="title">招聘专栏</span> <span onclick="javascript:location.href='${base}/student/jyzl/zpxx.html'" class="more"></span> </h2> <#if recruitList ??> <#list recruitList as recruit> <a class="fish" href="${base}/student/content/detail.html?id=${(recruit.id)!''}"> <span class="new">${(recruit.title)!''}</span> <span class="date">${DateHelper.dateToString(recruit.create_date,'yyyy-MM-dd')}</span> </a> </#list> </#if> </div> <div class="down"> <h2 class="mainHead bluehead"> <span class="title">服务导航</span> </h2> <div class="sys"> <a href="#">学生原创管理系统</a> </div> <div class="folder"> <a href="#">文件资料下载</a> </div> <div class="manger"> <a href="${base}/login.html">网站管理登录</a> </div> </div> </div> </div><!-- /main --> <!-- footer部分(可公用代码),将页面动态化时可以把这个div单独提取成一个文件,然后包含到这个位置 --> <#include "common/footer.html" /> <!-- /footer --> </div> <script src="${base}/resources/js/jquery.js"></script> <script src="${base}/resources/js/common.js"></script> <script src="${base}/student/resources/js/common.js"></script> </body> </html> <file_sep>package org.sevenstar.app.page.app.manager; import java.util.List; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.manager.domain.S_orgDomain; import org.sevenstar.web.action.java.DefaultAction; /** * @author rtm 2008-5-8 */ public class Org extends DefaultAction { private S_orgDomain s_orgDomain; public String view(){ if(s_orgDomain == null){ throw new ApplicationException("请先选择部门"); } s_orgDomain.load(); return super.SUCCESS; } public String edit(){ if(s_orgDomain == null){ throw new ApplicationException("请先选择部门"); } s_orgDomain.load(); return super.SUCCESS; } private List orgList; public String tree(){ orgList = (new S_orgDomain()).selectAll(); return super.SUCCESS; } public String left() { if(s_orgDomain == null || s_orgDomain.getId() == null){ return welcome(); } s_orgDomain.load(); return super.SUCCESS; } public String welcome(){ return "app/manager/org/welcome.html"; } public String input(){ if(s_orgDomain != null && s_orgDomain.getUpDomain() != null && s_orgDomain.getUpDomain().getId() != null){ s_orgDomain.getUpDomain().load(); if(s_orgDomain.getUpDomain().getLvl() != null){ s_orgDomain.setLvl(new Long(s_orgDomain.getUpDomain().getLvl().longValue() + 1)); }else{ s_orgDomain.setLvl(new Long(1)); } } return "app/manager/org/edit.html"; } public S_orgDomain getS_orgDomain() { return s_orgDomain; } public void setS_orgDomain(S_orgDomain domain) { s_orgDomain = domain; } public List getOrgList() { return orgList; } public void setOrgList(List orgList) { this.orgList = orgList; } } <file_sep>package cn.edu.zjut.web.page.lxgd; import java.util.List; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_faqsDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.service.Zjut_faqsService; public class Faq extends DefaultAction { private Long id; private static Zjut_organizationDomain organizationDomain; static { organizationDomain = new Zjut_organizationDomain(); organizationDomain.setName("study-abroad"); organizationDomain.loadEqual(); } private Zjut_faqsDomain zjut_faqsDomain; public String detail() { if (id == null) { throw new RuntimeException("缺少公告编号,不能查看"); } List<Zjut_faqsDomain> faqList = Zjut_faqsService.instance .getFaqsList(organizationDomain.getName()); for (Zjut_faqsDomain faqDomain : faqList) { if (id.equals(faqDomain.getId())) { zjut_faqsDomain = faqDomain; break; } } return super.SUCCESS; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Zjut_faqsDomain getZjut_faqsDomain() { return zjut_faqsDomain; } public void setZjut_faqsDomain(Zjut_faqsDomain zjut_faqsDomain) { this.zjut_faqsDomain = zjut_faqsDomain; } } <file_sep>package org.sevenstar.app.module.action; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import org.sevenstar.app.module.domain.S_moduleDomain; import org.sevenstar.app.module.service.S_moduleService; @SSAction(name = "s_module") public class S_moduleAction extends DefaultAction { private S_moduleDomain s_moduleDomain; private S_moduleService s_moduleService = new S_moduleService(); public String delete() throws Exception { s_moduleDomain.load(); String message = "删除模块[" + s_moduleDomain.getName() + "]成功"; s_moduleDomain.delete(); return message; } public String insert() throws Exception { s_moduleDomain.insert(); super.setMsg("添加模块[" + s_moduleDomain.getName() + "]成功"); if (s_moduleDomain.getUpDomain() != null && s_moduleDomain.getUpDomain().getId() != null) { super.setNextUrl("app/module/list.html?s_moduleDomain.id=" + s_moduleDomain.getUpDomain().getId()); } else { super.setNextUrl("app/module/list.html?s_moduleDomain.id=" + s_moduleDomain.getId()); } return super.REDIRECT; } public String update() throws Exception { s_moduleDomain.update(); super.setMsg("修改模块[" + s_moduleDomain.getName() + "]成功"); super.setNextUrl("app/module/view.html?s_moduleDomain.id=" + s_moduleDomain.getId()); return super.REDIRECT; } public String insertOrUpdate() throws Exception { s_moduleDomain.insertOrUpdate(); return "编辑模块[" + s_moduleDomain.getName() + "]成功" ; } public S_moduleDomain getS_moduleDomain() { return s_moduleDomain; } public void setS_moduleDomain(S_moduleDomain s_moduleDomain) { this.s_moduleDomain = s_moduleDomain; } public S_moduleService getS_moduleService() { return s_moduleService; } public void setS_moduleService(S_moduleService s_moduleService) { this.s_moduleService = s_moduleService; } } <file_sep>(function($) { $.fn.sySlider = function() { $(this).each(function(){ var $this = $(this); var html = '<span class="prev"></span><span class="next"></span><ul>'; var width = $this.width(), height = $this.height(), n = $this.find('a').length,index,$next,autoSlider $pic = $this.find('a'); $pic.eq(0).css('display','inline-block'); for (var i=0; i<n; i=i+1) { if (i===0) { html += '<li class="active"></li>'; } else { html += '<li></li>'; } } html += '</ul>'; $this.append(html); var $span = $this.find('span'); $span.css('top',((height/2) - ($span.height()/2)) + 'px'); $this.hover(function(){ $span.css('display','inline-block'); },function(){ $span.css('display','none'); }); //点击翻页按钮时 $span.on('click',function(){ clearInterval(autoSlider); var cls = $(this).attr('class'), $cur = $this.find('a:visible'); if (!$cur.is(':animated')) { if (cls === 'prev') { if ($cur.index() === 0) { index = n-1; } else { index = $cur.index() - 1; } $next = $this.find('a:eq('+index+')'); $next.css({'left':-width +'px','display':'inline-block'}).animate({'left':0},400); $cur.animate({'left':width +'px'},400).hide(10); }; if (cls === 'next') { if ($cur.index() === n-1) { index = 0; } else { index = $cur.index() + 1; } $next = $this.find('a:eq('+index+')'); $next.css({'left':width +'px','display':'inline-block'}).animate({'left':0},400); $cur.animate({'left':-width +'px'},400).hide(10); }; $this.find('li:eq('+index+')').addClass('active') .siblings().removeClass('active'); }; autoSlider = setInterval(auto,3000); return false; }); //点击页标按钮时 $this.find('li').on('click',function(){ clearInterval(autoSlider); var $cur = $this.find('a:visible'), index = $(this).index(); if (!$cur.is(':animated') && $cur.index() !== index){ $cur.fadeOut(400); $this.find('a:eq('+index+')').css('left',0).fadeIn(400); $(this).addClass('active').siblings().removeClass('active'); } autoSlider = setInterval(auto,3000); return false; }); function auto(){ var i, $cur = $this.find('a:visible'), ind = $cur.index(); if (ind === n-1) { i = 0; } else { i = ind+1; } if (!$cur.is(':animated')){ $cur.fadeOut(400); $this.find('a:eq('+i+')').css('left',0).fadeIn(400); $this.find('li:eq('+i+')').addClass('active').siblings().removeClass('active'); } } //无点击时自动播放 autoSlider = setInterval(auto,3000); }); } })(jQuery); $(function(){ //去除点击连接后,链接周围的虚线框 $('.leftNav a').focus(function(){ $(this).blur(); }); //导航 $('.leftNav li').on('click',function(){ var index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $(this).parent().next().find('.tabBody:eq('+index+')').addClass('active').siblings().removeClass('active'); return false; }); //选项卡 //ben.s 2013.4.1修改 $('.tab_t li').on('click',function(){ var index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $(this).parent().siblings('.tab_c').removeClass('active'); //$(this).parent().siblings('.tab_c:eq('+index+')').addClass('active').siblings().removeClass('active'); $(this).parent().siblings('.tab_c:eq('+index+')').addClass('active') }); //焦点图片切换 $('.theGallery').sySlider(); }); <file_sep>package cn.edu.zjut.web.action; import java.util.Date; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import cn.edu.zjut.cfg.domain.Zjut_faqsDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_faqDomain; import cn.edu.zjut.cfg.service.Zjut_faqsService; @SSAction(name = "zjut_faqs") public class Zjut_faqsDomainAction extends DefaultAction{ private Zjut_faqsDomain zjut_faqsDomain; private Zjut_organizationDomain zjut_organizationDomain; public String delete() { if(zjut_faqsDomain == null || zjut_faqsDomain.getId() == null){ throw new RuntimeException("缺少参数,不能删除!"); } zjut_faqsDomain.loadEqual(); Zjut_organization_faqDomain organization_faqDomain = new Zjut_organization_faqDomain(); organization_faqDomain.setFaqsDomain(zjut_faqsDomain); organization_faqDomain.loadEqual(); organization_faqDomain.delete(); zjut_faqsDomain.delete(); Zjut_faqsService.instance.reload(); return "删除["+zjut_faqsDomain.getTitle()+"]成功"; } public String insertOrUpdate() { if(zjut_faqsDomain == null || zjut_organizationDomain == null || zjut_organizationDomain.getId() == null){ throw new RuntimeException("缺少参数,不能录入!"); } Zjut_organization_faqDomain organization_faqDomain = null; if(zjut_faqsDomain.getId() == null){ organization_faqDomain = new Zjut_organization_faqDomain(); zjut_organizationDomain.loadEqual(); organization_faqDomain.setOrganizationDomain(zjut_organizationDomain); organization_faqDomain.setModify_date(new Date()); organization_faqDomain.setModifyUserDomain(ApplicationContext.get()); } zjut_faqsDomain.setModify_date(new Date()); zjut_faqsDomain.setModifyUserDomain(ApplicationContext.get()); zjut_faqsDomain.insertOrUpdate(); if(organization_faqDomain!=null){ organization_faqDomain.setFaqsDomain(zjut_faqsDomain); organization_faqDomain.insertOrUpdate(); } Zjut_faqsService.instance.reload(); return "添加["+zjut_faqsDomain.getTitle()+"]成功"; } public Zjut_faqsDomain getZjut_faqsDomain() { return zjut_faqsDomain; } public void setZjut_faqsDomain(Zjut_faqsDomain zjut_faqsDomain) { this.zjut_faqsDomain = zjut_faqsDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } } <file_sep>var xzfc_totalSize; var xzfc_currentPage=0; var xzfc_pageSize = 15; var xzfcList; var xzfcTitleSize = 30; var xzfcBaseUrl ; function xzfc_init(_xzfcList,baseUrl){ xzfcList = eval('(' + _xzfcList + ')'); xzfcBaseUrl = baseUrl; xzfc_totalSize = xzfcList.length; xzfc_generatePage(); xzfc_go2Page(1); } function xzfc_generatePage(){ var pagehtml="<a href=\"javascript:xzfc_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<xzfc_totalSize/xzfc_pageSize;i++){ var id = i+1; pagehtml+="<a id=xzfc_"+id+" href=\"javascript:xzfc_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:xzfc_goNext()\" class=\"next\">下一页</a>" $("#xzfc_page").html(pagehtml) } function xzfc_goPrev(){ if(xzfc_currentPage>0){ xzfc_go2Page(xzfc_currentPage); } } function xzfc_goNext(){ if(xzfc_currentPage<(xzfc_totalSize/xzfc_pageSize-1)){ xzfc_go2Page(xzfc_currentPage+2); } } function xzfc_go2Page(id){ xzfc_currentPage = id-1; var html=""; for(var i = xzfc_currentPage*xzfc_pageSize;i<(xzfc_currentPage+1)*xzfc_pageSize&&i<xzfc_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+xzfcBaseUrl+"/student/stdstyle/detail.html?id="+xzfcList[i].id+"\" title="+xzfcList[i].title+" href=\"#\" title="+xzfcList[i].title+"><span class=\"new\">"; var tempTitle=xzfcList[i].name+":"; if(xzfcList[i].motto.length>xzfcTitleSize){ tempTitle += tempTitlexzfcList[i].motto.substring(0,xzfcTitleSize)+"..."; }else{ tempTitle += xzfcList[i].motto; } html+=tempTitle+"</span><span class=\"date\">"+xzfcList[i].create_date+"</span>"; html+="</a>"; } $("#xzfc").empty(); $("#xzfc").append(html); //设置点中的样式 for(var i=1;i<=xzfc_totalSize/xzfc_pageSize;i++){ $("#xzfc_"+i).attr("class",""); } $("#xzfc_"+id).attr("class","cur"); } <file_sep>package cn.edu.zjut.web.page.manager; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_resource_typeDomain; public class Resourcetype extends DefaultAction { private Zjut_resource_typeDomain zjut_resource_typeDomain; private IbatisPage page; public String list() { page = (new Zjut_resource_typeDomain()).getSelectPage(page); return super.SUCCESS; } public String edit() { if (zjut_resource_typeDomain == null || zjut_resource_typeDomain.getId() == null) { throw new RuntimeException("缺少参数,不能编辑"); } zjut_resource_typeDomain.loadEqual(); return super.SUCCESS; } public String left() { if (zjut_resource_typeDomain == null || zjut_resource_typeDomain.getId() == null) { throw new RuntimeException("缺少参数,不能查看!"); } zjut_resource_typeDomain.loadEqual(); return super.SUCCESS; } public String input() { return "/manager/resourcetype/edit.html"; } public Zjut_resource_typeDomain getZjut_resource_typeDomain() { return zjut_resource_typeDomain; } public void setZjut_resource_typeDomain( Zjut_resource_typeDomain zjut_resource_typeDomain) { this.zjut_resource_typeDomain = zjut_resource_typeDomain; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } } <file_sep>package cn.edu.zjut.web.action; import java.util.Date; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.persistent.db.transaction.TransactionFactory; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_resourceDomain; import cn.edu.zjut.cfg.domain.Zjut_resource_typeDomain; import cn.edu.zjut.cfg.domain.Zjut_resourcesDomain; @SSAction(name = "zjut_resource") public class Zjut_resourceDomainAction extends DefaultAction { private Zjut_resourcesDomain zjut_resourceDomain; private Zjut_organizationDomain zjut_organizationDomain; private Zjut_resource_typeDomain zjut_resource_typeDomain; private String filedata; public Zjut_resourcesDomain getZjut_resourceDomain() { return zjut_resourceDomain; } public void setZjut_resourceDomain(Zjut_resourcesDomain zjut_resourceDomain) { this.zjut_resourceDomain = zjut_resourceDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } public String delete() { if (zjut_resourceDomain == null || zjut_resourceDomain.getId() == null) { throw new RuntimeException("缺少资源编号,不能删除!"); } zjut_resourceDomain.loadEqual(); Zjut_organization_resourceDomain zor = new Zjut_organization_resourceDomain(); zor.setResourceDomain(zjut_resourceDomain); try { TransactionFactory.startTransaction(); zor.loadEqual(); zor.delete(); zjut_resourceDomain.delete(); TransactionFactory.commitTransaction(); } finally { TransactionFactory.endTransaction(); } return "删除[" + zjut_resourceDomain.getName() + "]成功"; } public String insertOrUpdate() { Zjut_organization_resourceDomain zjut_organization_resouceDomain = null; Zjut_organization_resourceDomain zjut_organization_resourceDomain = new Zjut_organization_resourceDomain(); if (zjut_resourceDomain.getId() == null) { if (zjut_organizationDomain == null || zjut_organizationDomain.getId() == null) { throw new RuntimeException("缺少组织信息,不能新增新闻!"); } zjut_organizationDomain.loadEqual(); zjut_organization_resouceDomain = new Zjut_organization_resourceDomain(); zjut_organization_resouceDomain .setOrganizationDomain(zjut_organizationDomain); } zjut_resourceDomain.setModify_date(new Date()); zjut_resourceDomain.setModifyUserDomain(ApplicationContext.get()); zjut_resourceDomain.insertOrUpdate(); if (zjut_organization_resouceDomain != null) { zjut_organization_resouceDomain .setResourceDomain(zjut_resourceDomain); zjut_organization_resouceDomain.setResourceTypeDomain(zjut_resourceDomain.getTypeDomain()); zjut_organization_resouceDomain.setModify_date(new Date()); zjut_organization_resouceDomain .setModifyUserDomain(ApplicationContext.get()); zjut_organization_resouceDomain.insertOrUpdate(); } return "编辑成功!"; } public Zjut_resource_typeDomain getZjut_resource_typeDomain() { return zjut_resource_typeDomain; } public void setZjut_resource_typeDomain( Zjut_resource_typeDomain zjut_resource_typeDomain) { this.zjut_resource_typeDomain = zjut_resource_typeDomain; } public String getFiledata() { return filedata; } public void setFiledata(String filedata) { this.filedata = filedata; } } <file_sep>package cn.edu.zjut.web.page.lxgd; import java.util.List; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.service.Zjut_bulletinService; import cn.edu.zjut.cfg.service.Zjut_newService; public class En extends DefaultAction{ private static Zjut_organizationDomain organizationDomain; private List newList; private List bulletinList; static { organizationDomain = new Zjut_organizationDomain(); organizationDomain.setName("study-abroad"); organizationDomain.loadEqual(); } public String home() { newList = Zjut_newService.instance.getCommonNewsList( organizationDomain.getName(), "english", 5); bulletinList = Zjut_bulletinService.instance.getEnBulletinList(organizationDomain.getName(),10); return super.SUCCESS; } public List getNewList() { return newList; } public void setNewList(List newList) { this.newList = newList; } public List getBulletinList() { return bulletinList; } public void setBulletinList(List bulletinList) { this.bulletinList = bulletinList; } } <file_sep>var technology_announcement_totalSize; var technology_announcement_currentPage=0; var technology_announcement_pageSize = 15; var technology_announcementList; var technology_announcementTitleSize = 50; var technology_announcementBaseUrl ; function technology_announcement_init(_technology_announcementList,baseUrl){ technology_announcementList = eval('(' + _technology_announcementList + ')'); technology_announcementBaseUrl = baseUrl; technology_announcement_totalSize = technology_announcementList.length; technology_announcement_generatePage(); technology_announcement_go2Page(1); } function technology_announcement_generatePage(){ var pagehtml="<a href=\"javascript:technology_announcement_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<technology_announcement_totalSize/technology_announcement_pageSize;i++){ var id = i+1; pagehtml+="<a id=technology_announcement_"+id+" href=\"javascript:technology_announcement_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:technology_announcement_goNext()\" class=\"next\">下一页</a>" $("#technology_announcement_page").html(pagehtml) } function technology_announcement_goPrev(){ if(technology_announcement_currentPage>0){ technology_announcement_go2Page(technology_announcement_currentPage); } } function technology_announcement_goNext(){ if(technology_announcement_currentPage<(technology_announcement_totalSize/technology_announcement_pageSize-1)){ technology_announcement_go2Page(technology_announcement_currentPage+2); } } function technology_announcement_go2Page(id){ technology_announcement_currentPage = id-1; var html=""; for(var i = technology_announcement_currentPage*technology_announcement_pageSize;i<(technology_announcement_currentPage+1)*technology_announcement_pageSize&&i<technology_announcement_totalSize;i++){ html+="<a class=\"fish\" target=\"_blank\" href=\""+technology_announcementBaseUrl+"/student/content/detail.html?id="+technology_announcementList[i].id+"\" title="+technology_announcementList[i].title+" href=\"#\" title="+technology_announcementList[i].title+"><span class=\"new\">"; var tempTitle; if(technology_announcementList[i].title.length>technology_announcementTitleSize){ tempTitle = technology_announcementList[i].title.substring(0,technology_announcementTitleSize)+"..."; }else{ tempTitle = technology_announcementList[i].title; } html+=tempTitle+"</span><span class=\"date\">"+technology_announcementList[i].create_date+"</span>"; html+="</a>"; } $("#technology_announcement").empty(); $("#technology_announcement").append(html); //设置点中的样式 for(var i=1;i<=technology_announcement_totalSize/technology_announcement_pageSize;i++){ $("#technology_announcement_"+i).attr("class",""); } $("#technology_announcement_"+id).attr("class","cur"); } <file_sep>package test.cn.edu.zjut.cfg; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import junit.framework.Assert; import junit.framework.TestCase; public class TestZjut_organizationDomain extends TestCase{ public void testLoad(){ Zjut_organizationDomain zjut_organizationDomain = new Zjut_organizationDomain(); zjut_organizationDomain.setName("college"); zjut_organizationDomain.loadEqual(); Assert.assertEquals(1, zjut_organizationDomain.getNewList().size()); } } <file_sep>var life_totalSize; var life_currentPage=0; var life_pageSize = 25; var lifeList; var newBaseUrl; function life_init(_lifeList,_baseUrl){ lifeList = eval('(' + _lifeList + ')'); life_totalSize = lifeList.length; life_generatePage(); life_go2Page(1); newBaseUrl = _baseUrl; } function life_generatePage(){ var pagehtml="<a href=\"javascript:life_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<life_totalSize/life_pageSize;i++){ var id = i+1; pagehtml+="<a id=lifes_"+id+" href=\"javascript:life_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:life_goNext()\" class=\"next\">下一页</a>" $("#lifes_page").html(pagehtml) } function life_goPrev(){ if(life_currentPage>0){ life_go2Page(life_currentPage); } } function life_goNext(){ if(life_currentPage<(life_totalSize/life_pageSize-1)){ life_go2Page(life_currentPage+2); } } function life_go2Page(id){ life_currentPage = id-1; var html=""; for(var i = life_currentPage*life_pageSize;i<(life_currentPage+1)*life_pageSize&&i<life_totalSize;i++){ url = newBaseUrl+"/gjxy/life/detail.html?id="+lifeList[i].id; html+="<div class=\"life\" style=\"cursor:pointer\" onclick=\"javascript:location.href='"+url+"'\"><div class=\"pic\">"; html+="<img src="+lifeList[i].image+" alt=\"###\" title=\"##\" /></div>"; html+="<h3>"+lifeList[i].title+"</h3>" html+="<h4>"+lifeList[i].summary+"</h4>" html+="<span class=\"lifed\">"+lifeList[i].create_date+"</span>" html+="</div>"; } $("#lifes").empty(); $("#lifes").append(html); //设置点中的样式 for(var i=1;i<=life_totalSize/life_pageSize;i++){ $("#lifes_"+i).attr("class",""); } $("#lifes_"+id).attr("class","cur"); } <file_sep>package org.sevenstar.app.rbac.domain; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.system.domain.S_systemDomain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSCacheModel; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; @SSDomain(table="s_rbac_resource",condition="sts<>'N'") @SSId(generateType="seq",seq="seq_app") @SSCacheModel(selectAll=true) public class S_rbac_resourceDomain extends PersistentObject { @SSPrimaryKey private java.lang.Long id; private java.lang.String name; private java.lang.String description; @SSManyToOne(parameter = "systemDomain.id", column = "system_id") private S_systemDomain systemDomain; private java.lang.String sts; public S_systemDomain getSystemDomain() { return systemDomain; } public void setSystemDomain(S_systemDomain systemDomain) { this.systemDomain = systemDomain; } public void update( ){ this.setSts("Y"); S_rbac_resourceDomain paramDomain = new S_rbac_resourceDomain(); paramDomain.setName(this.getName()); if(paramDomain.updateExist(this.getId())){ throw new ApplicationException("资源名[" + this.getName() + "]已存在"); } super.update(); } public void insert( ) { this.setSts("Y"); if (hasResource(this.getName())) { throw new ApplicationException("资源名[" + this.getName() + "]已存在"); } super.insert(); } public void insertOrUpdate( ) { if(this.getId() != null){ this.update(); }else{ this.insert(); } } public void delete( ) { this.setSts("N"); super.update(); } public boolean hasResource(String name) { S_rbac_resourceDomain param = new S_rbac_resourceDomain(); param.setName(name); return param.exist(); } public void setId(java.lang.Long id) { this.id = id; } public java.lang.Long getId() { return this.id; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getName() { return this.name; } public void setDescription(java.lang.String description) { this.description = description; } public java.lang.String getDescription() { return this.description; } public void setSts(java.lang.String sts) { this.sts = sts; } public java.lang.String getSts() { return this.sts; } } <file_sep><div class="footer"> <p>JianXing Building,Pingfeng Campus,Zhejiang University of Technology,No.288 Liuhe Road,Hangzhou,Zhejiang Province</p> <p>PC : 310023 TEL(FAX) : 0571-85290780 E-MAIL : <a href="mailto:<EMAIL>"><EMAIL></a> </p> <p>浙江工业大学国际学院版权所有©2012</p> </div><file_sep>package cn.edu.zjut.cfg.domain; import java.util.Date; import org.sevenstar.app.manager.domain.S_userDomain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; import org.sevenstar.persistent.db.find.annotation.model.SSProperty; @SSDomain(table = "zjut_content_type", condition = "sts<>'N'") @SSId(generateType = "seq", seq = "zjut_app") public class Zjut_content_typeDomain extends PersistentObject { @SSPrimaryKey private Long id; private String name; private String display_name; private String description; @SSProperty(value = "sysdate", update = false) private Date create_date; @SSManyToOne(column = "create_user_id", parameter = "createUserDomain.id") private S_userDomain createUserDomain; @SSProperty(value = "sysdate") private Date modify_date; @SSManyToOne(column = "modify_user_id", parameter = "modifyUserDomain.id") private S_userDomain modifyUserDomain; private String sts; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplay_name() { return display_name; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getCreate_date() { return create_date; } public void setCreate_date(Date create_date) { this.create_date = create_date; } public S_userDomain getCreateUserDomain() { return createUserDomain; } public void setCreateUserDomain(S_userDomain createUserDomain) { this.createUserDomain = createUserDomain; } public Date getModify_date() { return modify_date; } public void setModify_date(Date modify_date) { this.modify_date = modify_date; } public S_userDomain getModifyUserDomain() { return modifyUserDomain; } public void setModifyUserDomain(S_userDomain modifyUserDomain) { this.modifyUserDomain = modifyUserDomain; } public String getSts() { return sts; } public void setSts(String sts) { this.sts = sts; } } <file_sep>package org.sevenstar.app.module.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sevenstar.persistent.db.ibatis.IbatisDao; /** * @author rtm 2008-5-8 */ public class S_moduleService { public List selectFirstMenu(String system_name) { Map map = new HashMap(); map.put("system_name", system_name); return IbatisDao.getDao().queryForList( "S_moduleDomain_exp_select_firstmenu", map); } public List selectFirstLevel(String system_name) { Map map = new HashMap(); map.put("system_name",system_name); return IbatisDao.getDao().queryForList( "S_moduleDomain_exp_select_firstlevel", map); } } <file_sep>var $$ = document.getElementById; /** * 检查有没有被选中 */ function hasChecked(itemName){ var items = document.all(itemName); if(items){ if(items.length){ for(var i=0;i<items.length;i++){ if(items[i].checked){ return true; } } }else{ return items.checked; } } return false; } /** * 检查多选框有没有被选中 */ function hasCheckedOne(itemName){ var count = 0; var items = document.all(itemName); if(items){ if(items.length){ for(var i=0;i<items.length;i++){ if(items[i].checked){ count++; } } }else{ if(items.checked){ count++; } } } if(count == 0){ alert("请选中一项"); return false; } if(count > 1){ alert("有多项被选中,请只选择一项"); return false; } return true; } /** * 取选中的多选框 */ function getCheckedObj(itemName){ var items = document.all(itemName); var checkedItems = new Array(); if(items){ if(items.length){ for(var i=0;i<items.length;i++){ if(items[i].checked){ checkedItems[checkedItems.length]=items[i]; } } }else{ if(items.checked){ return items; } } } if(checkedItems.length == 1){ return checkedItems[0]; }else{ return checkedItems; } } /** * 全选功能 */ function checkedAll(itemName,checked){ var items = document.all(itemName); if(items){ if(items.length){ for(var i=0;i<items.length;i++){ items[i].checked = checked; } }else{ items.checked = checked; } } } /** * 下拉框拷贝,保留已有的 */ function copySelect(from,to) { var fromObj = document.all[from]; var toObj = document.all[to]; var hasSelect = false; for (i=0;i<fromObj.options.length;i++){ var current = fromObj.options[i]; if (current.selected) { hasSelect = true; txt = current.text; val = current.value; toObj.options[toObj.length] = new Option(txt,val); fromObj.options[i] = null; i--; } } if (!hasSelect){ alert ('请先选中'); } } /** * 全选功能 */ function selectedAll(itemName,selected){ var items = document.all(itemName); for(var i=0;i<items.length;i++){ items.options[i].selected = selected; } } <file_sep>package cn.edu.zjut.web.action; import java.util.Date; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_videoDomain; import cn.edu.zjut.cfg.domain.Zjut_videosDomain; import cn.edu.zjut.cfg.service.Zjut_studentService; import cn.edu.zjut.cfg.service.Zjut_videoService; @SSAction(name = "zjut_videos") public class Zjut_videosDomainAction extends DefaultAction { private Zjut_videosDomain zjut_videosDomain; private Zjut_organizationDomain zjut_organizationDomain; public String delete() { if (zjut_videosDomain == null || zjut_videosDomain.getId() == null) { throw new RuntimeException("缺少必要的参数,不能删除学生风采内容!"); } zjut_videosDomain.loadEqual(); Zjut_organization_videoDomain organization_videoDomain = new Zjut_organization_videoDomain(); organization_videoDomain.setVideosDomain(zjut_videosDomain); organization_videoDomain.loadEqual(); organization_videoDomain.delete(); zjut_videosDomain.delete(); Zjut_videoService.instance.reload(); return "删除[" + zjut_videosDomain.getTitle() + "]成功!"; } public String insertOrUpdate() { if (zjut_videosDomain == null || zjut_organizationDomain == null || zjut_organizationDomain.getId() == null) { throw new RuntimeException("缺少必要的参数,不能编辑学生风采内容!"); } Zjut_organization_videoDomain zjut_organization_videoDomain = null; if (zjut_videosDomain.getId() == null) { zjut_organizationDomain.loadEqual(); zjut_organization_videoDomain = new Zjut_organization_videoDomain(); zjut_organization_videoDomain.setOrganizationDomain(zjut_organizationDomain); } zjut_videosDomain.setModify_date(new Date()); zjut_videosDomain.setModifyUserDomain(ApplicationContext.get()); zjut_videosDomain.insertOrUpdate(); Zjut_studentService.instance.load(); if (zjut_organization_videoDomain != null) { zjut_organization_videoDomain.setVideosDomain(zjut_videosDomain); zjut_organization_videoDomain.setModify_date(new Date()); zjut_organization_videoDomain.setModifyUserDomain(ApplicationContext.get()); zjut_organization_videoDomain.insert(); } Zjut_videoService.instance.reload(); return "编辑[" + zjut_videosDomain.getTitle() + "]成功!"; } public Zjut_videosDomain getZjut_videosDomain() { return zjut_videosDomain; } public void setZjut_videosDomain(Zjut_videosDomain zjut_videosDomain) { this.zjut_videosDomain = zjut_videosDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain(Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } } <file_sep>package cn.edu.zjut.web.page.student; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_studentDomain; public class Stdstyle extends DefaultAction { private Long id; private Zjut_studentDomain zjut_studentDomain; public String detail() { if (id == null) { throw new RuntimeException("缺少参数,不能查看!"); } zjut_studentDomain = new Zjut_studentDomain(); zjut_studentDomain.setId(id); try { zjut_studentDomain.loadEqual(); } catch (RuntimeException e) { throw new RuntimeException("找不到对应的内容!"); } return super.SUCCESS; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Zjut_studentDomain getZjut_studentDomain() { return zjut_studentDomain; } public void setZjut_studentDomain(Zjut_studentDomain zjut_studentDomain) { this.zjut_studentDomain = zjut_studentDomain; } } <file_sep>package cn.edu.zjut.cfg.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_questionDomain; import cn.edu.zjut.cfg.domain.Zjut_questionDomain; public enum Zjut_questionService { instance; private static Map<String,List<Zjut_questionDomain>> questionMap = null; public void reload(){ List<Zjut_organizationDomain> organizationList = (new Zjut_organizationDomain()).selectAll(); questionMap = new HashMap<String,List<Zjut_questionDomain>>(); for(Zjut_organizationDomain organizationDomain : organizationList){ List<Zjut_questionDomain> temps = new ArrayList<Zjut_questionDomain>(); Zjut_organization_questionDomain organization_questionDomain = new Zjut_organization_questionDomain(); organization_questionDomain.setOrganizationDomain(organizationDomain); List<Zjut_organization_questionDomain> list = organization_questionDomain.selectEqual(); for(Zjut_organization_questionDomain domain : list){ temps.add(domain.getQuestionDomain()); } questionMap.put(organizationDomain.getName(), temps); } } public List<Zjut_questionDomain> getQuestionList(String organizationName){ if(questionMap == null){ reload(); } return questionMap.get(organizationName); } } <file_sep>package org.sevenstar.component.tree; import java.util.List; import net.jcreate.e3.tree.support.WebTreeBuilder; import net.jcreate.e3.tree.support.WebTreeNode; public interface Tree { public String getRootScript(WebTreeNode node, WebTreeBuilder builder) ; public String getNodeScript(List nodeList, WebTreeBuilder builder) ; } <file_sep>package cn.edu.zjut.web.action; import java.util.Date; import java.util.List; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.persistent.db.transaction.TransactionFactory; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import cn.edu.zjut.cfg.domain.Zjut_newDomain; import cn.edu.zjut.cfg.domain.Zjut_new_typeDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_newDomain; import cn.edu.zjut.cfg.service.Zjut_newService; import cn.edu.zjut.util.ImagePathAnalyse; @SSAction(name = "zjut_new") public class Zjut_newDomainAction extends DefaultAction { private Zjut_newDomain zjut_newDomain; private Zjut_organizationDomain zjut_organizationDomain; private Zjut_new_typeDomain zjut_new_typeDomain; public Zjut_newDomain getZjut_newDomain() { return zjut_newDomain; } public void setZjut_newDomain(Zjut_newDomain zjut_newDomain) { this.zjut_newDomain = zjut_newDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } public String delete() { if (zjut_newDomain == null || zjut_newDomain.getId() == null) { throw new RuntimeException("缺少新闻主键,不能进行删除操作!"); } zjut_newDomain.loadEqual(); Zjut_organization_newDomain zjut_organization_newDomain = new Zjut_organization_newDomain(); zjut_organization_newDomain.setNewDomain(zjut_newDomain); zjut_organization_newDomain.loadEqual(); try { TransactionFactory.startTransaction(); zjut_organization_newDomain.delete(); zjut_newDomain.delete(); TransactionFactory.commitTransaction(); } finally { TransactionFactory.endTransaction(); } Zjut_newService.instance.reload(); return "删除成功!"; } public String insertOrUpdate() { Zjut_organization_newDomain zjut_organization_newDomain = null; String context = zjut_newDomain.getContext(); if (context.indexOf("'") >= 0) { zjut_newDomain.setContext(context.replaceAll("'", "‘")); } if (zjut_new_typeDomain.getId() == null || zjut_new_typeDomain.getId() == null) { throw new RuntimeException("缺少新闻类型!"); } zjut_new_typeDomain.loadEqual(); if (zjut_newDomain.getId() == null) { if (zjut_organizationDomain == null || zjut_organizationDomain.getId() == null) { throw new RuntimeException("缺少组织信息,不能新增新闻!"); } zjut_organizationDomain.loadEqual(); zjut_organization_newDomain = new Zjut_organization_newDomain(); zjut_organization_newDomain .setOrganizationDomain(zjut_organizationDomain); zjut_newDomain.setCreate_date(new Date()); zjut_newDomain.setCreateUserDomain(ApplicationContext.get()); } // 没有设置image2index图片的情况下默认第一张为首页图片 if (zjut_newDomain.getImage2index() == null || "".equals(zjut_newDomain.getImage2index())) { List imageList = ImagePathAnalyse.instance .analyseImagePaths(zjut_newDomain.getContext()); if (imageList != null && !imageList.isEmpty()) { zjut_newDomain.setImage2index(String.valueOf(imageList.get(0))); } } zjut_newDomain.setNewTypeDomain(zjut_new_typeDomain); zjut_newDomain.setModify_date(new Date()); zjut_newDomain.setModifyUserDomain(ApplicationContext.get()); zjut_newDomain.insertOrUpdate(); if (zjut_organization_newDomain != null) { zjut_organization_newDomain.setNewDomain(zjut_newDomain); zjut_organization_newDomain.setCreate_date(new Date()); zjut_organization_newDomain.setModify_date(new Date()); zjut_organization_newDomain.setCreateUserDomain(ApplicationContext .get()); zjut_organization_newDomain.setModifyUserDomain(ApplicationContext .get()); zjut_organization_newDomain.setNewTypeDomain(zjut_new_typeDomain); zjut_organization_newDomain.insert(); }else{ zjut_organization_newDomain = new Zjut_organization_newDomain(); zjut_organization_newDomain.setNewDomain(zjut_newDomain); zjut_organization_newDomain.loadEqual(); zjut_organization_newDomain.setNewTypeDomain(zjut_new_typeDomain); zjut_organization_newDomain.update(); } Zjut_newService.instance.reload(); return "编辑成功!"; } public Zjut_new_typeDomain getZjut_new_typeDomain() { return zjut_new_typeDomain; } public void setZjut_new_typeDomain(Zjut_new_typeDomain zjut_new_typeDomain) { this.zjut_new_typeDomain = zjut_new_typeDomain; } } <file_sep>package org.sevenstar.app.config.domain; import java.util.Date; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.manager.domain.S_userDomain; import org.sevenstar.app.system.domain.S_systemDomain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; import org.sevenstar.persistent.db.find.annotation.model.SSProperty; @SSDomain(table = "s_configure", condition = "sts<>'N'") @SSId(generateType = "seq", seq = "seq_app") public class S_configureDomain extends PersistentObject { @SSPrimaryKey private Long id; @SSManyToOne(column = "type_id", parameter = "typeDomain.id") private S_configure_typeDomain typeDomain; @SSManyToOne(parameter = "systemDomain.id", column = "system_id") private S_systemDomain systemDomain; private String code; private String name; private Long pos; @SSProperty(value = "sysdate", update = false) private Date create_date; @SSManyToOne(column = "create_user_id", parameter = "createUserDomain.id") private S_userDomain createUserDomain; @SSProperty(value = "sysdate") private Date modify_date; @SSManyToOne(column = "modify_user_id", parameter = "modifyUserDomain.id") private S_userDomain modifyUserDomain; private String sts; public void update() { this.setSts("Y"); S_configureDomain paramDomain = new S_configureDomain(); paramDomain.setName(this.getName()); paramDomain.setTypeDomain(this.getTypeDomain()); if (paramDomain.updateExist(this.getId())) { throw new ApplicationException("配置[" + this.getTypeDomain().getName() + "_" + this.getName() + "]已存在"); } super.update(); } public void insert() { this.setSts("Y"); S_configureDomain paramDomain = new S_configureDomain(); paramDomain.setName(this.getName()); paramDomain.setTypeDomain(this.getTypeDomain()); if (paramDomain.exist()) { throw new ApplicationException("配置[" + this.getTypeDomain().getName() + "_" + this.getName() + "]已存在"); } super.insert(); } public void insertOrUpdate() { if (this.getId() != null) { this.update(); } else { this.insert(); } } public void delete() { this.setSts("N"); super.update(); } public void setId(java.lang.Long id) { this.id = id; } public java.lang.Long getId() { return this.id; } public S_configure_typeDomain getTypeDomain() { return typeDomain; } public void setTypeDomain(S_configure_typeDomain typeDomain) { this.typeDomain = typeDomain; } public void setCode(java.lang.String code) { this.code = code; } public java.lang.String getCode() { return this.code; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getName() { return this.name; } public void setPos(java.lang.Long pos) { this.pos = pos; } public java.lang.Long getPos() { return this.pos; } public void setSts(java.lang.String sts) { this.sts = sts; } public java.lang.String getSts() { return this.sts; } public Date getCreate_date() { return create_date; } public void setCreate_date(Date create_date) { this.create_date = create_date; } public S_userDomain getCreateUserDomain() { return createUserDomain; } public void setCreateUserDomain(S_userDomain createUserDomain) { this.createUserDomain = createUserDomain; } public Date getModify_date() { return modify_date; } public void setModify_date(Date modify_date) { this.modify_date = modify_date; } public S_userDomain getModifyUserDomain() { return modifyUserDomain; } public void setModifyUserDomain(S_userDomain modifyUserDomain) { this.modifyUserDomain = modifyUserDomain; } public S_systemDomain getSystemDomain() { return systemDomain; } public void setSystemDomain(S_systemDomain systemDomain) { this.systemDomain = systemDomain; } } <file_sep>package cn.edu.zjut.cfg.domain; import java.util.Date; import org.sevenstar.app.common.context.ApplicationContext; import org.sevenstar.app.manager.domain.S_userDomain; import org.sevenstar.persistent.db.PersistentObject; import org.sevenstar.persistent.db.find.annotation.model.SSDomain; import org.sevenstar.persistent.db.find.annotation.model.SSId; import org.sevenstar.persistent.db.find.annotation.model.SSManyToOne; import org.sevenstar.persistent.db.find.annotation.model.SSPrimaryKey; import org.sevenstar.persistent.db.find.annotation.model.SSProperty; @SSDomain(table = "zjut_organization_resource", condition = "sts<>'N'") @SSId(generateType = "seq", seq = "zjut_app") public class Zjut_organization_resourceDomain extends PersistentObject { @SSPrimaryKey private Long id; @SSManyToOne(column = "organization_id", parameter = "organizationDomain.id") private Zjut_organizationDomain organizationDomain; @SSManyToOne(column = "resource_id", parameter = "resourceDomain.id") private Zjut_resourcesDomain resourceDomain; @SSManyToOne(column = "resource_type_id", parameter = "resourceTypeDomain.id") private Zjut_resource_typeDomain resourceTypeDomain; @SSProperty(value = "sysdate", update = false) private Date create_date; @SSManyToOne(column = "create_user_id", parameter = "createUserDomain.id") private S_userDomain createUserDomain; @SSProperty(value = "sysdate") private Date modify_date; @SSManyToOne(column = "modify_user_id", parameter = "modifyUserDomain.id") private S_userDomain modifyUserDomain; private String sts; public void insertOrUpdate() { if (this.id == null) { this.insert(); } else { super.update(); } } public void insert() { this.setSts("Y"); this.setCreate_date(new Date()); this.setCreateUserDomain(ApplicationContext.get()); super.insert(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Zjut_organizationDomain getOrganizationDomain() { return organizationDomain; } public void setOrganizationDomain(Zjut_organizationDomain organizationDomain) { this.organizationDomain = organizationDomain; } public Zjut_resourcesDomain getResourceDomain() { return resourceDomain; } public void setResourceDomain(Zjut_resourcesDomain resourceDomain) { this.resourceDomain = resourceDomain; } public Date getCreate_date() { return create_date; } public void setCreate_date(Date create_date) { this.create_date = create_date; } public S_userDomain getCreateUserDomain() { return createUserDomain; } public void setCreateUserDomain(S_userDomain createUserDomain) { this.createUserDomain = createUserDomain; } public Date getModify_date() { return modify_date; } public void setModify_date(Date modify_date) { this.modify_date = modify_date; } public S_userDomain getModifyUserDomain() { return modifyUserDomain; } public void setModifyUserDomain(S_userDomain modifyUserDomain) { this.modifyUserDomain = modifyUserDomain; } public String getSts() { return sts; } public void setSts(String sts) { this.sts = sts; } public Zjut_resource_typeDomain getResourceTypeDomain() { return resourceTypeDomain; } public void setResourceTypeDomain( Zjut_resource_typeDomain resourceTypeDomain) { this.resourceTypeDomain = resourceTypeDomain; } } <file_sep>package cn.edu.zjut.web.page.manager; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_questionDomain; import cn.edu.zjut.cfg.domain.Zjut_questionDomain; public abstract class Defaultquestion extends DefaultAction { private IbatisPage page; private Zjut_questionDomain zjut_questionDomain; private Zjut_organizationDomain zjut_organizationDomain; public abstract Zjut_organizationDomain getOrganizationDomain(); public abstract String getSource(); public String list() { Zjut_organization_questionDomain organization_questionDomain = new Zjut_organization_questionDomain(); organization_questionDomain .setOrganizationDomain(getOrganizationDomain()); page = organization_questionDomain.getSelectPage(page); return "manager/defaultquestion/list.html"; } public String edit() { if (zjut_questionDomain == null || zjut_questionDomain.getId() == null) { throw new RuntimeException("缺少参数!"); } zjut_questionDomain.loadEqual(); zjut_organizationDomain = getOrganizationDomain(); return "manager/defaultquestion/edit.html"; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public Zjut_questionDomain getZjut_questionDomain() { return zjut_questionDomain; } public void setZjut_questionDomain(Zjut_questionDomain zjut_questionDomain) { this.zjut_questionDomain = zjut_questionDomain; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } } <file_sep><html xmlns="http://www.w3.org/1999/xhtml"> <head> <#include "/common/page/head.html"> </script> </head> <body style="height:150%; OVERFLOW-Y:auto " > <#if fileList??> <#list fileList as file> 附件:<span id="${(file.id)!''}"><a href="${base}/${(file.url)!''}">${(file.name)!''}.${(file.ext)!''}</a></span></br> </#list> </#if> </body> </html> <file_sep>package cn.edu.zjut.web.page; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.sevenstar.util.DateHelper; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_bulletinDomain; import cn.edu.zjut.cfg.domain.Zjut_newDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_school_lifeDomain; import cn.edu.zjut.cfg.service.Zjut_bulletinService; import cn.edu.zjut.cfg.service.Zjut_newService; import cn.edu.zjut.cfg.service.Zjut_partner_universitiesService; import cn.edu.zjut.cfg.service.Zjut_school_lifeService; import cn.edu.zjut.util.JsonFormatUtil; import cn.edu.zjut.util.SummaryUtil; public class Gjxy extends DefaultAction { private List newList; private List imgNewList; private List bulletinList; private List lifeList; private List universitiyList; private String jsonNews; private String jsonBulletins; private String jsonLifes; private static Zjut_organizationDomain organizationDomain; static { organizationDomain = new Zjut_organizationDomain(); organizationDomain.setName("international-college"); organizationDomain.loadEqual(); } public String index() { newList = Zjut_newService.instance.getCommonNewsList(organizationDomain .getName(), "common", 12); imgNewList = Zjut_newService.instance.getCommonNewsList( organizationDomain.getName(), "image", 1); imgNewList = imgNewSummary(imgNewList); bulletinList = Zjut_bulletinService.instance.getBulletinList( organizationDomain.getName(), 12); lifeList = Zjut_school_lifeService.instance.getSchoolLifeList( organizationDomain.getName(), 2); List tempUniversitiyList = Zjut_partner_universitiesService.instance .getUniversitieList(); if (tempUniversitiyList.size() < 3) { // universitiyList = new ArrayList(); // for (int i = 0; i < 3; i++) { // universitiyList.add(tempUniversitiyList.get(i%tempUniversitiyList.size())); // } universitiyList = tempUniversitiyList; } else { universitiyList = tempUniversitiyList.subList(0, 3); } return super.SUCCESS; } private List imgNewSummary(List imgNewList) { if (imgNewList == null || imgNewList.isEmpty()) { return null; } List resultList = new ArrayList(); for (int i = 0; i < imgNewList.size(); i++) { Zjut_newDomain zjut_newDomain = (Zjut_newDomain) imgNewList.get(i); resultList.add(summary(zjut_newDomain)); } return resultList; } private Zjut_newDomain summary(Zjut_newDomain zjut_newDomain) { Zjut_newDomain tempDomain = new Zjut_newDomain(); tempDomain.setContext(SummaryUtil.instance.removeHtmlTag(zjut_newDomain .getContext())); tempDomain.setId(zjut_newDomain.getId()); tempDomain.setAuthor(zjut_newDomain.getAuthor()); tempDomain.setBrowse_count(zjut_newDomain.getBrowse_count()); tempDomain.setImage2index(zjut_newDomain.getImage2index()); tempDomain.setIs_top(zjut_newDomain.getIs_top()); tempDomain.setIs_valid(zjut_newDomain.getIs_valid()); tempDomain.setExpire_time(zjut_newDomain.getExpire_time()); return tempDomain; } public String news() { news_bulletins_lifes(); return "gjxy/news_life.html"; } public String bulletins() { news_bulletins_lifes(); return "gjxy/news_life.html"; } public String lifes() { news_bulletins_lifes(); return "gjxy/news_life.html"; } private void news2Json() { List<Zjut_newDomain> newList = Zjut_newService.instance .getCommonNewsList(organizationDomain.getName(), "common"); JSONArray json = new JSONArray(); for (Zjut_newDomain newDomain : newList) { java.util.Map map = new java.util.HashMap(); map.put("id", newDomain.getId()); map.put("title", newDomain.getTitle()); map.put("create_date", DateHelper.dateToString(newDomain .getCreate_date(), "yyyy-MM-dd")); json.put(map); } jsonNews = JsonFormatUtil.instance.format(json.toString()); } private void bulletins2Json() { List<Zjut_bulletinDomain> bulletinList = Zjut_bulletinService.instance .getBulletinList(organizationDomain.getName()); JSONArray json = new JSONArray(); for (Zjut_bulletinDomain bulletinDomain : bulletinList) { java.util.Map map = new java.util.HashMap(); map.put("id", bulletinDomain.getId()); map.put("title", bulletinDomain.getTitle()); map.put("create_date", DateHelper.dateToString(bulletinDomain .getCreate_date(), "yyyy-MM-dd")); json.put(map); } jsonBulletins = JsonFormatUtil.instance.format(json.toString()); } private void lifes2Json() { List<Zjut_school_lifeDomain> lifeList = Zjut_school_lifeService.instance .getSchoolLifeList(organizationDomain.getName()); JSONArray json = new JSONArray(); for (Zjut_school_lifeDomain lifeDomain : lifeList) { java.util.Map map = new java.util.HashMap(); map.put("id", lifeDomain.getId()); map.put("image", lifeDomain.getImage()); map.put("title", lifeDomain.getTitle()); map.put("summary", lifeDomain.getSummary()); //map.put("content", lifeDomain.getContent()); map.put("create_date", DateHelper.dateToString(lifeDomain .getCreate_date(), "yyyy-MM-dd")); json.put(map); } jsonLifes = JsonFormatUtil.instance.format(json.toString()); } private void news_bulletins_lifes() { this.news2Json(); this.bulletins2Json(); this.lifes2Json(); } public List getNewList() { return newList; } public void setNewList(List newList) { this.newList = newList; } public List getBulletinList() { return bulletinList; } public void setBulletinList(List bulletinList) { this.bulletinList = bulletinList; } public List getLifeList() { return lifeList; } public void setLifeList(List lifeList) { this.lifeList = lifeList; } public String getJsonNews() { return jsonNews; } public void setJsonNews(String jsonNews) { this.jsonNews = jsonNews; } public String getJsonBulletins() { return jsonBulletins; } public void setJsonBulletins(String jsonBulletins) { this.jsonBulletins = jsonBulletins; } public String getJsonLifes() { return jsonLifes; } public void setJsonLifes(String jsonLifes) { this.jsonLifes = jsonLifes; } public List getImgNewList() { return imgNewList; } public void setImgNewList(List imgNewList) { this.imgNewList = imgNewList; } public List getUniversitiyList() { return universitiyList; } public void setUniversitiyList(List universitiyList) { this.universitiyList = universitiyList; } } <file_sep>package cn.edu.zjut.web.page.manager; import java.util.ArrayList; import java.util.List; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_menu_contentDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; public abstract class DefaultMenucontents extends DefaultAction { private IbatisPage page; private Zjut_menu_contentDomain zjut_menu_contentDomain; private Zjut_organizationDomain zjut_organizationDomain; private List menuList; public abstract Zjut_organizationDomain getOrganizationDomain(); public String tree() { zjut_menu_contentDomain = new Zjut_menu_contentDomain(); zjut_menu_contentDomain.setOrganizationDomain(getOrganizationDomain()); try{ menuList = zjut_menu_contentDomain.selectEqual(); }catch(RuntimeException e){ menuList = new ArrayList(); } return "manager/menucontents/tree.html"; } public String main() { return "manager/menucontents/main.html"; } public String list() { zjut_menu_contentDomain = new Zjut_menu_contentDomain(); zjut_menu_contentDomain.setOrganizationDomain(getOrganizationDomain()); page = zjut_menu_contentDomain.getSelectPage(page); return "manager/menucontents/list.html"; } public String edit() { if (zjut_menu_contentDomain == null || zjut_menu_contentDomain.getId() == null) { throw new RuntimeException("缺少参数,不能编辑"); } zjut_menu_contentDomain.loadEqual(); return "manager/menucontents/edit.html"; } public String left() { if (zjut_menu_contentDomain == null || zjut_menu_contentDomain.getId() == null) { throw new RuntimeException("缺少参数,不能查看"); } zjut_menu_contentDomain.loadEqual(); return "manager/menucontents/left.html"; } public String input() { if (zjut_menu_contentDomain != null && zjut_menu_contentDomain.getUpDomain() != null && zjut_menu_contentDomain.getUpDomain().getId() != null) { zjut_menu_contentDomain.getUpDomain().loadEqual(); } zjut_organizationDomain = getOrganizationDomain(); return "manager/menucontents/edit.html"; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public Zjut_menu_contentDomain getZjut_menu_contentDomain() { return zjut_menu_contentDomain; } public void setZjut_menu_contentDomain( Zjut_menu_contentDomain zjut_menu_contentDomain) { this.zjut_menu_contentDomain = zjut_menu_contentDomain; } public List getMenuList() { return menuList; } public void setMenuList(List menuList) { this.menuList = menuList; } public Zjut_organizationDomain getZjut_organizationDomain() { return zjut_organizationDomain; } public void setZjut_organizationDomain( Zjut_organizationDomain zjut_organizationDomain) { this.zjut_organizationDomain = zjut_organizationDomain; } } <file_sep>package org.sevenstar.app.page.app.rbac; import java.util.List; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.rbac.domain.S_rbac_operationDomain; import org.sevenstar.app.rbac.domain.S_rbac_permissionDomain; import org.sevenstar.app.rbac.domain.S_rbac_resourceDomain; import org.sevenstar.app.system.domain.S_systemDomain; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; /** * @author rtm 2008-5-8 */ public class Permission extends DefaultAction { private IbatisPage page; private S_rbac_permissionDomain s_rbac_permissionDomain; private List resourceList; private List operationList; private List systemList; public String list() { if (s_rbac_permissionDomain == null) { s_rbac_permissionDomain = new S_rbac_permissionDomain(); } page = s_rbac_permissionDomain.getSelectPage(page); return super.SUCCESS; } public String input() { resourceList = (new S_rbac_resourceDomain()).selectAll(); operationList = (new S_rbac_operationDomain()).selectAll(); systemList = (new S_systemDomain()).selectAll(); return "app/rbac/permission/edit.html"; } public String edit(){ if(s_rbac_permissionDomain == null){ throw new ApplicationException("没有选中权限"); } resourceList = (new S_rbac_resourceDomain()).selectAll(); operationList = (new S_rbac_operationDomain()).selectAll(); s_rbac_permissionDomain.load(); systemList = (new S_systemDomain()).selectAll(); return super.SUCCESS; } public String view(){ if(s_rbac_permissionDomain == null){ throw new ApplicationException("没有选中权限"); } s_rbac_permissionDomain.load(); return super.SUCCESS; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public S_rbac_permissionDomain getS_rbac_permissionDomain() { return s_rbac_permissionDomain; } public void setS_rbac_permissionDomain(S_rbac_permissionDomain domain) { s_rbac_permissionDomain = domain; } public List getResourceList() { return resourceList; } public void setResourceList(List resourceList) { this.resourceList = resourceList; } public List getOperationList() { return operationList; } public void setOperationList(List operationList) { this.operationList = operationList; } public List getSystemList() { return systemList; } public void setSystemList(List systemList) { this.systemList = systemList; } } <file_sep>package org.sevenstar.app.rbac.action; import java.util.List; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.util.BeanHelper; import org.sevenstar.web.action.java.DefaultAction; import org.sevenstar.web.annotation.SSAction; import org.sevenstar.web.annotation.SSList; import org.sevenstar.app.common.exception.ApplicationException; import org.sevenstar.app.rbac.domain.S_rbac_groupDomain; import org.sevenstar.app.rbac.domain.S_rbac_roleDomain; import org.sevenstar.app.rbac.relation.domain.S_rbac_grouproleDomain; @SSAction(name="s_rbac_group") public class S_rbac_groupAction extends DefaultAction { private S_rbac_groupDomain s_rbac_groupDomain; @SSList(type="org.sevenstar.app.rbac.domain.S_rbac_groupDomain") private List groupList; @SSList(type="org.sevenstar.app.rbac.domain.S_rbac_roleDomain") private List roleList; private IbatisPage page; public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } public IbatisPage query() { if (s_rbac_groupDomain == null) { s_rbac_groupDomain = new S_rbac_groupDomain(); } page = s_rbac_groupDomain.getSelectPage(page); List dataList = page.getDataList(); if (dataList != null && dataList.size() > 0) { for (int i = 0; i < dataList.size(); i++) { S_rbac_groupDomain groupDomain = (S_rbac_groupDomain) dataList.get(i); S_rbac_groupDomain newGroupDomain = new S_rbac_groupDomain(); BeanHelper.copyNotNullPrimitiveProperties(groupDomain, newGroupDomain); dataList.set(i, newGroupDomain); } } return page; } public String deleteList() throws Exception { if (groupList != null && groupList.size() > 0) { for (int i = 0; i < groupList.size(); i++) { S_rbac_groupDomain s_rbac_groupDomain = (S_rbac_groupDomain) groupList .get(i); s_rbac_groupDomain.delete(); } } else { throw new ApplicationException("请先选择组"); } return "批量删除组成功"; } public String delete() throws Exception { super.setMsg("删除组[" + s_rbac_groupDomain.getName() + "]成功"); s_rbac_groupDomain.delete(); super.setNextUrl("app/rbac/group/list.html"); return super.REDIRECT; } public String insert() throws Exception { s_rbac_groupDomain.insert(); if(roleList != null && roleList.size() > 0){ for(int i=0;i<roleList.size();i++){ S_rbac_grouproleDomain s_rbac_grouproleDomain = new S_rbac_grouproleDomain(); s_rbac_grouproleDomain.setGroupDomain(s_rbac_groupDomain); s_rbac_grouproleDomain.setRoleDomain((S_rbac_roleDomain)roleList.get(i)); s_rbac_grouproleDomain.insert(); } } super.setMsg("添加组[" + s_rbac_groupDomain.getName() + "]成功"); super.setNextUrl("app/rbac/group/list.html"); return super.REDIRECT; } public String update() throws Exception { s_rbac_groupDomain.update(); doUpdateRole(); super.setMsg("修改组[" + s_rbac_groupDomain.getName() + "]成功"); super.setNextUrl("app/rbac/group/list.html"); return super.REDIRECT; } private void doUpdateRole() { S_rbac_grouproleDomain paramDomain = new S_rbac_grouproleDomain(); paramDomain.setGroupDomain(s_rbac_groupDomain); List groupRoleList = paramDomain.selectEqual(); for(int i=0;i<groupRoleList.size();i++){ S_rbac_grouproleDomain s_rbac_grouproleDomain = (S_rbac_grouproleDomain)groupRoleList.get(i); s_rbac_grouproleDomain.delete(); } if(roleList != null && roleList.size() > 0){ for(int i=0;i<roleList.size();i++){ S_rbac_grouproleDomain s_rbac_grouproleDomain = new S_rbac_grouproleDomain(); s_rbac_grouproleDomain.setGroupDomain(s_rbac_groupDomain); s_rbac_grouproleDomain.setRoleDomain((S_rbac_roleDomain)roleList.get(i)); s_rbac_grouproleDomain.insert(); } } } public String insertOrUpdate() throws Exception { s_rbac_groupDomain.insertOrUpdate(); doUpdateRole(); return "编辑组[" + s_rbac_groupDomain.getName() + "]成功"; } public S_rbac_groupDomain getS_rbac_groupDomain() { return s_rbac_groupDomain; } public void setS_rbac_groupDomain(S_rbac_groupDomain s_rbac_groupDomain) { this.s_rbac_groupDomain = s_rbac_groupDomain; } public List getGroupList() { return groupList; } public void setGroupList(List groupList) { this.groupList = groupList; } public List getRoleList() { return roleList; } public void setRoleList(List roleList) { this.roleList = roleList; } } <file_sep>package cn.edu.zjut.web.page.lxgd; import org.sevenstar.persistent.db.ibatis.IbatisPage; import org.sevenstar.web.action.java.DefaultAction; import cn.edu.zjut.cfg.domain.Zjut_menu_contentDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.cfg.domain.Zjut_organization_resourceDomain; import cn.edu.zjut.cfg.service.Zjut_menu_contentService; public class Menu extends DefaultAction { private Zjut_menu_contentDomain zjut_menu_contentDomain; private IbatisPage page = new IbatisPage(); private static Zjut_organizationDomain organizationDomain; static { organizationDomain = new Zjut_organizationDomain(); organizationDomain.setName("study-abroad"); organizationDomain.loadEqual(); } public String about_us() { getMenuDomain("about_us"); return super.SUCCESS; } public String gzzd() { getMenuDomain("gzzd"); return super.SUCCESS; } public String jxj(){ getMenuDomain("jxj"); return super.SUCCESS; } public String lxwm(){ getMenuDomain("lxwm"); return super.SUCCESS; } public String rxsq(){ getMenuDomain("rxsq"); return super.SUCCESS; } public String shzn(){ getMenuDomain("shzn"); return super.SUCCESS; } public String tsxm(){ getMenuDomain("tsxm"); return super.SUCCESS; } public String xxyd(){ getMenuDomain("xxyd"); return super.SUCCESS; } public String xyyzy(){ getMenuDomain("xyyzy"); return super.SUCCESS; } public String recruit_students() { getMenuDomain("recruit_students"); return super.SUCCESS; } public String teach() { Zjut_organization_resourceDomain organization_resourceDomain = new Zjut_organization_resourceDomain(); organization_resourceDomain.setOrganizationDomain(organizationDomain); page.setPagesize(10); page = organization_resourceDomain.getSelectPage(page); getMenuDomain("teach"); return super.SUCCESS; } public String fybz(){ getMenuDomain("feiyongbiaozhun"); return super.SUCCESS; } public String research() { getMenuDomain("research"); return super.SUCCESS; } public String schoolfellow() { getMenuDomain("schoolfellow"); return super.SUCCESS; } private void getMenuDomain(String menuName) { zjut_menu_contentDomain = Zjut_menu_contentService.instance .getMenuDomain(menuName, organizationDomain.getName()); } public Zjut_menu_contentDomain getZjut_menu_contentDomain() { return zjut_menu_contentDomain; } public void setZjut_menu_contentDomain( Zjut_menu_contentDomain zjut_menu_contentDomain) { this.zjut_menu_contentDomain = zjut_menu_contentDomain; } public IbatisPage getPage() { return page; } public void setPage(IbatisPage page) { this.page = page; } } <file_sep>package cn.edu.zjut.web.page.manager.studyabroad; import cn.edu.zjut.cfg.domain.Zjut_new_typeDomain; import cn.edu.zjut.cfg.domain.Zjut_organizationDomain; import cn.edu.zjut.web.page.manager.DefaultNews; public class News extends DefaultNews { private static final Zjut_organizationDomain zjut_organizationDomainOfCollege; private Zjut_new_typeDomain typeDomain; static { zjut_organizationDomainOfCollege = new Zjut_organizationDomain(); zjut_organizationDomainOfCollege.setName("study-abroad"); zjut_organizationDomainOfCollege.loadEqual(); } @Override public Zjut_organizationDomain getOrganizationDomain() { // TODO Auto-generated method stub return zjut_organizationDomainOfCollege; } @Override public String getSource(){ return "院办"; } public String list(){ super.list(); return super.SUCCESS; } public String edit(){ if(typeDomain == null || typeDomain.getId() == null){ typeDomain = new Zjut_new_typeDomain(); typeDomain.setName("common"); typeDomain.loadEqual(); }else{ typeDomain.loadEqual(); } super.edit(); return super.SUCCESS; } public String input(){ if(typeDomain == null || typeDomain.getId() == null){ typeDomain = new Zjut_new_typeDomain(); typeDomain.setName("common"); typeDomain.loadEqual(); }else{ typeDomain.loadEqual(); } super.input(); return "manager/studyabroad/news/edit.html"; } public Zjut_new_typeDomain getTypeDomain() { return typeDomain; } public void setTypeDomain(Zjut_new_typeDomain typeDomain) { this.typeDomain = typeDomain; } } <file_sep>locale=utf-8 default_encoding=utf-8 number_format=# date_format=yyyy-MM-dd time_format=HH:mm:Ss datetime_format=yyyy-MM-dd HH:mm:Ss auto_import=/common/page/common.ftl as c<file_sep>var events_totalSize; var events_currentPage=0; var events_pageSize = 25; var eventsList; var newTitleSize = 50; var newBaseUrl ; function events_init(_eventsList,baseUrl){ eventsList = eval('(' + _eventsList + ')'); newBaseUrl = baseUrl; events_totalSize = eventsList.length; events_generatePage(); events_go2Page(1); } function events_generatePage(){ var pagehtml="<a href=\"javascript:events_goPrev()\" class=\"prev\">上一页</a>"; for(var i=0;i<events_totalSize/events_pageSize;i++){ var id = i+1; pagehtml+="<a id=events_"+id+" href=\"javascript:events_go2Page("+id+");\">"+id+"</a>" } pagehtml+="<a href=\"javascript:events_goNext()\" class=\"next\">下一页</a>" $("#events_page").html(pagehtml) } function events_goPrev(){ if(events_currentPage>0){ events_go2Page(events_currentPage); } } function events_goNext(){ if(events_currentPage<(events_totalSize/events_pageSize-1)){ events_go2Page(events_currentPage+2); } } function events_go2Page(id){ events_currentPage = id-1; var html=""; for(var i = events_currentPage*events_pageSize;i<(events_currentPage+1)*events_pageSize&&i<events_totalSize;i++){ html+="<a class=\"fish\" href=\""+newBaseUrl+"/student/content/detail.html?id="+eventsList[i].id+"\" title="+eventsList[i].title+" href=\"#\" title="+eventsList[i].title+"><span class="new">"; var tempTitle; if(eventsList[i].title.length>newTitleSize){ tempTitle = eventsList[i].title.substring(0,newTitleSize)+"..."; }else{ tempTitle = eventsList[i].title; } html+=tempTitle+"</span><span class=\"date\">"+eventsList[i].create_date+"</span>"; html+="</a>"; } $("#events_page").empty(); $("#events_page").append(html); //设置点中的样式 for(var i=1;i<=events_totalSize/events_pageSize;i++){ $("#events_"+i).attr("class",""); } $("#events_"+id).attr("class","cur"); }
7d9024737834f95ab0006824d8bcb63e91f3aa2a
[ "SQL", "HTML", "JavaScript", "INI", "Java", "Text" ]
85
Java
shaobenbin/zjut
55ce1c9e8a028ecd210dca0f177ba7ee0e4c1da2
b0a34b6ea843d9da802fe5a8b092960724ecc7b5
refs/heads/master
<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 20 11:26:22 2018 @author: najmabachelani """ import jotto import unittest class JottoTests(unittest.TestCase) : def testJottocore (self): a = "aaaaa" b = "aabbb" self.assertEqual(jotto.jotto_score(a,b), 2) if __name__ == '__main__': unittest.main()<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 28 17:59:18 2018 @author: najmabachelani """ import collections import math as m import random # Initial file read def read_w5 () : w5file = "word5.txt" with open(w5file) as fin : result = [x.rstrip("\n") for x in fin.readlines()] return result w5 = read_w5() # Determines the jotto score given two strings. def jotto_score(a,b) : acnt = collections.Counter(a) bcnt = collections.Counter(b) total = 0 for c in acnt : total += min(acnt[c], bcnt[c]) return total # Count the distribution of jotto scores given a word and a candidate set. # Returns Counter dict of score->count. def count_jotto(word, cand) : dist = collections.Counter([jotto_score(word, x) for x in cand]) return dist # Produces a set of words from candidate set that are score n from def select_jotto(word, cand, n) : return [x for x in cand if jotto_score(word,x) == n] # Measure the entropy of a word in partitioning a candidate set. def word_entropy (word, cand) : dist = count_jotto(word, cand) # sum negative p log2(p) all_sum = sum(dist.values()) ent = 0 for k in dist : v = dist[k] p = v / all_sum ent += - p * m.log2(p) return ent # Count of the highest bin in a distrobution histogram of word vs candidate. def word_max (word, cand) : return max(count_jotto(word, cand).values()) # warning: is n^2 on the size of the candidates def find_best_entropy(cand) : best_value = 0 best_word = cand[0] for w in cand : ent = word_entropy(w, cand) if ent > best_value : best_value = ent best_word = w print ("picked", best_word, best_value) return best_word def find_best_max(cand) : best_value = 9999 best_word = "nope" for w in cand : m = word_max(w, cand) if m < best_value : best_value = m best_word = w print ("picked", best_word, best_value) return best_word class Game : def __init__(self, full_wordlist=w5) : print ("initing Game") self.full_wordlist = full_wordlist self.reset() def __str__(self) : return( "The word is " + self.secret_word) def reset (self) : self.candidates = self.full_wordlist self.guess_count = 0 self.guess_list = [] self.reset_word() def score(self, w) : return jotto_score(w, self.secret_word) def reset_word (self) : self.secret_word = random.choice(self.full_wordlist) #Satesless game def interactive_game_weak() : game = Game() count = 0 score = 0 while score is not 5 : w = input("Guess a Word ") count += 1 score = game.score(w) print ("Your score is ", score) print ("Done!", game) print ("Number of guesses is ",count) #Guess the first one game def interactive_game_cand() : game = Game() cand = w5 count = 0 score = 0 while score is not 5 : print ("Number of candidates left", len(cand)) print ("Candidates are ", cand[:55]) w = input("Guess a Word ") if len(w) == 0: w = cand[0] print (" OK, autopicking ", w) count += 1 score = game.score(w) cand = select_jotto(w, cand, score) print ("Your score is ", score) print ("Done!", game) print ("Final set", cand) print ("Number of guesses is ",count) #Guess the best entropy def interactive_game_ent() : game = Game() cand = w5 count = 0 score = 0 while score is not 5 : print ("Number of candidates left", len(cand)) print ("Candidates are ", cand[:55]) w = input("Guess a Word ") if len(w) == 0: w = find_best_entropy(cand) print (" OK, autopicking ", w) count += 1 score = game.score(w) cand = select_jotto(w, cand, score) print ("Your score is ", score) print ("Done!", game) print ("Final set", cand) print ("Number of guesses is ",count) #Guess the best entropy def interactive_game_max() : game = Game() cand = w5 count = 0 score = 0 while score is not 5 : print ("Number of candidates left", len(cand)) print ("Candidates are ", cand[:55]) w = input("Guess a Word ") if len(w) == 0: w = find_best_max(cand) print (" OK, autopicking ", w) count += 1 score = game.score(w) cand = select_jotto(w, cand, score) print ("Your score is ", score) print ("Done!", game) print ("Final set", cand) print ("Number of guesses is ",count)
51e034705b39f9f34a2ac3f2acdfdced61e77247
[ "Python" ]
2
Python
JeffreyBell/jotto
702795fc287f0b9a482c32fd87eefb64df237fef
baf49eae306f95f503ae6247111a1eae2008dc1e
refs/heads/master
<file_sep>package weiser; public class Hallo1 { public static void main(String[] args) { System.out.println("<NAME> wŁnscht Dir einen guten Tag!"); } }
fd4795b6a3f95eec791748fda63cfb43b67f0fc3
[ "Java" ]
1
Java
weiserj/test1e
525a9596477ea3511a41321d2ecee3c8a07d55b5
83bd8186a9334f2bcd92f33cae3e0e1963256e7e
refs/heads/master
<file_sep>import { createStore } from 'redux' import productsReducer from './reducers/products' const store = createStore(productsReducer) export default store<file_sep>Assignment Refactor the etsy homework to use react for the view, axios for the ajax calls, and redux.
c115261a946b0ca1d9b74635af6657eefd587d7f
[ "JavaScript", "Markdown" ]
2
JavaScript
JonathanCass/etsy-react
5a6a972cc2dbd6bef6b7fa6cccb59280628574a3
0f72fd3b9e7308eee47d8ba695e0422004e097ce
refs/heads/master
<file_sep>package com.smart.auto; import static org.testng.Assert.assertNotNull; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * 自动装配 * */ public class AutowireTest { private static String[] CONFIG_FILES = {"com/smart/auto/beans.xml"}; public ApplicationContext factory = null; @BeforeMethod public void setUp() throws Exception { factory = new ClassPathXmlApplicationContext(CONFIG_FILES); } @Test public void testAutoByName() { Boss boss = factory.getBean("boss", Boss.class); Car car = factory.getBean("car", Car.class); Office office = factory.getBean("office", Office.class); Office office1 = factory.getBean("office1", Office.class); assertNotNull(boss); System.out.println("car:" + car); System.out.println("office:" + office); System.out.println("office1:" + office1); System.out.println("boss:" + boss); } } <file_sep>package com.smart.name; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.Test; /** * @author niuhaijun * @date 2018/7/25 9:26 */ public class BeanNameTest { /** * Bean的命名 可以通过<bean/>的name属性和id属性设置 */ @Test public void testConfigBeanName() { String location = "classpath:com/smart/name/beans.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(location); Car car1 = context.getBean("car1", Car.class); car1.introduce(); Car car2 = context.getBean("car2", Car.class); car2.introduce(); Car car3 = context.getBean("car3", Car.class); car3.introduce(); Car car4 = context.getBean("car4", Car.class); car4.introduce(); Car car = context.getBean("com.smart.name.Car", Car.class); car.introduce(); } } <file_sep>package com.smart.ditype; import static org.testng.Assert.assertNotNull; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class DiTypeTest { private static String[] CONFIG_FILES = {"com/smart/ditype/beans.xml"}; public ApplicationContext factory = null; @BeforeClass public void setUp() throws Exception { factory = new ClassPathXmlApplicationContext(CONFIG_FILES); } @Test public void testCar() { Car car = (Car) factory.getBean("car"); assertNotNull(car); System.out.println(car); } @Test public void testBoss() { Boss boss = factory.getBean("boss", Boss.class); assertNotNull(boss); System.out.println("boss:" + boss); } @Test public void testCar2() { Car car2 = (Car) factory.getBean("car2"); assertNotNull(car2); System.out.println(car2); } @Test public void testCar3() { Car car3 = (Car) factory.getBean("car3"); assertNotNull(car3); System.out.println("car3:" + car3); } @Test public void testCar4() { Car car4 = (Car) factory.getBean("car4"); assertNotNull(car4); System.out.println("car4:" + car4); } @Test public void testCar5() { Car car5 = (Car) factory.getBean("car5"); assertNotNull(car5); System.out.println("car5:" + car5); } @Test public void testBoss1() { Boss boos1 = (Boss) factory.getBean("boss1"); assertNotNull(boos1); System.out.println("boos1:" + boos1); } @Test public void testCar6() { Car car6 = (Car) factory.getBean("car6"); assertNotNull(car6); System.out.println("car6:" + car6); } } <file_sep>package com.smart.simple; import static org.testng.Assert.assertNotNull; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BeanRetrieveTest { private static String[] CONFIG_FILES = {"com/smart/simple/beans.xml"}; public ApplicationContext factory = null; @BeforeClass public void setUp() throws Exception { factory = new ClassPathXmlApplicationContext(CONFIG_FILES); } @Test public void testBeanRetrieve() { Car car = factory.getBean("#car1", Car.class); assertNotNull(car); } }
c0c15089b440c01b7703cb9a7b2024385e27b352
[ "Java" ]
4
Java
niuhaijun/chapter5
26504850de9648f9bc28cd5c2248532e44d5b106
5d0bdc40d244a900ca33cb050ddf1ae83cd0402c
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Areas.projects.Models { public class Project { public int id { set; get; } public string title { get; set; } public string description { get; set; } public string imageURL { get; set; } public int year { get; set; } } }<file_sep>#include <vector> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; int main() { Mat myimage = imread("image.png", 0); // Reading the original image if (myimage.empty()) { // If there is no image it will return nothing cout << "can't open file" << endl; return -1; } Mat cannyimage; Canny(myimage, cannyimage, 50, 200, 3); // Canny edge formula Mat cannyconverted,edge; cvtColor(cannyimage, cannyconverted, CV_GRAY2BGR); // Converts from one one color space to another imshow("converted_image using Canny", cannyconverted); // Displays the canny image vector<Vec2f> lines; HoughLines(cannyimage, lines, 1, CV_PI / 180, 100, 0, 0); // Hough transformation to draw lines on the images for (size_t i = 0; i < lines.size(); i++) { double rho = lines[i][0], theta = lines[i][1]; // rho variable is the distance resolution in pixels // theta variable is angle resolution in radians Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(cannyconverted, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA); } imshow("Original Image", myimage); // Shows original image imshow("Transformation using Hough technique", cannyconverted); // Displays images with the boundaries made by lines waitKey(); return 0; }<file_sep>#include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "iostream" using namespace cv; using namespace std; int main() { Mat myimage; //myimage object myimage = imread("image.png"); // load image using imread namedWindow("Original image"); imshow("Original image", myimage); // open a window to show original image Mat destination, houghdestination; Canny(myimage, destination, 50, 200, 3); // Converts the original image to the canny image and puts it in destination object vector<Vec2f> lines; HoughLines(destination, lines, 1, CV_PI / 180, 100, 0, 0); for (size_t i = 0; i < lines.size(); i++) { float rho = lines[i][0], theta = lines[i][1]; Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(houghdestination, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA); } namedWindow("Canny_image", CV_WINDOW_AUTOSIZE); imshow("Canny_image", destination); namedWindow("Hough_Transformation", CV_WINDOW_AUTOSIZE); imshow("Hough_Transformation", houghdestination); waitKey(0); return 0; } <file_sep> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; using namespace cv; int main() { VideoCapture livecamera(0); // Fetching the live feed from the webcam if (!livecamera.isOpened()) { cout << "cannot open camera" ; // Webcam not opened } while (true) { Mat cannyImage; // cannyImage variable that is to be used in the hough transformation Mat frame; // frame variable from the video camera that is to be processed livecamera.read(frame); // Reading the frame from the video imshow("Live Video",frame); //opening the live video feed cvtColor(frame, cannyImage, CV_BGR2GRAY); // Converts from one one color space to another Canny(frame, cannyImage, 100, 200, 3); // Canny edge formula imshow("Canny Transformation", cannyImage); // opening Canny transformation vector<Vec2f> lines; HoughLines(cannyImage, lines, 1, CV_PI / 180, 80, 5, 0); // Hough transformation formula to draw lines on the images vector<Vec2f> cart_lines; //slope, b param, y = [0] * x + [1] if (lines.size() != 2) { continue; } for (size_t i = 0; i < lines.size(); i++) { double rho = lines[i][0],theta = lines[i][1]; // rho variable is the distance resolution in pixels // theta variable is angle resolution in radians Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA); Vec2f cart_line; cart_line[0] = (-cos(theta) / sin(theta)); cart_line[1] = rho / sin(theta); cart_lines.push_back(cart_line); } Vec2f frame_center; frame_center[0] = livecamera.get(3)/2 ; frame_center[1] = livecamera.get(4) / 2; Vec2f right_lane; Vec2f left_lane; if (cart_lines[0][0] < cart_lines[1][0]) { right_lane = cart_lines[0]; left_lane = cart_lines[1]; } else { right_lane = cart_lines[1]; left_lane = cart_lines[0]; } Point intercept_right; intercept_right.y = frame_center[1]; intercept_right.x = (frame_center[1] - right_lane[1]) / right_lane[0]; Point intercept_left; intercept_left.y = frame_center[1]; intercept_left.x = (frame_center[1] - left_lane[1]) / left_lane[0]; std::cout << "intercept_right: " << intercept_right.x << ", " << intercept_right.y << "\n"; std::cout << "intercept_left: " << intercept_left.x << ", " << intercept_left.y << "\n"; imshow("Hough Transformation", frame); //opening the hough transformation if (waitKey(120) >= 0) break; } return 0; }<file_sep>#include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "iostream" using namespace cv; using namespace std; int main() { Mat myimage; //myimage object myimage = imread("image.png"); // load image using imread namedWindow("Original image"); imshow("Original image", myimage); // open a window to show original image Mat gray, edge, convertedimage; cvtColor(myimage, gray, CV_BGR2GRAY); //Converts from one color space to another Canny(gray, edge, 50, 150, 3); // Canny edge formula edge.convertTo(convertedimage, CV_8U); namedWindow("converted_image", CV_WINDOW_AUTOSIZE); imshow("converted_image", convertedimage); // opens a new canny edge image waitKey(0); return 0; }<file_sep>#include "opencv2/highgui/highgui.hpp" #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <vector> #include <stdio.h> #include "string" #include <math.h> using namespace cv; using std::vector; int main(int argc, char** argv) { Mat src, dst, color_dst; if (argc != 2 || !(src = imread(argv[1], 0)).data) return -1; Canny(src, dst, 50, 200, 3); cvtColor(dst, color_dst, CV_GRAY2BGR); #if 0 vector<Vec2f> lines; HoughLines(dst, lines, 1, CV_PI / 180, 100); for (size_t i = 0; i < lines.size(); i++) { float rho = lines[i][0]; float theta = lines[i][1]; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; Point pt1(cvRound(x0 + 1000 * (-b)), cvRound(y0 + 1000 * (a))); Point pt2(cvRound(x0 - 1000 * (-b)), cvRound(y0 - 1000 * (a))); line(color_dst, pt1, pt2, Scalar(0, 0, 255), 3, 8); } #else vector <Vec4i> lines; HoughLinesP(dst, lines, 1, CV_PI / 180, 80, 30, 10); for (size_t i = 0; i < lines.size(); i++) { line(color_dst, Point(lines[i][0], lines[i][1]), Point(lines[i][2], lines[i][3]), Scalar(0, 0, 255), 3, 8); } #endif namedWindow("Source", 1); imshow("Source", src); namedWindow("Detected Lines", 1); imshow("Detected Lines", color_dst); waitKey(0); return 0; }<file_sep>#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; using namespace cv; int main() { VideoCapture livecamera(0); // Fetching the live feed from the webcam std::vector < std::vector < cv::Point > >contours; vector<Vec4i> hierarchy; if (!livecamera.isOpened()) { cout << "cannot open camera"; // Webcam not opened } while (true) { Mat cannyImage; // cannyImage variable that is to be used in the hough transformation Mat frame; // frame variable from the video camera that is to be processed Mat destination; livecamera.read(frame); // Reading the frame from the video imshow("Live Video", frame); //opening the live video feed Canny(frame, destination, 100, 200, 3); // Canny edge formula cvtColor(destination, cannyImage, CV_GRAY2BGR); // Converts from one one color space to another imshow("Canny Transformation", cannyImage); // opening Canny transformation vector<Vec4i> lines; lines.reserve(1000); try{ HoughLinesP(destination, lines, 1, CV_PI / 180, 80, 80,5); } catch (...) { } for (size_t i = 0; i < lines.size(); i++) { Vec4i l = lines[i]; line(cannyImage, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA); } imshow("Hough Transformation", cannyImage); //opening the hough transformation if (waitKey(120) >= 0) break; } return 0; }<file_sep>#include <vector> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat src = imread("image.png", 0); if (src.empty()) { cout << "can't open file" << endl; return -1; } Mat dst; Canny(src, dst, 50, 200, 3); Mat cdst; cvtColor(dst, cdst, CV_GRAY2BGR); vector<Vec2f> lines; HoughLines(dst, lines, 1, CV_PI / 180, 100, 0, 0); for (size_t i = 0; i < lines.size(); i++) { double rho = lines[i][0], theta = lines[i][1]; Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(cdst, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA); } imshow("source", src); imshow("detected lines", cdst); waitKey(); return 0; }<file_sep> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; using namespace cv; int main() { VideoCapture livecamera(0); // Fetching the live feed from the webcam std::vector < std::vector < cv::Point > >contours; vector<Vec4i> hierarchy; if (!livecamera.isOpened()) { cout << "cannot open camera"; // Webcam not opened } while (true) { Mat cannyImage; // cannyImage variable that is to be used in the hough transformation Mat frame; // frame variable from the video camera that is to be processed livecamera.read(frame); // Reading the frame from the video imshow("Live Video", frame); //opening the live video feed cvtColor(frame, cannyImage, CV_BGR2GRAY); // Converts from one one color space to another Canny(frame, cannyImage, 100, 200, 3); // Canny edge formula imshow("Canny Transformation", cannyImage); // opening Canny transformation vector<Vec2f> lines; HoughLines(cannyImage, lines, 1, CV_PI / 180, 100, 0, 0); // Hough transformation formula to draw lines on the images for (size_t i = 0; i < lines.size(); i++) { double rho = lines[i][0], theta = lines[i][1]; // rho variable is the distance resolution in pixels // theta variable is angle resolution in radians Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA); Point2f point1 = (pt2.x + pt1.x)*0.5; Point2f point2 = (pt2.y + pt1.y)*0.5; line(frame, point1, point2, Scalar(1, 3, 2), 6, CV_AA); } imshow("Hough Transformation", frame); //opening the hough transformation findContours(cannyImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); RNG rng(12345); cv::blur(cannyImage, cannyImage, cv::Size(5, 5), cv::Point(-1, -1)); cv::threshold(cannyImage, cannyImage, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); /// Get the moments vector<Moments> mu(contours.size()); for (int i = 0; i < contours.size(); i++) { mu[i] = moments(contours[i], false); } /// Get the mass centers: vector<Point2f> mc(contours.size()); for (int i = 0; i < contours.size(); i++) { mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00); } /// Draw contours Mat drawing = Mat::zeros(cannyImage.size(), CV_8UC3); for (int i = 0; i< contours.size(); i++) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point()); circle(drawing, mc[i], 4, color, -1, 8, 0); } /// Show in a window namedWindow("Contours", CV_WINDOW_AUTOSIZE); imshow("Contours", drawing); if (waitKey(120) >= 0) break; } return 0; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication1.Areas.projects.Controllers { public class projectsController : Controller { public ListProjects<Project> projectList = new List<Project> { new Project() { id = 1, title = "Project Title 1", description = "This is one of my projects", imageURL = "~/Content/cs.jpg" }, new Project() { id = 2, title = "Project Title 2", description = "This is one of my projects", imageURL = "~/Content/cs.jpg" }, new Project() { id = 3, title = "Project Title 3", description = "This is one of my projects", imageURL = "~/Content/cs.jpg" } }; // GET: projects/projects public ActionResult Index() { return View(); } public PartialViewResult ProjectsPartial() { return PartialView(); } } }
b6572e84f3f3683dafb6a840699d7eddd75e1a08
[ "C#", "C++" ]
10
C#
talhaahmedkhan/Projects
abee7757d33c2a1c79f5d8c9261e60e5e753215b
2abf3a504ac56a201db82ccb0c6d4b0fef9a5805
refs/heads/master
<file_sep>// // main.cpp // tree // // Created by <NAME> on 2016/11/15. // Copyright 2016年 姜震飞. All rights reserved. // //this program #include <iostream> #define max 100 typedef char datatype;// change type here //binary tree defined below struct node { struct node *lchild; struct node *rchild; datatype data; }; typedef struct node * btree; //thread binary tree defined below struct thnode { datatype data; struct thnode *lchild, *rchild; bool ltag, rtag; }; typedef struct thnode * thtree; typedef struct thnode * thhead; void threading(thtree &t); //1.至少采用两种方法,编写建立二叉树的二叉链表存储结构的程序,并以适当的形式显示并保存二叉树 //preorder create void pre_createBT(btree &t) { char ch; std::cin >> ch; if (ch == '#') { t = nullptr; } else { t = new struct node; t->data = ch; pre_createBT(t->lchild); pre_createBT(t->rchild); } } btree CreateBT(datatype v, btree ltree, btree rtree) { btree root; root = new struct node; root->data = v; root->lchild = ltree; root->rchild = rtree; return root; } //2.采用二叉树的二叉链表存储结构,编写程序实现二叉树的先序、中序和后序遍历的递归和非递归算法以及层序遍历算法,以适当的形式显示并保存二叉树和相应的遍历序列; //A.recursion //preorder traversal void preorder_r(btree bt) { if (bt != nullptr) { std::cout << bt->data; preorder_r(bt->lchild); preorder_r(bt->rchild); } } //inorder traversal void inorder_r(btree bt) { if (bt != nullptr) { inorder_r(bt->lchild); std::cout << bt->data; inorder_r(bt->rchild); } } //postorder traversal void postorder_r(btree bt){ if (bt != nullptr) { postorder_r(bt->lchild); postorder_r(bt->rchild); std::cout << bt->data; } } //B.none recursion //preorder traversal void preorder(btree root) { int top; btree s[max]; top = -1; while (root != nullptr || top != -1) { while (root != nullptr) { std::cout << root->data; s[++top] = root; root = root->lchild; } if (top != -1) { root = s[top--]; root = root->rchild; } } } //inorder traversal void inorder(btree root) { int top; btree s[max]; top = -1; while (root != nullptr || top != -1) { while (root != nullptr) { s[++top] = root; root = root->lchild; } if (top != -1) { root = s[top--]; std::cout << root->data; root = root->rchild; } } } //postorder traversal void postorder(btree root) { int top; btree s[max]; int flag[max]; top = -1; while (root != nullptr || top != -1) { while (root != nullptr) { top++; s[top] = root; flag[top] = 1; root = root->lchild; } while (-1 != top && 2 == flag[top]) { root = s[top--]; std::cout << root->data; } if (top != -1) { flag[top] = 2; root = s[top]->rchild; } if (-1 == top) { break; } } } //level order traversal void level_order(btree root) { btree Q[max],q;//queue int front,rear; front = rear = 0;//顺序队列 if (root == nullptr) { return; } Q[++rear] = root; while (front != rear) { q = Q[++front]; std::cout << q->data; if (q->lchild!=nullptr) { Q[++rear] = q->lchild; } if (q->rchild!=nullptr) { Q[++rear] = q->rchild; } } } //3.在二叉树的二叉链表存储结构基础上,编写程序实现二叉树的中序线索链表存储结构建立的算法,以适当的形式显示并保存二叉树的相应的线索链表; //按照先序中序线索化建立二叉树 thtree pre_createthT(thtree &t) { char ch; std::cin >> ch; if (ch == '#') { t = nullptr; } else { t = new struct thnode; t->data = ch; pre_createthT(t->lchild); pre_createthT(t->rchild); } return t; } //将其线索化 thtree pre = nullptr; void threading(thtree &t) { if (t != NULL) { threading(t->lchild);//左子树线索化 t->ltag = (t->lchild) ? true : false; t->rtag = (t->rchild) ? true : false; if (pre) {//若前驱存在 if (pre->rtag == false) {//p的r是线索 pre->rchild = t;//那就指向中序后继 } if (t->ltag == false) t->lchild = pre; } pre = t; threading(t->rchild); } } //建立并将其线索化 void create_th_tree(thtree &t,thtree &head) { pre_createthT(t);//建立t head = new struct thnode;//建立头节点 head->ltag = true; head->rtag = true;//true or false??????? //右指针回指 head->rchild = head; if (!t) { head->lchild = head; head->ltag = false; } else{ head->lchild = t; pre= head; threading(t); pre->rchild = head; pre->rtag = false; //head->rchild = pre; } } //4.在二叉树的线索链表存储结构上,编写程序分别实现求二叉树一个结点的先序、中序和 //后序遍历的后继结点算法; //求中序后继 thtree in_next(thtree p) { thtree q; q = p->rchild; if (p->rtag == true) { while (q->ltag == true) { q = q->lchild; } } return q; } //先序后继 thtree prenext(thtree p) { thtree q; if (p->ltag == true) { q = p->lchild; } else { q = p; while (q->rtag == false) { q = q->rchild; } q = q->rchild; } return q; } //后续后继 /* 对于节点p ,利用性质找到其父节点 f 如果f 的右儿子是 p, 则f 是p后序后继 如果 f没有右子树 f也是p后继 如果f的右儿子不是p 那后继就是在右子树里面找后继 */ thtree post_next(thtree p) { thtree q = NULL,j; if (p->rtag != true) { if (p->rchild->lchild == p) { if (p->rchild->rtag != true) { q = p->rchild; } else { q = p->rchild; while (q->rtag == true) { q = q->rchild; } while (q->ltag == true) { q = q->lchild; } } } else if (p->rchild->lchild->rchild == p) { q = p->rchild->lchild; } else { q = p->rchild->lchild; j = q; while (q->rtag == true) { j = q; q = q->rchild; } while (q->ltag == true) { j = q; q = q->lchild; } q = j; } } else if (p->rtag == true) { q = p; while (q->rtag == true) { q = q->rchild; }//找到r指向线索的节点 while (q->rtag != true) //为了找到他的父节点 { q = q->rchild; if(q == q->rchild) q = q->lchild; }//q是父节点 if (q->lchild == p) { q = q->rchild; while (q->ltag == true) { q = q->lchild; } while (q->rtag == true) { q = q->rchild; } } else if (q->rchild == p) { q = q; } else{ while (q->rchild !=p) { q = q->rchild; } } } return q; } //5.以上条要求为基础,编写程序实现对中序线索二叉树进行先序、中序和后序遍历的非递归算法,以适当的形式显示并保存二叉树和相应的遍历序列。 //先序遍历 需要有head void Th_pre_order(thtree head) { thtree tmp; tmp = head; do { if (tmp) { tmp = prenext(tmp); } if (tmp != head && tmp) { std::cout << tmp->data; } } while (tmp != head && tmp); } //中序遍历 需要有head void Th_in_order(thtree head) { thtree tmp; tmp = head; do { if (tmp) tmp = in_next(tmp); if (tmp != head&&tmp) { std::cout << tmp->data; } } while (tmp != head && tmp); } //后续遍历 需要有head void Th_post_order(thtree head) { //找到后续遍历的第一个节点 thtree tmp; tmp = head; while (tmp->ltag && tmp->rtag) { while (tmp->ltag) { tmp = tmp->lchild; } if (tmp->rtag) { tmp = tmp->rchild; } } std::cout << tmp->data; do { if (tmp) tmp = post_next(tmp); if (tmp != head&&tmp) { std::cout << tmp->data; } } while (tmp != head->lchild&&tmp); } /* head->lchild = T head->rchild = head ; head->ltag = TRUE ; head->rtag = TRUE ; */ int main(int argc, const char * argv[]){ // insert code here... //std::cout << "Hello, World!\n"; btree binary_tree; thtree th; thhead head;//头节点 std::cout << "输入先序建立二叉树的数据"<<std::endl; pre_createBT(binary_tree); std::cout <<"这是先序遍历的输出"<<std::endl; preorder(binary_tree);std::cout <<std::endl; preorder_r(binary_tree);std::cout <<std::endl; std::cout <<"这是中序遍历的输出"<<std::endl; inorder(binary_tree);std::cout <<std::endl; inorder_r(binary_tree);std::cout <<std::endl; std::cout <<"这是后序遍历的输出"<<std::endl; postorder(binary_tree);std::cout <<std::endl; postorder_r(binary_tree);std::cout <<std::endl; std::cout <<"这是层序遍历的输出"<<std::endl; level_order(binary_tree);std::cout <<std::endl; std::cout << "输入先序建立中序线索化二叉树的数据" << std::endl; create_th_tree(th,head); std::cout << "中序线索二叉树建立完毕" << std::endl; std::cout <<"这是先序遍历的输出"<<std::endl; Th_pre_order(head); std::cout <<std::endl; std::cout <<"这是中序遍历的输出"<<std::endl; Th_in_order(head); std::cout <<std::endl; std::cout << "这是后序遍历的输出" << std::endl; Th_post_order(head); std::cout << std::endl; return 0; }
c2d05d57429ef023ad07173cec5769ae58b87e15
[ "C++" ]
1
C++
KentonJiang/my_tree
b585be9f29076e9d58a828468b1422da62f2dc71
a34da9cd061df7a5eb97001b8bb8e89751b5f974
refs/heads/master
<repo_name>t3reezhou/gomod<file_sep>/go.mod module gomod go 1.15 <file_sep>/hello.go package hello func HelloWorld() string { return "hello world t3reezhou" }
2d8414ec043e4587d7820ff47e5c749f302729d5
[ "Go", "Go Module" ]
2
Go Module
t3reezhou/gomod
1f24d098785a56f5aed3a81fd4c36c7065f9a0ef
d647ce66e544296015f5830d7761a8ef6e7276c0
refs/heads/master
<file_sep>package tags.fbconnect; import groovy.lang.Closure; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import play.Play; import play.modules.fbconnect.FBConnectPlugin; import play.mvc.Http.Request; import play.templates.FastTags; import play.templates.GroovyTemplate.ExecutableTemplate; @FastTags.Namespace("fbconnect") public class FBConnectTags extends FastTags { public static void _button(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { Object labelArg = args.get("label"); Object classArg = args.get("cssClass"); Object scopeArg = args.get("scope"); String label = labelArg != null ? labelArg.toString() : "Sign in with Facebook"; String className = classArg != null ? classArg.toString() : "play-fbconnect-button"; String scope = scopeArg != null ? scopeArg.toString() : null; //String tagUrl = Request.current().url; Map<String , Object> extraMap = new HashMap<String , Object>(); args.remove("label"); args.remove("cssClass"); args.remove("scope"); for(Object key : args.keySet()) extraMap.put(key.toString() , args.get(key)); String url = Play.plugin(FBConnectPlugin.class).session().getLoginUrl(scope , extraMap); out.println("<a href='" + url + "' class='" + className + "'>" + label + "</a>"); Request.current().headers.get("refer"); } }
069df42d79200c4936bb686846651358266d89db
[ "Java" ]
1
Java
smallufo/play-fbconnect
b3f030928a3c167f32227135ad50a188439b3b61
5bccfb91b7ba8f29e6cdd32e0c443ce67ec684e2
refs/heads/master
<repo_name>k32918kk/Pandas-Practice<file_sep>/Pandas.py # coding: utf-8 # In[1]: import pandas as pd # # pandas的資料結構 # # #### 1.Series:用來處理時間序列相關的資料(如感測器資料等),主要為建立索引的一維陣列。 # #### 2.DataFrame:用來處理結構化(Table like)的資料,有列索引與欄標籤的二維資料集,例如關聯式資料庫、CSV 等等。 # #### 3.Panel:用來處理有資料及索引、列索引與欄標籤的三維資料集。 # In[3]: #Series # input is an array cars = ["BMW", "BENZ", "Toyota", "Nissan", "Lexus"] select = pd.Series(cars) print(select) # In[11]: # input is a dictionary dictionaries = { "factory": "Taipei", "sensor1": "1", "sensor2": "2", "sensor3": "3", "sensor4": "4", "sensor5": "5" } select = pd.Series(dictionaries, index = dictionaries.keys()) # 排序與原 dict 相同 print(select) print('='*20, 'use index to access values') print(select[0]) print('='*20, 'use keys to access values') print(select['sensor1']) print('='*20, 'use multiple index to access key-value') print(select[[0, 2, 4]]) print('='*20, 'use multiple keys to access values') print(select[['factory', 'sensor1', 'sensor3']]) print('='*20, 'use slice to select partial value') print(select[:2]) print('='*20, 'use slice to select partial value') print(select['sensor2':]) #%% # input is a single data cars = "Benz" select = pd.Series(cars, index = range(3)) print(select) #%% # DataFrame ## data is dictionary group = ["Movies", "Sports", "Coding", "Fishing", "Dancing", "cooking"] num = [46, 8, 12, 12, 6, 58] dictionary = {"groups": group, "num":num} select_df = pd.DataFrame(dictionary) select_df #%% ## data is an array arr = [["Movies", 46], ["Sports", 8], ["Coding", 7], ["Fishing", 12]] df = pd.DataFrame(arr, columns = ["name", "num"]) df #%% print(select_df.shape) print("===========") print(select_df.describe()) print("===========") print(select_df.tail(3)) print("===========") print(select_df.columns) print("===========") print(select_df.index) print("===========") print(select_df.info) #%% # chose elements # df.iloc[index of row, index of column] print('======選第一列第二欄========') print(select_df.iloc[0, 1]) print('======選第一到第二列的組名與人數========') print(select_df.iloc[0:2, :]) print('======選第二欄:各組的人數========') print(select_df.iloc[:, 1]) print('======各組人數========') print(select_df["num"]) print('======各組人數========') print(select_df.num) #%% # use boolean to filter # df.loc[index of row, name of column] #選出超過10人的群組 out_df = select_df[select_df.loc[:, "num"] > 10] print(out_df) #%% # sort by index select_df.sort_index(axis = 0, ascending = True) # sort by value select_df.sort_values(by = 'num') #%% # ## finding missing value df = pd.read_csv('Pandas-Practice\shop_list2.csv') print(df) print("======") # find where is missing value and return boolean print(df[df.loc[:, "shop name"].isnull()]) print("======") print(df[df.loc[:, "maket size"].notnull()]) # ## missing value handling print("======") print(df) print("===drop this row if there is a missing value===") drop_value = df.dropna() print(drop_value) print("===fill missing value with 0===") filled_value = df.fillna(0) print(filled_value) print("===fill value according to columns==") filled_value_column = df.fillna({"shop name":"Null", "maket size":0}) print(filled_value_column)
cad851f7b52ff9a79d7540d1b0bf2984961595af
[ "Python" ]
1
Python
k32918kk/Pandas-Practice
07c260adde3df969a5a3bfdc890ab78c05099005
70e3f6d8b5ccbd1acba2c575ee433301d6a56cfe
refs/heads/master
<repo_name>VitalyOne/rango<file_sep>/rango/urls.py from django.conf.urls import url from rango import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^about/', views.about, name='about'), url(r'^test/', views.test, name='test'), url(r'^add_category/$', views.add_category, name='add_category'), url(r'^register/$', views.register, name='register'), url(r'^login/$', views.login_user, name='login_user'), url(r'^about/$', views.about, name='about'), url(r'^logout/$', views.logout_user, name='logout_user'), url(r'category/(?P<category_name_slug>[\w\-]+)/add_page/', views.add_page, name="add_page"), url(r'goto/', views.track_url, name="goto"), url(r'gotoc/', views.track_cat, name="gotoc"), url(r'category/(?P<category_name_slug>[\w\-]+)/$', views.category, name="category") ] <file_sep>/sc_rango.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings') import django django.setup() from rango.models import * def add_cat(name, views=0, likes=0): c = Category.objects.get_or_create(name=name)[0] c.views=views c.likes=likes c.save() return c def add_page(cat, title, url, views=0): p = Page.objects.get_or_create(category=cat, title=title)[0] p.url=url p.views=views p.save() return p def populate(): python_cat = add_cat(name='Python', views=128, likes=64) add_page(cat=python_cat, title='Python Tutorial', url='python.org', views = 500) add_page(cat=python_cat, title='Python for DUMMIES', url='dummies-python.ru', views = 200) add_page(cat=python_cat, title='Python 10 min', url='life-10.ru') django_cat = add_cat(name='Django', views=64, likes=32) add_page(cat=django_cat, title='tango_with_django_project', url='tango_with_django_project.org', views=600) add_page(cat=django_cat, title='tango tutorial', url='django.org', views = 300) add_page(cat=django_cat, title='Django 1.10', url='django-hard.ru') frame_cat = add_cat(name='Other frameworks', views=32, likes=16) add_page(cat=frame_cat, title='Flask', url='flask.org', views = 400) add_page(cat=frame_cat, title='Bottle', url='Bottle.ru') for c in Category.objects.all(): for p in Page.objects.filter(category=c): print(str(c)+' - ' + str(p)) if __name__== '__main__': print('Start sc to complete db...') populate()<file_sep>/rango/models.py from django.template.defaultfilters import slugify from django.contrib.auth.models import User from django.db import models class Category(models.Model): name = models.CharField(max_length=128, unique = True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def __str__(self): return self.name class Page(models.Model): category=models.ForeignKey(Category) title=models.CharField(max_length=128, unique=True) url=models.URLField() views=models.IntegerField(default=0) def __str__(self): return self.title class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_images', blank=True) def __str__(self): return self.user.username class Test(models.Model): val = models.IntegerField(default=0) def __str__(self): return str(self.val)
0cd2c4d075c82a260d9818ae824d1655a4954a3a
[ "Python" ]
3
Python
VitalyOne/rango
628a2cf46ebacff370c38e5da8cceb309e53b391
aa14211ca3664e9a104aeddc8cc68139d4c2bd9d
refs/heads/master
<file_sep>##DashieDB Chat app demo DashieDB GitHub <a href="https://github.com/developeramino/DashieDB">repo</a> ```json // token.json for this demo "demo": { "username": "demo", "password": "<PASSWORD>", "rules": { "read": true, "write": true } } ``` This demo require package(s) to run <li>Express</li> ``` // Database init object(MUST) { "message" [] } ``` #How to run this app? Please making sure DashieDB is running<br> Next run npm install command to install all the dependencies for this app ```bash $ npm install ``` ##Config the the Database By default DashieDB should running on port `8080`<br> You should see a file named `db.json` at this repo<br> If you did't set up the `token.json` for DashieDB before,please visit the <a href="https://github.com/developeramino/DashieDB/blob/master/docs/rules.md#basic">docs</a> at GitHub<br> Once you have your token,please visit the console page at `http://localhost:8080/console/$username/$password`<br> And upload a the `db.json` at the `Import JSON data to database` session<br> #Run the chat app Once the dependencies is installed,and database is good to go,run the app itself by using ```bash $ npm start ``` And by default,you can visiton `http://localhost:8081` is using the chat app<file_sep>const express = require("express"), app = express() app.get("/", (req,res) => { res.sendFile(`${__dirname}/views/index.html`); }); app.listen(8081,function () { console.log("DEMO is running on port 8081"); });
0d682df293520eafcafb492400e9fd43bb3cc674
[ "Markdown", "JavaScript" ]
2
Markdown
felixfong227/DashieDB-demo-chat-app
7e954ded2bf1017a468fc84fc15b54a3bce384d3
9e7649ec784e26c8d5943bac9a004446a73f35b1
refs/heads/master
<file_sep># Scarne-s-Dice Google Android Workshop project 2<br/> Player vs AI roll a dice <br/> if result is 1: lose all scores gained this turn. lose this turn <br/> if result is 2-6: accumulate to this turn's score. choose continue rolling or hold <br/> choosing hold will add this turn's score to total score and end this turn. \n the first to reach 100 points wins this game.<br/> <br/> I've searched in Github for a solution to milestone 5. <br/> I didn't really find any. Therefore I decided to write one myself <br/> Here's my answer to it in "computer turn" method. Instead of the while loop, we can <br/> recursively let the computer roll the dice and add a delay to it. <br/> <br/> I will improve the AI or the mechanic of this game later. <br/> <file_sep>package xuanqixu.info.scarne_dice; import android.media.Image; import android.os.Handler; 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.ImageView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //global variables private int userOverallScore; private int userTurnScore; private int computerOverallScore; private int computerTurnScore; //buttons private Button roll; private Button hold; private Button reset; private TextView scoreboard; private ImageView dicePicture; private static int diceFaces[] = { R.drawable.dice1, R.drawable.dice2, R.drawable.dice3, R.drawable.dice4, R.drawable.dice5, R.drawable.dice6 }; Handler handler = new Handler(); int random; boolean computerRoll = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); roll = findViewById(R.id.roll); hold = findViewById(R.id.hold); reset= findViewById(R.id.reset); scoreboard = findViewById(R.id.scoreboard); dicePicture= findViewById(R.id.dicepicture); roll.setOnClickListener(this); hold.setOnClickListener(this); reset.setOnClickListener(this); } private void rollDice(){ handler=new Handler(); Runnable r1 = new Runnable() { @Override public void run() { computerRoll=true; computerTurn(); enableButtons(); } }; int random =(int) (Math.random()*6) +1; dicePicture.setImageResource(diceFaces[random-1]); if(random==1){ userTurnScore=0; updateScoreboard(); disableButtons(); Toast.makeText(this,"You rolled 1. Computer turn",Toast.LENGTH_LONG).show(); handler.postDelayed(r1,2000); } else { userTurnScore+=random; updateScoreboard(); } } private void holdTurn(){ userOverallScore+=userTurnScore; userTurnScore=0; updateScoreboard(); disableButtons(); if(userOverallScore>=100){ scoreboard.setText("You Win!"); return; } computerRoll=true; computerTurn(); enableButtons(); } private void resetGame(){ dicePicture.setImageResource(diceFaces[0]); userTurnScore=0; userOverallScore=0; computerOverallScore=0; computerTurnScore=0; scoreboard.setText("New Game"); enableButtons(); } private void computerTurn(){ if(computerRoll=false){return;} if(computerTurnScore>20){ computerOverallScore+=computerTurnScore; computerTurnScore=0; updateScoreboard(); Toast.makeText(this,"Computer finished roll. Your turn",Toast.LENGTH_LONG).show(); return; } random =(int) (Math.random()*6) +1; dicePicture.setImageResource(diceFaces[random-1]); if(random==1){ computerTurnScore=0; updateScoreboard(); enableButtons(); Toast.makeText(this, "Computer rolled 1. Your turn", Toast.LENGTH_SHORT).show(); computerRoll=false; return; } else{ Runnable r1 = new Runnable() { @Override public void run() { computerTurn(); } }; Log.d("Score", "CPU rolled " + random); computerTurnScore+=random; updateScoreboard(); handler.postDelayed(r1,2000); } if(computerOverallScore>=100){ scoreboard.setText("Computer Wins"); disableButtons(); computerRoll=false; return; } } public void computerRoll(){ } private void updateScoreboard(){ String s =""; s+= "Your score:"+userOverallScore+" Your turn score:"+userTurnScore+"\n"+ "Computer score:"+computerOverallScore+" Computer turn score:"+computerTurnScore; scoreboard.setText(s); } private void disableButtons() { roll.setEnabled(false); hold.setEnabled(false); } private void enableButtons() { roll.setEnabled(true); hold.setEnabled(true); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.roll: rollDice(); break; case R.id.hold: holdTurn(); break; case R.id.reset: resetGame(); break; } } }
4d04fe0de498401589a3dd41df1e3f7b05263a19
[ "Markdown", "Java" ]
2
Markdown
Ralts1337/Scarne-s-Dice
a5245f1641eba2d9ce7cc816feb95fb3a3cb4e81
e11f287c559c6255cef1e5e80531d2c054bd89ac
refs/heads/main
<repo_name>ypalnati/Netflix-Data-Analysis<file_sep>/graph_simulator.cpp #include "Graph.h" void generateConnectedGraph(int n, ofstream& outfile) { Graph g1(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { g1.addEdge(i, j); } } g1.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g1.connectedComponents(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g1.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 1; g1.DijkstraSP(start, outfile); } void generateEmptyGraph(int n, ofstream& outfile) { Graph g1(n); g1.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g1.connectedComponents(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g1.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 1; g1.DijkstraSP(start, outfile); } void generateHeap(int n, ofstream& outfile) { Graph g1(n); for (int i = 0; i < n; i++) { int x; x = (i - 1) / 2; if (x >= 0 && x < n) g1.addEdge(i, x); x = ((2 * n) + 1) / 2; if (x >= 0 && x < n) g1.addEdge(i, x); x = ((2 * n) - 1) / 2; if (x >= 0 && x < n) g1.addEdge(i, x); } g1.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g1.connectedComponents(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g1.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 1; g1.DijkstraSP(start, outfile); } void generateTruncatedHeap(int n, int m, ofstream& outfile) { Graph g1(n); for (int i = m; i < n; i++) { int x; x = (i - 1) / 2; if (x >= m && x < n) g1.addEdge(i,x); x = ((2 * n) + 1) / 2; if (x >= m && x < n) g1.addEdge(i,x); x = ((2 * n) - 1) / 2; if (x >= m && x < n) g1.addEdge(i,x); } g1.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g1.connectedComponents(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g1.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 6; g1.DijkstraSP(start, outfile); } void generateEquivalenceModKGraph(int n, int k, ofstream& outfile) { Graph g1(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((i - j) % k == 0) g1.addEdge(i, j); } } g1.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g1.connectedComponents(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g1.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 6; g1.DijkstraSP(start, outfile); } void generateNcycleGraph(int n, ofstream& outfile) { Graph g1(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (abs(i - j) ==1 || abs(i - j) == n - 1) { g1.addEdge(i, j); } } } g1.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g1.connectedComponents(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g1.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 1; g1.DijkstraSP(start, outfile); }<file_sep>/NetflixDataAOA.cpp #include <iostream> using namespace std; #include"make_graph.h" int main() { //calling adjacency criteria APIs adjacencyCriteria1(); adjacencyCriteria2(); adjacencyCriteria3(); //while testing called functions individually to record the runtime and memeory for each criteria; return; } <file_sep>/graph_operations.cpp #include "Graph.h" void Graph::DFSConnectedComponentsUtilCount(int v, bool visited[], ofstream& outfile, int* count) { visited[v] = true; (*count)++; for (auto i : adj[v]) if (!visited[i]) DFSConnectedComponentsUtilCount(i, visited, outfile, count); } //prints the count of each connected components void Graph::connectedComponentsCount(ofstream& outfile) { int count = 0; bool* visited = new bool[V]; for (int v = 0; v < V; v++) visited[v] = false; for (int v = 0; v < V; v++) { if (visited[v] == false) { DFSConnectedComponentsUtilCount(v, visited, outfile, &count); outfile << count << "\n"; count = 0; } } delete[] visited; } void Graph::DFSConnectedComponentsUtil(int v, bool visited[], ofstream& outfile) { visited[v] = true; outfile << v << " "; for (auto i : adj[v]) if (!visited[i]) DFSConnectedComponentsUtil(i, visited, outfile); } //prints the connected componenets elements void Graph::connectedComponents(ofstream& outfile) { bool* visited = new bool[V]; for (int v = 0; v < V; v++) visited[v] = false; for (int v = 0; v < V; v++) { if (visited[v] == false) { DFSConnectedComponentsUtil(v, visited, outfile); outfile << "\n"; } } delete[] visited; } bool Graph::DFSCycleUtil(int v, int par, vector<bool>& visited, vector<int>& parent, int* cycle_start, int* cycle_end) { visited[v] = true; for (int u : adj[v]) { if (u == par) continue; if (visited[u]) { *cycle_end = v; *cycle_start = u; return true; } parent[u] = v; if (DFSCycleUtil(u, parent[u], visited, parent, cycle_start, cycle_end)) return true; } return false; } //prints one cycle elements if cycle is present else prints as Acyclic void Graph::one_cycle(ofstream& outfile) { vector<bool> visited; vector<int> parent; int cycle_start, cycle_end; visited.assign(V, false); parent.assign(V, -1); cycle_start = -1; for (int v = 0; v < V; v++) { if (!visited[v] && DFSCycleUtil(v, parent[v], visited, parent, &cycle_start, &cycle_end)) break; } if (cycle_start == -1) { outfile << "Acyclic" << endl; } else { vector<int> cycle; cycle.push_back(cycle_start); for (int v = cycle_end; v != cycle_start; v = parent[v]) cycle.push_back(v); cycle.push_back(cycle_start); outfile << "Cycle found: "; for (int v : cycle) outfile << v << " "; outfile << endl; } } void Graph::printDijkstraPathUtil(vector<int> parent, int j, ofstream& outfile) { if (parent[j] == -1) return; printDijkstraPathUtil(parent, parent[j],outfile); outfile << "- " << j << " "; } void Graph::printDijkstraShortestPath(vector<int>& dist, int& start, vector<int> parent, ofstream& outfile) { outfile << "\nPrinting the shortest paths for node " << start << ".\n"; for (int i = 0; i < dist.size(); i++) { if (dist[i] == INF) { outfile << "There is no path from " << start << " to node " << i; } else { outfile << "The distance from node " << start << " to node " << i << " is: " << dist[i] << " and the path is " << start << " "; printDijkstraPathUtil(parent, i,outfile); } outfile << "\n"; } } //find shortest path from start to all other nodes vector<int> Graph::DijkstraSP(int& start, ofstream& outfile) { outfile << "\nGetting the shortest path from " << start << " to all other nodes.\n"; vector<int> dist; vector<int> parent; for (int i = 0; i < V; i++) { dist.push_back(INF); parent.push_back(-1); } priority_queue<pair<int, int>, vector< pair<int, int> >, greater<pair<int, int> > > pq; pq.push(make_pair(start, 0)); dist[start] = 0; while (pq.empty() == false) { int u = pq.top().first; pq.pop(); for (auto d : adj[u]) {if (dist[d] > dist[u] + 1) { parent[d] = u; dist[d] = dist[u] + 1; pq.push(make_pair(d, dist[d])); } } } printDijkstraShortestPath(dist, start, parent, outfile); return dist; }<file_sep>/make_graph.cpp #pragma once #include <iostream> #include <set> #include <iterator> #include <map> #include <fstream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <cstdio> #include "make_graph.h" #include <thread> #include<mutex> using namespace std; map<int, User*> userMap; map<int, Movie*> movieMap; map<int, int> customerIds; int userCount=0; std::mutex mtx1; std::mutex mtx2; void populateGraph(Graph g, ofstream& outfile) { g.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g.connectedComponents(outfile); // or can call g.connectedComponentsCount(outfile) to print connected componenets count at each level not the elements. outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 1; g.DijkstraSP(start, outfile); } //it will read the file and process the data void reader1(string filename) { ifstream MyFile(filename); string line; int current_movie = 0; while (getline(MyFile, line)) { if (line.back() == ':') { //if : is found in line which means it is a movie row we update the current_movie line.pop_back(); stringstream temp(line); current_movie = 0; temp >> current_movie; } else { int user_id = 0, rating = 0; char date[15] = { '\0' }; int year, dd, mm; //else extract all the values and if passes thecriteria we insert in the map sscanf_s(line.c_str(), "%d,%d,%s", &user_id, &rating, date, sizeof(date)); sscanf_s(date, "%d-%d-%d", &year, &mm, &dd); if (year < 2005) continue; if (rating < 4) continue; int review_key = current_movie * 10 + rating; mtx1.lock(); if (userMap.find(user_id) == userMap.end()) { userMap[user_id] = new User(user_id); } //cout << current_movie << " " << user_id << " " << rating << " " << date << endl; userMap[user_id]->add_review(review_key); mtx1.unlock(); } } } void reader3(string filename) { ifstream MyFile(filename); string line; int current_movie = 0; while (getline(MyFile, line)) { if (line.back() == ':') { line.pop_back(); stringstream temp(line); current_movie = 0; temp >> current_movie; } else { int user_id = 0, rating = 0; char date[15] = { '\0' }; int year, dd, mm; sscanf_s(line.c_str(), "%d,%d,%s", &user_id, &rating, date, sizeof(date)); sscanf_s(date, "%d-%d-%d", &year, &mm, &dd); if (year < 2005) continue; //criteria is same day same movie so storing those fields as unique key unsigned long int review_key = current_movie * 10000+ year * 10000 + mm * 100+ dd; mtx1.lock(); if (userMap.find(user_id) == userMap.end()) { userMap[user_id] = new User(user_id); } //cout << current_movie << " " << user_id << " " << rating << " " << date << endl; userMap[user_id]->add_review(review_key); mtx1.unlock(); } } } void reader2(string filename) { ifstream MyFile(filename); string line; int current_movie = 0; while (getline(MyFile, line)) { if (line.back() == ':') { line.pop_back(); stringstream temp(line); current_movie = 0; temp >> current_movie; } else { int user_id = 0, rating = 0; char date[15] = { '\0' }; int year, dd, mm; sscanf_s(line.c_str(), "%d,%d,%s", &user_id, &rating, date, sizeof(date)); sscanf_s(date, "%d-%d-%d", &year, &mm, &dd); if (rating != 5) continue; mtx1.lock(); //storing customers in a map to get the index values of customers if (customerIds.find(user_id) == customerIds.end()) { customerIds[user_id] = userCount; userCount++; } //for each movie storing all the customers who rated 5 if (movieMap.find(current_movie) == movieMap.end()) { movieMap[current_movie] = new Movie(current_movie); } //cout << current_movie << " " << user_id << " " << rating << " " << date << endl; movieMap[current_movie]->add_user(user_id); mtx1.unlock(); } } } void adjacencyCriteria3() { //thread t1(reader1, "D:\\AOA\\assignment\\final\\data.txt"); thread t1(reader3, "D:\\ratings_data_1.txt"); thread t2(reader3, "D:\\ratings_data_2.txt"); thread t3(reader3, "D:\\ratings_data_3.txt"); thread t4(reader3, "D:\\ratings_data_4.txt"); t1.join(); t2.join(); t3.join(); t4.join(); vector <User*> v; for (map<int, User*>::iterator it = userMap.begin(); it != userMap.end(); ++it) { v.push_back(it->second); } Graph g(v.size()); int itr, ktr; //criteria is to iterate all the customers and relate customers who went to atleast one movie on same day for (itr = 0; itr < v.size(); itr++) { for (ktr = itr + 1; ktr < v.size(); ktr++) { if (v[itr]->add_if_match(v[ktr], 1)) { g.addEdge(itr, ktr); } } } std::ofstream outfile; outfile.open("d:\\netflixtest3.txt", std::ios_base::app); populateGraph(g, outfile); userMap.clear(); } void adjacencyCriteria1() { //thread t1(reader1, "D:\\AOA\\assignment\\final\\data.txt"); thread t1(reader1, "D:\\ratings_data_1.txt"); thread t2(reader1, "D:\\ratings_data_2.txt"); thread t3(reader1, "D:\\ratings_data_3.txt"); thread t4(reader1, "D:\\ratings_data_4.txt"); t1.join(); t2.join(); t3.join(); t4.join(); vector <User*> v; for (map<int, User*>::iterator it = userMap.begin(); it != userMap.end(); ++it) { v.push_back(it->second); } Graph g(v.size()); int itr, ktr; //criteria is to iterate all customers with each other and relate them if they have given same rating atleast for 4 movies (and above 4 rating) for (itr = 0; itr < v.size(); itr++) { for (ktr = itr + 1; ktr < v.size(); ktr++) { if (v[itr]->add_if_match(v[ktr], 4)) { g.addEdge(itr, ktr); } } } std::ofstream outfile; outfile.open("d:\\netflixtest1.txt", std::ios_base::app); populateGraph(g,outfile); userMap.clear(); } void adjacencyCriteria2() { //thread t1(reader2, "D:\\AOA\\assignment\\final\\data.txt"); thread t1(reader2, "D:\\ratings_data_1.txt"); thread t2(reader2, "D:\\ratings_data_2.txt"); thread t3(reader2, "D:\\ratings_data_3.txt"); thread t4(reader2, "D:\\ratings_data_4.txt"); t1.join(); t2.join(); t3.join(); t4.join(); cout << "completed reading data" << endl; Graph g(customerIds.size()); vector <Movie*> v; //criteria is to iterate each movie liked customers (rating=5) and add an edge between them //which means adding an edge if atleast one movie is in common for (map<int, Movie*>::iterator it = movieMap.begin(); it != movieMap.end(); ++it) { vector<int> matches = it->second->users; for (int itr = 0; itr < matches.size(); itr++) { for (int jtr = itr+1; jtr < matches.size(); jtr++) { g.addEdge(customerIds[matches[itr]], customerIds[matches[jtr]]); } } } cout << "completed adding edges" << endl; std::ofstream outfile; outfile.open("d:\\netflixtest2.txt", std::ios_base::app); populateGraph(g,outfile); movieMap.clear(); } <file_sep>/make_graph.h #include"Graph.h" #include<mutex> #include <thread> struct Counter { struct value_type { template<typename T> value_type(const T&) { } }; void push_back(const value_type&) { ++count; } size_t count = 0; }; void populateGraph(Graph g,ofstream& outfile); void adjacencyCriteria1(); void adjacencyCriteria2(); void adjacencyCriteria3(); class Movie { public: int movie_id; vector<int> users; Movie(int id) { movie_id = id; } void add_user(int userid) { users.push_back(userid); } }; class User { public: int user_id; vector<unsigned long int> reviews; User(int id) { user_id = id; } void add_review(int review) { reviews.push_back(review); } vector<User*> related_users; //Returns true if it finds minCount intersections between 2 customer reviews bool add_if_match(User* new_user, int minCount) { Counter c; std::sort(reviews.begin(), reviews.end()); std::sort(new_user->reviews.begin(), new_user->reviews.end()); set_intersection(reviews.begin(), reviews.end(), new_user->reviews.begin(), new_user->reviews.end(), std::back_inserter(c)); if (c.count >= minCount) { return true; } return false; } }; <file_sep>/Graph.cpp #include "Graph.h" Graph::Graph(int V) { this->V = V; adj = new vector<int>[V]; } void Graph::addEdge(int node1, int node2) { adj[node1].push_back(node2); adj[node2].push_back(node1); } void Graph::printGraph(ofstream& outfile) { for (int v = 0; v < V; ++v) { outfile << "\n Adjacency list of vertex "<< v << "\n head "; for (auto x : adj[v]) outfile << "-> " << x; printf("\n"); } } <file_sep>/simulated_test.cpp #include "graph_simulator.h" int main() { bool* visited = new bool[14]; for (int i = 0; i < 14; i++) visited[i] = false; int cycleVertices[14]; for (int i = 0; i < 14; i++) cycleVertices[i] = -1; Graph g(14); g.addEdge(1, 2); g.addEdge(2, 3); g.addEdge(3, 4); g.addEdge(4, 6); g.addEdge(4, 7); g.addEdge(5, 6); g.addEdge(3, 5); g.addEdge(7, 8); g.addEdge(6, 10); g.addEdge(5, 9); g.addEdge(10, 11); g.addEdge(11, 12); g.addEdge(11, 13); g.addEdge(12, 13); std::ofstream outfile; outfile.open("D:\\SimulatedTestResults.txt", std::ios_base::app); int noOfVertices; cout << "enter the size of graph needed to test" << endl; scanf("%d", &noOfVertices); if (!outfile.is_open()) { outfile << "\n ----------------------------error opening out put file---------------- \n"; } g.printGraph(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n Following are connected components \n"; g.connectedComponents(outfile); outfile << "\n -------------------------------------------- \n"; outfile << "\n finding cycle\n"; g.one_cycle(outfile); outfile << "\n --------------shortest path------------------------------ \n"; int start = 1; g.DijkstraSP(start, outfile); outfile << "\n --------------testing simulator functions------------------------------ \n"; outfile << "\n --------------testing with n cycle------------------------------ \n"; generateNcycleGraph(noOfVertices, outfile); outfile << "\n --------------testing with connected graph------------------------------ \n"; generateConnectedGraph(noOfVertices,outfile); outfile << "\n --------------testing with empty graph------------------------------ \n"; generateEmptyGraph(noOfVertices, outfile); outfile << "\n --------------testing with heap ----------------------------- \n"; generateHeap(11,outfile); outfile << "\n --------------testing with truncated heap ----------------------------- \n"; generateTruncatedHeap(noOfVertices, 4,outfile); outfile << "\n --------------testing with EquivalenceModKGraph ----------------------------- \n"; generateEquivalenceModKGraph(noOfVertices, 4, outfile); return 0; } <file_sep>/Graph.h #pragma once #include<iostream> using namespace std; #include<cstdlib> #include <list> #include <set> #define INF 0x3f3f3f3f #include <vector> #include <queue> #include <fstream> class Graph { int V; vector <int>* adj; void DFSConnectedComponentsUtil(int v, bool visited[], ofstream& outfile); bool DFSCycleUtil(int v, int par, vector<bool>& visited, vector<int>& parent, int* cycle_start, int* cycle_end); void printDijkstraPathUtil(vector<int> parent, int j, ofstream& outfile); void printDijkstraShortestPath(vector<int>& dist, int& start, vector<int> parent, ofstream& outfile); void DFSConnectedComponentsUtilCount(int v, bool visited[], ofstream& outfile, int* count); public: Graph(int V); void addEdge(int v, int w); void printGraph(ofstream& outfile); void connectedComponents(ofstream& outfile); void find_cycle(ofstream& outfile); vector<int> DijkstraSP(int& start, ofstream& outfile); void connectedComponentsCount(ofstream& outfile) };<file_sep>/README.md # Netflix-Data-Analysis In this project we have created collection of general graph functions. Then, in the second part we have translated movie rating data from Netflix into graphs and analyzed the graphs with our implemented functions. We made a liberal use of the STL structures, like list, map, set, and vector. In this project, we are implementing the functions in c++ language. **Data structure for storing Graph:** Graph.h file Used adjacency list for implementation because it takes less space and comparatively with adjacency matrix there will be few less comparisons. class Graph { int V; //-> no of nodes(customers) vector <int>* adj; //used array of vectors }; Graph.cpp It contains the basic functions of graph like adding edges in graph, printing the graph. Graph_Operations.cpp It contains the graph operations. void connectedComponents(ofstream& outfile); - Used DFS traversal and it passes through all the elements that are connected. void one_cycle(ofstream& outfile); - While doing dfs if the node is visited previously ( or for the second time) we say it as found cycle and store this node as cyclestart and we will go back till to printcycle. vector<int> DijkstraSP(int& start, ofstream& outfile);- used dijkshtra algorithm with priority queues and calculated shortest path. Graph_simulator.h && Graph_simulator.cpp void generateConnectedGraph(int n, ofstream& outfile); void generateEmptyGraph(int n, ofstream& outfile); void generateHeap(int n, ofstream& outfile); void generateTruncatedHeap(int n, int m, ofstream& outfile); void generateEquivalenceModKGraph(int n, int k, ofstream& outfile); void generateNcycleGraph(int n, ofstream& outfile);This file contains the 6 functions to generate the simulator graphs required to test the graph operations test cases. Used mathematical conditions to generate the graph. Simulated_test.cpp It has the main method to call the simulated graph functions: For each type of graph, we called all the 3 operations, and the output is stored in SimulatesTestResults.txt included in zip file **SUMMARY ** For simulated data: For n=100 it took 550ms and memory is 5kb For n=1000 it took 2.58 mins and memory is 5010.5kb For n=10000 it took 125 mins and memory is 2607341.18kb Observed that heap is taking very less time 16 mins for n=10000 and other graphs are taking 0(n^2) time. All of them are n^2 loops adding edges with mathematical conditions. For Netflix data : Each criteria took minimum of 240 mins and minimum memory of 5 mb for filtered data in memory. Each criteria of ours takes o(n^3) time to process. <file_sep>/graph_simulator.h #pragma once #include "Graph.h" void generateConnectedGraph(int n, ofstream& outfile); void generateEmptyGraph(int n, ofstream& outfile); void generateHeap(int n, ofstream& outfile); void generateTruncatedHeap(int n, int m, ofstream& outfile); void generateEquivalenceModKGraph(int n, int k, ofstream& outfile); void generateNcycleGraph(int n, ofstream& outfile);
5db3340460a813de4ca5af03f0e8dd5a076e0828
[ "Markdown", "C", "C++" ]
10
C++
ypalnati/Netflix-Data-Analysis
5ba6c6072f2aaf4a5e4bf92b624efb7a9c75e87f
54216f566509a4740801f7f4bedafc08d7f1c0b1
refs/heads/master
<repo_name>r21meghashyam/megh.tk<file_sep>/scripts/make-some-magic.js 'use strict'; particlesJS.load('particles-js', './scripts/particles.json'); $(document).ready(function(){ $(document).scroll(function(){ if($(this).scrollTop()>=$('#skills').position().top) $(".me").fadeIn(); else $(".me").fadeOut(); }); $(document).scroll(); $("a[href^='#']").click(function(e){ e.preventDefault(); location.hash=""; $('html,body').animate({ scrollTop:$($(this).attr("href")).position().top },500); }); $(".menu-icon").click(function(){ if( $(".telepathy ul").css("display")=="none") $(".telepathy ul").fadeIn(); else $(".telepathy ul").fadeOut(); }); $("form").submit(function(e){ e.preventDefault(); var name=$("[name=name]").val(), email=$("[name=email]").val(), msg=$("[name=message]").val(); if(!name.trim().length) toast("Please enter your name"); else if(!email.trim().length) toast("Please enter your email"); else if(!msg.trim().length) toast("What's the message?"); else { let db = firebase.firestore(); db.collection("comments").add({name:name,email:email,msg:msg,date:new Date()}) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); toast("Message sent"); $('form')[0].reset(); }) .catch(function(error) { console.error("Error adding document: ", error); toast("Some error occured :("); }); } }); $(".nav-skills>.right").click(function(){ var current = Number($(".skills-list").attr('data')); var next = current+1; $("#item-"+current).hide(); $("#item-"+next).css('display','inline-block'); $(".skills-list").attr('data',next); if($("#item-"+(next+1)).length==0) $(".nav-skills .right").hide(); $(".nav-skills .left").css('display','inline-block'); }); $(".nav-skills .left").click(function(){ var current = Number($(".skills-list").attr('data')); var next = current-1; $("#item-"+current).hide(); $("#item-"+next).css('display','inline-block'); $(".skills-list").attr('data',next); if($("#item-"+(next-1)).length==0) $(".nav-skills .left").hide(); $(".nav-skills .right").css('display','inline-block'); }); $(".nav-sites>.right").click(function(){ var current = Number($(".works-list").attr('data')); var next = current+1; $("#site-"+current).hide(); $("#site-"+next).css('display','inline-block'); $(".works-list").attr('data',next); if($("#site-"+(next+1)).length==0) $(".nav-sites .right").hide(); $(".nav-sites .left").css('display','inline-block'); }); $(".nav-sites .left").click(function(){ var current = Number($(".works-list").attr('data')); var next = current-1; $("#site-"+current).hide(); $("#site-"+next).css('display','inline-block'); $(".works-list").attr('data',next); if($("#site-"+(next-1)).length==0) $(".nav-sites .left").hide(); $(".nav-sites .right").css('display','inline-block'); }); }); function toast(msg){ var t=document.createElement("span"),th=document.createElement("div"); th.className="toast-holder"; t.className="toast"; th.appendChild(t); document.body.appendChild(th); t.innerHTML=msg; $(th).animate({ bottom:100 },500).delay(2000).fadeOut(function(){ $(this).remove(); }); }
aa5fb68903060b96097f93326edd54ad5ba105a6
[ "JavaScript" ]
1
JavaScript
r21meghashyam/megh.tk
db3d403b47513e4991041a9ebfa2a94413aa4b6f
7712650800259278cafa2abf8d6c962f348e2d1a
refs/heads/master
<file_sep>--- name: <NAME> position: Engineer image_path: https://source.unsplash.com/collection/139386/605x605?a=.png twitter: CloudCannonApp blurb: Robin is often found tending to her majestic vegetable garden. --- <file_sep>#!/bin/bash set -e cd "$(dirname "$0")" bundler bundle exec jekyll serve --host=0.0.0.0 --port=8080 --incremental<file_sep>--- name: <NAME> position: General Director image_path: https://source.unsplash.com/collection/139386/601x601?a=.png blurb: Geek ---
03517ade68e4ff7afe6d47dc72f7d665e6a0a833
[ "Markdown", "Shell" ]
3
Markdown
Bit-Clouded/www.bitclouded.io
04d86e0306cd10d593cd7955e19c0c7a8152b80a
48fb61d2683c8f900b121613f1afcd4f8e850c05